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.apache.shiro.grails.SavedHttpServletRequest.java

public SavedHttpServletRequest(HttpServletRequest request) {
    super(request);

    // Copy the content from the request input stream to a byte array.
    int contentLength = request.getContentLength();
    ByteArrayOutputStream output = new ByteArrayOutputStream(contentLength == -1 ? 1024 : contentLength);
    try {/*from  w w w . ja v  a 2s  .  c  om*/
        IOUtils.copy(request.getInputStream(), output);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // Save the byte array (the request content) and the request parameters.
    savedContent = output.toByteArray();
    parameterMap = new Hashtable(request.getParameterMap());
}

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

/**
 * Decode request//from   w  w  w  . j av a 2  s.co  m
 * @param req                    Request
 * @return                       Remoting packet
 * @throws Exception             General exception
 */
protected RemotingPacket decodeRequest(HttpServletRequest req) throws Exception {
    ByteBuffer reqBuffer = ByteBuffer.allocate(req.getContentLength());
    ServletUtils.copy(req.getInputStream(), reqBuffer.asOutputStream());
    reqBuffer.flip();
    RemotingPacket packet = (RemotingPacket) codecFactory.getSimpleDecoder().decode(null, reqBuffer);
    String path = req.getContextPath();
    if (path == null) {
        path = "";
    }
    if (req.getPathInfo() != null) {
        path += req.getPathInfo();
    }
    if (path.length() > 0 && path.charAt(0) == '/') {
        path = path.substring(1);
    }
    packet.setScopePath(path);
    reqBuffer.release();
    reqBuffer = null;
    return packet;
}

From source file:edu.slu.tpen.servlet.LoginServlet.java

/**
 * Handles the HTTP <code>POST</code> method by logging in using the given credentials.  Credentials
 * should be specified as a JSON object in the request body.  There is also a deprecated way of passing
 * the credentials as query parameters.//from   w w  w .j av  a  2 s .  c o  m
 *
 * @param req servlet request
 * @param resp servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {
        String mail = null, password = null;
        if (req.getContentLength() > 0) {
            String contentType = getBaseContentType(req);
            if (contentType.equals("application/json")) {
                ObjectMapper mapper = new ObjectMapper();
                Map<String, String> creds = mapper.readValue(req.getInputStream(),
                        new TypeReference<Map<String, String>>() {
                        });
                mail = creds.get("mail");
                password = creds.get("password");
            }
        } else {
            // Deprecated approach where user-name and password are passed on the query string.
            mail = req.getParameter("uname");
            password = req.getParameter("password");
        }
        if (mail != null && password != null) {
            User u = new User(mail, password);
            if (u.getUID() > 0) {
                HttpSession sess = req.getSession(true);
                sess.setAttribute("UID", u.getUID());
            } else {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
        } else if (mail == null && password == null) {
            // Passing null data indicates a logout.
            HttpSession sess = req.getSession(true);
            sess.removeAttribute("UID");
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            // Only supplied one of user-id and password.
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } catch (NoSuchAlgorithmException ex) {
        reportInternalError(resp, ex);
    }
}

From source file:com.ecyrd.jspwiki.dav.WikiDavServlet.java

@Override
public void doMkCol(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getContentLength() > 0) {
        response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Message may contain no body");
    } else {// ww w.  ja  v  a 2  s .  c om
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "JSPWiki is read-only.");
    }
}

From source file:org.craftercms.engine.http.impl.HttpProxyImpl.java

protected void copyOriginalRequestBody(HttpPost httpRequest, HttpServletRequest request) throws IOException {
    int contentLength = request.getContentLength();
    if (contentLength > 0) {
        String contentType = request.getContentType();
        InputStream content = request.getInputStream();

        httpRequest.setEntity(new InputStreamEntity(content, contentLength, ContentType.create(contentType)));
    }//w  w  w  .jav  a  2s.c  om
}

From source file:org.apache.shindig.social.core.oauth2.OAuth2NormalizedRequest.java

private String getBodyAsString(HttpServletRequest request) {
    if (request.getContentLength() == 0) {
        return "";
    }//ww  w .java2s  .  c om
    InputStream is = null;
    try {
        String line;
        StringBuilder sb = new StringBuilder();
        is = request.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        is.close();
        return sb.toString();
    } catch (IOException ioe) {
        LOG.logp(Level.WARNING, classname, "getBodyAsString", MessageKeys.INVALID_OAUTH, ioe);
        return null;
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:it.greenvulcano.gvesb.adapter.http.utils.DumpUtils.java

public static void dump(HttpServletRequest request, StringBuffer log) throws IOException {
    String hN;/*from w w w  .j  av a 2s. c o  m*/

    log.append("-- DUMP HttpServletRequest START").append("\n");
    log.append("Method             : ").append(request.getMethod()).append("\n");
    log.append("RequestedSessionId : ").append(request.getRequestedSessionId()).append("\n");
    log.append("Scheme             : ").append(request.getScheme()).append("\n");
    log.append("IsSecure           : ").append(request.isSecure()).append("\n");
    log.append("Protocol           : ").append(request.getProtocol()).append("\n");
    log.append("ContextPath        : ").append(request.getContextPath()).append("\n");
    log.append("PathInfo           : ").append(request.getPathInfo()).append("\n");
    log.append("QueryString        : ").append(request.getQueryString()).append("\n");
    log.append("RequestURI         : ").append(request.getRequestURI()).append("\n");
    log.append("RequestURL         : ").append(request.getRequestURL()).append("\n");
    log.append("ContentType        : ").append(request.getContentType()).append("\n");
    log.append("ContentLength      : ").append(request.getContentLength()).append("\n");
    log.append("CharacterEncoding  : ").append(request.getCharacterEncoding()).append("\n");

    log.append("---- Headers START\n");
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        hN = headerNames.nextElement();
        log.append("[" + hN + "]=");
        Enumeration<String> headers = request.getHeaders(hN);
        while (headers.hasMoreElements()) {
            log.append("[" + headers.nextElement() + "]");
        }
        log.append("\n");
    }
    log.append("---- Headers END\n");

    log.append("---- Body START\n");
    log.append(IOUtils.toString(request.getInputStream())).append("\n");
    log.append("---- Body END\n");

    log.append("-- DUMP HttpServletRequest END \n");
}

From source file:gwtupload.server.gae.BlobstoreUploadAction.java

@SuppressWarnings("serial")
@Override/* w  w  w. ja v  a  2 s. com*/
protected final AbstractUploadListener createNewListener(HttpServletRequest request) {
    return new MemCacheUploadListener(uploadDelay, request.getContentLength()) {
        int cont = 1;

        // In blobStore we cannot know the fileSize emulating progress
        public long getBytesRead() {
            return getContentLength() / (isFinished() ? 1 : 10 * (1 + (cont++ % 10)));
        }

        public long getContentLength() {
            return 100;
        }
    };
}

From source file:org.polymap.core.workbench.dnd.DndUploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.debug("POST-Request: " + request.getContentType() + ", length: " + request.getContentLength());
    OutputStream fout = null;/*from   www .  j av a2  s.c  om*/
    try {
        // copy content into temp file
        final String contentType = request.getContentType();
        File dir = getUploadTempDir(request.getSession());
        final String filename = request.getHeader("X-Filename");
        assert filename != null;
        final File f = new File(dir, filename + "_" + System.currentTimeMillis());
        fout = new FileOutputStream(f);
        IOUtils.copy(request.getInputStream(), fout);
        fout.close();
        log.debug("    uploaded: " + f.getAbsolutePath());

        // create event
        final DesktopDropEvent event = new FileDropEvent() {
            public InputStream getInputStream() throws IOException {
                return new BufferedInputStream(new FileInputStream(f));
            }

            public String getContentType() {
                return contentType != null ? contentType : "";
            }

            public String getFileName() {
                return filename;
            }
        };
        synchronized (uploads) {
            uploads.put(request.getSession().getId(), event);
        }
    } catch (Exception e) {
        log.error(e.getLocalizedMessage(), e);
        //throw new ServletException( e.getLocalizedMessage() );
        response.setStatus(409);
        response.getWriter().append(e.getLocalizedMessage()).flush();
        //sendError( 409, e.getLocalizedMessage() );
    } finally {
        IOUtils.closeQuietly(fout);
    }
}

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

/** {@inheritDoc} */
@Override/* w w  w .  j a va 2s  .c o m*/
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    //Continuation cont = ContinuationSupport.getContinuation(req, this);
    log.info("Service");

    if (req.getContentLength() == 0 || req.getContentType() == null
            || !req.getContentType().equals(APPLICATION_AMF)) {
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.getWriter().write("Gateway");
        resp.flushBuffer();
        return;
    }

    ByteBuffer reqBuffer = null;
    try {

        //req.getSession().getAttribute(REMOTING_CONNECTOR);

        reqBuffer = ByteBuffer.allocate(req.getContentLength());
        ServletUtils.copy(req.getInputStream(), reqBuffer.asOutputStream());
        reqBuffer.flip();

        // Connect to the server.
        VmPipeConnector connector = new VmPipeConnector();
        IoHandler handler = new Handler(req, resp);
        ConnectFuture connectFuture = connector.connect(new VmPipeAddress(5080), handler);
        connectFuture.join();
        IoSession session = connectFuture.getSession();
        session.setAttachment(resp);
        session.write(reqBuffer);

        ContinuationSupport.getContinuation(req, handler).suspend(1000);

    } catch (IOException e) {

        log.error(e);

    }
    log.info("End");
}