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.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter.java

private HttpResponse forward(HttpClient httpclient, String verb, String uri, HttpServletRequest request,
        MultiValueMap<String, String> headers, MultiValueMap<String, String> params, InputStream requestEntity)
        throws Exception {
    Map<String, Object> info = this.helper.debug(verb, uri, headers, params, requestEntity);
    URL host = RequestContext.getCurrentContext().getRouteHost();
    HttpHost httpHost = getHttpHost(host);
    uri = StringUtils.cleanPath((host.getPath() + uri).replaceAll("/{2,}", "/"));
    int contentLength = request.getContentLength();
    InputStreamEntity entity = new InputStreamEntity(requestEntity, contentLength,
            request.getContentType() != null ? ContentType.create(request.getContentType()) : null);

    HttpRequest httpRequest = buildHttpRequest(verb, uri, entity, headers, params);
    try {//from w w w  . ja  va 2  s  .  co  m
        log.debug(httpHost.getHostName() + " " + httpHost.getPort() + " " + httpHost.getSchemeName());
        HttpResponse zuulResponse = forwardRequest(httpclient, httpHost, httpRequest);
        this.helper.appendDebug(info, zuulResponse.getStatusLine().getStatusCode(),
                revertHeaders(zuulResponse.getAllHeaders()));
        return zuulResponse;
    } 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.apache.marmotta.platform.core.webservices.resource.MetaWebService.java

public Response putMeta(String uri, String mimetype, HttpServletRequest request) throws HttpErrorException {
    try {/*from w  w  w  .j  a  va  2s  .c  om*/
        // create parser
        RDFFormat parser = kiWiIOService.getParser(mimetype);
        if (parser == null) {
            return status(Status.UNSUPPORTED_MEDIA_TYPE)
                    .header(CONTENT_TYPE, appendMetaTypes(kiWiIOService.getProducedTypes()))
                    .entity("media type " + mimetype + " not supported").build();
        }
        if (request.getContentLength() == 0) {
            throw new HttpErrorException(Status.BAD_REQUEST, uri, "content may not be empty in resource update",
                    ImmutableMap.of(ACCEPT, mimetype));
        }

        // a intercepting connection that filters out all triples that have
        // the wrong subject
        InterceptingRepositoryConnection connection = new InterceptingRepositoryConnectionWrapper(
                sesameService.getRepository(), sesameService.getConnection());
        //RepositoryConnection connection = sesameService.getConnection();
        try {
            connection.begin();
            final Resource subject = connection.getValueFactory().createURI(uri);

            connection.addRepositoryConnectionInterceptor(new ResourceSubjectMetadata(subject));

            // delete all triples for given subject
            connection.remove(subject, null, null, (Resource) null);

            // add RDF data from input to the suject
            connection.add(request.getReader(), configurationService.getBaseUri(), parser,
                    contextService.getDefaultContext());
        } finally {
            connection.commit();
            connection.close();
        }
        return ok().build();
    } catch (URISyntaxException e) {
        throw new HttpErrorException(Status.INTERNAL_SERVER_ERROR, uri, "invalid target context",
                ImmutableMap.of(ACCEPT, mimetype));
    } catch (IOException | RDFParseException e) {
        throw new HttpErrorException(Status.NOT_ACCEPTABLE, uri, "could not parse request body",
                ImmutableMap.of(ACCEPT, mimetype));
    } catch (RepositoryException e) {
        throw new HttpErrorException(Status.INTERNAL_SERVER_ERROR, request, e);
    }
}

From source file:org.sigmah.server.servlet.FileServlet.java

/**
 * See {@link ServletMethod#UPLOAD} for JavaDoc.
 * /*from   w  ww .  ja  v a 2  s.  c o m*/
 * @param request
 *          The HTTP request containing the file id parameter.
 * @param response
 *          The HTTP response on which the file content is written.
 * @param context
 *          The execution context.
 * @throws Exception
 *           If an error occurs during process.
 */
protected void upload(final HttpServletRequest request, final HttpServletResponse response,
        final ServletExecutionContext context) throws Exception {

    // --
    // Verify content length.
    // --

    final int contentLength = request.getContentLength();

    if (contentLength == 0) {
        LOG.error("Empty file.");
        throw new StatusServletException(Response.SC_NO_CONTENT);
    }

    if (contentLength > FileUploadUtils.MAX_UPLOAD_FILE_SIZE) {
        LOG.error("File's size is too big to be uploaded (size: {}, maximum : {}).", contentLength,
                FileUploadUtils.MAX_UPLOAD_FILE_SIZE);
        throw new StatusServletException(Response.SC_REQUEST_ENTITY_TOO_LARGE);
    }

    final String fileName = generateUniqueName();

    // --
    // Writing the file.
    // --

    final MultipartRequest multipartRequest = new MultipartRequest(request);
    final long size = this.processUpload(multipartRequest, response, fileName, false);
    final Map<String, String> properties = multipartRequest.getProperties();

    conflicts.searchForFileAddConflicts(properties, context.getLanguage(), context.getUser());

    // --
    // Create the associated entries in File and FileVersion tables.
    // --

    final Integer fileId = fileDAO.saveOrUpdate(properties, fileName, (int) size);
    final FileVersion fileVersion = fileDAO.getLastVersion(fileId);

    // --
    // If a monitored point must be created.
    // --

    final MonitoredPoint monitoredPoint = parseMonitoredPoint(properties);

    if (monitoredPoint != null) {

        final Integer projectId = ClientUtils.asInt(properties.get(FileUploadUtils.DOCUMENT_PROJECT));
        final Project project = projectDAO.findById(projectId);

        monitoredPoint.setFile(fileDAO.findById(fileId));

        MonitoredPointList list = project.getPointsList();

        if (list == null) {
            list = new MonitoredPointList();
            project.setPointsList(list);
        }

        if (list.getPoints() == null) {
            list.setPoints(new ArrayList<MonitoredPoint>());
        }

        // Adds the point to the list.
        list.addMonitoredPoint(monitoredPoint);

        // Saves monitored point.
        monitoredPointDAO.persist(monitoredPoint, context.getUser());
    }

    final MonitoredPointDTO monitoredPointDTO = mapper().map(monitoredPoint, new MonitoredPointDTO(),
            MonitoredPointDTO.Mode.BASE);
    final FileVersionDTO fileVersionDTO = mapper().map(fileVersion, new FileVersionDTO());

    response.setContentType(FileType.HTML.getContentType());
    response.getWriter().write(FileUploadResponse.serialize(fileVersionDTO, monitoredPointDTO));
}

From source file:org.bedework.eventreg.web.AbstractController.java

/**
 * @param req request/*w  w w  . j  ava  2 s  . co m*/
 */
public void dumpRequest(final HttpServletRequest req) {
    try {
        @SuppressWarnings("unchecked")
        final Enumeration<String> names = req.getParameterNames();

        final String title = "Request parameters";

        debug(title + " - global info and uris");
        debug("getRequestURI = " + req.getRequestURI());
        debug("getRemoteUser = " + req.getRemoteUser());
        debug("getRequestedSessionId = " + req.getRequestedSessionId());
        debug("HttpUtils.getRequestURL(req) = " + req.getRequestURL());
        debug("query=" + req.getQueryString());
        debug("contentlen=" + req.getContentLength());
        debug("request=" + req);
        debug("parameters:");

        debug(title);

        while (names.hasMoreElements()) {
            final String key = names.nextElement();
            final String[] vals = req.getParameterValues(key);
            for (final String val : vals) {
                debug("  " + key + " = \"" + val + "\"");
            }
        }
    } catch (final Throwable t) {
        error(t);
    }
}

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(//  www. j  a  v  a2 s  .c om
            new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
    return eProxyRequest;
}

From source file:org.wings.session.SessionServlet.java

/**
 * this method references to//ww  w. jav  a 2 s . c  o m
 * {@link #doGet(HttpServletRequest, HttpServletResponse)}
 */
public final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
    //value chosen to limit denial of service
    if (req.getContentLength() > getSession().getMaxContentLength() * 1024) {
        res.setContentType("text/html");
        ServletOutputStream out = res.getOutputStream();
        out.println("<html><head><meta http-equiv=\"expires\" content=\"0\"><title>Too big</title></head>");
        out.println("<body><h1>Error - content length &gt; " + getSession().getMaxContentLength() + "k");
        out.println("</h1></body></html>");
    } else {
        doGet(req, res);
    }
    // sollte man den obigen Block nicht durch folgende Zeile ersetzen?
    //throw new RuntimeException("this method must never be called!");
    // bsc: Wieso?
}

From source file:org.sakaiproject.tool.assessment.ui.servlet.delivery.UploadAudioMediaServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    boolean mediaIsValid = true;
    ServletContext context = super.getServletContext();
    String repositoryPath = (String) context.getAttribute("FILEUPLOAD_REPOSITORY_PATH");
    String saveToDb = (String) context.getAttribute("FILEUPLOAD_SAVE_MEDIA_TO_DB");

    log.debug("req content length =" + req.getContentLength());
    log.debug("req content type =" + req.getContentType());

    // we get media location in assessmentXXX/questionXXX/agentId/audio_assessmentGradingIdXXX.au form
    String suffix = req.getParameter("suffix");
    if (suffix == null || ("").equals(suffix))
        suffix = "au";
    String mediaLocation = req.getParameter("media") + "." + suffix;
    log.debug("****media location=" + mediaLocation);
    String response = "empty";

    // test for nonemptiness first
    if (mediaLocation != null && !(mediaLocation.trim()).equals("")) {
        File repositoryPathDir = new File(repositoryPath);
        mediaLocation = repositoryPathDir.getCanonicalPath() + "/" + mediaLocation;
        File mediaFile = new File(mediaLocation);

        if (mediaFile.getCanonicalPath().equals(mediaLocation)) {
            File mediaDir = mediaFile.getParentFile();
            if (!mediaDir.exists())
                mediaDir.mkdirs();//from w  w w.  j a v  a  2 s  .c  o  m
            //log.debug("*** directory exist="+mediaDir.exists());
            mediaIsValid = writeToFile(req, mediaLocation);
        } else {
            log.debug("****Error in file paths " + mediaFile.getCanonicalPath() + " is not equal to "
                    + mediaLocation);
            mediaIsValid = false;
        }

        //this is progess for SAK-5792, comment is out for now
        //zip_mediaLocation = createZipFile(mediaDir.getPath(), mediaLocation);
    }

    //#2 - record media as question submission
    if (mediaIsValid) {
        // note that this delivery bean is empty. this is not the same one created for the
        // user during take assessment.
        try {
            response = submitMediaAsAnswer(req, mediaLocation, saveToDb);
            log.info(
                    "Audio has been saved and submitted as answer to the question. Any old recordings have been removed from the system.");
        } catch (Exception ex) {
            log.info(ex.getMessage());
        }
    }
    res.setContentType("text/plain");
    res.setContentLength(response.length());
    PrintWriter out = res.getWriter();
    out.println(response);
    out.close();
    out.flush();
}

From source file:org.geoserver.filters.LoggingFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    String message = "";
    String body = null;//from  w  w w.j ava  2 s .co  m
    String path = "";

    if (enabled) {
        if (req instanceof HttpServletRequest) {
            HttpServletRequest hreq = (HttpServletRequest) req;

            path = hreq.getRemoteHost() + " \"" + hreq.getMethod() + " " + hreq.getRequestURI();
            if (hreq.getQueryString() != null) {
                path += "?" + hreq.getQueryString();
            }
            path += "\"";

            message = "" + path;
            message += " \"" + noNull(hreq.getHeader("User-Agent"));
            message += "\" \"" + noNull(hreq.getHeader("Referer")) + "\" ";
            message += "\" \"" + noNull(hreq.getHeader("Content-type")) + "\" ";

            if (logBodies && (hreq.getMethod().equals("PUT") || hreq.getMethod().equals("POST"))) {
                message += " request-size: " + hreq.getContentLength();
                message += " body: ";

                String encoding = hreq.getCharacterEncoding();
                if (encoding == null) {
                    // the default encoding for HTTP 1.1
                    encoding = "ISO-8859-1";
                }
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] bytes;
                try (InputStream is = hreq.getInputStream()) {
                    IOUtils.copy(is, bos);
                    bytes = bos.toByteArray();

                    body = new String(bytes, encoding);
                }

                req = new BufferedRequestWrapper(hreq, encoding, bytes);
            }
        } else {
            message = "" + req.getRemoteHost() + " made a non-HTTP request";
        }

        logger.info(message + (body == null ? "" : "\n" + body + "\n"));
        long startTime = System.currentTimeMillis();
        chain.doFilter(req, res);
        long requestTime = System.currentTimeMillis() - startTime;
        logger.info(path + " took " + requestTime + "ms");
    } else {
        chain.doFilter(req, res);
    }

}

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

private CloseableHttpResponse forward(CloseableHttpClient httpclient, String verb, String uri,
        HttpServletRequest request, MultiValueMap<String, String> headers, MultiValueMap<String, String> params,
        InputStream requestEntity) throws Exception {
    Map<String, Object> info = this.helper.debug(verb, uri, headers, params, requestEntity);
    URL host = RequestContext.getCurrentContext().getRouteHost();
    HttpHost httpHost = getHttpHost(host);
    uri = StringUtils.cleanPath((host.getPath() + uri).replaceAll("/{2,}", "/"));
    HttpRequest httpRequest;/*from   w  ww  .j a  v  a2  s  .  co  m*/
    int contentLength = request.getContentLength();
    InputStreamEntity entity = new InputStreamEntity(requestEntity, contentLength,
            request.getContentType() != null ? ContentType.create(request.getContentType()) : null);
    switch (verb.toUpperCase()) {
    case "POST":
        HttpPost httpPost = new HttpPost(uri + this.helper.getQueryString(params));
        httpRequest = httpPost;
        httpPost.setEntity(entity);
        break;
    case "PUT":
        HttpPut httpPut = new HttpPut(uri + this.helper.getQueryString(params));
        httpRequest = httpPut;
        httpPut.setEntity(entity);
        break;
    case "PATCH":
        HttpPatch httpPatch = new HttpPatch(uri + this.helper.getQueryString(params));
        httpRequest = httpPatch;
        httpPatch.setEntity(entity);
        break;
    default:
        httpRequest = new BasicHttpRequest(verb, uri + this.helper.getQueryString(params));
        log.debug(uri + this.helper.getQueryString(params));
    }
    try {
        httpRequest.setHeaders(convertHeaders(headers));
        log.debug(httpHost.getHostName() + " " + httpHost.getPort() + " " + httpHost.getSchemeName());
        CloseableHttpResponse zuulResponse = forwardRequest(httpclient, httpHost, httpRequest);
        RequestContext.getCurrentContext().set("zuulResponse", zuulResponse);
        this.helper.appendDebug(info, zuulResponse.getStatusLine().getStatusCode(),
                revertHeaders(zuulResponse.getAllHeaders()));
        return zuulResponse;
    } 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.apache.struts.extras.SecureJakartaStreamMultiPartRequest.java

/**
 * Defines whether the request allowed based on content length.
 *
 * @param request/*w  ww  .ja  va  2  s .c o m*/
 * @return
 */
private boolean isRequestSizePermitted(HttpServletRequest request) {
    // if maxSize is specified as -1, there is no sanity check and it's
    // safe to return true for any request, delegating the failure
    // checks later in the upload process.
    if (maxSize == -1 || request == null)
        return true;

    return request.getContentLength() < maxSize;
}