Example usage for javax.servlet.http HttpServletRequest getContentLength

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

Introduction

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

Prototype

public int getContentLength();

Source Link

Document

Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known ir is greater than Integer.MAX_VALUE.

Usage

From source file:org.primeframework.mvc.parameter.RequestBodyWorkflowTest.java

@Test
public void multipleFiles() throws IOException, ServletException {
    String body = FileUtils.readFileToString(
            new File("src/test/java/org/primeframework/mvc/servlet/http-test-body-multiple-files.txt"));

    HttpServletRequest request = EasyMock.createStrictMock(HttpServletRequest.class);
    EasyMock.expect(request.getParameterMap()).andReturn(new HashMap<>());
    EasyMock.expect(request.getContentType()).andReturn("multipart/form-data, boundary=AaB03x").times(2);
    EasyMock.expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes()));
    EasyMock.expect(request.getCharacterEncoding()).andReturn("UTF-8");
    EasyMock.expect(request.getContentLength()).andReturn(body.length());
    final Capture<Map<String, List<FileInfo>>> capture = new Capture<>();
    request.setAttribute(eq(RequestKeys.FILE_ATTRIBUTE), capture(capture));
    EasyMock.replay(request);/*w  ww .ja  va  2 s . com*/

    final AtomicBoolean run = new AtomicBoolean(false);
    MockWorkflowChain chain = new MockWorkflowChain(() -> {
        Map<String, List<FileInfo>> files = capture.getValue();
        assertEquals(files.size(), 1);
        try {
            assertEquals(FileUtils.readFileToString(files.get("userfiles").get(0).file), "test");
            assertEquals(FileUtils.readFileToString(files.get("userfiles").get(1).file), "test2");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        run.set(true);
    });

    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request);
    RequestBodyWorkflow workflow = new RequestBodyWorkflow(wrapper);
    workflow.perform(chain);
    assertTrue(run.get());

    assertEquals(wrapper.getParameter("field1"), "value1");
    assertEquals(wrapper.getParameter("field2"), "value2");

    EasyMock.verify(request);
}

From source file:se.vgregion.portal.requestlogger.RequestLoggerController.java

private Map<String, String> getRequestInfo(PortletRequest request) {
    Map<String, String> requestResult = new TreeMap<String, String>();

    HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(request);

    requestResult.put("RemoteUser", httpRequest.getRemoteUser());
    requestResult.put("P3P.USER_LOGIN_ID", getRemoteUserId(request));
    requestResult.put("RemoteAddr", httpRequest.getRemoteAddr());
    requestResult.put("RemoteHost", httpRequest.getRemoteHost());
    requestResult.put("RemotePort", String.valueOf(httpRequest.getRemotePort()));
    requestResult.put("AuthType", httpRequest.getAuthType());
    requestResult.put("CharacterEncoding", httpRequest.getCharacterEncoding());
    requestResult.put("ContentLength", String.valueOf(httpRequest.getContentLength()));
    requestResult.put("ContentType", httpRequest.getContentType());
    requestResult.put("ContextPath", httpRequest.getContextPath());
    requestResult.put("LocalAddr", httpRequest.getLocalAddr());
    requestResult.put("Locale", httpRequest.getLocale().toString());
    requestResult.put("LocalName", httpRequest.getLocalName());
    requestResult.put("LocalPort", String.valueOf(httpRequest.getLocalPort()));
    requestResult.put("Method", httpRequest.getMethod());
    requestResult.put("PathInfo", httpRequest.getPathInfo());
    requestResult.put("PathTranslated", httpRequest.getPathTranslated());
    requestResult.put("Protocol", httpRequest.getProtocol());
    requestResult.put("QueryString", httpRequest.getQueryString());
    requestResult.put("RequestedSessionId", httpRequest.getRequestedSessionId());
    requestResult.put("RequestURI", httpRequest.getRequestURI());
    requestResult.put("Scheme", httpRequest.getScheme());
    requestResult.put("ServerName", httpRequest.getServerName());
    requestResult.put("ServerPort", String.valueOf(httpRequest.getServerPort()));
    requestResult.put("ServletPath", httpRequest.getServletPath());

    return requestResult;
}

From source file:org.apache.solr.servlet.SolrRequestParserTest.java

License:asdf

public HttpServletRequest getMock(String uri, String contentType, int contentLength) {
    HttpServletRequest request = createMock(HttpServletRequest.class);
    expect(request.getHeader("User-Agent")).andReturn(null).anyTimes();
    expect(request.getRequestURI()).andReturn(uri).anyTimes();
    expect(request.getContentType()).andReturn(contentType).anyTimes();
    expect(request.getContentLength()).andReturn(contentLength).anyTimes();
    expect(request.getAttribute(EasyMock.anyObject(String.class))).andReturn(null).anyTimes();
    return request;
}

From source file:net.sourceforge.subsonic.controller.UploadController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    Map<String, Object> map = new HashMap<String, Object>();
    List<File> uploadedFiles = new ArrayList<File>();
    List<File> unzippedFiles = new ArrayList<File>();
    TransferStatus status = null;//w ww  . j ava 2 s  .  c  o m

    try {

        status = statusService.createUploadStatus(playerService.getPlayer(request, response, false, false));
        status.setBytesTotal(request.getContentLength());

        request.getSession().setAttribute(UPLOAD_STATUS, status);

        // Check that we have a file upload request
        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new Exception("Illegal request.");
        }

        File dir = null;
        boolean unzip = false;

        UploadListener listener = new UploadListenerImpl(status);

        FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
        ServletFileUpload upload = new ServletFileUpload(factory);

        List<?> items = upload.parseRequest(request);

        // First, look for "dir" and "unzip" parameters.
        for (Object o : items) {
            FileItem item = (FileItem) o;

            if (item.isFormField() && "dir".equals(item.getFieldName())) {
                dir = new File(item.getString());
            } else if (item.isFormField() && "unzip".equals(item.getFieldName())) {
                unzip = true;
            }
        }

        if (dir == null) {
            throw new Exception("Missing 'dir' parameter.");
        }

        // Look for file items.
        for (Object o : items) {
            FileItem item = (FileItem) o;

            if (!item.isFormField()) {
                String fileName = item.getName();
                if (fileName.trim().length() > 0) {

                    File targetFile = new File(dir, new File(fileName).getName());

                    if (!securityService.isUploadAllowed(targetFile)) {
                        throw new Exception("Permission denied: " + StringUtil.toHtml(targetFile.getPath()));
                    }

                    if (!dir.exists()) {
                        dir.mkdirs();
                    }

                    item.write(targetFile);
                    uploadedFiles.add(targetFile);
                    LOG.info("Uploaded " + targetFile);

                    if (unzip && targetFile.getName().toLowerCase().endsWith(".zip")) {
                        unzip(targetFile, unzippedFiles);
                    }
                }
            }
        }

    } catch (Exception x) {
        LOG.warn("Uploading failed.", x);
        map.put("exception", x);
    } finally {
        if (status != null) {
            statusService.removeUploadStatus(status);
            request.getSession().removeAttribute(UPLOAD_STATUS);
            User user = securityService.getCurrentUser(request);
            securityService.updateUserByteCounts(user, 0L, 0L, status.getBytesTransfered());
        }
    }

    map.put("uploadedFiles", uploadedFiles);
    map.put("unzippedFiles", unzippedFiles);

    ModelAndView result = super.handleRequestInternal(request, response);
    result.addObject("model", map);
    return result;
}

From source file:org.red5.server.net.servlet.RTMPTServlet.java

/**
 * Add data for an established session./*  w  w w. j a v a2 s  . c  om*/
 *
 * @param req
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
protected void handleSend(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    RTMPTConnection client = getClient(req);
    if (client == null) {
        handleBadRequest("Unknown client.", resp);
        return;
    }

    client.setServletRequest(req);

    // Put the received data in a ByteBuffer
    int length = req.getContentLength();
    ByteBuffer data = ByteBuffer.allocate(length);
    ServletUtils.copy(req.getInputStream(), data.asOutputStream());
    data.flip();

    // Decode the objects in the data
    List messages = client.decode(data);
    data = null;
    if (messages == null || messages.isEmpty()) {
        returnMessage(client.getPollingDelay(), resp);
        return;
    }

    // Execute the received RTMP messages
    RTMPTHandler handler = (RTMPTHandler) getServletContext().getAttribute(RTMPTHandler.HANDLER_ATTRIBUTE);
    Iterator it = messages.iterator();
    while (it.hasNext()) {
        try {
            handler.messageReceived(client, client.getState(), it.next());
        } catch (Exception e) {
            log.error("Could not process message.", e);
        }
    }

    // Send results to client
    returnPendingMessages(client, resp);
}

From source file:org.frontcache.hystrix.FC_BypassCache.java

/**
 * forward all kind of requests (GET, POST, PUT, ...)
 * /*from w w  w .  ja va 2  s  . co m*/
 * @param httpclient
 * @param verb
 * @param uri
 * @param request
 * @param headers
 * @param params
 * @param requestEntity
 * @return
 * @throws Exception
 */
private HttpResponse forward(HttpClient httpclient, String verb, String uri, HttpServletRequest request,
        Map<String, List<String>> headers, InputStream requestEntity) throws Exception {

    URL host = context.getOriginURL();
    HttpHost httpHost = FCUtils.getHttpHost(host);
    uri = (host.getPath() + uri).replaceAll("/{2,}", "/");

    HttpRequest httpRequest;
    switch (verb.toUpperCase()) {
    case "POST":
        HttpPost httpPost = new HttpPost(uri + context.getRequestQueryString());
        httpRequest = httpPost;
        httpPost.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
        break;
    case "PUT":
        HttpPut httpPut = new HttpPut(uri + context.getRequestQueryString());
        httpRequest = httpPut;
        httpPut.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
        break;
    case "PATCH":
        HttpPatch httpPatch = new HttpPatch(uri + context.getRequestQueryString());
        httpRequest = httpPatch;
        httpPatch.setEntity(new InputStreamEntity(requestEntity, request.getContentLength()));
        break;
    default:
        httpRequest = new BasicHttpRequest(verb, uri + context.getRequestQueryString());
    }

    try {
        httpRequest.setHeaders(FCUtils.convertHeaders(headers));
        Header acceptEncoding = httpRequest.getFirstHeader("accept-encoding");
        if (acceptEncoding != null && acceptEncoding.getValue().contains("gzip")) {
            httpRequest.setHeader("accept-encoding", "gzip");
        }
        HttpResponse originResponse = httpclient.execute(httpHost, httpRequest);
        return originResponse;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        // httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.gwtspringhibernate.reference.rlogman.spring.GwtServiceExporter.java

private String readPayloadAsUtf8(HttpServletRequest request) throws IOException, ServletException {
    int contentLength = request.getContentLength();
    if (contentLength == -1) {
        // Content length must be known.
        throw new ServletException("Content-Length must be specified");
    }//from   w  w  w .j  a va2  s .c om

    String contentType = request.getContentType();
    boolean contentTypeIsOkay = false;
    // Content-Type must be specified.
    if (contentType != null) {
        // The type must be plain text.
        if (contentType.startsWith("text/plain")) {
            // And it must be UTF-8 encoded (or unspecified, in which case
            // we assume
            // that it's either UTF-8 or ASCII).
            if (contentType.indexOf("charset=") == -1)
                contentTypeIsOkay = true;
            else if (contentType.indexOf("charset=utf-8") != -1)
                contentTypeIsOkay = true;
        }
    }
    if (!contentTypeIsOkay)
        throw new ServletException(
                "Content-Type must be 'text/plain' with 'charset=utf-8' (or unspecified charset)");

    InputStream in = request.getInputStream();
    try {
        byte[] payload = new byte[contentLength];
        int offset = 0;
        int len = contentLength;
        int byteCount;
        while (offset < contentLength) {
            byteCount = in.read(payload, offset, len);
            if (byteCount == -1)
                throw new ServletException("Client did not send " + contentLength + " bytes as expected");
            offset += byteCount;
            len -= byteCount;
        }
        return new String(payload, "UTF-8");
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:org.red5.server.net.rtmpt.RTMPTServlet.java

/**
 * Skip data sent by the client.//from  w w w . j av a 2 s  . co m
 * 
 * @param req
 *            Servlet request
 * @throws IOException
 *             I/O exception
 */
protected void skipData(HttpServletRequest req) throws IOException {
    log.trace("skipData {}", req);
    int length = req.getContentLength();
    log.trace("Skipping {} bytes", length);
    IoBuffer data = IoBuffer.allocate(length);
    ServletUtils.copy(req, data.asOutputStream());
    data.flip();
    data.free();
    data = null;
    log.trace("Skipped {} bytes", length);
}

From source file:com.kolich.curacao.examples.controllers.NonBlockingIOExampleController.java

@PUT("/api/nonblocking")
public final void nonblocking(final AsyncContext context, final HttpServletRequest request,
        final HttpServletResponse response, final ServletInputStream input, final ServletOutputStream output)
        throws Exception {

    final Queue<Option<String>> queue = new ConcurrentLinkedQueue<Option<String>>();

    final WriteListener writer = new StupidWriteListener(context, queue, output);

    final ReadListener reader = new StupidReadListener(queue, input, output, writer,
            request.getContentLength());

    // Producer//w w w  .j av a2  s . c  o  m
    input.setReadListener(reader);
    logger__.info("Tomcat, is input ready?: " + input.isReady());
    reader.onDataAvailable();

    // Consumer
    output.setWriteListener(writer);
    logger__.info("Tomcat, is input ready?: " + output.isReady());
    writer.onWritePossible();

}

From source file:test.integ.be.fedict.performance.servlet.OcspServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String caName = request.getParameter(CA_QUERY_PARAM);
    if (null == caName) {
        throw new ServletException("No CA name found.");
    }//from   w ww . ja  v a2  s. co m

    CAConfiguration ca = TestPKI.get().findCa(caName);
    if (null == ca) {
        throw new ServletException("CA Config not found for " + caName);
    }

    try {

        if (null == request.getContentType() || !request.getContentType().equals("application/ocsp-request")) {
            LOG.error("Wrong content type: " + request.getContentType());
            return;
        }

        int len = request.getContentLength();
        byte[] ocspRequestData = new byte[len];
        ServletInputStream reader = request.getInputStream();
        int result = reader.read(ocspRequestData);
        if (-1 == result) {
            LOG.error("No data found ?!");
            return;
        }

        BigInteger maxRevokedSN = new BigInteger(Long.toString(ca.getCrlRecords()));

        OCSPReq ocspRequest = new OCSPReq(ocspRequestData);

        BasicOCSPRespGenerator ocspRespGen = new BasicOCSPRespGenerator(ca.getKeyPair().getPublic());
        for (Req req : ocspRequest.getRequestList()) {

            LOG.debug("OCSP request for CA=" + caName + " sn=" + req.getCertID().getSerialNumber());

            if (-1 == req.getCertID().getSerialNumber().compareTo(maxRevokedSN)) {
                LOG.debug("revoked");
                ocspRespGen.addResponse(req.getCertID(),
                        new RevokedStatus(new RevokedInfo(new ASN1GeneralizedTime(new Date()), null)));
            } else {
                ocspRespGen.addResponse(req.getCertID(), CertificateStatus.GOOD);
            }
        }

        BasicOCSPResp ocspResp;
        ocspResp = ocspRespGen.generate("SHA1WITHRSA", ca.getKeyPair().getPrivate(), null, new Date(), "BC");

        OCSPRespGenerator og = new OCSPRespGenerator();

        response.setContentType("application/ocsp-response");
        response.getOutputStream().write((og.generate(OCSPRespGenerator.SUCCESSFUL, ocspResp)).getEncoded());

    } catch (Exception e) {
        LOG.error("Exception: " + e.getMessage(), e);
        throw new ServletException(e);
    }
}