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 containerDrainedBody() throws IOException, ServletException {
    HttpServletRequest request = createStrictMock(HttpServletRequest.class);
    expect(request.getParameterMap()).andReturn(new HashMap<>());
    expect(request.getContentType()).andReturn("application/x-www-form-urlencoded");
    expect(request.getInputStream()).andReturn(new MockServletInputStream(new byte[0]));
    expect(request.getContentLength()).andReturn(0);
    expect(request.getCharacterEncoding()).andReturn("UTF-8");
    replay(request);//from w w  w. ja  va  2s  .  co m

    WorkflowChain chain = createStrictMock(WorkflowChain.class);
    chain.continueWorkflow();
    replay(chain);

    // This is the assert since the request would be unwrapped if the body contained parameters
    RequestBodyWorkflow workflow = new RequestBodyWorkflow(request);
    workflow.perform(chain);

    verify(request, chain);
}

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

@Test
public void parseCombine() throws IOException, ServletException {
    Map<String, String[]> oldParams = new HashMap<>();
    oldParams.put("param1", new String[] { "oldvalue1", "oldvalue2" });
    oldParams.put("param2", new String[] { "oldvalue3" });

    String body = "param1=value1&param1=value2&param2=value3";
    HttpServletRequest request = createStrictMock(HttpServletRequest.class);
    expect(request.getParameterMap()).andReturn(oldParams);
    expect(request.getContentType()).andReturn("application/x-www-form-urlencoded");
    expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes()));
    expect(request.getContentLength()).andReturn(body.getBytes().length);
    expect(request.getCharacterEncoding()).andReturn("UTF-8");
    replay(request);//ww  w.ja  va2  s  .c o m

    WorkflowChain chain = createStrictMock(WorkflowChain.class);
    chain.continueWorkflow();
    replay(chain);

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

    @SuppressWarnings("unchecked")
    Map<String, String[]> actual = wrapper.getParameterMap();
    Map<String, String[]> expected = MapBuilder.<String, String[]>map()
            .put("param1", new String[] { "oldvalue1", "oldvalue2", "value1", "value2" })
            .put("param2", new String[] { "oldvalue3", "value3" }).done();
    assertParameterMapsEquals(actual, expected);

    verify(request, chain);
}

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

@Test
public void parseMultiple() throws IOException, ServletException {
    String body = "param1=value1&param1=value2&param2=value3";
    HttpServletRequest request = createStrictMock(HttpServletRequest.class);
    expect(request.getParameterMap()).andReturn(new HashMap<>());
    expect(request.getContentType()).andReturn("application/x-www-form-urlencoded");
    expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes()));
    expect(request.getContentLength()).andReturn(body.getBytes().length);
    expect(request.getCharacterEncoding()).andReturn("UTF-8");
    replay(request);//from   w  w w  .j  a v  a  2  s  .  c om

    WorkflowChain chain = createStrictMock(WorkflowChain.class);
    chain.continueWorkflow();
    replay(chain);

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

    @SuppressWarnings("unchecked")
    Map<String, String[]> actual = wrapper.getParameterMap();
    Map<String, String[]> expected = MapBuilder.<String, String[]>map()
            .put("param1", new String[] { "value1", "value2" }).put("param2", new String[] { "value3" }).done();
    assertParameterMapsEquals(actual, expected);

    verify(request, chain);
}

From source file:org.silverpeas.web.upload.AjaxFileUploadServlet.java

/**
 * Do the effective upload of files./*from w w w  . j  a  v  a 2  s .c  o  m*/
 *
 * @param session the HttpSession
 * @param request the multpart request
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private void doFileUpload(HttpSession session, HttpServletRequest request) throws IOException {
    try {
        session.setAttribute(UPLOAD_ERRORS, "");
        session.setAttribute(UPLOAD_FATAL_ERROR, "");
        List<String> paths = new ArrayList<>();
        session.setAttribute(FILE_UPLOAD_PATHS, paths);
        FileUploadListener listener = new FileUploadListener(request.getContentLength());
        session.setAttribute(FILE_UPLOAD_STATS, listener.getFileUploadStats());
        FileItemFactory factory = new MonitoringFileItemFactory(listener);
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        startingToSaveUploadedFile(session);
        String errorMessage = "";
        for (FileItem fileItem : items) {
            if (!fileItem.isFormField() && fileItem.getSize() > 0L) {
                try {
                    String filename = fileItem.getName();
                    if (filename.indexOf('/') >= 0) {
                        filename = filename.substring(filename.lastIndexOf('/') + 1);
                    }
                    if (filename.indexOf('\\') >= 0) {
                        filename = filename.substring(filename.lastIndexOf('\\') + 1);
                    }
                    if (!isInWhiteList(filename)) {
                        errorMessage += "The file " + filename + " is not uploaded!";
                        errorMessage += (StringUtil.isDefined(whiteList)
                                ? " Only " + whiteList.replaceAll(" ", ", ") + " file types can be uploaded<br>"
                                : " No allowed file format has been defined for upload<br>");
                        session.setAttribute(UPLOAD_ERRORS, errorMessage);
                    } else {
                        filename = System.currentTimeMillis() + "-" + filename;
                        File targetDirectory = new File(uploadDir, fileItem.getFieldName());
                        targetDirectory.mkdirs();
                        File uploadedFile = new File(targetDirectory, filename);
                        OutputStream out = null;
                        try {
                            out = new FileOutputStream(uploadedFile);
                            IOUtils.copy(fileItem.getInputStream(), out);
                            paths.add(uploadedFile.getParentFile().getName() + '/' + uploadedFile.getName());
                        } finally {
                            IOUtils.closeQuietly(out);
                        }
                    }
                } finally {
                    fileItem.delete();
                }
            }
        }
    } catch (Exception e) {
        getLogger(this).warn(e.getMessage());
        session.setAttribute(UPLOAD_FATAL_ERROR,
                "Could not process uploaded file. Please see log for details.");
    } finally {
        endingToSaveUploadedFile(session);
    }
}

From source file:com.tasktop.c2c.server.web.proxy.HttpProxy.java

@Override
protected void proxy(String targetUrl, final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {

    final HttpMethod proxyRequest = createProxyRequest(targetUrl, request);

    if (proxyRequest instanceof EntityEnclosingMethod) {
        EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) proxyRequest;
        RequestEntity requestEntity = new InputStreamRequestEntity(request.getInputStream(),
                request.getContentLength(), request.getContentType());
        entityEnclosingMethod.setRequestEntity(requestEntity);
    }/*from   w  w w . ja v  a2s.  com*/
    int code = httpClient.executeMethod(proxyRequest);
    response.setStatus(code);
    copyProxyReponse(proxyRequest, response);

}

From source file:org.vuphone.vandyupon.media.incoming.event.ImageParser.java

public boolean isRequestValid(HttpServletRequest request) {
    boolean isValid = false;

    if (request.getParameter(ImageParser.TIME) == null) {
        logger_.log(Level.SEVERE, "Unable to get time from the request");
    } else if (request.getContentType() == null
            || !request.getContentType().equalsIgnoreCase(ImageParser.CONTENT_TYPE)) {
        logger_.log(Level.SEVERE,
                "Expected Content Type to be " + ImageParser.CONTENT_TYPE + " not " + request.getContentType());
    } else if (request.getContentLength() <= 0) {
        logger_.log(Level.SEVERE, "Expected Content Length to be greater than 0");
    } else if (request.getParameter(ImageParser.EVENTID) == null) {
        logger_.log(Level.SEVERE, "Unable to get wreckid from the request");
    } else {/*from  w  ww  .  ja v  a2 s.com*/
        isValid = true;
    }
    return isValid;
}

From source file:com.silverpeas.servlets.upload.AjaxFileUploadServlet.java

/**
 * Do the effective upload of files.//  w  ww . ja v  a2 s. co  m
 *
 * @param session the HttpSession
 * @param request the multpart request
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private void doFileUpload(HttpSession session, HttpServletRequest request) throws IOException {
    try {
        session.setAttribute(UPLOAD_ERRORS, "");
        session.setAttribute(UPLOAD_FATAL_ERROR, "");
        List<String> paths = new ArrayList<String>();
        session.setAttribute(FILE_UPLOAD_PATHS, paths);
        FileUploadListener listener = new FileUploadListener(request.getContentLength());
        session.setAttribute(FILE_UPLOAD_STATS, listener.getFileUploadStats());
        FileItemFactory factory = new MonitoringFileItemFactory(listener);
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
        startingToSaveUploadedFile(session);
        String errorMessage = "";
        for (FileItem fileItem : items) {
            if (!fileItem.isFormField() && fileItem.getSize() > 0L) {
                try {
                    String filename = fileItem.getName();
                    if (filename.indexOf('/') >= 0) {
                        filename = filename.substring(filename.lastIndexOf('/') + 1);
                    }
                    if (filename.indexOf('\\') >= 0) {
                        filename = filename.substring(filename.lastIndexOf('\\') + 1);
                    }
                    if (!isInWhiteList(filename)) {
                        errorMessage += "The file " + filename + " is not uploaded!";
                        errorMessage += (StringUtil.isDefined(whiteList)
                                ? " Only " + whiteList.replaceAll(" ", ", ")
                                        + " file types can be uploaded<br/>"
                                : " No allowed file format has been defined for upload<br/>");
                        session.setAttribute(UPLOAD_ERRORS, errorMessage);
                    } else {
                        filename = System.currentTimeMillis() + "-" + filename;
                        File targetDirectory = new File(uploadDir, fileItem.getFieldName());
                        targetDirectory.mkdirs();
                        File uploadedFile = new File(targetDirectory, filename);
                        OutputStream out = null;
                        try {
                            out = new FileOutputStream(uploadedFile);
                            IOUtils.copy(fileItem.getInputStream(), out);
                            paths.add(uploadedFile.getParentFile().getName() + '/' + uploadedFile.getName());
                        } finally {
                            IOUtils.closeQuietly(out);
                        }
                    }
                } finally {
                    fileItem.delete();
                }
            }
        }
    } catch (Exception e) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.WARNING, e.getMessage());
        session.setAttribute(UPLOAD_FATAL_ERROR,
                "Could not process uploaded file. Please see log for details.");
    } finally {
        endingToSaveUploadedFile(session);
    }
}

From source file:waffle.spring.NegotiateSecurityFilter.java

@Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    NegotiateSecurityFilter.LOGGER.debug("{} {}, contentlength: {}", request.getMethod(),
            request.getRequestURI(), Integer.valueOf(request.getContentLength()));

    final AuthorizationHeader authorizationHeader = new AuthorizationHeader(request);

    // authenticate user
    if (!authorizationHeader.isNull()
            && this.provider.isSecurityPackageSupported(authorizationHeader.getSecurityPackage())) {

        // log the user in using the token
        IWindowsIdentity windowsIdentity;

        try {//from  ww  w . ja  va  2 s.c  o  m
            windowsIdentity = this.provider.doFilter(request, response);
            if (windowsIdentity == null) {
                return;
            }
        } catch (final IOException e) {
            NegotiateSecurityFilter.LOGGER.warn("error logging in user: {}", e.getMessage());
            NegotiateSecurityFilter.LOGGER.trace("{}", e);
            this.sendUnauthorized(response, true);
            return;
        }

        if (!this.allowGuestLogin && windowsIdentity.isGuest()) {
            NegotiateSecurityFilter.LOGGER.warn("guest login disabled: {}", windowsIdentity.getFqn());
            this.sendUnauthorized(response, true);
            return;
        }

        try {
            NegotiateSecurityFilter.LOGGER.debug("logged in user: {} ({})", windowsIdentity.getFqn(),
                    windowsIdentity.getSidString());

            final WindowsPrincipal principal = new WindowsPrincipal(windowsIdentity, this.principalFormat,
                    this.roleFormat);

            NegotiateSecurityFilter.LOGGER.debug("roles: {}", principal.getRolesString());

            final Authentication authentication = new WindowsAuthenticationToken(principal,
                    this.grantedAuthorityFactory, this.defaultGrantedAuthority);

            if (!this.setAuthentication(request, response, authentication)) {
                return;
            }

            NegotiateSecurityFilter.LOGGER.info("successfully logged in user: {}", windowsIdentity.getFqn());

        } finally {
            windowsIdentity.dispose();
        }
    }

    chain.doFilter(request, response);
}

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();
        }//from   ww  w.  j av  a 2s .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:tds.student.web.handlers.TestResponseHandler.java

@RequestMapping(value = "Response.axd/update", produces = "application/xml")
@ResponseBody/*from   www. j a  v a 2  s. c o m*/
private void updateResponses(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {
        long startTime = System.currentTimeMillis();
        if (request.getContentLength() == 0)
            return;
        long timeServerReceived = System.currentTimeMillis();

        // make sure the student is authenticated before doing anything
        checkAuthenticated();

        // get context objects
        TestOpportunity testOpp = StudentContext.getTestOpportunity();

        // validate context
        if (testOpp == null)
            StudentContext.throwMissingException();

        // get the last page the client has received responses for
        int lastPage = WebHelper.getQueryValueInt("lastPage");

        // create server latency
        ServerLatency latency = ServerLatency.getCurrent(HttpContext.getCurrentContext());

        /****************
         * SAVE RESPONSES
         ****************/

        // get the request information from tehe browser
        TestResponseReader responseReader = TestResponseReaderSax.parseSax(request.getInputStream(), testOpp);

        _eventLogger.putField("responses_updated", responseReader);

        /*
         * Ping
         */

        // TODO Shajib: ProxyService commented out
        /*
         * if (StudentSettings.getIsDataEntry()) { ProxyService _proxyService =
         * ServiceLocator.Resolve<ProxyService>();
         * _proxyService.Ping(testOpp.OppInstance, ProxyContext.GetProctor()); }
         */
        // If scoring is done sychronously, then score and then updateDB
        // If scoring is done asynchronously, then updateDB (with score -1 and
        // status WaitingForMachineScore) and then score
        List<ItemResponseUpdateStatus> responseResults = null;
        responseResults = _itemScoringService.updateResponses(testOpp.getOppInstance(),
                responseReader.getResponses(), responseReader.getPageDuration());
        /*
         * } catch (ReturnStatusException rse) {
         * response.setStatus(HttpServletResponse.SC_FORBIDDEN);
         * 
         * response.setContentType("application/json"); ObjectMapper mapper =
         * new ObjectMapper(); ResponseData<ReturnStatus> out = new
         * ResponseData<ReturnStatus> (TDSReplyCode.ReturnStatus.getCode(),
         * rse.getReturnStatus().getReason(), null);
         * mapper.writeValue(response.getOutputStream(), out); return;
         */

        // save updating responses latency
        for (ItemResponseUpdateStatus responseResult : responseResults) {
            latency.setDbLatency(latency.getDbLatency() + responseResult.getDbLatency());
        }

        /****************
         * PREFETCH
         ****************/

        // get test manager
        TestManager testManager = new TestManager(testOpp);

        // if we didn't update responses then we need to validate (unless we are in read only mode)
        boolean validateResponses = (responseReader.getResponses().size() == 0);
        if (_studentSettings.isReadOnly()) {
            validateResponses = false;
        }

        // load current responses
        StopWatch dbTimer = new StopWatch();
        dbTimer.start();
        testManager.LoadResponses(validateResponses);
        dbTimer.stop();

        // save loading responses latency
        // TODO Shajib: need verify this is same as dbTimer.ElapsedMilliseconds
        latency.setDbLatency(dbTimer.getTime());
        // add item info to latency
        LoadServerLatencyItems(latency, responseReader);

        // update the test config
        // UpdateTestConfig(testManager);

        int prefetchCount = 0; // how many times prefetch occured
        int prefetchMax = testOpp.getTestConfig().getTestLength() + 1; // max #
                                                                       // of
                                                                       // times
                                                                       // prefetch
                                                                       // can occur (safety)

        // check if test is completed
        try {
            testManager.CheckIfTestComplete();
        } catch (Exception e) {
            _logger.error("Error in updateResponses :CheckIfTestComplete:: " + e);
        }
        // if the test is not completed then check if prefetch is available
        while (testManager.CheckPrefetchAvailability(testOpp.getTestConfig().getPrefetch())) {
            // call adaptive algorithm to get the next item group
            NextItemGroupResult nextItemGroup = testManager.CreateNextItemGroup();
            if (nextItemGroup == null) {
                break;
            }

            _eventLogger.putField("prefetched_item_responses", nextItemGroup);

            latency.setDbLatency(latency.getDbLatency() + nextItemGroup.getDbLatency());
            prefetchCount++;

            // check if we exceeded prefetch max
            if (prefetchCount >= prefetchMax)
                break;

            // check if test is completed
            testManager.CheckIfTestComplete();
        }
        if (prefetchCount == prefetchMax) {

            String message = String.format(
                    "PREFETCH: The # of successful prefetch attempts for this one request reached %s tries. "
                            + "The # of prefetch attempts is bounded by the test length. "
                            + "Prefetch was stopped and this should be reviewed.",
                    testOpp.getTestConfig().getTestLength());
            _tdsLogger.applicationError(message, "updateResponses", request, null);
        }

        _eventLogger.putField("last_page", testManager.getLastPage());
        _eventLogger.putField("prefetch_count", prefetchCount);

        // set latency operation type
        boolean prefetched = (prefetchCount > 0);
        latency.setOperation(
                prefetched ? ServerLatency.OperationType.Selection : ServerLatency.OperationType.Update);

        // new groups
        PageList pageList = testManager.GetVisiblePages(lastPage);

        /****************
         * WRITE XML
         ****************/

        // begin writing

        // TODO Shajib: Revisit following line
        // SetMIMEType (ContentType.Xml);

        TestResponseWriter responseWriter = new TestResponseWriter(response.getOutputStream());

        // test info
        int eventID = responseReader.getEventID();
        responseWriter.writeStart(eventID);
        responseWriter.writeSummary(testManager, testOpp, prefetched);

        // timestamps
        long timeClientSent = responseReader.getTimestamp();
        long timeServerCompleted = System.currentTimeMillis();
        responseWriter.writeTimestamps(timeClientSent, timeServerReceived, timeServerCompleted);

        // response updates performed
        responseWriter.writeResponseUpdates(responseResults);

        // new groups
        responseWriter.writePages(pageList);

        // generate the HTML for each group and write it out
        // xmlResponse.WriteContents(testOpp, itemResponseGroups);
        _logger.info("<<<updateResponse Total ...  Time: " + (System.currentTimeMillis() - startTime)
                + " ms ThreadId: " + Thread.currentThread().getId());
        // close writing
        responseWriter.writeEnd();
    } catch (ReturnStatusException e) {
        _logger.error("Error in updateResponses : ", e);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getReturnStatus().getReason());
    } catch (Exception e) {
        _logger.error("Error in updateResponses : ", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "A problem was encountered while processing the request. You will be logged out.");
    }
}