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.BRF2011PublicityChair.java

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

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

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {//  w  w w  .  j  a  v  a  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);
    }
    try {
        System.out.println("Publicty 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);

        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);
        System.out.println("11111111111111111111111111111");

        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);
        System.out.println("33333333333333333333333");
        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();

        }
        System.out.println("222222222222222222222222222222222");
        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);
        System.out.println("444444444444444444444444444444444444");
        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++;
            }
            System.out.println("55555555555555555555555555555");
            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("6666666666666666666666666666");
        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.osaf.cosmo.mc.MorseCodeServlet.java

/**
 * Handles update requests./*  w  ww.  ja  va 2s  . c  o  m*/
 */
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (log.isDebugEnabled())
        log.debug("handling POST for " + req.getPathInfo());

    CollectionPath cp = CollectionPath.parse(req.getPathInfo());
    if (cp != null) {
        String tokenStr = req.getHeader(HEADER_SYNC_TOKEN);
        if (StringUtils.isBlank(tokenStr)) {
            String msg = "Missing sync token";
            handleGeneralException(new BadRequestException(msg), resp);
            return;
        }

        if (!checkWritePreconditions(req, resp))
            return;

        EimmlStreamReader reader = null;
        try {
            SyncToken token = SyncToken.deserialize(tokenStr);

            reader = new EimmlStreamReader(req.getReader());
            if (!reader.getCollectionUuid().equals(cp.getUid())) {
                String msg = "EIMML collection uid " + reader.getCollectionUuid()
                        + " does not match target collection uid " + cp.getUid();
                handleGeneralException(new BadRequestException(msg), resp);
                return;
            }

            EimmlStreamReaderIterator i = new EimmlStreamReaderIterator(reader);
            PubRecords records = new PubRecords(i, reader.getCollectionName(), reader.getCollectionHue());

            PubCollection pubCollection = controller.updateCollection(cp.getUid(), token, records);

            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
            resp.addHeader(HEADER_SYNC_TOKEN, pubCollection.getToken().serialize());
            return;
        } catch (CosmoSecurityException e) {
            if (e instanceof ItemSecurityException) {
                InsufficientPrivilegesException ipe = new InsufficientPrivilegesException(
                        (ItemSecurityException) e);
                handleGeneralException(ipe, resp);
            } else {
                resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
            }
            return;
        } catch (EimmlStreamException e) {
            Throwable cause = e.getCause();
            String msg = "Unable to read EIM stream: " + e.getMessage();
            msg += cause != null ? ": " + cause.getMessage() : "";
            handleGeneralException(new BadRequestException(msg, e), resp);
            return;
        } catch (CollectionLockedException e) {
            resp.sendError(SC_LOCKED, "Collection is locked for update");
            return;
        } catch (StaleCollectionException e) {
            resp.sendError(HttpServletResponse.SC_RESET_CONTENT,
                    "Collection contains more recently updated items");
            return;
        } catch (MorseCodeException e) {
            Throwable root = e.getCause();
            if (root != null && root instanceof EimmlStreamException) {
                String msg = "Unable to read EIM stream: " + root.getMessage();
                handleGeneralException(new BadRequestException(msg, e), resp);
                return;
            }
            if (root != null && root instanceof EimSchemaException) {
                String msg = "Unable to process EIM records: " + root.getMessage();
                handleGeneralException(new BadRequestException(msg, e), resp);
                return;
            }

            handleGeneralException(e, resp);
            return;
        } catch (RuntimeException e) {
            handleGeneralException(new MorseCodeException(e), resp);
            return;
        } finally {
            if (reader != null)
                reader.close();
        }
    }
    resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}

From source file:pa_SymposiumPlanner.RuleML2012TGAgent.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from   ww  w .j  a  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("TG Agent 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:pa_SymposiumPlanner.BRF2011LiaisonChair.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {//  www. j a  va 2  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("Liaison 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:pa_SymposiumPlanner.RuleML2010ProgramChair.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {//  w w  w  .  j  ava2  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("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:pa_SymposiumPlanner.BRF2011PanelChair.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("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:servlets.User_servlets.java

private void user_sign_in_handler(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from www  . ja v a2s .c om
        DAO dao_instance = null;
        User user = null;
        try {
            /**
             * *******************************************************
             * STEP 1 Check if the user exists in the DB. IF ERROR -->
             * throws MySQL exception, GO TO STEP 2b throws
             * NoSuchAlgorithmException, GO TO STEP 2b ELSE --> GO TO STEP 2
             * *******************************************************
             */
            JsonParser parser = new JsonParser();
            JsonObject requestData = (JsonObject) parser.parse(request.getReader());

            String email = requestData.get("email").getAsString();
            String password = requestData.get("password").getAsString();
            password = SHA1.getHash(password);

            boolean isEmail = true;
            boolean last_experiment = true;
            Object[] params = { password, last_experiment, isEmail };
            dao_instance = DAOProvider.getDAOByName("User");

            user = (User) ((User_JDBCDAO) dao_instance).findByID(email, params);
            /**
             * *******************************************************
             * STEP 2 Check if user exists. IF NOT --> throws Exception, GO
             * TO STEP 2b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            if (user == null) {
                throw new AccessControlException("User not found. Please check the username and password.");
            }

            user.setSessionToken(UserSessionManager.getUserSessionManager().registerNewUser(email));

        } catch (Exception e) {
            ServerErrorManager.handleException(e, User_servlets.class.getName(), "userLoginPostHandler",
                    e.getMessage());
        } finally {
            /**
             * *******************************************************
             * STEP 3b CATCH ERROR. GO TO STEP 4
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());
            } else {
                /**
                 * *******************************************************
                 * STEP 3A WRITE RESPONSE ERROR. GO TO STEP 4
                 * *******************************************************
                 */
                response.setStatus(200);
                response.getWriter().print(user.toJSON());
            }
            /**
             * *******************************************************
             * STEP 4 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(), "userLoginPostHandler",
                e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}

From source file:de.tu_dortmund.ub.hb_ng.middleware.MiddlewareHbNgEndpoint.java

protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    // CORS ORIGIN RESPONSE HEADER
    httpServletResponse.setHeader("Access-Control-Allow-Origin",
            config.getProperty(HBNGStatics.CORS_ACCESS_CONTROL_ALLOW_ORIGIN_IDENTIFIER));

    String authorization = "";
    String contenttype = "";

    Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {

        String headerNameKey = headerNames.nextElement();
        this.logger.debug("headerNameKey = " + headerNameKey + " / headerNameValue = "
                + httpServletRequest.getHeader(headerNameKey));

        if (headerNameKey.equals("Authorization")) {
            authorization = httpServletRequest.getHeader(headerNameKey);
        }/*from  w w w.  j  a v  a 2 s  .co  m*/
        if (headerNameKey.equals("Content-Type")) {
            contenttype = httpServletRequest.getHeader(headerNameKey);
        }
    }

    this.logger.info("contenttype = " + contenttype);

    try {

        // TODO validate Content-Type

        String data = httpServletRequest.getReader().lines()
                .collect(Collectors.joining(System.lineSeparator()));

        if (data == null || data.equals("")) {

            this.logger.error(HttpServletResponse.SC_NO_CONTENT + " - No Content");
            httpServletResponse.sendError(HttpServletResponse.SC_NO_CONTENT, "No Content");
        } else {

            String postableData = null;

            // TODO bind interface Preprocessing
            if (Lookup.lookupAll(PreprocessingInterface.class).size() > 0) {

                PreprocessingInterface preprocessingInterface = Lookup.lookup(PreprocessingInterface.class);
                // init Authorization Service
                preprocessingInterface.init(this.config);

                postableData = preprocessingInterface.process(data);
            } else {

                // TODO correct error handling
                this.logger.error("[" + this.config.getProperty("service.name") + "] "
                        + HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": "
                        + "Authorization Interface not implemented!");
            }

            if (postableData != null) {

                // TODO if successful then POST as application/sparql-update to LinkedDataPlatform
                String sparql_url = this.config.getProperty("ldp.sparql-endpoint");

                // HTTP Request
                int timeout = Integer.parseInt(this.config.getProperty("ldp.timeout"));

                RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                        .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();

                CloseableHttpClient httpclient = HttpClients.custom()
                        .setDefaultRequestConfig(defaultRequestConfig).build();

                try {

                    HttpPost httpPost = new HttpPost(sparql_url);
                    httpPost.addHeader("Content-Type", "application/sparql-update");
                    httpPost.addHeader("Authorization", this.config.getProperty("ldp.authorization"));
                    httpPost.setEntity(new StringEntity(postableData));

                    CloseableHttpResponse httpResponse = null;

                    long start = System.nanoTime();
                    try {

                        httpResponse = httpclient.execute(httpPost);
                    } catch (ConnectTimeoutException | SocketTimeoutException e) {

                        this.logger.info("[" + this.getClass().getName() + "] " + e.getClass().getName() + ": "
                                + e.getMessage());
                        httpResponse = httpclient.execute(httpPost);
                    }
                    long elapsed = System.nanoTime() - start;
                    this.logger.info("[" + this.getClass().getName() + "] LDP request - "
                            + (elapsed / 1000.0 / 1000.0 / 1000.0) + " s");

                    try {

                        int statusCode = httpResponse.getStatusLine().getStatusCode();
                        HttpEntity httpEntity = httpResponse.getEntity();

                        // TODO
                        httpServletResponse.setStatus(statusCode);
                        httpServletResponse.getWriter().println(httpResponse.getStatusLine().getReasonPhrase());

                        EntityUtils.consume(httpEntity);

                    } finally {
                        httpResponse.close();
                    }
                } finally {

                    httpclient.close();
                }
            }
        }
    } catch (Exception e) {

        this.logger.error("something went wrong", e);
        httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "something went wrong");
    }
}

From source file:pa_SymposiumPlanner.ECAI2012DocSymposiumChair.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//w w  w .j a v  a  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("5 Publicty 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();
}