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:com.github.restdriver.clientdriver.unit.ClientDriverHandlerTest.java

/**
 * with an expectation set, and a request made, the handler checks for a match and returns the match if one is found
 *///w  ww.  j  av  a 2 s  .  com
@Test
public void testExpectedRequest() throws IOException, ServletException {

    Request mockRequest = mock(Request.class);
    HttpServletRequest mockHttpRequest = mock(Request.class);
    HttpServletResponse mockHttpResponse = mock(HttpServletResponse.class);

    ClientDriverRequest realRequest = new ClientDriverRequest("yarr").withMethod(Method.GET).withParam("gooo",
            "gredge");
    ClientDriverResponse realResponse = new ClientDriverResponse("lovely", "fhieow").withStatus(404)
            .withHeader("hhh", "JJJ");

    when(mockHttpRequest.getMethod()).thenReturn("GET");
    when(mockHttpRequest.getReader()).thenReturn(new BufferedReader(new StringReader("")));
    when(mockHttpRequest.getInputStream())
            .thenReturn(new DummyServletInputStream(new ByteArrayInputStream("".getBytes())));
    when(mockRequestMatcher.isMatch((RealRequest) anyObject(), (ClientDriverRequest) anyObject()))
            .thenReturn(true);

    mockHttpResponse.setContentType("fhieow");
    mockHttpResponse.setStatus(404);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    when(mockHttpResponse.getOutputStream()).thenReturn(new DummyServletOutputStream(baos));

    sut.addExpectation(realRequest, realResponse);
    sut.handle("", mockRequest, mockHttpRequest, mockHttpResponse);

    assertThat(new String(baos.toByteArray()), equalTo("lovely"));
}

From source file:csiro.pidsvc.servlet.controller.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *     response)//from  w ww  .  ja  va2 s  .  c  om
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String cmd = request.getParameter("cmd");
    if (cmd == null || cmd.isEmpty())
        return;

    Manager mgr = null;
    try {
        Settings.init(this);
        mgr = new Manager(request);

        _logger.info("Processing \"{}\" command.", cmd);
        if (cmd.equalsIgnoreCase("create_mapping"))
            mgr.createMapping(request.getInputStream(), false);
        else if (cmd.equalsIgnoreCase("delete_mapping"))
            mgr.deleteMapping(request.getParameter("mapping_path"));
        else if (cmd.equalsIgnoreCase("import"))
            response.getWriter().write(mgr.importMappings(request));
        else if (cmd.equalsIgnoreCase("merge_upload")) {
            String jsonRet = mgr.mergeMappingUpload(request);
            response.setStatus(302);
            response.addHeader("Location",
                    "merge.html?json=" + URLEncoder.encode(jsonRet, "UTF-8").replace("+", "%20"));
        } else if (cmd.equalsIgnoreCase("merge")) {
            final String mappingPath = request.getParameter("mapping_path");
            final String targetXml = request.getParameter("target_xml");
            final String inputData = Stream.readInputStream(request.getInputStream());
            final boolean replace = "1".equals(request.getParameter("replace"));

            JSONObject json = (mappingPath != null && !mappingPath.isEmpty())
                    ? mgr.mergeMappingByPath(mappingPath, inputData, replace)
                    : mgr.mergeMappingImpl(targetXml, inputData, replace);

            response.setContentType("text/json");
            response.getWriter().write(json.toString());
        } else if (cmd.equalsIgnoreCase("bundle_restore")) {
            // Applies a set of mapping conditions to a mapping path.
            final String mappingPath = request.getParameter("mapping_path");
            final String parent = request.getParameter("parent");
            final String type = request.getParameter("type");
            final String inputData = Stream.readInputStream(request.getInputStream());

            String targetXml = "<mapping xmlns=\"urn:csiro:xmlns:pidsvc:backup:1.0\">" + "   <path>"
                    + StringEscapeUtils.escapeXml(mappingPath) + "</path>"
                    + (parent != null && !parent.isEmpty()
                            ? "<parent>" + StringEscapeUtils.escapeXml(parent) + "</parent>"
                            : "")
                    + "   <type>" + StringEscapeUtils.escapeXml(type) + "</type>" + "</mapping>";

            response.setContentType("text/json");
            response.getWriter().write(mgr.mergeMappingImpl(targetXml, inputData, true).toString());
        } else if (cmd.equalsIgnoreCase("purge_data_store"))
            mgr.purgeDataStore();
        else if (cmd.equalsIgnoreCase("save_settings"))
            mgr.saveSettings(request.getParameterMap());
        else if (cmd.equalsIgnoreCase("create_lookup"))
            mgr.createLookup(request.getInputStream());
        else if (cmd.equalsIgnoreCase("delete_lookup"))
            mgr.deleteLookup(request.getParameter("ns"));
        else if (cmd.equalsIgnoreCase("import_lookup"))
            response.getWriter().write(mgr.importLookup(request));
        else if (cmd.equalsIgnoreCase("create_condition_set"))
            mgr.createConditionSet(request.getInputStream());
        else if (cmd.equalsIgnoreCase("delete_condition_set"))
            mgr.deleteConditionSet(request.getParameter("name"));
        else
            response.setStatus(404);
    } catch (Exception e) {
        _logger.error(e);
        Http.returnErrorCode(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    } finally {
        if (mgr != null)
            mgr.close();
    }
}

From source file:ch.ralscha.extdirectspring.controller.RouterController.java

@RequestMapping(value = "/router", method = RequestMethod.POST, params = "!extAction")
public void router(HttpServletRequest request, HttpServletResponse response, Locale locale) throws IOException {

    Object requestData = this.configurationService.getJsonHandler().readValue(request.getInputStream(),
            Object.class);

    List<ExtDirectRequest> directRequests = null;
    if (requestData instanceof Map) {
        directRequests = Collections.singletonList(
                this.configurationService.getJsonHandler().convertValue(requestData, ExtDirectRequest.class));
    } else if (requestData instanceof List) {
        directRequests = new ArrayList<ExtDirectRequest>();
        for (Object oneRequest : (List<?>) requestData) {
            directRequests.add(this.configurationService.getJsonHandler().convertValue(oneRequest,
                    ExtDirectRequest.class));
        }/*from w  ww .  jav a 2  s .c  om*/
    }

    if (directRequests != null) {
        if (directRequests.size() == 1) {
            handleMethodCallOne(directRequests.get(0), request, response, locale);
        } else if (this.configurationService.getConfiguration()
                .getBatchedMethodsExecutionPolicy() == BatchedMethodsExecutionPolicy.SEQUENTIAL) {
            handleMethodCallsSequential(directRequests, request, response, locale);
        } else if (this.configurationService.getConfiguration()
                .getBatchedMethodsExecutionPolicy() == BatchedMethodsExecutionPolicy.CONCURRENT) {
            handleMethodCallsConcurrent(directRequests, request, response, locale);
        }
    }

}

From source file:gov.nih.nci.caarray.web.fileupload.MonitoredMultiPartRequest.java

private RequestContext createRequestContext(final HttpServletRequest req) {
    return new RequestContext() {
        public String getCharacterEncoding() {
            return req.getCharacterEncoding();
        }// w  w w .  jav  a2s.c  o  m

        public String getContentType() {
            return req.getContentType();
        }

        public int getContentLength() {
            return req.getContentLength();
        }

        public InputStream getInputStream() throws IOException {
            return req.getInputStream();
        }
    };
}

From source file:de.mpg.mpdl.service.rest.screenshot.service.HtmlScreenshotServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/* w  w  w.  ja va  2  s  . com*/
        if (ServletFileUpload.isMultipartContent(req)) {
            file = screenshotService.takeScreenshot(getUploadedFiles(req));
        } else {
            File html = File.createTempFile("htmlScreenshot", ".html");
            if (req.getParameter("html") != null) {
                IOUtils.write(req.getParameter("html").getBytes(), new FileOutputStream(html));
            } else {
                IOUtils.copy(req.getInputStream(), new FileOutputStream(html));
            }
            System.out.println(html.getAbsolutePath());
            // TO Do After the copy the of the files
            browserWidth = (readBrowserParam(req, "browserWidth") != "")
                    ? Integer.parseInt(req.getParameter("browserWidth"))
                    : HtmlScreenshotService.DEFAULT_WIDTH;
            browserHeight = (readBrowserParam(req, "browserHeight") != "")
                    ? Integer.parseInt(req.getParameter("browserHeight"))
                    : HtmlScreenshotService.DEFAULT_HEIGHT;
            useFireFox = (readBrowserParam(req, "useFireFox") != "")
                    ? Boolean.parseBoolean(req.getParameter("useFireFox"))
                    : false;

            file = screenshotService.takeScreenshot(html, browserWidth, browserHeight, useFireFox);
            if (transformScreenshot(req)) {
                imageTransformer.transform(file, resp.getOutputStream(), readParam(req, "format"),
                        readParam(req, "size"), readParam(req, "crop"), readParam(req, "priority"),
                        readParam(req, "params1"), readParam(req, "params2"));
            } else
                IOUtils.copy(new FileInputStream(file), resp.getOutputStream());
        }
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        e.printStackTrace();
    }
}

From source file:br.org.indt.ndg.servlets.ReceiveImage.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("RECEIVE IMAGE: executing doPost method.");

    response.reset();//from   w  w  w  . jav  a 2 s  .c o m
    response.setContentType("image/jpg");

    InputStream inputStream = request.getInputStream();
    DataOutputStream dataOutputStream = new DataOutputStream(response.getOutputStream());

    if (inputStream != null) {
        log.debug("RECEIVE IMAGE: creating file ImageFromClient.jpg...");

        FileOutputStream fileOutputStream = new FileOutputStream("ImageFromClient.jpg");

        byte buffer[] = new byte[1024 * 128];
        int i = 0;

        while ((i = inputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, i);
        }

        fileOutputStream.close();
        inputStream.close();

        dataOutputStream.writeBytes(SUCCESS);
        dataOutputStream.close();

        log.debug("RECEIVE IMAGE: SUCCESS");
    } else {
        dataOutputStream.writeBytes(FAILURE);

        log.debug("RECEIVE IMAGE: FAILURE");
    }
}

From source file:org.openxdata.server.servlet.WMDownloadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from ww w.  ja va 2s .  c  o m
        String action = request.getParameter(OpenXDataConstants.REQUEST_PARAMETER_ACTION);

        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", -1);
        response.setHeader("Cache-Control", "no-store");
        response.setContentType(OpenXDataConstants.HTTP_HEADER_CONTENT_TYPE_XML);

        if (action == null) {
            new FormsServer(formDownloadService).processConnection(request.getInputStream(),
                    response.getOutputStream());
        } else {

            if (OpenXDataConstants.ACTION_DOWNLOAD_STUDIES.equalsIgnoreCase(action)) {
                downloadStudies(response);
            } else if (OpenXDataConstants.REQUEST_ACTION_DOWNLOAD_FORMS.equalsIgnoreCase(action)) {
                String studyId = request.getParameter("studyid");
                if (studyId != null && studyId.length() > 0) {
                    downloadForms(response, Integer.parseInt(studyId));
                }
            } else if (OpenXDataConstants.REQUEST_ACTION_UPLOAD_DATA.equalsIgnoreCase(action)) {
                // do nothing???
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.github.restdriver.clientdriver.unit.HttpRealRequestTest.java

@Test
public void instantiationWithHttpRequestPopulatesCorrectly() throws IOException {

    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    String expectedPathInfo = "someUrlPath";
    String expectedMethod = "GET";
    Enumeration<String> expectedHeaderNames = Collections.enumeration(Arrays.asList("header1"));

    String bodyContent = "bodyContent";
    String expectedContentType = "contentType";

    when(mockRequest.getPathInfo()).thenReturn(expectedPathInfo);
    when(mockRequest.getMethod()).thenReturn(expectedMethod);
    when(mockRequest.getQueryString()).thenReturn("hello=world");
    when(mockRequest.getHeaderNames()).thenReturn(expectedHeaderNames);
    when(mockRequest.getHeader("header1")).thenReturn("thisIsHeader1");
    when(mockRequest.getInputStream())
            .thenReturn(new DummyServletInputStream(IOUtils.toInputStream(bodyContent)));
    when(mockRequest.getContentType()).thenReturn(expectedContentType);

    RealRequest realRequest = new HttpRealRequest(mockRequest);

    assertThat((String) realRequest.getPath(), is(expectedPathInfo));
    assertThat(realRequest.getMethod(), is(Method.GET));
    assertThat(realRequest.getParams().size(), is(1));
    assertThat((String) realRequest.getParams().get("hello").iterator().next(), is("world"));
    assertThat((String) realRequest.getHeaders().get("header1"), is("thisIsHeader1"));
    assertThat((String) realRequest.getBodyContentType(), is(expectedContentType));

}

From source file:com.geocent.owf.openlayers.DataRequestProxy.java

/**
 * Gets the data from the provided remote URL.
 * Note that the data will be returned from the method and not automatically
 * populated into the response object./*from  w  ww.  j  a v a 2 s.  c  o m*/
 * 
 * @param request       ServletRequest object containing the request data.
 * @param response      ServletResponse object for the response information.
 * @param url           URL from which the data will be retrieved.
 * @return              Data from the provided remote URL.
 * @throws IOException 
 */
public String getData(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {

    if (!allowUrl(url)) {
        throw new UnknownHostException("Request to invalid host not allowed.");
    }

    HttpURLConnection connection = (HttpURLConnection) (new URL(url).openConnection());
    connection.setRequestMethod(request.getMethod());

    // Detects a request with a payload inside the message body
    if (request.getContentLength() > 0) {
        connection.setRequestProperty("Content-Type", request.getContentType());
        connection.setDoOutput(true);
        connection.setDoInput(true);
        byte[] requestPayload = IOUtils.toByteArray(request.getInputStream());
        connection.getOutputStream().write(requestPayload);
        connection.getOutputStream().flush();
    }

    // Create handler for the given content type and proxy the extracted information
    Handler contentHandler = HandlerFactory.getHandler(connection.getContentType());
    return contentHandler.handleContent(response, connection.getInputStream());
}

From source file:com.centurylink.mdw.hub.servlet.SoapServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    CodeTimer timer = new CodeTimer("SoapServlet.doPost()", true);

    InputStream reqInputStream = request.getInputStream();
    // read the POST request contents
    String requestString = getRequestString(request);
    if (logger.isMdwDebugEnabled()) {
        logger.mdwDebug("SOAP Listener POST Request:\n" + requestString);
    }/*from   ww  w  .j  a v  a2 s  .  c  o  m*/

    Map<String, String> metaInfo = buildMetaInfo(request);

    String responseString = null;
    MessageFactory factory = null;
    String soapVersion = SOAPConstants.SOAP_1_1_PROTOCOL;
    try {
        SOAPMessage message = null;
        SOAPBody body = null;
        try {
            // Intuitively guess which SOAP version is needed
            // factory = getMessageFactory(requestString, true);
            soapVersion = getSoapVersion(requestString, true);
            factory = getSoapMessageFactory(soapVersion);
            reqInputStream = new ByteArrayInputStream(requestString.getBytes());

            message = factory.createMessage(null, reqInputStream);
            body = message.getSOAPBody();
        } catch (SOAPException e) {
            // Unlikely, but just in case the SOAP version guessing
            // has guessed incorrectly, this catches any SOAP exception,
            // in which case try the other version
            if (logger.isMdwDebugEnabled()) {
                logger.mdwDebug(
                        "SOAPListenerServlet failed to find correct Message Factory:" + "\n" + e.getMessage());
            }
            // Try with the other unintuitive MessageFactory
            // factory = getMessageFactory(requestString, false);
            soapVersion = getSoapVersion(requestString, false);
            factory = getSoapMessageFactory(soapVersion);
            reqInputStream = new ByteArrayInputStream(requestString.getBytes());

            message = factory.createMessage(null, reqInputStream);
            body = message.getSOAPBody();
            // Only 2 versions, so let any exceptions bubble up
        }
        Node childElem = null;
        Iterator<?> it = body.getChildElements();
        while (it.hasNext()) {
            Node node = (Node) it.next();
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                childElem = node;
                break;
            }
        }
        if (childElem == null)
            throw new SOAPException("SOAP body child element not found");

        String requestXml = null;

        boolean oldStyleRpcRequest = false;
        if (request.getServletPath().endsWith(RPC_SERVICE_PATH)
                || RPC_SERVICE_PATH.equals(request.getPathInfo())) {
            NodeList nodes = childElem.getChildNodes();
            for (int i = 0; i < nodes.getLength(); i++) {
                if (StringUtils.isNotBlank(nodes.item(i).getNodeName())
                        && nodes.item(i).getNodeName().equals("RequestDetails")) {
                    oldStyleRpcRequest = true;
                    Node requestNode = nodes.item(i).getFirstChild();
                    if (requestNode.getNodeType() == Node.CDATA_SECTION_NODE) {
                        requestXml = requestNode.getTextContent();
                    } else {
                        requestXml = DomHelper.toXml(requestNode);
                        if (requestXml.contains("&lt;"))
                            requestXml = StringEscapeUtils.unescapeXml(requestXml);
                    }
                }
            }
        } else {
            requestXml = DomHelper.toXml(childElem);
        }

        metaInfo = addSoapMetaInfo(metaInfo, message);
        ListenerHelper helper = new ListenerHelper();

        try {
            authenticate(request, metaInfo, requestXml);
            String handlerResponse = helper.processEvent(requestXml, metaInfo);

            try {
                // standard response indicates a potential problem
                MDWStatusMessageDocument responseDoc = MDWStatusMessageDocument.Factory.parse(handlerResponse,
                        Compatibility.namespaceOptions());
                MDWStatusMessage responseMsg = responseDoc.getMDWStatusMessage();
                if ("SUCCESS".equals(responseMsg.getStatusMessage()))
                    responseString = createSoapResponse(soapVersion, handlerResponse);
                else
                    responseString = createSoapFaultResponse(soapVersion,
                            String.valueOf(responseMsg.getStatusCode()), responseMsg.getStatusMessage());
            } catch (XmlException xex) {
                if (Listener.METAINFO_ERROR_RESPONSE_VALUE
                        .equalsIgnoreCase(metaInfo.get(Listener.METAINFO_ERROR_RESPONSE))) {
                    // Support for custom error response
                    responseString = handlerResponse;
                } else {
                    // not parseable as standard response doc (a good thing)
                    if (oldStyleRpcRequest) {
                        responseString = createOldStyleSoapResponse(soapVersion,
                                "<m:invokeWebServiceResponse xmlns:m=\"http://mdw.qwest.com/listener/webservice\"><Response>"
                                        + StringEscapeUtils.escapeXml(handlerResponse)
                                        + "</Response></m:invokeWebServiceResponse>");
                    } else {
                        responseString = createSoapResponse(soapVersion, handlerResponse);
                    }
                }
            }
        } catch (ServiceException ex) {
            logger.severeException(ex.getMessage(), ex);
            responseString = createSoapFaultResponse(soapVersion, String.valueOf(ex.getCode()),
                    ex.getMessage());
        }
    } catch (Exception ex) {
        logger.severeException(ex.getMessage(), ex);
        try {
            responseString = createSoapFaultResponse(soapVersion, null, ex.getMessage());
        } catch (Exception tex) {
            logger.severeException(tex.getMessage(), tex);
        }
    }

    if (logger.isMdwDebugEnabled()) {
        logger.mdwDebug("SOAP Listener Servlet POST Response:\n" + responseString);
    }

    if (metaInfo.get(Listener.METAINFO_CONTENT_TYPE) != null) {
        response.setContentType(metaInfo.get(Listener.METAINFO_CONTENT_TYPE));
    } else {
        if (soapVersion.equals(SOAPConstants.SOAP_1_1_PROTOCOL))
            response.setContentType(Listener.CONTENT_TYPE_XML);
        else
            response.setContentType("application/soap+xml");
    }

    response.getOutputStream().print(responseString);

    timer.stopAndLogTiming("");
}