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:com.code.savemarks.utils.Utils.java

/**
 * Deserialize an object from an HttpServletRequest input stream. Does not
 * throw any exceptions; instead, exceptions are logged and null is returned.
 * /*from ww  w .  j  a  va2s .co  m*/
 * @param req An HttpServletRequest that contains a serialized object.
 * @return An object instance, or null if an exception occurred.
 */
public static Object deserialize(HttpServletRequest req) {
    if (req.getContentLength() == 0) {
        log.severe("request content length is 0");
        return null;
    }
    try {
        byte[] bytesIn = new byte[req.getContentLength()];
        req.getInputStream().readLine(bytesIn, 0, bytesIn.length);
        return deserialize(bytesIn);
    } catch (IOException e) {
        log.log(Level.SEVERE, "Error deserializing task", e);
        return null; // don't retry task
    }
}

From source file:com.newatlanta.appengine.taskqueue.Deferred.java

/**
 * Deserialize an object from an HttpServletRequest input stream. Does not
 * throw any exceptions; instead, exceptions are logged and null is returned.
 *
 * @param req An HttpServletRequest that contains a serialized object.
 * @return An object instance, or null if an exception occurred.
 *///from   w  w  w.  j  a v a  2  s .  co m
private static Object deserialize(HttpServletRequest req) {
    if (req.getContentLength() == 0) {
        log.severe("request content length is 0");
        return null;
    }
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[8192];
        int len;
        while ((len = req.getInputStream().read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        return deserialize(baos.toByteArray());
    } catch (IOException e) {
        log.log(Level.SEVERE, "Error deserializing task", e);
        return null; // don't retry task
    }
}

From source file:com.gwtquickstarter.server.Deferred.java

/**
 * Deserialize an object from an HttpServletRequest input stream. Does not
 * throw any exceptions; instead, exceptions are logged and null is returned.
 *
 * @param req An HttpServletRequest that contains a serialized object.
 * @return An object instance, or null if an exception occurred.
 *//* www .  j a v a2 s. com*/
private static Object deserialize(HttpServletRequest req) {
    if (req.getContentLength() == 0) {
        log.severe("request content length is 0");
        return null;
    }
    try {
        byte[] bytesIn = new byte[req.getContentLength()];
        req.getInputStream().readLine(bytesIn, 0, bytesIn.length);
        return deserialize(bytesIn);
    } catch (IOException e) {
        log.log(Level.SEVERE, "Error deserializing task", e);
        return null; // don't retry task
    }
}

From source file:com.newatlanta.appengine.datastore.CachingDatastoreService.java

private static Object deserialize(HttpServletRequest req) throws Exception {
    if (req.getContentLength() == 0) {
        return null;
    }/*  w  w  w  .  j a v a  2  s.c o  m*/
    byte[] bytesIn = new byte[req.getContentLength()];
    req.getInputStream().readLine(bytesIn, 0, bytesIn.length);
    if (isDevelopment()) { // workaround for issue #2097
        bytesIn = decodeBase64(bytesIn);
    }
    ObjectInputStream objectIn = new ObjectInputStream(
            new BufferedInputStream(new ByteArrayInputStream(bytesIn)));
    try {
        return objectIn.readObject();
    } finally {
        objectIn.close();
    }
}

From source file:de.highbyte_le.weberknecht.request.RequestWrapper.java

/**
 * read URL encoded parameters (enctype="application/x-www-form-urlencoded") from HTTP method body (HTTP POST)
 * //from  w  w w.  jav  a  2  s  . c  om
 * <p>the default reader is used to read the method body.
 * The specified encoding is only used to decode the URL parameters, not to read the method body.
 * </p>
 * 
 * @param request
 * @param urlEncoding
 *       the character set encoding used to decode the URL encoded parameters.
 */
public static RequestWrapper createFromUrlEncodedContent(HttpServletRequest request, String urlEncoding)
        throws IOException {
    RequestWrapper wrapper = new RequestWrapper();
    int contentLength = request.getContentLength();
    if (logger.isDebugEnabled())
        logger.debug("content length is " + contentLength);

    if (contentLength > 0) {
        String query = extractQuery(request);

        if (logger.isDebugEnabled())
            logger.debug("query is '" + query + "'");

        int startIndex = 0;
        int i;
        do {
            i = query.indexOf("&", startIndex);
            String nameValue;
            if (i != -1) {
                nameValue = query.substring(startIndex, i);
            } else {
                nameValue = query.substring(startIndex, query.length());
            }

            int j = nameValue.indexOf("=");
            if (j != -1) {
                String name = URLDecoder.decode(nameValue.substring(0, j), urlEncoding);
                String value = URLDecoder.decode(nameValue.substring(j + 1, nameValue.length()), urlEncoding);
                wrapper.addParameter(name, value);
                logger.debug("createFromUrlEncodedContent(HttpServletRequest, String) - found parameter: "
                        + name + "=" + value);
            }

            startIndex = i + 1;
        } while (i != -1);
    }

    return wrapper;
}

From source file:com.jaspersoft.jasperserver.rest.RESTUtils.java

/**
 * Extract the attachments from the request and put the in the list of
 * input attachments of the service./*w ww.  j av  a  2s . com*/
 *
 * The method returns the currenst HttpServletRequest if the message is not
 * multipart, otherwise it returns a MultipartHttpServletRequest
 *
 *
 * @param service
 * @param hRequest
 */
public static HttpServletRequest extractAttachments(LegacyRunReportService service,
        HttpServletRequest hRequest) {
    //Check whether we're dealing with a multipart request
    MultipartResolver resolver = new CommonsMultipartResolver();

    // handles the PUT multipart requests
    if (isMultipartContent(hRequest) && hRequest.getContentLength() != -1) {
        MultipartHttpServletRequest mreq = resolver.resolveMultipart(hRequest);
        if (mreq != null && mreq.getFileMap().size() != 0) {
            Iterator iterator = mreq.getFileNames();
            String fieldName = null;
            while (iterator.hasNext()) {
                fieldName = (String) iterator.next();
                MultipartFile file = mreq.getFile(fieldName);
                if (file != null) {
                    DataSource ds = new MultipartFileDataSource(file);
                    service.getInputAttachments().put(fieldName, ds);
                }
            }
            if (log.isDebugEnabled()) {
                log.debug(service.getInputAttachments().size() + " attachments were extracted from the PUT");
            }
            return mreq;
        }
        // handles the POST multipart requests
        else {
            if (hRequest instanceof DefaultMultipartHttpServletRequest) {
                DefaultMultipartHttpServletRequest dmServletRequest = (DefaultMultipartHttpServletRequest) hRequest;

                Iterator iterator = ((DefaultMultipartHttpServletRequest) hRequest).getFileNames();
                String fieldName = null;
                while (iterator.hasNext()) {
                    fieldName = (String) iterator.next();
                    MultipartFile file = dmServletRequest.getFile(fieldName);
                    if (file != null) {
                        DataSource ds = new MultipartFileDataSource(file);
                        service.getInputAttachments().put(fieldName, ds);
                    }
                }
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(service.getInputAttachments().size() + " attachments were extracted from the POST");
    }
    return hRequest;

}

From source file:org.synchronoss.cloud.nio.multipart.example.web.MultipartController.java

static MultipartContext getMultipartContext(final HttpServletRequest request) {
    String contentType = request.getContentType();
    int contentLength = request.getContentLength();
    String charEncoding = request.getCharacterEncoding();
    return new MultipartContext(contentType, contentLength, charEncoding);
}

From source file:de.micromata.genome.logging.LogRequestDumpAttribute.java

/**
 * Gen http request dump.//from w  w  w .  j a  v  a 2s .  c  o m
 *
 * @param req the req
 * @return the string
 */
@SuppressWarnings("unchecked")
public static String genHttpRequestDump(HttpServletRequest req) {
    StringBuilder sb = new StringBuilder();

    sb.append("method: ").append(req.getMethod()).append('\n')//
            .append("requestURL: ").append(req.getRequestURL()).append('\n')//
            .append("servletPath: ").append(req.getServletPath()).append('\n')//
            .append("requestURI: ").append(req.getRequestURI()).append('\n') //
            .append("queryString: ").append(req.getQueryString()).append('\n') //
            .append("pathInfo: ").append(req.getPathInfo()).append('\n')//
            .append("contextPath: ").append(req.getContextPath()).append('\n') //
            .append("characterEncoding: ").append(req.getCharacterEncoding()).append('\n') //
            .append("localName: ").append(req.getLocalName()).append('\n') //
            .append("contentLength: ").append(req.getContentLength()).append('\n') //
    ;
    sb.append("Header:\n");
    for (Enumeration<String> en = req.getHeaderNames(); en.hasMoreElements();) {
        String hn = en.nextElement();
        sb.append("  ").append(hn).append(": ").append(req.getHeader(hn)).append("\n");
    }
    sb.append("Attr: \n");
    Enumeration en = req.getAttributeNames();
    for (; en.hasMoreElements();) {
        String k = (String) en.nextElement();
        Object v = req.getAttribute(k);
        sb.append("  ").append(k).append(": ").append(Objects.toString(v, StringUtils.EMPTY)).append('\n');
    }

    return sb.toString();
}

From source file:com.scistor.tab.auth.controller.HomeRestController.java

@RequestMapping(value = "/license", method = RequestMethod.POST, consumes = "text/plain")
public void postLicense(HttpServletRequest request) throws IOException {
    int size = request.getContentLength();
    if (size > KeyValue.MAX_SIZE) {

    }//from   w w w .j a v  a  2  s.c o m
    byte[] data = IOUtils.toByteArray(request.getInputStream(), size);
    License license = new LicenseValidator().decryptAndVerifyLicense(request.getInputStream());
    keyValueRepository.save(new KeyValue("license", data));
}

From source file:com.yahoo.parsec.web.ParsecServletRequestWrapper.java

/**
 * Constructs a request object wrapping the given request.
 *
 * @param request servlet request/*from   ww w  .j  a v a  2 s.  com*/
 */
public ParsecServletRequestWrapper(HttpServletRequest request) {
    super(request);
    int contentLength = request.getContentLength();
    contentStream = new ByteArrayOutputStream(contentLength >= 0 ? contentLength : 1024);
}