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:pa_SymposiumPlanner.RuleML2009PanelChair.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from  w  w w  .  j  ava 2  s.c  om*/
        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);
    }

    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
        System.out.println("Panel 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:org.springframework.faces.mvc.annotation.support.AnnotatedMethodInvoker.java

/**
 * Resolve a standard argument type. This method can be overridden by subclasses to extend supported argument types.
 * @param parameterType The paramter type to resolve
 * @param webRequest The web request/*from ww  w  . j ava 2s .co m*/
 * @return The resolved argument (can be <tt>null</tt>) or {@link WebArgumentResolver#UNRESOLVED} if the argument
 * @throws Exception on error
 */
protected Object resolveStandardArgument(Class parameterType, NativeWebRequest webRequest) throws Exception {
    if ((webRequest.getNativeRequest() instanceof HttpServletRequest)
            && (webRequest.getNativeResponse() instanceof HttpServletResponse)) {

        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
        HttpServletResponse response = (HttpServletResponse) webRequest.getNativeResponse();

        if (ServletRequest.class.isAssignableFrom(parameterType)) {
            return request;
        } else if (ServletResponse.class.isAssignableFrom(parameterType)) {
            return response;
        } else if (HttpSession.class.isAssignableFrom(parameterType)) {
            return request.getSession();
        } else if (Principal.class.isAssignableFrom(parameterType)) {
            return request.getUserPrincipal();
        } else if (Locale.class.equals(parameterType)) {
            return RequestContextUtils.getLocale(request);
        } else if (InputStream.class.isAssignableFrom(parameterType)) {
            return request.getInputStream();
        } else if (Reader.class.isAssignableFrom(parameterType)) {
            return request.getReader();
        } else if (OutputStream.class.isAssignableFrom(parameterType)) {
            return response.getOutputStream();
        } else if (Writer.class.isAssignableFrom(parameterType)) {
            return response.getWriter();
        } else if (WebRequest.class.isAssignableFrom(parameterType)) {
            return webRequest;
        }
    }
    return WebArgumentResolver.UNRESOLVED;
}

From source file:pa_SymposiumPlanner.ECAI2012LiaisonChair.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//  ww  w.ja  v a  2  s.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);
    }

    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {

        System.out.println("Liaison Chair Servlet 123");
        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;
        System.out.println("1");
        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");
        }
        System.out.println("2");
        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.BRF2011ProgramChair.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  va2 s .co  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("Programming 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.impala.paga.all.QueryBalance.java

/**
 * // w  ww .  java2  s  .c o  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;
    // These represent parameters received over the network
    String username = "", password = "", receiverqueryurl = "", sourcemsisdn = "";

    String responseobject = "";
    Properties prop = new Properties();
    String hashkey = prop.getProperty("hashkey");
    String principal = prop.getProperty("principal");
    String credentials = prop.getProperty("credentials");

    // 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 = "";

    // 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();
        username = root.getAsJsonObject().get("username").getAsString();
        password = root.getAsJsonObject().get("password").getAsString();
        receiverqueryurl = root.getAsJsonObject().get("receiverqueryurl").getAsString();
        sourcemsisdn = root.getAsJsonObject().get("sourceaccount").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)) {

        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 + hashkey;
    System.out.println("saltedToken:" + saltedToken);
    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();

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

    toPaga.put("referenceNumber", "");

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

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

    //assign the remit url from properties.config
    CLIENT_URL = receiverqueryurl;
    //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);

    //add 

    String success = "S001";

    if (responseCode == 0) {

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

        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", "");
    expected.put("status_code", "");
    expected.put("status_description", "");

    String jsonResult = g.toJson(expected);

    return jsonResult;

}

From source file:org.jitsi.videobridge.rest.HandlerImpl.java

/**
 * Modifies a <tt>Conference</tt> with ID <tt>target</tt> in (the
 * associated) <tt>Videobridge</tt>.
 *
 * @param target the ID of the <tt>Conference</tt> to modify in (the
 * associated) <tt>Videobridge</tt>
 * @param baseRequest the original unwrapped {@link Request} object
 * @param request the request either as the {@code Request} object or a
 * wrapper of that request//  www. j a  v  a  2 s  .  c o  m
 * @param response the response either as the {@code Response} object or a
 * wrapper of that response
 * @throws IOException
 * @throws ServletException
 */
private void doPatchConferenceJSON(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    Videobridge videobridge = getVideobridge();

    if (videobridge == null) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else {
        Conference conference = videobridge.getConference(target, null);

        if (conference == null) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (RESTUtil.isJSONContentType(request.getContentType())) {
            Object requestJSONObject = null;
            int status = 0;

            try {
                requestJSONObject = new JSONParser().parse(request.getReader());
                if ((requestJSONObject == null) || !(requestJSONObject instanceof JSONObject)) {
                    status = HttpServletResponse.SC_BAD_REQUEST;
                }
            } catch (ParseException pe) {
                status = HttpServletResponse.SC_BAD_REQUEST;
            }
            if (status == 0) {
                ColibriConferenceIQ requestConferenceIQ = JSONDeserializer
                        .deserializeConference((JSONObject) requestJSONObject);

                if ((requestConferenceIQ == null) || ((requestConferenceIQ.getID() != null)
                        && !requestConferenceIQ.getID().equals(conference.getID()))) {
                    status = HttpServletResponse.SC_BAD_REQUEST;
                } else {
                    ColibriConferenceIQ responseConferenceIQ = null;

                    try {
                        IQ responseIQ = videobridge.handleColibriConferenceIQ(requestConferenceIQ,
                                Videobridge.OPTION_ALLOW_NO_FOCUS);

                        if (responseIQ instanceof ColibriConferenceIQ) {
                            responseConferenceIQ = (ColibriConferenceIQ) responseIQ;
                        } else {
                            status = getHttpStatusCodeForResultIq(responseIQ);
                        }
                    } catch (Exception e) {
                        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                    }
                    if (status == 0 && responseConferenceIQ != null) {
                        JSONObject responseJSONObject = JSONSerializer
                                .serializeConference(responseConferenceIQ);

                        if (responseJSONObject == null)
                            responseJSONObject = new JSONObject();

                        response.setStatus(HttpServletResponse.SC_OK);
                        responseJSONObject.writeJSONString(response.getWriter());
                    }
                }
            }
            if (status != 0)
                response.setStatus(status);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        }
    }
}

From source file:pa_SymposiumPlanner.ECAI2012IntlRuleChalChair.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from  w  ww.ja va2  s . 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);
    }
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
        System.out.println("5 International Rule Challenge Steering Committee 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());
        System.out.println("TEST");
        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:org.intermine.webservice.server.lists.ListUploadService.java

/**
 * Get the reader for the identifiers uploaded with this request.
 * @param request The request object.//from w  w w  .  j a  va2s  . c  om
 * @return A buffered reader for reading the identifiers.
 */
protected BufferedReader getReader(final HttpServletRequest request) {
    BufferedReader r = null;

    if (ServletFileUpload.isMultipartContent(request)) {
        final ServletFileUpload upload = new ServletFileUpload();
        try {
            final FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                final FileItemStream item = iter.next();
                final String fieldName = item.getFieldName();
                if (!item.isFormField() && "identifiers".equalsIgnoreCase(fieldName)) {
                    final InputStream stream = item.openStream();
                    final InputStreamReader in = new InputStreamReader(stream);
                    r = new BufferedReader(in);
                    break;
                }
            }
        } catch (FileUploadException e) {
            throw new InternalErrorException("Could not read request body", e);
        } catch (IOException e) {
            throw new InternalErrorException(e);
        }
    } else {
        if (!requestIsOfSuitableType()) {
            throw new BadRequestException("Bad content type - " + request.getContentType() + USAGE);
        }
        try {
            r = request.getReader();
        } catch (IOException e) {
            throw new InternalErrorException(e);
        }
    }
    if (r == null) {
        throw new BadRequestException("No identifiers found in request." + USAGE);
    }
    return r;
}

From source file:org.tinymce.spellchecker.TinyMCESpellCheckerServlet.java

/**
 * @param request//  ww  w  .j a  v a 2 s.co  m
 * @return read the request content and return it as String object
 * @throws IOException
 */
private String getRequestBody(HttpServletRequest request) throws IOException, SpellCheckException {
    if (request.getHeader("content-type") == null)
        throw new SpellCheckException("Invalid content-type: not defined (null)");

    StringBuilder sb = new StringBuilder();
    if (request.getHeader("content-type").equals("application/x-www-form-urlencoded")) {
        if (request.getParameter("method") == null)
            throw new SpellCheckException("Invalid method: not defined (null)");
        if (!request.getParameter("method").equals("spellcheck"))
            throw new SpellCheckException("Invalid method: use spellcheck method instead.");
        sb.append("{\"method\": \"spellcheck\", ");
        sb.append("\"params\": { ");
        sb.append("\"lang\": \"" + request.getParameter("lang") + "\", ");
        sb.append("\"words\": [");
        String sep = "";
        for (String word : getWords(request.getParameter("text"))) {
            sb.append(sep + "\"" + word.replaceAll("\\n", "") + "\"");
            sep = ",";
        }
        sb.append("]}}");
    } else if (request.getHeader("content-type").equals("application/json")) {
        String line = request.getReader().readLine();
        while (null != line) {
            sb.append(line);
            line = request.getReader().readLine();
        }
    } else {
        throw new SpellCheckException("Invalid content-type " + request.getHeader("content-type")
                + ". Expected values are 'application/x-www-form-urlencoded' or 'application/json'");
    }
    return sb.toString();
}

From source file:servlets.User_servlets.java

private void update_user_handler(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/* w ww. java  2s.c om*/
        boolean ROLLBACK_NEEDED = false;
        DAO dao_instance = null;

        try {

            /**
             * *******************************************************
             * STEP 1 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP. IF
             * ERROR --> throws exception if not valid session, GO TO STEP
             * 5b ELSE --> GO TO STEP 2
             * *******************************************************
             */
            Map<String, Cookie> cookies = this.getCookies(request);
            JsonParser parser = new JsonParser();
            JsonObject requestData = (JsonObject) parser.parse(request.getReader());

            String loggedUser, loggedUserID = null, sessionToken;
            loggedUser = cookies.get("loggedUser").getValue();
            sessionToken = cookies.get("sessionToken").getValue();
            loggedUserID = cookies.get("loggedUserID").getValue();
            String userID = request.getPathInfo().replaceAll("/", "");

            if (!checkAccessPermissions(loggedUser, sessionToken)) {
                throw new AccessControlException("Your session is invalid. User or session token not allowed.");
            }

            /**
             * *******************************************************
             * STEP 2 PARSE THE JSON DATA AND GET THE NEW OBJECT. IF ERROR
             * --> throws exception if not valid session, GO TO STEP 4b ELSE
             * --> GO TO STEP 3
             * *******************************************************
             */
            String newpass = requestData.get("newpass").getAsString();
            if (newpass != null) {
                newpass = new String(Base64.decodeBase64(newpass));
                newpass = SHA1.getHash(newpass);
            }

            /**
             * *******************************************************
             * STEP 3 UPDATE IN DATABASE. IF ERROR --> throws exception if
             * not valid session, GO TO STEP 4b ELSE --> GO TO STEP 4
             * *******************************************************
             */
            dao_instance = DAOProvider.getDAOByName("User");

            boolean isEmail = true;
            Object[] params = { null, false, isEmail };
            User user = (User) ((User_JDBCDAO) dao_instance).findByID(loggedUser, params);

            if (user == null) {
                throw new Exception("User not valid.");
            }

            if (!userID.equals(user.getUserID()) && !isValidAdminUser(loggedUser)) {
                throw new Exception("User not allowed for this action.");
            }

            user.setPassword(newpass);

            dao_instance.disableAutocommit();
            ROLLBACK_NEEDED = true;
            dao_instance.update(user);

            /**
             * *******************************************************
             * STEP 4 COMMIT CHANGES IN DB. IF ERROR --> throws exception if
             * not valid session, GO TO STEP 4b ELSE --> GO TO STEP 5
             * *******************************************************
             */
            dao_instance.doCommit();

        } catch (Exception e) {
            ServerErrorManager.handleException(e, User_servlets.class.getName(), "updateUserPostHandler",
                    e.getMessage());
        } finally {
            /**
             * *******************************************************
             * STEP 4b CATCH ERROR, CLEAN CHANGES. throws SQLException
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());

                if (ROLLBACK_NEEDED) {
                    dao_instance.doRollback();
                }
            } else {
                JsonObject obj = new JsonObject();
                obj.add("success", new JsonPrimitive(true));
                response.getWriter().print(obj.toString());
            }
            /**
             * *******************************************************
             * STEP 6 Close connection.
             * ********************************************************
             */
            if (dao_instance != null) {
                dao_instance.closeConnection();
            }
        }
        //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE 
    } catch (Exception e) {
        ServerErrorManager.handleException(e, User_servlets.class.getName(), "updateUserPostHandler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}