Example usage for javax.servlet.http HttpServletRequest getReader

List of usage examples for javax.servlet.http HttpServletRequest getReader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getReader.

Prototype

public BufferedReader getReader() throws IOException;

Source Link

Document

Retrieves the body of the request as character data using a BufferedReader.

Usage

From source file:com.impala.paga.all.BankRouteRemit1.java

/**
 * /* w  w  w  .  j av  a2 s .co m*/
 * @param request
 * @return
 * @throws IOException
 */
private String moneytransfer(HttpServletRequest request)
        throws IOException, JSONException, NoSuchAlgorithmException {

    // joined json string
    String join = "";
    JsonElement root = null;
    JsonElement root2 = null;
    JsonElement root3 = null;

    String responseobject = "";
    String remiturl = "https://www.mypaga.com/paga-webservices/business-rest/secured/depositToBank";
    String hashkey = "372e9b1c62ef47db83c566cf2db033cb4e1b847e12ec435997971ebd7ab8121cbd8458176374480eae7d4cb55f722f4ab328207b461f423a85a9bbad8850ce66";
    String principal = "02A10715-0E53-4A8C-982E-2B7BFC7CF550";
    String credentials = "QE3@u=jd*2b+";

    // These represent parameters received over the network
    String referenceNumber = "", amount = "", currency = "", destinationBankUUID = "",
            destinationBankAccountNumber = "", recipientPhoneNumber = "";

    // Get all parameters, the keys of the parameters are specified
    List<String> lines = IOUtils.readLines(request.getReader());

    // used to format/join incoming JSon string
    join = StringUtils.join(lines.toArray(), "");

    //###############################################################################
    // instantiate the JSon
    //Note
    //The = sign is encoded to \u003d. Hence you need to use disableHtmlEscaping().
    //###############################################################################

    Gson g = new GsonBuilder().disableHtmlEscaping().create();
    //Gson g = new Gson();
    Map<String, String> expected = new HashMap<>();

    try {
        // parse the JSon string

        root = new JsonParser().parse(join);

        referenceNumber = root.getAsJsonObject().get("referenceNumber").getAsString();
        amount = root.getAsJsonObject().get("amount").getAsString();
        currency = root.getAsJsonObject().get("currency").getAsString();
        destinationBankAccountNumber = root.getAsJsonObject().get("destinationBankAccountNumber").getAsString();
        destinationBankUUID = root.getAsJsonObject().get("destinationBankUUID").getAsString();
        recipientPhoneNumber = root.getAsJsonObject().get("recipientPhoneNumber").getAsString();

    } catch (Exception e) {

        expected.put("command_status", "COMMANDSTATUS_INVALID_PARAMETERS");
        String jsonResult = g.toJson(expected);
        System.out.println(e);

        return jsonResult;
    }
    /*String referenceNumber = "",  amount = "",currency="",destinationBankUUID="",
      destinationBankAccountNumber= "", recipientPhoneNumber = ""
     ,  credentials = "";*/
    // check for the presence of all required parameters
    if (StringUtils.isBlank(referenceNumber) || StringUtils.isBlank(amount) || StringUtils.isBlank(currency)
            || StringUtils.isBlank(destinationBankUUID) || StringUtils.isBlank(destinationBankAccountNumber)
            || StringUtils.isBlank(recipientPhoneNumber)) {

        expected.put("am_referenceid", referenceNumber);
        expected.put("am_timestamp", "tombwa");
        expected.put("status_code", statuscode);
        expected.put("status_description", Statusdescription);
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }
    MessageDigest md = null;
    String saltedToken = referenceNumber + amount + destinationBankUUID + destinationBankAccountNumber
            + hashkey;
    md = MessageDigest.getInstance("SHA-512");
    md.update(saltedToken.getBytes());
    byte byteData[] = md.digest();

    //convert the byte to hex format method 1
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < byteData.length; i++) {
        sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
    }

    System.out.println("Hex format : " + sb.toString());
    String hash = sb.toString();

    Double intamount = Double.parseDouble(amount);

    /*{ referenceNumber": "", "amount": "", "currency": "",
    "destinationBankUUID": "","destinationBankAccountNumber": "", 
    "recipientPhoneNumber": ""}
    */

    toPaga.put("referenceNumber", referenceNumber);
    toPaga.put("amount", amount);
    toPaga.put("currency", currency);
    toPaga.put("destinationBankUUID", destinationBankUUID);
    toPaga.put("destinationBankAccountNumber", destinationBankAccountNumber);
    toPaga.put("recipientPhoneNumber", recipientPhoneNumber);

    //toVitesse.put("source","IMPALAPAY");

    System.out.println(toPaga.toString());

    //assign the remit url from properties.config
    CLIENT_URL = remiturl;
    //principal = "" , credentials = "", hash = ""
    PostWithIgnoreSSLPaga = new PostWithIgnoreSSLPaga(CLIENT_URL, toPaga.toString(), principal, credentials,
            hash);

    //capture the switch respoinse.
    responseobject = PostWithIgnoreSSLPaga.doPost();

    System.out.println(responseobject);

    //pass the returned json string
    JsonElement roots = new JsonParser().parse(responseobject);

    int responseCode = roots.getAsJsonObject().get("responseCode").getAsInt();

    String switchresponse = Integer.toString(responseCode);

    //exctract a specific json element from the object(status_code)
    String statusdescription = roots.getAsJsonObject().get("message").getAsString();

    //add 

    String success = "S001";

    if (responseCode == 0) {

        expected.put("am_referenceid", referenceNumber);
        expected.put("am_timestamp", success);
        expected.put("status_code", "S001");
        expected.put("status_description", statusdescription);
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }

    expected.put("am_referenceid", "");
    expected.put("am_timestamp", responseCode + "");
    expected.put("status_code", "00029");
    expected.put("status_description", statusdescription);

    String jsonResult = g.toJson(expected);

    return jsonResult;

}

From source file:com.comcast.cmb.common.controller.EndpointServlet.java

private EndpointMessage parseMessage(HttpServletRequest request) throws IOException {

    EndpointMessage msg = new EndpointMessage();

    String pathInfo = request.getPathInfo();
    msg.id = pathInfo.substring(pathInfo.lastIndexOf("/") + 1);

    SimpleDateFormat fmt = new SimpleDateFormat("yy-MM-dd HH:mm:ss");

    msg.host = request.getRemoteAddr() + "/" + request.getRemoteHost();
    msg.recvOn = fmt.format(new Date());
    msg.url = request.getRequestURL().toString();
    msg.method = request.getMethod();/*  w  w  w  .ja v  a 2s  .  c  o m*/
    msg.msg = "";

    if (msg.method.equals("POST")) {

        BufferedReader reader = request.getReader();
        String line;

        while ((line = reader.readLine()) != null) {
            msg.msg += line;
        }
    }

    return msg;
}

From source file:code.Servlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w w w .  j a v  a 2 s . c o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();

        conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
        stmt = conn.createStatement();
        String sql = "SELECT * FROM Event where now() < date_start";
        ResultSet res = stmt.executeQuery(sql);
        // Register JDBC driver
        try (PrintWriter out = response.getWriter()) {

            BufferedReader reader = request.getReader();

            String firstline = null;
            firstline = reader.readLine();
            if (firstline != null) {
                System.out.println(firstline);

                switch (firstline) {
                //login
                case "{'message_type':'1',":
                    login(reader, response, stmt, out);
                    break;
                case "{'message_type':'2',":
                    register(reader, response, stmt, out);
                    System.out.println("register");

                    break;
                case "{'message_type':'3',":
                    getList(reader, response, stmt, out);
                    System.out.println("getList");
                    break;
                case "{'message_type':'4',":
                    AddedUserEvent(reader, response, stmt, out);
                    System.out.println("add in the match");
                    break;
                case "{'message_type':'5',"://LOLLO
                    send_image(reader, response, stmt, out);
                    System.out.println("fine send image");
                    break;
                case "{'message_type':'6',":
                    getStartData(reader, response, stmt, out);
                    System.out.println("getStartData");
                    break;
                case "{'message_type':'7',":
                    getTipsData(reader, response, stmt, out);
                    System.out.println("getTipsData");
                    break;
                case "{'message_type':'8',":
                    userFoundTreasure(reader, response, stmt, out);
                    System.out.println("userFoundTreasure");
                    break;
                case "{'message_type':'9',":
                    timeExceeded(reader, response, stmt, out);
                    System.out.println("userFoundTreasure");
                    break;
                case "{'message_type':'10',":
                    matchResume(reader, response, stmt, out);
                    System.out.println("userFoundTreasure");
                    break;
                default:
                    System.out.println("non capisco il mex");
                }

            }

        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
        Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:fll.web.api.SubjectiveScoresServlet.java

@SuppressFBWarnings(value = {
        "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING" }, justification = "columns and category are dynamic")
@Override// w w w . j  a  v a2  s .co m
protected final void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {
    int numModified = 0;
    final ObjectMapper jsonMapper = new ObjectMapper();

    final ServletContext application = getServletContext();

    final ChallengeDescription challengeDescription = ApplicationAttributes
            .getChallengeDescription(application);

    Connection connection = null;
    PreparedStatement deletePrep = null;
    PreparedStatement noShowPrep = null;
    PreparedStatement insertPrep = null;
    try {
        final DataSource datasource = ApplicationAttributes.getDataSource(application);
        connection = datasource.getConnection();

        final int currentTournament = Queries.getCurrentTournament(connection);

        final StringWriter debugWriter = new StringWriter();
        IOUtils.copy(request.getReader(), debugWriter);

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Read data: " + debugWriter.toString());
        }

        final Reader reader = new StringReader(debugWriter.toString());

        final Map<String, Map<String, Map<Integer, SubjectiveScore>>> allScores = jsonMapper.readValue(reader,
                ScoresTypeInfo.INSTANCE);
        for (final Map.Entry<String, Map<String, Map<Integer, SubjectiveScore>>> catEntry : allScores
                .entrySet()) {
            final String category = catEntry.getKey();
            final ScoreCategory categoryDescription = challengeDescription
                    .getSubjectiveCategoryByName(category);

            deletePrep = connection.prepareStatement("DELETE FROM " + category //
                    + " WHERE TeamNumber = ?" //
                    + " AND Tournament = ?" //
                    + " AND Judge = ?" //
            );
            deletePrep.setInt(2, currentTournament);

            noShowPrep = connection.prepareStatement("INSERT INTO " + category //
                    + "(TeamNumber, Tournament, Judge, NoShow) VALUES(?, ?, ?, ?)");
            noShowPrep.setInt(2, currentTournament);
            noShowPrep.setBoolean(4, true);

            final int NUM_COLUMNS_BEFORE_GOALS = 6;
            insertPrep = createInsertStatement(connection, categoryDescription);
            insertPrep.setInt(2, currentTournament);
            insertPrep.setBoolean(4, false);

            for (final Map.Entry<String, Map<Integer, SubjectiveScore>> judgeEntry : catEntry.getValue()
                    .entrySet()) {
                final String judgeId = judgeEntry.getKey();
                deletePrep.setString(3, judgeId);
                noShowPrep.setString(3, judgeId);
                insertPrep.setString(3, judgeId);

                for (final Map.Entry<Integer, SubjectiveScore> teamEntry : judgeEntry.getValue().entrySet()) {
                    final int teamNumber = teamEntry.getKey();
                    final SubjectiveScore score = teamEntry.getValue();

                    if (score.getModified()) {
                        deletePrep.setInt(1, teamNumber);
                        noShowPrep.setInt(1, teamNumber);
                        insertPrep.setInt(1, teamNumber);
                        insertPrep.setString(5, score.getNote());

                        ++numModified;
                        if (score.getDeleted()) {
                            if (LOGGER.isTraceEnabled()) {
                                LOGGER.trace("Deleting team: " + teamNumber + " judge: " + judgeId
                                        + " category: " + category);
                            }

                            deletePrep.executeUpdate();
                        } else if (score.getNoShow()) {
                            if (LOGGER.isTraceEnabled()) {
                                LOGGER.trace("NoShow team: " + teamNumber + " judge: " + judgeId + " category: "
                                        + category);
                            }

                            deletePrep.executeUpdate();
                            noShowPrep.executeUpdate();
                        } else {
                            if (LOGGER.isTraceEnabled()) {
                                LOGGER.trace("scores for team: " + teamNumber + " judge: " + judgeId
                                        + " category: " + category);
                            }

                            int goalIndex = 0;
                            for (final AbstractGoal goalDescription : categoryDescription.getGoals()) {
                                if (!goalDescription.isComputed()) {

                                    final String goalName = goalDescription.getName();
                                    if (goalDescription.isEnumerated()) {
                                        final String value = score.getEnumSubScores().get(goalName);
                                        if (null == value) {
                                            insertPrep.setNull(goalIndex + NUM_COLUMNS_BEFORE_GOALS,
                                                    Types.VARCHAR);
                                        } else {
                                            insertPrep.setString(goalIndex + NUM_COLUMNS_BEFORE_GOALS,
                                                    value.trim());
                                        }
                                    } else {
                                        final Double value = score.getStandardSubScores().get(goalName);
                                        if (null == value) {
                                            insertPrep.setNull(goalIndex + NUM_COLUMNS_BEFORE_GOALS,
                                                    Types.DOUBLE);
                                        } else {
                                            insertPrep.setDouble(goalIndex + NUM_COLUMNS_BEFORE_GOALS, value);
                                        }
                                    }
                                    ++goalIndex;

                                } // not computed

                            } // end for

                            deletePrep.executeUpdate();
                            insertPrep.executeUpdate();
                        }
                    } // is modified
                } // foreach team score
            } // foreach judge

            SQLFunctions.close(deletePrep);
            deletePrep = null;

            SQLFunctions.close(noShowPrep);
            noShowPrep = null;

            SQLFunctions.close(insertPrep);
            insertPrep = null;

        } // foreach category

        UploadSubjectiveData.removeNullSubjectiveRows(connection, currentTournament, challengeDescription);

        final Tournament tournament = Tournament.findTournamentByID(connection, currentTournament);
        tournament.recordSubjectiveModified(connection);

        final UploadResult result = new UploadResult(true, "Successfully uploaded scores", numModified);
        response.reset();
        response.setContentType("application/json");
        final PrintWriter writer = response.getWriter();
        jsonMapper.writeValue(writer, result);

    } catch (final SQLException sqle) {
        LOGGER.error("Error uploading scores", sqle);

        final UploadResult result = new UploadResult(false, sqle.getMessage(), numModified);
        response.reset();
        response.setContentType("application/json");
        final PrintWriter writer = response.getWriter();
        jsonMapper.writeValue(writer, result);

    } finally {
        SQLFunctions.close(deletePrep);
        SQLFunctions.close(noShowPrep);
        SQLFunctions.close(insertPrep);
        SQLFunctions.close(connection);
    }

}

From source file:jp.or.openid.eiwg.scim.servlet.Users.java

/**
 * POST?/*from   ww w .  j  a v  a2s  .co m*/
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?
    ServletContext context = getServletContext();

    // ??
    Operation op = new Operation();
    boolean result = op.Authentication(context, request);

    if (!result) {
        // 
        errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
    } else {
        // ?
        String targetId = request.getPathInfo();
        String attributes = request.getParameter("attributes");

        if (targetId != null && !targetId.isEmpty()) {
            // ?'/'???
            targetId = targetId.substring(1);
        }

        if (targetId == null || targetId.isEmpty()) {
            // POST(JSON)?
            request.setCharacterEncoding("UTF-8");
            String body = IOUtils.toString(request.getReader());

            // ?
            LinkedHashMap<String, Object> resultObject = op.createUserInfo(context, request, attributes, body);
            if (resultObject != null) {
                // javaJSON??
                ObjectMapper mapper = new ObjectMapper();
                StringWriter writer = new StringWriter();
                mapper.writeValue(writer, resultObject);

                // Location?URL?
                String location = request.getScheme() + "://" + request.getServerName();
                int serverPort = request.getServerPort();
                if (serverPort != 80 && serverPort != 443) {
                    location += ":" + Integer.toString(serverPort);
                }
                location += request.getContextPath();
                location += "/scim/Users/";
                if (resultObject.get("id") != null) {
                    location += resultObject.get("id").toString();
                }

                // ??
                response.setStatus(HttpServletResponse.SC_CREATED);
                response.setContentType("application/scim+json;charset=UTF-8");
                response.setHeader("Location", location);

                PrintWriter out = response.getWriter();
                out.println(writer.toString());
            } else {
                // 
                errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
            }
        } else {
            errorResponse(response, HttpServletResponse.SC_BAD_REQUEST, null,
                    MessageConstants.ERROR_NOT_SUPPORT_OPERATION);
        }
    }
}

From source file:jp.or.openid.eiwg.scim.servlet.Users.java

/**
 * PUT?//w  w  w .j  a va 2s . c  o  m
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?
    ServletContext context = getServletContext();

    // ??
    Operation op = new Operation();
    boolean result = op.Authentication(context, request);

    if (!result) {
        // 
        errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
    } else {
        // ?
        String targetId = request.getPathInfo();
        String attributes = request.getParameter("attributes");

        if (targetId != null && !targetId.isEmpty()) {
            // ?'/'???
            targetId = targetId.substring(1);
        }

        if (targetId != null && !targetId.isEmpty()) {
            // PUT(JSON)?
            request.setCharacterEncoding("UTF-8");
            String body = IOUtils.toString(request.getReader());

            // 
            LinkedHashMap<String, Object> resultObject = op.updateUserInfo(context, request, targetId,
                    attributes, body);
            if (resultObject != null) {
                // javaJSON??
                ObjectMapper mapper = new ObjectMapper();
                StringWriter writer = new StringWriter();
                mapper.writeValue(writer, resultObject);

                // Location?URL?
                String location = request.getScheme() + "://" + request.getServerName();
                int serverPort = request.getServerPort();
                if (serverPort != 80 && serverPort != 443) {
                    location += ":" + Integer.toString(serverPort);
                }
                location += request.getContextPath();
                location += "/scim/Users/";
                if (resultObject.get("id") != null) {
                    location += resultObject.get("id").toString();
                }

                // ??
                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType("application/scim+json;charset=UTF-8");
                response.setHeader("Location", location);

                PrintWriter out = response.getWriter();
                out.println(writer.toString());
            } else {
                // 
                errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
            }
        } else {
            errorResponse(response, HttpServletResponse.SC_BAD_REQUEST, null,
                    MessageConstants.ERROR_NOT_SUPPORT_OPERATION);
        }
    }
}

From source file:pa_SymposiumPlanner.BRF2011GeneralChair.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html; charset=UTF-8");
    //PrintWriter out = response.getWriter();
    try {/* w ww.j a  v a 2  s . com*/
        address = PAConfiguration.getAddress();
        port = PAConfiguration.getPort(instantiation);
        poslAddress = PAConfiguration.getPOSL(instantiation, topic);
        rdfAddress = PAConfiguration.getRDFTaxonomy(instantiation);
        messageEndpoint = PAConfiguration.getEndpointName(instantiation, topic);
    } catch (BadConfigurationException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        System.exit(0);
    }
    try {
        System.out.println("General Chair Servlet");
        System.out.println(response.toString());

        BufferedReader brd = request.getReader();

        String input = "";
        String message = "";

        while (!input.equals("</RuleML>")) {
            input = brd.readLine();
            message = message + input;
        }
        String[] varOrder = getVariableOrder(message);
        System.out.println("Received Message: " + message);

        //BackwardReasoner br = new BackwardReasoner();
        //Iterator solit =null;
        //DefiniteClause dc = null;
        //SymbolTable.reset();

        POSLParser pp = new POSLParser();

        Date t1 = new GregorianCalendar().getTime();
        //System.out.println(t1.getHours() + ":" + t1.getMinutes());
        //append time to contents

        //System.out.println("day: " + t1.getDay());
        //System.out.println("day: " + t1.getYear());
        //System.out.println("day: " + t1.getMonth());

        //time
        String time = "time(" + t1.getHours() + ":integer).";
        //System.out.println(time);

        //String url = "http://www.jdrew.org/oojdrew/test.posl";
        String contents = "";

        //day of the week
        int day = t1.getDay();
        boolean weekday = true;

        if (day == 0 || day == 6) {
            weekday = false;
        }

        String dayOfWeek;

        if (weekday) {
            dayOfWeek = "day(weekday).";
        } else {
            dayOfWeek = "day(weekend).";
        }
        //full date
        Calendar cal = new GregorianCalendar();

        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day2 = cal.get(Calendar.DAY_OF_MONTH);

        String date;

        String day3 = "" + day2;

        if (day2 == 1 || day2 == 2 || day2 == 3 || day2 == 4 || day2 == 5 || day2 == 6 || day2 == 7 || day2 == 8
                || day2 == 9) {

            day3 = "0" + day2;
        }

        if (month == 10 || month == 11 || month == 12) {
            date = "" + year + month + day3;
        } else {
            date = "" + year + "0" + month + day3;
        }

        date = "date(" + date + ":integer).";

        //System.out.println(date);

        String url = poslAddress;
        String url2 = rdfAddress;
        HttpClient client2 = new HttpClient();
        GetMethod method2 = new GetMethod(url2);
        method2.setFollowRedirects(true);
        String typestr = "";

        // Execute the GET method
        int statusCode2 = client2.executeMethod(method2);
        if (statusCode2 != -1) {
            typestr = method2.getResponseBodyAsString();
        }
        Types.reset();
        RDFSParser.parseRDFSString(typestr);

        try {
            HttpClient client = new HttpClient();
            GetMethod method = new GetMethod(url);
            method.setFollowRedirects(true);

            // Execute the GET method
            int statusCode = client.executeMethod(method);
            if (statusCode != -1) {
                contents = method.getResponseBodyAsString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        contents = contents + "\n" + time;
        contents = contents + "\n" + dayOfWeek;
        contents = contents + "\n" + date;

        BackwardReasoner br = new BackwardReasoner();

        SymbolTable.reset();

        pp.parseDefiniteClauses(contents);
        br.loadClauses(pp.iterator());

        Iterator it = pp.iterator();
        while (it.hasNext()) {
            DefiniteClause d = (DefiniteClause) it.next();
            System.out.println("Loaded clause: " + d.toPOSLString());
        }

        br = new BackwardReasoner(br.clauses, br.oids);

        MessageParser m = new MessageParser(message);
        Element atom = null;

        try {
            atom = m.parseForContent();
        } catch (Exception e) {
            System.out.println("Invalid Message");
            //out.flush();
        }

        QueryBuilder q = new QueryBuilder(atom);
        String query = q.generateDoc();
        System.out.println("ABOUT TO INPUT THIS QUERY:" + query);
        RuleMLParser qp = new RuleMLParser();

        DefiniteClause dc = null;
        try {
            dc = qp.parseRuleMLQuery(query);
        } catch (Exception e) {
            System.out.println("Invalid Query");
            //out.flush();
        }

        int varSize = 0;

        Iterator solit = br.iterativeDepthFirstSolutionIterator(dc);
        while (solit.hasNext()) {

            Vector data = new Vector();

            BackwardReasoner.GoalList gl = (BackwardReasoner.GoalList) solit.next();

            Hashtable varbind = gl.varBindings;
            javax.swing.tree.DefaultMutableTreeNode root = br.toTree();
            root.setAllowsChildren(true);

            javax.swing.tree.DefaultTreeModel dtm = new DefaultTreeModel(root);

            int i = 0;
            Object[][] rowdata = new Object[varbind.size()][2];
            varSize = varbind.size();

            Enumeration e = varbind.keys();
            while (e.hasMoreElements()) {
                Object k = e.nextElement();
                Object val = varbind.get(k);
                String ks = (String) k;
                rowdata[i][0] = ks;
                rowdata[i][1] = val;

                i++;
            }

            data.addElement(rowdata);
            String[] messages = new String[data.size()];
            MessageGenerator g = new MessageGenerator(data, varSize, messageEndpoint, m.getId(),
                    m.getProtocol(), m.getRel(), varOrder);
            //messages = g.Messages2();
            messages = g.Messages2();
            String appender = "";

            URL sender = new URL(address + ":" + port);
            HttpMessage msg = new HttpMessage(sender);
            Properties props = new Properties();

            for (int i1 = 0; i1 < data.size(); i1++) {
                System.out.println(i1 + ")" + messages[i1].toString());
                props.put("text", messages[i1].toString());
                InputStream in = msg.sendGetMessage(props);
            }
            System.out.println("NEXT MESSAGE");
        }

        MessageGenerator g = new MessageGenerator(null, varSize, messageEndpoint, m.getId(), m.getProtocol(),
                m.getRel());

        URL sender = new URL(address + ":" + port);
        HttpMessage msg = new HttpMessage(sender);
        Properties props = new Properties();

        String finalMessage = g.finalMessage(query);

        System.out.println(finalMessage);

        props.put("text", finalMessage);
        InputStream in = msg.sendGetMessage(props);

        System.out.println("Stop_Communication");
    } catch (Exception e) {
        System.out.println("ERROR has occured : " + e.toString());
    }
    //out.close();
}

From source file:pa_SymposiumPlanner.RuleML2010RRChair.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {//from   w  w w  .  ja v a 2s  . c  o  m
        address = PAConfiguration.getAddress();
        port = PAConfiguration.getPort(instantiation);
        poslAddress = PAConfiguration.getPOSL(instantiation, topic);
        rdfAddress = PAConfiguration.getRDFTaxonomy(instantiation);
        messageEndpoint = PAConfiguration.getEndpointName(instantiation, topic);
    } catch (BadConfigurationException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        System.exit(0);
    }
    try {
        System.out.println("RR Chair Servlet");
        System.out.println(response.toString());

        BufferedReader brd = request.getReader();

        String input = "";
        String message = "";

        while (!input.equals("</RuleML>")) {

            input = brd.readLine();

            message = message + input;
        }
        String[] varOrder = getVariableOrder(message);
        System.out.println("Received Message: " + message);

        //   BackwardReasoner br = new BackwardReasoner();
        //   Iterator solit =null;
        //   DefiniteClause dc = null;
        //   SymbolTable.reset();

        POSLParser pp = new POSLParser();
        // String contents = "c(a).\nc(b).\nc(c).";

        Date t1 = new GregorianCalendar().getTime();
        System.out.println(t1.getHours() + ":" + t1.getMinutes());
        //append time to contents

        System.out.println("day: " + t1.getDay());
        System.out.println("day: " + t1.getYear());
        System.out.println("day: " + t1.getMonth());

        //time
        String time = "time(" + t1.getHours() + ":integer).";
        System.out.println(time);

        String url = poslAddress;

        //String url = "http://www.jdrew.org/oojdrew/test.posl";
        String contents = "";

        //day of the week
        int day = t1.getDay();
        boolean weekday = true;

        if (day == 0 || day == 6) {
            weekday = false;
        }

        String dayOfWeek;

        if (weekday) {
            dayOfWeek = "day(weekday).";
        } else {
            dayOfWeek = "day(weekend).";
        }
        //full date
        Calendar cal = new GregorianCalendar();

        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day2 = cal.get(Calendar.DAY_OF_MONTH);

        String date;

        String day3 = "" + day2;

        if (day2 == 1 || day2 == 2 || day2 == 3 || day2 == 4 || day2 == 5 || day2 == 6 || day2 == 7 || day2 == 8
                || day2 == 9) {

            day3 = "0" + day2;
        }

        if (month == 10 || month == 11 || month == 12) {
            date = "" + year + month + day3;
        } else {
            date = "" + year + "0" + month + day3;
        }

        date = "date(" + date + ":integer).";

        System.out.println(date);

        String url2 = rdfAddress;
        HttpClient client2 = new HttpClient();
        GetMethod method2 = new GetMethod(url2);
        method2.setFollowRedirects(true);
        String typestr = "";
        // Execute the GET method
        int statusCode2 = client2.executeMethod(method2);
        if (statusCode2 != -1) {
            typestr = method2.getResponseBodyAsString();
        }
        try {
            Types.reset();

            RDFSParser.parseRDFSString(typestr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            HttpClient client = new HttpClient();
            GetMethod method = new GetMethod(url);
            method.setFollowRedirects(true);

            // Execute the GET method
            int statusCode = client.executeMethod(method);
            if (statusCode != -1) {
                contents = method.getResponseBodyAsString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        contents = contents + "\n" + time;
        contents = contents + "\n" + dayOfWeek;
        contents = contents + "\n" + date;

        BackwardReasoner br = new BackwardReasoner();
        Iterator solit = null;
        DefiniteClause dc = null;
        SymbolTable.reset();
        pp.parseDefiniteClauses(contents);

        br.loadClauses(pp.iterator());

        Iterator it = pp.iterator();
        while (it.hasNext()) {
            DefiniteClause d = (DefiniteClause) it.next();
            System.out.println("Loaded clause: " + d.toPOSLString());
        }

        br = new BackwardReasoner(br.clauses, br.oids);

        MessageParser m = new MessageParser(message);
        Element atom = null;

        try {
            atom = m.parseForContent();
        } catch (Exception e) {
            System.out.println("Invalid Message");
            //out.flush();
        }
        QueryBuilder q = new QueryBuilder(atom);
        String query = q.generateDoc();
        System.out.println("ABOUT TO INPUT THIS QUERY:" + query);
        RuleMLParser qp = new RuleMLParser();

        try {
            dc = qp.parseRuleMLQuery(query);
        } catch (Exception e) {
            System.out.println("Invalid Query");
            //out.flush();
        }

        //solit = br.iterativeDepthFirstSolutionIterator(dc);

        solit = br.iterativeDepthFirstSolutionIterator(dc);
        int varSize = 0;
        while (solit.hasNext()) {
            Vector data = new Vector();
            BackwardReasoner.GoalList gl = (BackwardReasoner.GoalList) solit.next();

            Hashtable varbind = gl.varBindings;
            javax.swing.tree.DefaultMutableTreeNode root = br.toTree();
            root.setAllowsChildren(true);

            javax.swing.tree.DefaultTreeModel dtm = new DefaultTreeModel(root);

            int i = 0;
            Object[][] rowdata = new Object[varbind.size()][2];
            varSize = varbind.size();

            Enumeration e = varbind.keys();
            while (e.hasMoreElements()) {
                Object k = e.nextElement();
                Object val = varbind.get(k);
                String ks = (String) k;
                rowdata[i][0] = ks;
                rowdata[i][1] = val;

                i++;
            }
            data.addElement(rowdata);
            String[] messages = new String[data.size()];
            MessageGenerator g = new MessageGenerator(data, varSize, messageEndpoint, m.getId(),
                    m.getProtocol(), m.getRel(), varOrder);
            messages = g.Messages2();

            String appender = "";

            URL sender = new URL(address + ":" + port);
            HttpMessage msg = new HttpMessage(sender);
            Properties props = new Properties();

            for (int i1 = 0; i1 < data.size(); i1++) {
                System.out.println(i1 + ")" + messages[i1].toString());
                props.put("text", messages[i1].toString());
                InputStream in = msg.sendGetMessage(props);
            }
            System.out.println("NEXT MESSAGE");
        }

        MessageGenerator g = new MessageGenerator(null, varSize, messageEndpoint, m.getId(), m.getProtocol(),
                m.getRel());

        URL sender = new URL(address + ":" + port);
        HttpMessage msg = new HttpMessage(sender);
        Properties props = new Properties();

        String finalMessage = g.finalMessage(query);
        System.out.println("nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn");
        System.out.println(finalMessage);

        props.put("text", finalMessage);
        InputStream in = msg.sendGetMessage(props);

        System.out.println("Stop_Communication");

    } catch (Exception e) {
        System.out.println("ERROR has occured : " + e.toString());
    }
    out.close();
}

From source file:pa_SymposiumPlanner.BRF2011RRChair.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {/*from  w ww.j ava 2s  .c o  m*/
        address = PAConfiguration.getAddress();
        port = PAConfiguration.getPort(instantiation);
        poslAddress = PAConfiguration.getPOSL(instantiation, topic);
        rdfAddress = PAConfiguration.getRDFTaxonomy(instantiation);
        messageEndpoint = PAConfiguration.getEndpointName(instantiation, topic);
    } catch (BadConfigurationException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        System.exit(0);
    }
    try {
        System.out.println("RR Chair Servlet");
        System.out.println(response.toString());

        BufferedReader brd = request.getReader();

        String input = "";
        String message = "";

        while (!input.equals("</RuleML>")) {

            input = brd.readLine();

            message = message + input;
        }
        String[] varOrder = getVariableOrder(message);
        System.out.println("Received Message: " + message);

        //   BackwardReasoner br = new BackwardReasoner();
        //   Iterator solit =null;
        //   DefiniteClause dc = null;
        //   SymbolTable.reset();

        POSLParser pp = new POSLParser();
        // String contents = "c(a).\nc(b).\nc(c).";

        Date t1 = new GregorianCalendar().getTime();
        System.out.println(t1.getHours() + ":" + t1.getMinutes());
        //append time to contents

        System.out.println("day: " + t1.getDay());
        System.out.println("day: " + t1.getYear());
        System.out.println("day: " + t1.getMonth());

        //time
        String time = "time(" + t1.getHours() + ":integer).";
        System.out.println(time);

        String url = poslAddress;

        //String url = "http://www.jdrew.org/oojdrew/test.posl";
        String contents = "";

        //day of the week
        int day = t1.getDay();
        boolean weekday = true;

        if (day == 0 || day == 6) {
            weekday = false;
        }

        String dayOfWeek;

        if (weekday) {
            dayOfWeek = "day(weekday).";
        } else {
            dayOfWeek = "day(weekend).";
        }
        //full date
        Calendar cal = new GregorianCalendar();

        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day2 = cal.get(Calendar.DAY_OF_MONTH);

        String date;

        String day3 = "" + day2;

        if (day2 == 1 || day2 == 2 || day2 == 3 || day2 == 4 || day2 == 5 || day2 == 6 || day2 == 7 || day2 == 8
                || day2 == 9) {

            day3 = "0" + day2;
        }

        if (month == 10 || month == 11 || month == 12) {
            date = "" + year + month + day3;
        } else {
            date = "" + year + "0" + month + day3;
        }

        date = "date(" + date + ":integer).";

        System.out.println(date);

        String url2 = rdfAddress;
        HttpClient client2 = new HttpClient();
        GetMethod method2 = new GetMethod(url2);
        method2.setFollowRedirects(true);
        String typestr = "";
        // Execute the GET method
        int statusCode2 = client2.executeMethod(method2);
        if (statusCode2 != -1) {
            typestr = method2.getResponseBodyAsString();
        }
        System.out.println("Types: " + typestr);
        Types.reset();
        RDFSParser.parseRDFSString(typestr);

        try {
            HttpClient client = new HttpClient();
            GetMethod method = new GetMethod(url);
            method.setFollowRedirects(true);

            // Execute the GET method
            int statusCode = client.executeMethod(method);
            if (statusCode != -1) {
                contents = method.getResponseBodyAsString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        contents = contents + "\n" + time;
        contents = contents + "\n" + dayOfWeek;
        contents = contents + "\n" + date;

        BackwardReasoner br = new BackwardReasoner();
        Iterator solit = null;
        DefiniteClause dc = null;
        SymbolTable.reset();

        pp.parseDefiniteClauses(contents);

        br.loadClauses(pp.iterator());

        Iterator it = pp.iterator();
        while (it.hasNext()) {
            DefiniteClause d = (DefiniteClause) it.next();
            System.out.println("Loaded clause: " + d.toPOSLString());
        }

        br = new BackwardReasoner(br.clauses, br.oids);

        MessageParser m = new MessageParser(message);
        Element atom = null;

        try {
            atom = m.parseForContent();
        } catch (Exception e) {
            System.out.println("Invalid Message");
            //out.flush();
        }

        QueryBuilder q = new QueryBuilder(atom);
        String query = q.generateDoc();
        System.out.println("ABOUT TO INPUT THIS QUERY:" + query);
        RuleMLParser qp = new RuleMLParser();

        try {
            dc = qp.parseRuleMLQuery(query);
        } catch (Exception e) {
            System.out.println("Invalid Query");
            //out.flush();
        }

        //solit = br.iterativeDepthFirstSolutionIterator(dc);

        solit = br.iterativeDepthFirstSolutionIterator(dc);
        int varSize = 0;

        while (solit.hasNext()) {
            Vector data = new Vector();
            BackwardReasoner.GoalList gl = (BackwardReasoner.GoalList) solit.next();

            Hashtable varbind = gl.varBindings;
            javax.swing.tree.DefaultMutableTreeNode root = br.toTree();
            root.setAllowsChildren(true);

            javax.swing.tree.DefaultTreeModel dtm = new DefaultTreeModel(root);

            int i = 0;
            Object[][] rowdata = new Object[varbind.size()][2];
            varSize = varbind.size();

            Enumeration e = varbind.keys();
            while (e.hasMoreElements()) {
                Object k = e.nextElement();
                Object val = varbind.get(k);
                String ks = (String) k;
                rowdata[i][0] = ks;
                rowdata[i][1] = val;

                i++;
            }

            data.addElement(rowdata);
            String[] messages = new String[data.size()];
            MessageGenerator g = new MessageGenerator(data, varSize, messageEndpoint, m.getId(),
                    m.getProtocol(), m.getRel(), varOrder);
            messages = g.Messages2();

            String appender = "";

            URL sender = new URL(address + ":" + port);
            HttpMessage msg = new HttpMessage(sender);
            Properties props = new Properties();

            for (int i1 = 0; i1 < data.size(); i1++) {
                System.out.println(i1 + ")" + messages[i1].toString());
                props.put("text", messages[i1].toString());
                InputStream in = msg.sendGetMessage(props);
            }
            System.out.println("NEXT MESSAGE");
        }

        MessageGenerator g = new MessageGenerator(null, varSize, messageEndpoint, m.getId(), m.getProtocol(),
                m.getRel());

        URL sender = new URL(address + ":" + port);
        HttpMessage msg = new HttpMessage(sender);
        Properties props = new Properties();

        String finalMessage = g.finalMessage(query);

        System.out.println(finalMessage);

        props.put("text", finalMessage);
        InputStream in = msg.sendGetMessage(props);

        System.out.println("Stop_Communication");

    } catch (Exception e) {
        System.out.println("ERROR has occured : " + e.toString());
    }
    out.close();
}

From source file:com.redblackit.web.server.EchoServlet.java

/**
 * doEcho/*w ww.j av  a 2  s  .  c  o m*/
 * 
 * <ul>
 * <li>Log method, URL, headers, body</li>
 * <li>Replicate request headers, except for setting location to received
 * URL</li>
 * <li>Replicate request body in response</li>
 * </ul>
 * 
 * @param req
 * @param resp
 * @param method
 */
@SuppressWarnings("rawtypes")
private void doEcho(HttpServletRequest req, HttpServletResponse resp, String method) throws IOException {
    String reqURI = req.getRequestURI();
    logger.debug(this.getClass().getName() + ":" + method + " - " + reqURI);

    for (Enumeration hdrse = req.getHeaderNames(); hdrse.hasMoreElements();) {
        String headerName = (String) hdrse.nextElement();
        int hnct = 0;
        for (Enumeration hdre = req.getHeaders(headerName); hdre.hasMoreElements();) {
            String headerValue = (String) hdre.nextElement();
            logger.debug(
                    this.getClass().getName() + ":  header[" + headerName + "," + hnct + "]=" + headerValue);
            if (!headerName.equals("Location")) {
                resp.addHeader(headerName, headerValue);
            }
            hnct++;
        }

        if (hnct == 0) {
            resp.setHeader(headerName, "");
            logger.info(this.getClass().getName() + ":  header[" + headerName + "," + hnct + "]='' (empty)");
        }
    }

    resp.setHeader("Location", reqURI);
    resp.setStatus(HttpServletResponse.SC_OK);

    if (req.getContentLength() > 0 && !(method.equals("HEAD") || method.equals("DELETE"))) {
        String body = FileCopyUtils.copyToString(req.getReader());
        logger.debug(this.getClass().getName() + ":  body>>\n" + body + "\nbody<<");
        FileCopyUtils.copy(body, resp.getWriter());
        resp.flushBuffer();
        resp.setContentLength(req.getContentLength());
    } else {
        logger.debug(this.getClass().getName() + ":  body is empty");
        resp.setContentLength(0);
    }

}