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:tds.student.web.handlers.TestResponseHandler.java

@SuppressWarnings("unused")
private void UpdateResponsesTemp(HttpServletRequest request, HttpServletResponse response)
        throws TDSSecurityException {
    if (request.getContentLength() == 0)
        return;/*from   ww w .  j  a v  a 2  s  .  c o  m*/
    // TODO Shajib: following line is commented temporarily

    // make sure the student is authenticated before doing anything
    checkAuthenticated();
    try {
        URL contentXmlUrl = this.getClass().getClassLoader().getResource("dummyUpdateResponse.xml");
        BufferedReader bfr = new BufferedReader(new FileReader(contentXmlUrl.getFile()));
        StringBuffer output = new StringBuffer();
        String line = null;
        while ((line = bfr.readLine()) != null) {
            output.append(line);
        }
        bfr.close();
        response.setContentType("text/xml");
        response.getOutputStream().write(output.toString().getBytes());
    } catch (Exception exp) {
        throw new ContentRequestException("Error loading dummy data: " + exp.toString());
    }
}

From source file:org.atomserver.server.servlet.BlockingFilter.java

private boolean contentNotBlockedByLength(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    boolean isWrite = request.getMethod().equals("POST") || request.getMethod().equals("PUT");
    if (isWrite && settings.getMaxContentLength() >= 0) {
        if (request.getContentLength() > settings.getMaxContentLength()) {
            String message = "TOO MUCH DATA :: (Content length exceeds the maximum length allowed.) :: "
                    + request.getRequestURI();
            setError(response, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, message);
            return false;
        }/*  w  w w.  j a  v a 2  s  .  com*/
    }
    return true;
}

From source file:org.apache.hadoop.gateway.dispatch.HttpClientDispatch.java

protected HttpEntity createRequestEntity(HttpServletRequest request) throws IOException {

    String contentType = request.getContentType();
    int contentLength = request.getContentLength();
    InputStream contentStream = request.getInputStream();

    HttpEntity entity;/* w w w .j  a  v  a 2 s.c  o m*/
    if (contentType == null) {
        entity = new InputStreamEntity(contentStream, contentLength);
    } else {
        entity = new InputStreamEntity(contentStream, contentLength, ContentType.parse(contentType));
    }

    if ("true".equals(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) {

        //Check if delegation token is supplied in the request
        boolean delegationTokenPresent = false;
        String queryString = request.getQueryString();
        if (queryString != null) {
            delegationTokenPresent = queryString.startsWith("delegation=")
                    || queryString.contains("&delegation=");
        }
        if (!delegationTokenPresent && getReplayBufferSize() > 0) {
            entity = new CappedBufferHttpEntity(entity, getReplayBufferSize() * 1024);
        }
    }

    return entity;
}

From source file:org.springframework.integration.http.DefaultInboundRequestMapper.java

private byte[] createPayloadFromInputStream(HttpServletRequest request) throws Exception {
    InputStream stream = request.getInputStream();
    int length = request.getContentLength();
    if (length == -1) {
        throw new ResponseStatusCodeException(HttpServletResponse.SC_LENGTH_REQUIRED);
    }/*from  ww  w  .jav a  2  s  .c  om*/
    if (logger.isDebugEnabled()) {
        logger.debug("received " + request.getMethod() + " request, "
                + "creating byte array payload with content lenth: " + length);
    }
    byte[] bytes = new byte[length];
    stream.read(bytes, 0, length);
    return bytes;
}

From source file:org.opencastproject.staticfiles.endpoint.StaticFileRestService.java

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)//  w w  w. j  a va  2 s  .  c  o m
@Path("")
@RestQuery(name = "postStaticFile", description = "Post a new static resource", bodyParameter = @RestParameter(description = "The static resource file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = {
        @RestResponse(description = "Returns the id of the uploaded static resource", responseCode = HttpServletResponse.SC_CREATED),
        @RestResponse(description = "No filename or file to upload found", responseCode = HttpServletResponse.SC_BAD_REQUEST),
        @RestResponse(description = "The upload size is too big", responseCode = HttpServletResponse.SC_BAD_REQUEST) }, returnDescription = "")
public Response postStaticFile(@Context HttpServletRequest request) {
    if (maxUploadSize > 0 && request.getContentLength() > maxUploadSize) {
        logger.warn("Preventing upload of static file as its size {} is larger than the max size allowed {}",
                request.getContentLength(), maxUploadSize);
        return Response.status(Status.BAD_REQUEST).build();
    }
    ProgressInputStream inputStream = null;
    try {
        String filename = null;
        if (ServletFileUpload.isMultipartContent(request)) {
            boolean isDone = false;
            for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) {
                FileItemStream item = iter.next();
                if (item.isFormField()) {
                    continue;
                } else {
                    logger.debug("Processing file item");
                    filename = item.getName();
                    inputStream = new ProgressInputStream(item.openStream());
                    inputStream.addPropertyChangeListener(new PropertyChangeListener() {
                        @Override
                        public void propertyChange(PropertyChangeEvent evt) {
                            long totalNumBytesRead = (Long) evt.getNewValue();
                            if (totalNumBytesRead > maxUploadSize) {
                                logger.warn("Upload limit of {} bytes reached, returning a bad request.",
                                        maxUploadSize);
                                throw new WebApplicationException(Status.BAD_REQUEST);
                            }
                        }
                    });
                    isDone = true;
                }
                if (isDone)
                    break;
            }
        } else {
            logger.warn("Request is not multi part request, returning a bad request.");
            return Response.status(Status.BAD_REQUEST).build();
        }

        if (filename == null) {
            logger.warn("Request was missing the filename, returning a bad request.");
            return Response.status(Status.BAD_REQUEST).build();
        }

        if (inputStream == null) {
            logger.warn("Request was missing the file, returning a bad request.");
            return Response.status(Status.BAD_REQUEST).build();
        }

        String uuid = staticFileService.storeFile(filename, inputStream);
        try {
            return Response.created(getStaticFileURL(uuid)).entity(uuid).build();
        } catch (NotFoundException e) {
            logger.error("Previous stored file with uuid {} couldn't beren found: {}", uuid,
                    ExceptionUtils.getStackTrace(e));
            return Response.serverError().build();
        }
    } catch (WebApplicationException e) {
        return e.getResponse();
    } catch (Exception e) {
        logger.error("Unable to store file because: {}", ExceptionUtils.getStackTrace(e));
        return Response.serverError().build();
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatch.java

protected HttpEntity createRequestEntity(HttpServletRequest request) throws IOException {

    String contentType = request.getContentType();
    int contentLength = request.getContentLength();
    InputStream contentStream = request.getInputStream();

    HttpEntity entity;/* w  w w.  j  a va2 s.  co  m*/
    if (contentType == null) {
        entity = new InputStreamEntity(contentStream, contentLength);
    } else {
        entity = new InputStreamEntity(contentStream, contentLength, ContentType.parse(contentType));
    }
    GatewayConfig config = (GatewayConfig) request.getServletContext()
            .getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
    if (config != null && config.isHadoopKerberosSecured()) {
        //Check if delegation token is supplied in the request
        boolean delegationTokenPresent = false;
        String queryString = request.getQueryString();
        if (queryString != null) {
            delegationTokenPresent = queryString.startsWith("delegation=")
                    || queryString.contains("&delegation=");
        }
        if (replayBufferSize < 0) {
            replayBufferSize = config.getHttpServerRequestBuffer();
        }
        if (!delegationTokenPresent && replayBufferSize > 0) {
            entity = new PartiallyRepeatableHttpEntity(entity, replayBufferSize);
        }
    }

    return entity;
}

From source file:com.woonoz.proxy.servlet.HttpPostRequestHandler.java

private HttpEntity createHttpEntity(HttpServletRequest request, HttpPost httpPost)
        throws FileUploadException, IOException {
    if (ServletFileUpload.isMultipartContent(request)) {
        return createMultipartEntity(request, httpPost);
    } else {/* w  w  w .java  2s .c o  m*/
        return new BufferedHttpEntity(
                new InputStreamEntity(request.getInputStream(), request.getContentLength()));
    }
}

From source file:io.vertigo.struts2.impl.multipartrequest.Servlet3MultiPartRequest.java

@Override
protected List<FileItem> parseRequest(final HttpServletRequest servletRequest, final String saveDir)
        throws FileUploadException {
    // gestion de la configuration struts.multipart.maxSize
    if (maxSize >= 0) {
        final int requestSize = servletRequest.getContentLength();
        if (requestSize != -1 && requestSize > maxSize) {
            throw new FileUploadBase.SizeLimitExceededException(String.format(
                    "the request was rejected because its size (%s) exceeds the configured maximum (%s)",
                    Long.valueOf(requestSize), Long.valueOf(maxSize)), requestSize, maxSize);
        }//from  w  w w  . j  a va 2 s .  com
    }
    // gestion du contenu de la requete
    try {
        final Collection<Part> parts = servletRequest.getParts();
        final List<FileItem> ret = new ArrayList<>(parts.size());
        for (final Part part : parts) {
            ret.add(new PartFileItem(part, saveDir));
        }
        return ret;
    } catch (IOException | ServletException e) {
        throw new FileUploadException("Impossible de rcuprer les fichiers de la requte en mode Servlet 3",
                e);
    }
}

From source file:es.tid.cep.esperanza.Events.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w  w w.j  a v  a 2s .  co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("events doPost");
    PrintWriter out = response.getWriter();
    try {
        response.setContentType("application/json;charset=UTF-8");
        ServletInputStream sis = request.getInputStream();
        byte[] b = new byte[request.getContentLength()];
        sis.read(b, 0, b.length);
        sis.close();
        String eventText = new String(b);
        logger.debug("event as text:" + eventText);
        org.json.JSONObject jo = new JSONObject(eventText);
        logger.debug("event as JSONObject: " + jo);
        Map<String, Object> otro = Utils.JSONObject2Map(jo);
        logger.debug("event as map: " + otro);
        epService.getEPRuntime().sendEvent(otro, "iotEvent");
        logger.debug("event was sent: " + otro);
    } catch (JSONException je) {
        logger.debug("error: " + je.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":\"%s\"}\n", je.getMessage());

    } finally {
        out.close();
    }
}

From source file:org.bedework.notifier.web.MethodBase.java

protected Map<?, ?> getJson(final HttpServletRequest req, final HttpServletResponse resp) throws NoteException {
    final int len = req.getContentLength();
    if (len == 0) {
        return null;
    }/*from  w ww.  j  a  v a 2  s .c  o m*/

    try {
        return (Map<?, ?>) om.readValue(req.getInputStream(), Object.class);
    } catch (Throwable t) {
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw new NoteException(t);
    }
}