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.niconico.mylasta.direction.sponsor.NiconicoMultipartRequestHandler.java

protected void handleSizeLimitExceededException(HttpServletRequest request, SizeLimitExceededException e) {
    final long actual = e.getActualSize();
    final long permitted = e.getPermittedSize();
    String msg = "Exceeded size of the multipart request: actual=" + actual + " permitted=" + permitted;
    request.setAttribute(MAX_LENGTH_EXCEEDED_KEY, new MultipartExceededException(msg, actual, permitted, e));
    try {/*from  w  ww  .ja  va 2 s. co m*/
        final InputStream is = request.getInputStream();
        try {
            final byte[] buf = new byte[1024];
            @SuppressWarnings("unused")
            int len = 0;
            while ((len = is.read(buf)) != -1) {
            }
        } catch (Exception ignored) {
        } finally {
            try {
                is.close();
            } catch (Exception ignored) {
            }
        }
    } catch (Exception ignored) {
    }
}

From source file:com.streamsets.pipeline.stage.destination.http.TestHttpClientTarget.java

@Before
public void setUp() throws Exception {
    int port = getFreePort();
    server = new Server(port);
    server.setHandler(new AbstractHandler() {
        @Override//from  w  w  w. jav a 2  s  . c  om
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {
            serverRequested = true;
            if (returnErrorResponse) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }

            compressionType = request.getHeader(HttpConstants.CONTENT_ENCODING_HEADER);
            InputStream is = request.getInputStream();
            if (compressionType != null && compressionType.equals(HttpConstants.SNAPPY_COMPRESSION)) {
                is = new SnappyFramedInputStream(is, true);
            } else if (compressionType != null && compressionType.equals(HttpConstants.GZIP_COMPRESSION)) {
                is = new GZIPInputStream(is);
            }
            requestPayload = IOUtils.toString(is);
            requestContentType = request.getContentType();
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
        }
    });
    server.start();
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTResource.java

/**
 * The PUT service is used to create a new resource in the repository...
 *
 * @param req/*from   w  ww .j  a  v a2  s .c om*/
 * @param resp
 * @throws ServiceException
 */
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {

    HttpServletRequest mreq = restUtils.extractAttachments(runReportService, req);

    String resourceDescriptorXml = null;

    // get the resource descriptor...
    if (mreq instanceof MultipartHttpServletRequest) {
        resourceDescriptorXml = mreq.getParameter(restUtils.REQUEST_PARAMENTER_RD);
    } else {
        try {
            resourceDescriptorXml = IOUtils.toString(req.getInputStream());
        } catch (IOException ex) {
            throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage());
        }
    }

    if (resourceDescriptorXml == null) {
        restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "Missing parameter "
                + restUtils.REQUEST_PARAMENTER_RD + " " + runReportService.getInputAttachments());
        return;
    }

    // Parse the resource descriptor...
    InputSource is = new InputSource(new StringReader(resourceDescriptorXml));
    Document doc = null;
    ResourceDescriptor rd = null;
    try {
        doc = XMLUtil.getNewDocumentBuilder().parse(is);
        rd = Unmarshaller.readResourceDescriptor(doc.getDocumentElement());
        if (log.isDebugEnabled()) {
            log.debug("resource descriptor was created successfully for: " + rd.getUriString());
        }

        // we force the rd to be new...
        rd.setIsNew(true);

        ResourceDescriptor createdRd = resourcesManagementRemoteService.putResource(rd);

        Marshaller m = new Marshaller();
        String xml = m.writeResourceDescriptor(createdRd);
        // send the xml...
        restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, "");

    } catch (SAXException ex) {
        log.error("Unexpected error during resource descriptor marshaling: " + ex.getMessage(), ex);
        restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "Invalid resource descriptor");
    } catch (ServiceException ex) {
        throw ex;
    } catch (Exception ex) {
        log.error("Unexpected error during resource save: " + ex.getMessage(), ex);
        throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage());
    }

}

From source file:com.ibm.watson.ta.retail.DemoServlet.java

/**
 * Create and POST a request to the Watson service
 *
 * @param req//from   w ww  . j  a v  a 2  s. c  om
 *            the Http Servlet request
 * @param resp
 *            the Http Servlet response
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    req.setCharacterEncoding("UTF-8");
    try {
        String queryStr = req.getQueryString();
        String url = baseURL + "/v1/dilemmas";
        if (queryStr != null) {
            url += "?" + queryStr;
        }
        URI uri = new URI(url).normalize();
        logger.info("posting to " + url);

        Request newReq = Request.Post(uri);
        newReq.addHeader("Accept", "application/json");
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream());
        newReq.bodyString(EntityUtils.toString(entity, "UTF-8"), ContentType.APPLICATION_JSON);

        Executor executor = this.buildExecutor(uri);
        Response response = executor.execute(newReq);
        HttpResponse httpResponse = response.returnResponse();
        resp.setStatus(httpResponse.getStatusLine().getStatusCode());

        ServletOutputStream servletOutputStream = resp.getOutputStream();
        httpResponse.getEntity().writeTo(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();

        logger.info("post done");
    } catch (Exception e) {
        // Log something and return an error message
        logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
        resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
    }
}

From source file:com.google.nigori.server.NigoriServlet.java

private String getJsonAsString(HttpServletRequest req, int maxLength) throws ServletException {

    if (maxLength != 0 && req.getContentLength() > maxLength) {
        return null;
    }/*from w ww  .j a v a  2s .c  o m*/

    String charsetName = req.getCharacterEncoding();
    if (charsetName == null) {
        charsetName = MessageLibrary.CHARSET;
    }

    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(req.getInputStream(), charsetName));
        StringBuilder json = new StringBuilder();
        char[] buffer = new char[64 * 1024];
        int charsRemaining = maxJsonQueryLength;
        int charsRead;
        while ((charsRead = in.read(buffer)) != -1) {
            charsRemaining -= charsRead;
            if (charsRemaining < 0) {
                throw new ServletException(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                        "Json request exceeds server maximum length of " + maxLength);
            }
            json.append(buffer, 0, charsRead);
        }
        return json.toString();
    } catch (IOException ioe) {
        throw new ServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Internal error receiving data from client.");
    }
}

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

protected void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Map<String, Object> requestObject = JSONUtil.parse(request.getInputStream(), null);

    String username = (String) requestObject.get("username");
    String password = (String) requestObject.get("password");

    User user = users.get(username);//from  w ww.  jav a  2s  .com
    if (user == null || password == null || !password.equals(user.getPassword())) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("application/json");

    Session session = addSession(user);
    Cookie cookie = new Cookie("SESSION", session.getID());
    cookie.setPath("/");
    response.addCookie(cookie);

    Map<String, Object> responseObject = new LinkedHashMap<String, Object>();
    responseObject.put("sessid", session.getID());
    responseObject.put("token", session.getCSRFToken());
    InputStream body = JSONUtil.build(responseObject);

    try {
        ServletOutputStream out = response.getOutputStream();
        IOUtil.copy(body, out);
        out.flush();
    } finally {
        IOUtil.closeSilent(body);
    }
}

From source file:com.ultrapower.eoms.common.plugin.ajaxupload.AjaxMultiPartRequest.java

/**
 * Creates a RequestContext needed by Jakarta Commons Upload.
 * //from   www. ja  v  a2 s. co m
 * @param req
 *            the request.
 * @return a new request context.
 */
private RequestContext createRequestContext(final HttpServletRequest req) {
    return new RequestContext() {
        public String getCharacterEncoding() {
            return req.getCharacterEncoding();
        }

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

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

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

From source file:it.geosolutions.httpproxy.service.impl.ProxyServiceImpl.java

/**
 * Sets up the given {@link PostMethod} to send the same standard POST data as was sent in the given {@link HttpServletRequest}
 * /*from  www. j  av a 2 s . co  m*/
 * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a standard POST request
 * @param httpServletRequest The {@link HttpServletRequest} that contains the POST data to be sent via the {@link PostMethod}
 * @throws IOException
 */
private void handleStandard(EntityEnclosingMethod methodProxyRequest, HttpServletRequest httpServletRequest)
        throws IOException {
    try {

        methodProxyRequest.setRequestEntity(new InputStreamRequestEntity(httpServletRequest.getInputStream()));
        //LOGGER.info("original request content length:" + httpServletRequest.getContentLength());
        //LOGGER.info("proxied request content length:" +methodProxyRequest.getRequestEntity().getContentLength()+"");

    } catch (IOException e) {
        throw new IOException(e);
    }
}

From source file:eu.impact_project.iif.t2.client.HelperTest.java

/**
 * Test of parseRequest method, of class Helper.
 *///  www .j  av  a2 s. co  m
@Test
public void testParseRequest() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    URL url = this.getClass().getResource("/prueba.txt");
    File testFile = new File(url.getFile());
    Part[] parts = new Part[] { new StringPart("user", "user"), new FilePart("file_workflow", testFile),
            new FilePart("comon_file", testFile) };

    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
            new PostMethod().getParams());

    ByteArrayOutputStream requestContent = new ByteArrayOutputStream();

    multipartRequestEntity.writeRequest(requestContent);

    final ByteArrayInputStream inputContent = new ByteArrayInputStream(requestContent.toByteArray());

    when(request.getInputStream()).thenReturn(new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return inputContent.read();
        }
    });

    when(request.getContentType()).thenReturn(multipartRequestEntity.getContentType());

    Helper.parseRequest(request);

}

From source file:cn.knet.showcase.demos.servletproxy.ProxyServlet.java

private HttpRequest newProxyRequestWithEntity(String method, String proxyRequestUri,
        HttpServletRequest servletRequest) throws IOException {
    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(/*from ww w .j ava2s.  c  om*/
            new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
    return eProxyRequest;
}