Example usage for javax.servlet.http HttpServletRequest getInputStream

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

Introduction

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

Prototype

public ServletInputStream getInputStream() throws IOException;

Source Link

Document

Retrieves the body of the request as binary data using a ServletInputStream .

Usage

From source file:be.milieuinfo.core.proxy.controller.ProxyServlet.java

@SuppressWarnings("deprecation")
@Override/*from   w  w w .  j  a v  a2  s .co  m*/
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    // Make the Request
    //note: we won't transfer the protocol version because I'm not sure it would truly be compatible
    String method = servletRequest.getMethod();
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);
    HttpRequest proxyRequest;
    //spec: RFC 2616, sec 4.3: either these two headers signal that there is a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        // Add the input entity (streamed)
        //  note: we don't bother ensuring we close the servletInputStream since the container handles it
        eProxyRequest.setEntity(
                new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        proxyRequest = eProxyRequest;
    } else
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);

    copyRequestHeaders(servletRequest, proxyRequest);

    try {
        // Execute the request
        if (doLog) {
            log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }
        HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest);

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            //just to be sure, but is probably a no-op
            EntityUtils.consume(proxyResponse.getEntity());
            return;
        }

        // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the
        //  reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletResponse);

        // Send the content to the client
        copyResponseEntity(proxyResponse, servletResponse);

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        if (e instanceof ServletException)
            throw (ServletException) e;
        if (e instanceof IOException)
            throw (IOException) e;
        throw new RuntimeException(e);
    }
}

From source file:com.grameenfoundation.ictc.controllers.SaleforceIntegrationController.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  ww  w  .  j  av  a  2 s  . co  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Logger log = Logger.getLogger(SaleforceIntegrationController.class.getName());
    response.setContentType("text/xml;charset=UTF-8");
    BiodataModel biodataModel = new BiodataModel();
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        String theString = IOUtils.toString(request.getInputStream(), "UTF-8");
        System.out.println("Salesforce data/n " + theString);
        //gets request input stream
        InputStream in = request.getInputStream();
        InputSource input = null;
        Transaction tx;
        tx = ICTCDBUtil.getInstance().getGraphDB().beginTx();
        org.neo4j.graphdb.Node FarmerParent;

        try {

            System.out.println(" " + request.getContentType());

            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(theString));
            System.out.println("After parsing XML");
            Document doc = db.parse(is);
            System.out.println("Should be normalised now");
            doc.getDocumentElement().normalize();

            Element ele = doc.getDocumentElement();
            //System.out.println("Root element :" + doc.getDocumentElement());
            Node node = doc.getDocumentElement();

            System.out.println("Root element " + doc.getDocumentElement());

            //get fields from objects
            NodeList sObject = doc.getElementsByTagName("sObject");

            for (int j = 0; j < sObject.getLength(); j++) {

                Node rowNode = sObject.item(j);
                //  Map<String,String> m = (Map<String,String>) rowNode.getAttributes();
                String salesforceObj = rowNode.getAttributes().getNamedItem("xsi:type").getNodeValue();
                System.out.println(salesforceObj);

                if (salesforceObj.equalsIgnoreCase("sf:Farmer_Biodata__c")) {
                    org.neo4j.graphdb.Node biodataNode = ICTCDBUtil.getInstance().getGraphDB()
                            .createNode(Labels.FARMER);
                    for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) {

                        // System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent());
                        if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) {
                            System.out.println(
                                    "id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()));
                            biodataNode.setProperty(
                                    getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()),
                                    rowNode.getChildNodes().item(k).getTextContent());
                        }

                        if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")
                                && !rowNode.getChildNodes().item(k).getNodeName().equals("#text")) {

                            System.out
                                    .println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()));
                            biodataNode.setProperty(
                                    getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()),
                                    rowNode.getChildNodes().item(k).getTextContent());

                        }
                    }

                    FarmerParent = ParentNode.FarmerParentNode();
                    FarmerParent.createRelationshipTo(biodataNode, ICTCRelationshipTypes.FARMER);

                    log.log(Level.INFO, "new node created {0}", biodataNode.getId());
                    tx.success();

                    out.println(sendAck());
                } else if (salesforceObj.equals("sf:Harvest__c")) {
                    org.neo4j.graphdb.Node HarvestParent;
                    org.neo4j.graphdb.Node harvestNode = ICTCDBUtil.getInstance().getGraphDB()
                            .createNode(Labels.HARVEST);

                    String farmerID = getXmlNodeValue("sf:Farmer_Biodata__c", ele);
                    System.out.println("farmerid " + farmerID);
                    for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) {

                        //System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent());
                        if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) {
                            System.out.println(
                                    "id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()));
                            harvestNode.setProperty(
                                    getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()),
                                    rowNode.getChildNodes().item(k).getTextContent());
                        }

                        if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")
                                && !rowNode.getChildNodes().item(k).getNodeName().equals("#text") && !rowNode
                                        .getChildNodes().item(k).getNodeName().equals("sf:Farmer_Biodata__c")) {

                            System.out
                                    .println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()));
                            harvestNode.setProperty(
                                    getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()),
                                    rowNode.getChildNodes().item(k).getTextContent());

                        }
                    }

                    HarvestParent = ParentNode.HarvestParentNode();
                    HarvestParent.createRelationshipTo(harvestNode, ICTCRelationshipTypes.HARVEST);

                    log.log(Level.INFO, "new node created {0}", harvestNode.getId());

                    Biodata b = biodataModel.getBiodata("Id", farmerID);

                    biodataModel.BiodataToHarvest(b.getId(), harvestNode);

                    tx.success();

                    out.println(sendAck());
                } else if (salesforceObj.equals("sf:FarmManagement__c")) {
                    org.neo4j.graphdb.Node FarmManagementParent;
                    org.neo4j.graphdb.Node FarmManagementNode = ICTCDBUtil.getInstance().getGraphDB()
                            .createNode(Labels.FARM_MANAGEMENT);

                    String farmerID = getXmlNodeValue("sf:Farmer_Biodata__c", ele);
                    System.out.println("farmerid " + farmerID);
                    for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) {

                        //System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent());
                        if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) {
                            System.out.println(
                                    "id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()));
                            FarmManagementNode.setProperty(
                                    getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()),
                                    rowNode.getChildNodes().item(k).getTextContent());
                        }

                        if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")
                                && !rowNode.getChildNodes().item(k).getNodeName().equals("#text") && !rowNode
                                        .getChildNodes().item(k).getNodeName().equals("sf:Farmer_Biodata__c")) {

                            System.out
                                    .println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()));
                            FarmManagementNode.setProperty(
                                    getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()),
                                    rowNode.getChildNodes().item(k).getTextContent());

                        }
                    }

                    FarmManagementParent = ParentNode.FMParentNode();
                    FarmManagementParent.createRelationshipTo(FarmManagementNode,
                            ICTCRelationshipTypes.FARM_MANAGEMENT);

                    log.log(Level.INFO, "new node created {0}", FarmManagementNode.getId());

                    Biodata b = biodataModel.getBiodata("Id", farmerID);

                    biodataModel.BiodataToFarmManagement(b.getId(), FarmManagementNode);

                    tx.success();

                    out.println(sendAck());
                } else if (salesforceObj.equals("sf:FarmOperations__c")) {
                    org.neo4j.graphdb.Node FarmOperationParent;
                    org.neo4j.graphdb.Node FarmOperationNode = ICTCDBUtil.getInstance().getGraphDB()
                            .createNode(Labels.FARM_OPERATION);

                    String farmerID = getXmlNodeValue("sf:Farmer_Biodata__c", ele);
                    System.out.println("farmerid " + farmerID);
                    for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) {

                        //System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent());
                        if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) {
                            System.out.println(
                                    "id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()));
                            FarmOperationNode.setProperty(
                                    getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()),
                                    rowNode.getChildNodes().item(k).getTextContent());
                        }

                        if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")
                                && !rowNode.getChildNodes().item(k).getNodeName().equals("#text") && !rowNode
                                        .getChildNodes().item(k).getNodeName().equals("sf:Farmer_Biodata__c")) {

                            System.out
                                    .println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()));
                            FarmOperationNode.setProperty(
                                    getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()),
                                    rowNode.getChildNodes().item(k).getTextContent());

                        }
                    }

                    FarmOperationParent = ParentNode.OperationsParentNode();
                    FarmOperationParent.createRelationshipTo(FarmOperationNode,
                            ICTCRelationshipTypes.FARM_OPERATION);

                    log.log(Level.INFO, "new node created {0}", FarmOperationNode.getId());

                    Biodata b = biodataModel.getBiodata("Id", farmerID);

                    biodataModel.BiodataToOperations(b.getId(), FarmOperationNode);

                    tx.success();

                    out.println(sendAck());
                } else if (salesforceObj.equals("sf:Marketing__c")) {
                    org.neo4j.graphdb.Node MarketingParent;
                    org.neo4j.graphdb.Node MarketingNode = ICTCDBUtil.getInstance().getGraphDB()
                            .createNode(Labels.MARKETING);

                    String farmerID = getXmlNodeValue("sf:Farmer_Biodata__c", ele);
                    System.out.println("farmerid " + farmerID);
                    for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) {

                        //System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent());
                        if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) {
                            System.out.println(
                                    "id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()));
                            MarketingNode.setProperty(
                                    getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()),
                                    rowNode.getChildNodes().item(k).getTextContent());
                        }

                        if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")
                                && !rowNode.getChildNodes().item(k).getNodeName().equals("#text") && !rowNode
                                        .getChildNodes().item(k).getNodeName().equals("sf:Farmer_Biodata__c")) {

                            System.out
                                    .println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()));
                            MarketingNode.setProperty(
                                    getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()),
                                    rowNode.getChildNodes().item(k).getTextContent());

                        }
                    }

                    MarketingParent = ParentNode.MarketingParentNode();
                    MarketingParent.createRelationshipTo(MarketingNode, ICTCRelationshipTypes.MARKETING);

                    log.log(Level.INFO, "new node created {0}", MarketingNode.getId());

                    Biodata b = biodataModel.getBiodata("Id", farmerID);

                    biodataModel.BiodataToMarketing(b.getId(), MarketingNode);

                    tx.success();

                    out.println(sendAck());
                } else if (salesforceObj.equals("sf:PostHarvest__c")) {
                    org.neo4j.graphdb.Node PostHarvestParent;
                    org.neo4j.graphdb.Node PostHarvestNode = ICTCDBUtil.getInstance().getGraphDB()
                            .createNode(Labels.POSTHARVEST);

                    String farmerID = getXmlNodeValue("sf:Farmer_Biodata__c", ele);
                    System.out.println("farmerid " + farmerID);
                    for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) {

                        // System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent());
                        if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) {
                            System.out.println(
                                    "id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()));
                            PostHarvestNode.setProperty(
                                    getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()),
                                    rowNode.getChildNodes().item(k).getTextContent());
                        }

                        if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")
                                && !rowNode.getChildNodes().item(k).getNodeName().equals("#text") && !rowNode
                                        .getChildNodes().item(k).getNodeName().equals("sf:Farmer_Biodata__c")) {

                            System.out
                                    .println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()));
                            PostHarvestNode.setProperty(
                                    getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()),
                                    rowNode.getChildNodes().item(k).getTextContent());

                        }
                    }

                    PostHarvestParent = ParentNode.PostHarvestParentNode();
                    PostHarvestParent.createRelationshipTo(PostHarvestNode, ICTCRelationshipTypes.POST_HARVEST);

                    log.log(Level.INFO, "new node created {0}", PostHarvestNode.getId());

                    Biodata b = biodataModel.getBiodata("Id", farmerID);

                    biodataModel.BiodataToPostHarvest(b.getId(), PostHarvestNode);

                    tx.success();

                    out.println(sendAck());
                } else if (salesforceObj.equals("sf:Storage__c")) {
                    org.neo4j.graphdb.Node StorageParent;
                    org.neo4j.graphdb.Node StorageNode = ICTCDBUtil.getInstance().getGraphDB()
                            .createNode(Labels.STORAGE);

                    String farmerID = getXmlNodeValue("sf:Farmer_Biodata__c", ele);
                    System.out.println("farmerid " + farmerID);
                    for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) {

                        System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": "
                                + rowNode.getChildNodes().item(k).getTextContent());
                        if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) {
                            System.out.println(
                                    "id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()));
                            StorageNode.setProperty(
                                    getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()),
                                    rowNode.getChildNodes().item(k).getTextContent());
                        }

                        if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")
                                && !rowNode.getChildNodes().item(k).getNodeName().equals("#text") && !rowNode
                                        .getChildNodes().item(k).getNodeName().equals("sf:Farmer_Biodata__c")) {

                            System.out
                                    .println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()));
                            StorageNode.setProperty(
                                    getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()),
                                    rowNode.getChildNodes().item(k).getTextContent());

                        }
                    }

                    StorageParent = ParentNode.StorageParentNode();
                    StorageParent.createRelationshipTo(StorageNode, ICTCRelationshipTypes.STORAGE);

                    log.log(Level.INFO, "new node created {0}", StorageNode.getId());

                    Biodata b = biodataModel.getBiodata("Id", farmerID);

                    biodataModel.BiodataToStorage(b.getId(), StorageNode);

                    tx.success();

                    out.println(sendAck());
                }

                else if (salesforceObj.equals("sf:TechnicalNeeds__c")) {
                    org.neo4j.graphdb.Node TNParent;
                    org.neo4j.graphdb.Node TNNode = ICTCDBUtil.getInstance().getGraphDB()
                            .createNode(Labels.TECHNICAL_NEEDS);

                    String farmerID = getXmlNodeValue("sf:Farmer_Biodata__c", ele);
                    System.out.println("farmerid " + farmerID);
                    for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) {

                        System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": "
                                + rowNode.getChildNodes().item(k).getTextContent());
                        if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) {
                            System.out.println(
                                    "id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()));
                            TNNode.setProperty(getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()),
                                    rowNode.getChildNodes().item(k).getTextContent());
                        }

                        if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")
                                && !rowNode.getChildNodes().item(k).getNodeName().equals("#text") && !rowNode
                                        .getChildNodes().item(k).getNodeName().equals("sf:Farmer_Biodata__c")) {

                            System.out
                                    .println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()));
                            TNNode.setProperty(
                                    getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()),
                                    rowNode.getChildNodes().item(k).getTextContent());

                        }
                    }

                    TNParent = ParentNode.TechNeedParentNode();
                    TNParent.createRelationshipTo(TNNode, ICTCRelationshipTypes.TECHNICAL_NEED);

                    log.log(Level.INFO, "new node created {0}", TNNode.getId());

                    Biodata b = biodataModel.getBiodata("Id", farmerID);

                    biodataModel.BiodataToTechNeeds(b.getId(), TNNode);

                    tx.success();

                    out.println(sendAck());
                }

            }

        } catch (Exception ex) {
            Logger.getLogger(SaleforceIntegrationController.class.getName()).log(Level.SEVERE, null, ex);
            tx.failure();
        } finally {
            tx.finish();
        }

    }
}

From source file:com.funambol.transport.http.server.Sync4jServlet.java

/**
 * Returns the content of HTTP request./* w  w  w  .ja  v a  2s  . c o m*/
 * Uncompresses the request if the Content-Encoding is gzip or deflate.
 * Updates the Content-Length with the length of the uncompressed request.
 *
 * @param httpRequest the HttpServletRequest
 * @param contentEncoding the content encoding
 * @param requestTime the time in which the request is arrived to servlet
 * @param sessionId the session identifier
 *
 * @return requestData the uncompressed request content
 * @throws java.io.IOException if an error occurs
 */
private byte[] getRequestContent(HttpServletRequest httpRequest, String contentEncoding, long requestTime,
        String sessionId) throws IOException {

    byte[] requestData = null;
    InputStream in = null;

    try {

        in = httpRequest.getInputStream();

        int contentLength = httpRequest.getContentLength();
        if (contentLength <= 0) {
            contentLength = SIZE_INPUT_BUFFER;
        }

        if (logMessages) {
            //
            // Read the compressed request data to log it
            //
            requestData = IOTools.readContent(in, contentLength);
            logRequest(httpRequest, requestData, requestTime, sessionId);

            //
            // Create a new InputStream to pass at the decompressor
            //
            in = new ByteArrayInputStream(requestData);
        }

        if (contentEncoding != null) {
            if (contentEncoding.equals(COMPRESSION_TYPE_GZIP)) {

                if (log.isTraceEnabled()) {
                    log.trace("Reading the request using: " + COMPRESSION_TYPE_GZIP);
                }
                in = new GZIPInputStream(in);

            } else if (contentEncoding.equals(COMPRESSION_TYPE_DEFLATE)) {

                if (log.isTraceEnabled()) {
                    log.trace("Reading the request using: " + COMPRESSION_TYPE_DEFLATE);
                }
                in = new InflaterInputStream(in);
            }

            String uncompressedContentLength = httpRequest.getHeader("Uncompressed-Content-Length");

            if (uncompressedContentLength != null) {
                contentLength = Integer.parseInt(uncompressedContentLength);
            } else {
                contentLength = SIZE_INPUT_BUFFER;
            }

        }

        if (!logMessages || contentEncoding != null) {
            requestData = IOTools.readContent(in, contentLength);
        }

    } finally {
        if (in != null) {
            in.close();
        }
    }

    return requestData;
}

From source file:org.ocpsoft.rewrite.servlet.config.proxy.ProxyServlet.java

protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    /*/*from  w w w . ja  v  a 2 s .  co  m*/
     * Note: we won't transfer the protocol version because I'm not sure it would truly be compatible
     */
    String method = servletRequest.getMethod();
    HttpRequest proxyRequest;
    /*
     * Spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
     */
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, targetUri);
        /*
         * Add the input entity (streamed) note: we don't bother ensuring we close the servletInputStream since the
         * container handles it
         */
        eProxyRequest.setEntity(
                new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        proxyRequest = eProxyRequest;
    } else
        proxyRequest = new BasicHttpRequest(method, targetUri);

    copyRequestHeaders(servletRequest, proxyRequest);

    try {
        /*
         * Execute the request
         */
        if (doLog) {
            logger.debug("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }
        HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUriObj), proxyRequest);

        /*
         * Process the response
         */
        int statusCode = proxyResponse.getStatusLine().getStatusCode();

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            /*
             * just to be sure, but is probably a no-op
             */
            EntityUtils.consume(proxyResponse.getEntity());
            return;
        }

        /*
         * Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the
         * reason along too. noinspection deprecation
         */
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletResponse);

        /*
         * Send the content to the client
         */
        copyResponseEntity(proxyResponse, servletResponse);

    } catch (Exception e) {
        /*
         * abort request, according to best practice with HttpClient
         */
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        if (e instanceof ServletException)
            throw (ServletException) e;
        // noinspection ConstantConditions
        if (e instanceof IOException)
            throw (IOException) e;
        throw new RuntimeException(e);
    }
}

From source file:uk.co.bubobubo.web.HttpClientProxy.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    // Make the Request
    //note: we won't transfer the protocol version because I'm not sure it would truly be compatible
    String method = servletRequest.getMethod();
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);
    HttpRequest proxyRequest;//w w w. java2  s.co  m
    //spec: RFC 2616, sec 4.3: either these two headers signal that there is a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        // Add the input entity (streamed)
        //  note: we don't bother ensuring we close the servletInputStream since the container handles it
        eProxyRequest.setEntity(
                new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        proxyRequest = eProxyRequest;
    } else
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);

    copyRequestHeaders(servletRequest, proxyRequest);

    try {
        // Execute the request
        if (doLog) {
            log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }

        proxyRequest.removeHeaders("authorization");
        if (targetUri.getUserInfo() != null && !targetUri.getUserInfo().equalsIgnoreCase("")
                && !targetUri.getUserInfo().equalsIgnoreCase(":")) {
            Credentials credentials = new UsernamePasswordCredentials(targetUri.getUserInfo().split(":")[0],
                    targetUri.getUserInfo().split(":")[1]);
            proxyClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
        }

        HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest);

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            //just to be sure, but is probably a no-op
            EntityUtils.consume(proxyResponse.getEntity());
            return;
        }

        // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the
        //  reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletResponse);

        // Send the content to the client
        copyResponseEntity(proxyResponse, servletResponse);

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        if (e instanceof ServletException)
            throw (ServletException) e;
        if (e instanceof IOException)
            throw (IOException) e;
        throw new RuntimeException(e);
    }
}

From source file:com.chaosinmotion.securechat.server.MessageServlet.java

/**
 * Handle POST commands. This uses the cookie mechanism for Java
 * servlets to track users for security reasons, and handles the
 * commands for getting a token, for verifying server status, and for
 * logging in and changing a password./*from  w w  w .  j  a  va 2s  .  com*/
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ReturnResult retVal = null;

    /*
     * Step 1: determine the path element after the api/1/ URL. This
     * determines the command
     */

    String path = req.getPathInfo();
    if (path == null) {
        resp.sendError(404);
        return;
    }
    if (path.startsWith("/"))
        path = path.substring(1);

    try {
        /*
         * All commands require authentication. This determines if we have
         * it or not.
         */
        HttpSession session = req.getSession();
        Login.UserInfo userinfo = (Login.UserInfo) session.getAttribute("userinfo");
        if (userinfo == null) {
            retVal = new ReturnResult(Errors.ERROR_UNAUTHORIZED, "Not authorized");
        } else {

            if (path.equalsIgnoreCase("sendmessages")) {
                /*
                 * Process the send messages request. This takes an array
                 * of device IDs and messages. The assumption is that each
                 * messages.
                 */

                JSONTokener tokener = new JSONTokener(req.getInputStream());
                JSONObject requestParams = new JSONObject(tokener);
                retVal = SendMessages.processRequest(userinfo, requestParams);

            } else if (path.equalsIgnoreCase("getmessages")) {
                /*
                 * Process the get messages request. This gets the messages
                 * associated with the device provided, so long as it is
                 * tied to the username that we've logged into. This will
                 * pull the data and delete the messages from the back
                 * end as they are pulled.
                 */

                JSONTokener tokener = new JSONTokener(req.getInputStream());
                JSONObject requestParams = new JSONObject(tokener);
                retVal = GetMessages.processRequest(userinfo, requestParams);

            } else if (path.equalsIgnoreCase("dropmessages")) {
                /*
                 * Process the get messages request. This gets the messages
                 * associated with the device provided, so long as it is
                 * tied to the username that we've logged into. This will
                 * pull the data and delete the messages from the back
                 * end as they are pulled.
                 */

                JSONTokener tokener = new JSONTokener(req.getInputStream());
                JSONObject requestParams = new JSONObject(tokener);
                DropMessages.processRequest(userinfo, requestParams);
                retVal = new ReturnResult();

            } else if (path.equalsIgnoreCase("notifications")) {
                /*
                 * Process notification endpoint; this returns the
                 * port of the network connection endpoint the user
                 * can use for immediate notifications. This may also
                 * return failure if we were unable to open a port
                 * to receive connections.
                 */

                NotificationService n = NotificationService.getShared();
                if (n.isRunning()) {
                    SimpleReturnResult r = new SimpleReturnResult();
                    r.put("port", n.getServerPort());
                    r.put("host", n.getServerAddress());
                    r.put("ssl", n.getSSLFlag());
                    retVal = r;
                } else {
                    retVal = new ReturnResult(Errors.ERROR_NOTIFICATION, "No notification service");
                }
            }
        }
    } catch (Throwable th) {
        retVal = new ReturnResult(th);
    }

    /*
     * If we get here and we still haven't initialized return value,
     * set to a 404 error. We assume this reaches here with a null
     * value because the path doesn't exist.
     */

    if (retVal == null) {
        resp.sendError(404);

    } else {
        /*
         * We now have a return result. Formulate the response
         */

        ServletOutputStream stream = resp.getOutputStream();
        resp.setContentType("application/json");
        stream.print(retVal.toString());
    }
}

From source file:snoopware.api.ProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    // Make the Request
    //note: we won't transfer the protocol version because I'm not sure it would truly be compatible
    String method = servletRequest.getMethod();
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);
    HttpRequest proxyRequest;/*from w  w  w .j a  va  2s  .com*/
    //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        // Add the input entity (streamed)
        //  note: we don't bother ensuring we close the servletInputStream since the container handles it
        eProxyRequest.setEntity(
                new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        proxyRequest = eProxyRequest;
    } else {
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }

    copyRequestHeaders(servletRequest, proxyRequest);

    try {
        // Execute the request
        if (doLog) {
            log("proxy " + method + " uri: " + servletRequest.getRequestURL().toString() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }
        HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest);

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            //just to be sure, but is probably a no-op
            EntityUtils.consume(proxyResponse.getEntity());
            return;
        }

        // Pass the response code. This method with the "reason phrase" is deprecated but 
        // it's the only way to pass the
        //  reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletResponse);

        // Send the content to the client
        copyResponseEntity(proxyResponse, servletResponse);

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        if (e instanceof ServletException) {
            throw (ServletException) e;
        }
        //noinspection ConstantConditions
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.userstorage.tests.util.USSServer.java

protected void updateBlob(HttpServletRequest request, HttpServletResponse response, File blobFile,
        File etagFile, boolean exists) throws IOException {
    String ifMatch = getETag(request, "If-Match");

    if (exists) {
        String etag = IOUtil.readUTF(etagFile);

        if (StringUtil.isEmpty(ifMatch) || !ifMatch.equals(etag)) {
            response.setHeader("ETag", "\"" + etag + "\"");
            response.sendError(HttpServletResponse.SC_CONFLICT);
            return;
        }/*w w  w  . j a  v a 2  s  .c o  m*/
    }

    String etag = UUID.randomUUID().toString();

    IOUtil.mkdirs(blobFile.getParentFile());
    FileOutputStream out = new FileOutputStream(blobFile);
    InputStream body = null;

    try {
        Map<String, Object> requestObject = JSONUtil.parse(request.getInputStream(), "value");
        body = (InputStream) requestObject.get("value");

        IOUtil.copy(body, out);
    } finally {
        IOUtil.closeSilent(body);
        IOUtil.close(out);
    }

    IOUtil.writeUTF(etagFile, etag);

    response.setStatus(exists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_CREATED);
    response.setHeader("ETag", "\"" + etag + "\"");
}

From source file:com.codeabovelab.dm.gateway.proxy.common.HttpProxy.java

private HttpEntity createEntity(HttpServletRequest servletRequest) throws IOException {
    final String contentType = servletRequest.getContentType();
    // body with 'application/x-www-form-urlencoded' is handled by tomcat therefore we cannot
    // obtain it through input stream and need some workaround
    if (ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType)) {
        List<NameValuePair> entries = new ArrayList<>();
        // obviously that we also copy params from url, but we cannot differentiate its
        Enumeration<String> names = servletRequest.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            entries.add(new BasicNameValuePair(name, servletRequest.getParameter(name)));
        }//w ww  . ja  v a  2  s .co  m
        return new UrlEncodedFormEntity(entries, servletRequest.getCharacterEncoding());
    }

    // Add the input entity (streamed)
    //  note: we don't bother ensuring we close the servletInputStream since the container handles it
    return new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength(),
            ContentType.create(contentType));
}

From source file:com.cloud.bridge.service.controller.s3.S3BucketAction.java

private void executeMultiObjectDelete(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    int contentLength = request.getContentLength();
    StringBuffer xmlDeleteResponse = null;
    boolean quite = true;

    if (contentLength > 0) {
        InputStream is = null;//from  w w  w  .j  a v  a 2  s.c  o  m
        String versionID = null;
        try {
            is = request.getInputStream();
            String xml = StringHelper.stringFromStream(is);
            String elements[] = { "Key", "VersionId" };
            Document doc = XmlHelper.parse(xml);
            Node node = XmlHelper.getRootNode(doc);

            if (node == null) {
                System.out.println("Invalid XML document, no root element");
                return;
            }

            xmlDeleteResponse = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                    + "<DeleteResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">");

            String bucket = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);

            S3DeleteObjectRequest engineRequest = new S3DeleteObjectRequest();
            engineRequest.setBucketName(bucket);
            is.close();

            doc.getDocumentElement().normalize();
            NodeList qList = doc.getElementsByTagName("Quiet");

            if (qList.getLength() == 1) {
                Node qNode = qList.item(0);
                if (qNode.getFirstChild().getNodeValue().equalsIgnoreCase("true") == false)
                    quite = false;

                logger.debug("Quite value  :" + qNode.getFirstChild().getNodeValue());
            }

            NodeList objList = doc.getElementsByTagName("Object");

            for (int i = 0; i < objList.getLength(); i++) {

                Node key = objList.item(i);
                NodeList key_data = key.getChildNodes();

                if (key.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) key;
                    String key_name = getTagValue(elements[0], eElement);
                    engineRequest.setBucketName(bucket);
                    engineRequest.setKey(key_name);

                    if (key_data.getLength() == 2) {
                        versionID = getTagValue(elements[1], eElement);
                        engineRequest.setVersion(versionID);
                    }

                    S3Response engineResponse = ServiceProvider.getInstance().getS3Engine()
                            .handleRequest(engineRequest);
                    int resultCode = engineResponse.getResultCode();
                    String resutlDesc = engineResponse.getResultDescription();
                    if (resultCode == 204) {
                        if (quite) { // show response depending on quite/verbose
                            xmlDeleteResponse.append("<Deleted><Key>" + key_name + "</Key>");
                            if (resutlDesc != null)
                                xmlDeleteResponse.append(resutlDesc);
                            xmlDeleteResponse.append("</Deleted>");
                        }
                    } else {
                        logger.debug("Error in delete ::" + key_name + " eng response:: "
                                + engineResponse.getResultDescription());
                        xmlDeleteResponse.append("<Error><Key>" + key_name + "</Key>");
                        if (resutlDesc != null)
                            xmlDeleteResponse.append(resutlDesc);
                        xmlDeleteResponse.append("</Error>");
                    }

                }
            }

            String version = engineRequest.getVersion();
            if (null != version)
                response.addHeader("x-amz-version-id", version);

        } catch (IOException e) {
            logger.error("Unable to read request data due to " + e.getMessage(), e);
            throw new NetworkIOException(e);

        } finally {
            if (is != null)
                is.close();
        }

        xmlDeleteResponse.append("</DeleteResult>");

    }
    response.setStatus(200);
    response.setContentType("text/xml; charset=UTF-8");
    S3RestServlet.endResponse(response, xmlDeleteResponse.toString());

}