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.catalina.valves.ExtendedAccessLogValve.java

/**
 * Get app specific data./* w  ww. j  a v a2  s.  c  om*/
 * @param fieldInfo The field to decode
 * @param request Where we will pull the data from.
 * @return The appropriate value
 */
private String getAppSpecific(FieldInfo fieldInfo, Request request) {

    ServletRequest sr = request.getRequest();
    HttpServletRequest hsr = null;
    if (sr instanceof HttpServletRequest)
        hsr = (HttpServletRequest) sr;

    switch (fieldInfo.xType) {
    case FieldInfo.X_PARAMETER:
        return wrap(urlEncode(sr.getParameter(fieldInfo.value)));
    case FieldInfo.X_REQUEST:
        return wrap(sr.getAttribute(fieldInfo.value));
    case FieldInfo.X_SESSION:
        HttpSession session = null;
        if (hsr != null) {
            session = hsr.getSession(false);
            if (session != null)
                return wrap(session.getAttribute(fieldInfo.value));
        }
        break;
    case FieldInfo.X_COOKIE:
        Cookie[] c = hsr.getCookies();
        for (int i = 0; c != null && i < c.length; i++) {
            if (fieldInfo.value.equals(c[i].getName())) {
                return wrap(c[i].getValue());
            }
        }
    case FieldInfo.X_APP:
        return wrap(request.getContext().getServletContext().getAttribute(fieldInfo.value));
    case FieldInfo.X_SERVLET_REQUEST:
        if (fieldInfo.location == FieldInfo.X_LOC_AUTHTYPE) {
            return wrap(hsr.getAuthType());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REMOTEUSER) {
            return wrap(hsr.getRemoteUser());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONID) {
            return wrap(hsr.getRequestedSessionId());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDFROMCOOKIE) {
            return wrap("" + hsr.isRequestedSessionIdFromCookie());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDVALID) {
            return wrap("" + hsr.isRequestedSessionIdValid());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CONTENTLENGTH) {
            return wrap("" + hsr.getContentLength());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CHARACTERENCODING) {
            return wrap(hsr.getCharacterEncoding());
        } else if (fieldInfo.location == FieldInfo.X_LOC_LOCALE) {
            return wrap(hsr.getLocale());
        } else if (fieldInfo.location == FieldInfo.X_LOC_PROTOCOL) {
            return wrap(hsr.getProtocol());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SCHEME) {
            return wrap(hsr.getScheme());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SECURE) {
            return wrap("" + hsr.isSecure());
        }
        break;
    default:
        ;
    }

    return "-";

}

From source file:org.georchestra.security.Proxy.java

private HttpRequestBase makeRequest(HttpServletRequest request, RequestType requestType, String sURL)
        throws IOException {
    HttpRequestBase targetRequest;/*from w w w  .jav a 2 s.  c  om*/
    try {
        // Split URL
        URL url = new URL(sURL);
        URI uri = buildUri(url);

        switch (requestType) {
        case GET: {
            logger.debug("New request is: " + sURL + "\nRequest is GET");

            HttpGet get = new HttpGet(uri);
            targetRequest = get;
            break;
        }
        case POST: {
            logger.debug("New request is: " + sURL + "\nRequest is POST");

            HttpPost post = new HttpPost(uri);
            HttpEntity entity;
            request.setCharacterEncoding("UTF8");
            if (isFormContentType(request)) {
                logger.debug("Post is recognized as a form post.");
                List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
                    String name = (String) e.nextElement();
                    String[] v = request.getParameterValues(name);
                    for (String value : v) {
                        NameValuePair nv = new BasicNameValuePair(name, value);
                        parameters.add(nv);
                    }
                }
                String charset = request.getCharacterEncoding();
                try {
                    Charset.forName(charset);
                } catch (Throwable t) {
                    charset = null;
                }
                if (charset == null) {
                    charset = defaultCharset;
                }
                entity = new UrlEncodedFormEntity(parameters, charset);
                post.setEntity(entity);

            } else {
                logger.debug("Post is NOT recognized as a form post. (Not an error, just a comment)");
                int contentLength = request.getContentLength();
                ServletInputStream inputStream = request.getInputStream();
                entity = new InputStreamEntity(inputStream, contentLength);
            }
            post.setEntity(entity);
            targetRequest = post;
            break;
        }
        case TRACE: {
            logger.debug("New request is: " + sURL + "\nRequest is TRACE");

            HttpTrace post = new HttpTrace(uri);

            targetRequest = post;
            break;
        }
        case OPTIONS: {
            logger.debug("New request is: " + sURL + "\nRequest is OPTIONS");

            HttpOptions post = new HttpOptions(uri);

            targetRequest = post;
            break;
        }
        case HEAD: {
            logger.debug("New request is: " + sURL + "\nRequest is HEAD");

            HttpHead post = new HttpHead(uri);

            targetRequest = post;
            break;
        }
        case PUT: {
            logger.debug("New request is: " + sURL + "\nRequest is PUT");

            HttpPut put = new HttpPut(uri);

            put.setEntity(new InputStreamEntity(request.getInputStream(), request.getContentLength()));

            targetRequest = put;
            break;
        }
        case DELETE: {
            logger.debug("New request is: " + sURL + "\nRequest is DELETE");

            HttpDelete delete = new HttpDelete(uri);

            targetRequest = delete;
            break;
        }
        default: {
            String msg = requestType + " not yet supported";
            logger.error(msg);
            throw new IllegalArgumentException(msg);
        }

        }
    } catch (URISyntaxException e) {
        logger.error("ERROR creating URI from " + sURL, e);
        throw new IOException(e);
    }

    return targetRequest;
}

From source file:org.asynchttpclient.test.EchoHandler.java

@Override
public void handle(String pathInContext, Request request, HttpServletRequest httpRequest,
        HttpServletResponse httpResponse) throws IOException, ServletException {

    LOGGER.debug("Echo received request {} on path {}", request, pathInContext);

    if (httpRequest.getHeader("X-HEAD") != null) {
        httpResponse.setContentLength(1);
    }//from  w  w w  .j a  v  a2  s  . c o m

    if (httpRequest.getHeader("X-ISO") != null) {
        httpResponse.setContentType(TestUtils.TEXT_HTML_CONTENT_TYPE_WITH_ISO_8859_1_CHARSET);
    } else {
        httpResponse.setContentType(TestUtils.TEXT_HTML_CONTENT_TYPE_WITH_UTF_8_CHARSET);
    }

    if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
        httpResponse.addHeader("Allow", "GET,HEAD,POST,OPTIONS,TRACE");
    }

    Enumeration<String> e = httpRequest.getHeaderNames();
    String headerName;
    while (e.hasMoreElements()) {
        headerName = e.nextElement();
        if (headerName.startsWith("LockThread")) {
            final int sleepTime = httpRequest.getIntHeader(headerName);
            try {
                Thread.sleep(sleepTime == -1 ? 40 : sleepTime * 1000);
            } catch (InterruptedException ex) {
                //
            }
        }

        if (headerName.startsWith("X-redirect")) {
            httpResponse.sendRedirect(httpRequest.getHeader("X-redirect"));
            return;
        }
        httpResponse.addHeader("X-" + headerName, httpRequest.getHeader(headerName));
    }

    String pathInfo = httpRequest.getPathInfo();
    if (pathInfo != null)
        httpResponse.addHeader("X-pathInfo", pathInfo);

    String queryString = httpRequest.getQueryString();
    if (queryString != null)
        httpResponse.addHeader("X-queryString", queryString);

    httpResponse.addHeader("X-KEEP-ALIVE", httpRequest.getRemoteAddr() + ":" + httpRequest.getRemotePort());

    Cookie[] cs = httpRequest.getCookies();
    if (cs != null) {
        for (Cookie c : cs) {
            httpResponse.addCookie(c);
        }
    }

    Enumeration<String> i = httpRequest.getParameterNames();
    if (i.hasMoreElements()) {
        StringBuilder requestBody = new StringBuilder();
        while (i.hasMoreElements()) {
            headerName = i.nextElement();
            httpResponse.addHeader("X-" + headerName, httpRequest.getParameter(headerName));
            requestBody.append(headerName);
            requestBody.append("_");
        }

        if (requestBody.length() > 0) {
            String body = requestBody.toString();
            httpResponse.getOutputStream().write(body.getBytes());
        }
    }

    String requestBodyLength = httpRequest.getHeader("X-" + CONTENT_LENGTH);

    if (requestBodyLength != null) {
        byte[] requestBodyBytes = IOUtils.toByteArray(httpRequest.getInputStream());
        int total = requestBodyBytes.length;

        httpResponse.addIntHeader("X-" + CONTENT_LENGTH, total);
        String md5 = TestUtils.md5(requestBodyBytes, 0, total);
        httpResponse.addHeader(CONTENT_MD5.toString(), md5);

        httpResponse.getOutputStream().write(requestBodyBytes, 0, total);
    } else {
        int size = 16384;
        if (httpRequest.getContentLength() > 0) {
            size = httpRequest.getContentLength();
        }
        if (size > 0) {
            int read = 0;
            while (read > -1) {
                byte[] bytes = new byte[size];
                read = httpRequest.getInputStream().read(bytes);
                if (read > 0) {
                    httpResponse.getOutputStream().write(bytes, 0, read);
                }
            }
        }
    }

    request.setHandled(true);
    httpResponse.getOutputStream().flush();
    // FIXME don't always close, depends on the test, cf ReactiveStreamsTest
    httpResponse.getOutputStream().close();
}

From source file:it.geosolutions.servicebox.FileUploadCallback.java

/**
 * Handle a POST request//from  ww  w  .  ja  v a 2  s .  c o m
 * 
 * @param request
 * @param response
 * 
 * @return CallbackResult
 * 
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public ServiceBoxActionParameters onPost(HttpServletRequest request, HttpServletResponse response,
        ServiceBoxActionParameters callbackResult) throws IOException {

    // Get items if already initialized
    List<FileItem> items = null;
    if (callbackResult == null) {
        callbackResult = new ServiceBoxActionParameters();
    } else {
        items = callbackResult.getItems();
    }

    String temp = callbackConfiguration.getTempFolder();
    int buffSize = callbackConfiguration.getBuffSize();
    int itemSize = 0;
    long maxSize = 0;
    String itemName = null;
    boolean fileTypeMatch = true;

    File tempDir = new File(temp);

    try {
        if (items == null && ServletFileUpload.isMultipartContent(request) && tempDir != null
                && tempDir.exists()) {
            // items are not initialized. Read it from the request

            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

            /*
             * Set the size threshold, above which content will be stored on
             * disk.
             */
            fileItemFactory.setSizeThreshold(buffSize); // 1 MB

            /*
             * Set the temporary directory to store the uploaded files of
             * size above threshold.
             */
            fileItemFactory.setRepository(tempDir);

            ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

            /*
             * Parse the request
             */
            items = uploadHandler.parseRequest(request);

        }

        // Read items
        if (items != null) {

            itemSize = items.size();
            callbackResult.setItems(items);
            if (itemSize <= this.callbackConfiguration.getMaxItems()) {
                // only if item size not exceeded max
                for (FileItem item : items) {
                    itemName = item.getName();
                    if (item.getSize() > maxSize) {
                        maxSize = item.getSize();
                        if (maxSize > this.callbackConfiguration.getMaxSize()) {
                            // max size exceeded
                            break;
                        } else if (this.callbackConfiguration.getFileTypePatterns() != null) {
                            fileTypeMatch = false;
                            int index = 0;
                            while (!fileTypeMatch
                                    && index < this.callbackConfiguration.getFileTypePatterns().size()) {
                                Pattern pattern = this.callbackConfiguration.getFileTypePatterns().get(index++);
                                fileTypeMatch = pattern.matcher(itemName).matches();
                            }
                            if (!fileTypeMatch) {
                                break;
                            }
                        }
                    }
                }
            }
        } else {
            itemSize = 1;
            maxSize = request.getContentLength();
            // TODO: Handle file type
        }

    } catch (Exception ex) {
        if (LOGGER.isLoggable(Level.SEVERE))
            LOGGER.log(Level.SEVERE, "Error encountered while parsing the request");

        response.setContentType("text/html");

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("success", false);
        jsonObj.put("errorMessage", ex.getLocalizedMessage());

        Utilities.writeResponse(response, jsonObj.toString(), LOGGER);

    }

    // prepare and send error if exists
    boolean error = false;
    int errorCode = -1;
    String message = null;
    Map<String, Object> errorDetails = null;
    if (itemSize > this.callbackConfiguration.getMaxItems()) {
        errorDetails = new HashMap<String, Object>();
        error = true;
        errorDetails.put("expected", this.callbackConfiguration.getMaxItems());
        errorDetails.put("found", itemSize);
        errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.MAX_ITEMS.ordinal();
        message = "Max items size exceeded (expected: '" + this.callbackConfiguration.getMaxItems()
                + "', found: '" + itemSize + "').";
    } else if (maxSize > this.callbackConfiguration.getMaxSize()) {
        errorDetails = new HashMap<String, Object>();
        error = true;
        errorDetails.put("expected", this.callbackConfiguration.getMaxSize());
        errorDetails.put("found", maxSize);
        errorDetails.put("item", itemName);
        errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.MAX_ITEM_SIZE.ordinal();
        message = "Max item size exceeded (expected: '" + this.callbackConfiguration.getMaxSize()
                + "', found: '" + maxSize + "' on item '" + itemName + "').";
    } else if (fileTypeMatch == false) {
        errorDetails = new HashMap<String, Object>();
        error = true;
        String expected = this.callbackConfiguration.getFileTypes();
        errorDetails.put("expected", expected);
        errorDetails.put("found", itemName);
        errorDetails.put("item", itemName);
        errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.ITEM_TYPE.ordinal();
        message = "File type not maches with known file types: (expected: '" + expected + "', item '" + itemName
                + "').";
    }
    if (error) {
        callbackResult.setSuccess(false);
        Utilities.writeError(response, errorCode, errorDetails, message, LOGGER);
    } else {
        callbackResult.setSuccess(true);
    }

    return callbackResult;
}

From source file:io.hops.hopsworks.api.kibana.KibanaProxyServlet.java

/**
 * Authorize user to access particular index.
 *
 * @param servletRequest/*  w ww . j av a  2s  .c o  m*/
 * @param servletResponse
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    if (servletRequest.getUserPrincipal() == null) {
        servletResponse.sendError(401, "User is not logged in");
        return;
    }
    String email = servletRequest.getUserPrincipal().getName();

    if (servletRequest.getParameterMap().containsKey("projectId")) {
        String projectId = servletRequest.getParameterMap().get("projectId")[0];
        try {
            ProjectDTO projectDTO = projectController.getProjectByID(Integer.parseInt(projectId));
            currentProjects.put(email, projectDTO.getProjectName());
        } catch (ProjectException ex) {
            LOG.log(Level.SEVERE, null, ex);
            servletResponse.sendError(403,
                    "Kibana was not accessed from Hopsworks, no current project information is available.");
            return;
        }
    }

    //Do not authorize admin
    if (email.equals(Settings.AGENT_EMAIL)) {
        super.service(servletRequest, servletResponse);
        return;
    }

    MyRequestWrapper myRequestWrapper = new MyRequestWrapper((HttpServletRequest) servletRequest);
    KibanaFilter kibanaFilter = null;
    //Filter requests based on path
    if (servletRequest.getRequestURI().contains("api/saved_objects")) {
        kibanaFilter = KibanaFilter.KIBANA_SAVED_OBJECTS_API;
    } else if (servletRequest.getRequestURI().contains("elasticsearch/*/_search")) {
        kibanaFilter = KibanaFilter.ELASTICSEARCH_SEARCH;
    } else if (servletRequest.getRequestURI().contains("legacy_scroll_start")
            || servletRequest.getRequestURI().contains("settings/defaultIndex")) {
        return;
    }

    //initialize request attributes from caches if unset by a subclass by this point
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // Make the Request
    //note: we won't transfer the protocol version because I'm not sure it would truly be compatible
    String method = servletRequest.getMethod();
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);
    HttpRequest proxyRequest;
    //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        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(
                new InputStreamEntity(myRequestWrapper.getInputStream(), servletRequest.getContentLength()));
        proxyRequest = eProxyRequest;
    } else {
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }

    copyRequestHeaders(servletRequest, proxyRequest);

    super.setXForwardedForHeader(servletRequest, proxyRequest);

    HttpResponse proxyResponse = null;
    try {
        // Execute the request
        LOG.log(Level.FINE, "proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- "
                + proxyRequest.getRequestLine().getUri());

        proxyResponse = super.proxyClient.execute(super.getTargetHost(myRequestWrapper), proxyRequest);

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();

        if (doResponseRedirectOrNotModifiedLogic(myRequestWrapper, servletResponse, proxyResponse,
                statusCode)) {
            //the response is already "committed" now without any body to send
            //TODO copy response headers?
            return;
        }

        // Pass the response code. This method with the "reason phrase" is 
        // deprecated but it's the only way to pass the reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletRequest, servletResponse);

        // Send the content to the client
        copyResponseEntity(proxyResponse, servletResponse, kibanaFilter, email);

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        if (e instanceof ServletException) {
            throw (ServletException) e;
        }
        //noinspection ConstantConditions
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new RuntimeException(e);

    } finally {
        // make sure the entire entity was consumed, so the connection is released
        if (proxyResponse != null) {
            consumeQuietly(proxyResponse.getEntity());
        }
        //Note: Don't need to close servlet outputStream:
        // http://stackoverflow.com/questions/1159168/should-one-call-close-on-
        //httpservletresponse-getoutputstream-getwriter
    }
}

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

public void forward(HttpServletRequest request, HttpServletResponse response) throws IOException {
    debug(request, "forward");

    Packet packet = new Packet();
    packet.reset();/*from  w w w  . j  a va2  s.co  m*/
    // AJP13_FORWARD_REQUEST
    packet.write(Type.REQUEST_FORWARD.code);
    packet.write(computeMethod(request.getMethod()).code);
    packet.write(request.getProtocol());
    packet.write(request.getRequestURI());
    packet.write(request.getRemoteAddr());
    packet.write(request.getRemoteAddr());
    packet.write(request.getServerName());
    packet.write(request.getServerPort());
    packet.write(request.isSecure());

    // request headers
    Map<String, String> headers = new HashMap<String, String>();
    @SuppressWarnings("rawtypes")
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement().toString();
        String headerValue = request.getHeader(headerName);
        headerValue = headerFilter.processRequestHeader(headerName, headerValue);
        if (headerValue != null) {
            headers.put(headerName, headerValue);
        }
    }
    packet.write(headers.size());
    for (Map.Entry<String, String> header : headers.entrySet()) {
        HttpRequestHeader headerType = HttpRequestHeader.fromHeaderName(header.getKey());
        if (headerType != null) {
            packet.write(headerType.code);
        } else {
            packet.write(header.getKey());
        }
        String headerValue = header.getValue();
        packet.write(headerValue == null ? "" : headerValue);
    }

    // request attributes
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        packet.write(Attribute.REMOTE_USER.code);
        packet.write(authentication.getName());
    }

    String queryString = request.getQueryString();
    if (queryString != null) {
        packet.write(Attribute.QUERY_STRING.code);
        packet.write(queryString);
    }

    // packet terminator
    packet.write((byte) 0xff);

    final Object socketKey = new AjpPoolableConnectionFactory.Key(proxyHost, proxyPort);
    Socket connection;

    try {
        connection = allocateSocket(socketKey);
        debug("allocated", connection);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RuntimeException(e);
    }

    boolean invalidate = true;
    try {
        OutputStream outputStream = connection.getOutputStream();
        InputStream inputStream = connection.getInputStream();
        packet.write(outputStream);
        packet.reset();

        int bytesWritten = 0;

        int contentLength = request.getContentLength();
        if (contentLength == -1) { // Unknown content length
            contentLength = Integer.MAX_VALUE;
        }
        ServletInputStream requestInput = request.getInputStream();

        OutputStream responseOutput = null;
        boolean reuse = false;

        if (request.getHeader("Content-Length") != null) {
            bytesWritten += processRequestBody(packet, outputStream, bytesWritten, contentLength, requestInput,
                    contentLength);
            debug("sent [" + bytesWritten + "] initial body bytes", connection);
        }

        for (;; packet.reset()) {
            debug("reading packet", connection);
            packet.read(inputStream);

            Type packetType = Type.fromCode(packet.readByte());
            debug("received " + packetType, connection);
            if (packetType == Type.END_RESPONSE) {
                reuse = packet.readBoolean();
                break;
            }
            switch (packetType) {
            case GET_BODY_CHUNK:
                int requestedSize = packet.readInt();
                packet.reset();
                int chunkSize = processRequestBody(packet, outputStream, bytesWritten, contentLength,
                        requestInput, requestedSize);
                bytesWritten += chunkSize;
                debug("sent [" + chunkSize + "] bytes of body chunk", connection);
                break;
            case SEND_HEADERS: {
                response.reset();
                int httpStatusCode = packet.readInt();
                packet.readString(); // status message, not used
                response.setStatus(httpStatusCode);
                int headerCount = packet.readInt();
                for (int x = 0; x < headerCount; ++x) {
                    byte b = packet.readByte();
                    packet.unreadByte();
                    String headerName;
                    if (b == ((byte) 0xA0)) {
                        int headerCode = packet.readInt();
                        headerName = HttpResponseHeader.fromCode(headerCode).headerName;
                    } else {
                        headerName = packet.readString();
                    }
                    String headerValue = packet.readString();
                    headerValue = headerFilter.processResponseHeader(headerName, headerValue);
                    if (headerValue != null) {
                        response.setHeader(headerName, headerValue);
                    }
                }
            }
                break;
            case SEND_BODY_CHUNK:
                if (responseOutput == null) {
                    responseOutput = response.getOutputStream();
                }
                packet.copy(responseOutput);
                break;
            }
        }

        // ORDER DEPENDENCY: this should come last
        invalidate = !reuse;

        if (responseOutput != null) {
            responseOutput.close();
        }
    } finally {
        if (!shareConnections) {
            invalidate = true;
        }
        deallocateSocket(socketKey, connection, invalidate);
        debug("released " + (invalidate ? "invalidate" : "reuse"), connection);
    }
}

From source file:org.kurento.repository.internal.http.RepositoryHttpServlet.java

protected void uploadContent(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    String sessionId = extractSessionId(req);

    RepositoryHttpEndpointImpl elem = repoHttpManager.getHttpRepoItemElem(sessionId);

    if (elem == null) {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;/*from   w  ww.ja  va 2 s  . c  o  m*/
    }

    elem.stopCurrentTimer();
    elem.fireStartedEventIfFirstTime();

    try (InputStream requestInputStream = req.getInputStream()) {

        OutputStream repoItemOutputStream = elem.getRepoItemOutputStream();

        Range range = parseContentRange(req, resp);

        if (range != null) {

            if (range.start > elem.getWrittenBytes()) {
                resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
                resp.getOutputStream().println(
                        "The server doesn't support writing ranges " + "ahead of previously written bytes");
            } else if (range.end == elem.getWrittenBytes()) {

                // TODO We assume that the put range is the same than
                // the
                // previous one. Do we need to check this?

                resp.setStatus(SC_OK);
                resp.getOutputStream().println("The server has detected that the submited range "
                        + "has already submited in a previous request");
            } else if (range.start < elem.getWrittenBytes() && range.end > elem.getWrittenBytes()) {

                Range copyRange = new Range();
                copyRange.start = elem.getWrittenBytes() - range.start;
                copyRange.end = range.end - range.start;

                copyStreamsRange(requestInputStream, repoItemOutputStream, copyRange);

                resp.setStatus(SC_OK);

            } else if (range.start == elem.getWrittenBytes()) {

                IOUtils.copy(requestInputStream, repoItemOutputStream);

                resp.setStatus(SC_OK);
            }

        } else {

            boolean isMultipart = ServletFileUpload.isMultipartContent(req);

            if (isMultipart) {

                uploadMultipart(req, resp, repoItemOutputStream);

            } else {

                try {

                    log.debug("Start to receive bytes (estimated " + req.getContentLength() + " bytes)");
                    int bytes = IOUtils.copy(requestInputStream, repoItemOutputStream);
                    resp.setStatus(SC_OK);
                    log.debug("Bytes received: " + bytes);

                } catch (Exception e) {

                    log.warn("Exception when uploading content", e);

                    elem.fireSessionErrorEvent(e);
                    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }
            }
        }

    } finally {
        elem.stopInTimeout();
    }
}

From source file:axiom.servlet.AbstractServletClient.java

protected void parseParameters(HttpServletRequest request, RequestTrans reqtrans, String encoding)
        throws Exception {

    HashMap parameters = new HashMap();

    try {/*from w  w  w  .  j  ava 2 s.  c  o  m*/
        Context cx = Context.enter();
        cx.setClassShutter(new ClassShutter() {
            public boolean visibleToScripts(String fullClassName) {
                return false;
            }
        });

        ImporterTopLevel scope = new ImporterTopLevel(cx, true);

        // Parse any posted parameters in the input stream
        String contentType;
        boolean isPost = false, isForm = false, isJson = false, isXml = false;
        if ("POST".equals(request.getMethod())) {
            isPost = true;
        }
        if (isPost && (contentType = request.getContentType()) != null) {
            contentType = contentType.split(";")[0];
            if ("application/x-www-form-urlencoded".equals(contentType)) {
                isForm = true;
            } else if ("text/json".equals(contentType)) {
                isJson = true;
            } else if ("text/xml".equals(contentType)) {
                isXml = true;
            }
        }

        // Parse any query string parameters from the request
        String queryString = request.getQueryString();
        if (queryString != null) {
            try {
                parseParameters(parameters, queryString.getBytes(), encoding, isPost);

                Scriptable sqparam = cx.newObject(scope);
                for (Iterator i = parameters.entrySet().iterator(); i.hasNext();) {
                    Map.Entry entry = (Map.Entry) i.next();
                    String key = (String) entry.getKey();
                    String[] values = (String[]) entry.getValue();

                    if ((values != null) && (values.length > 0)) {
                        if (values.length == 1) {
                            sqparam.put(key, sqparam, values[0]);
                        } else {
                            NativeArray na = new NativeArray(values);
                            ScriptRuntime.setObjectProtoAndParent(na, scope);
                            sqparam.put(key, sqparam, na);
                        }
                    }
                }
                reqtrans.setQueryParams(sqparam);
            } catch (Exception e) {
                System.err.println("Error parsing query string: " + e);
            }
        }

        if (isForm || isJson || isXml) {
            try {
                int max = request.getContentLength();
                int len = 0;
                byte[] buf = new byte[max];
                ServletInputStream is = request.getInputStream();

                while (len < max) {
                    int next = is.read(buf, len, max - len);

                    if (next < 0) {
                        break;
                    }

                    len += next;
                }

                if (isForm) {
                    HashMap formMap = new HashMap();
                    parseParameters(formMap, buf, encoding, isPost);
                    Scriptable spparam = cx.newObject(scope);
                    for (Iterator i = formMap.entrySet().iterator(); i.hasNext();) {
                        Map.Entry entry = (Map.Entry) i.next();
                        String key = (String) entry.getKey();
                        String[] values = (String[]) entry.getValue();
                        if (values.length > 0) {
                            if (values.length == 1) {
                                spparam.put(key, spparam, values[0]);
                            } else {
                                NativeArray na = new NativeArray(values);
                                ScriptRuntime.setObjectProtoAndParent(na, scope);
                                spparam.put(key, spparam, na);
                            }
                        }
                    }

                    reqtrans.setPostBody(new String(buf, encoding));
                    reqtrans.setPostParams(spparam);
                    parameters.putAll(formMap);
                } else if (isJson) {
                    String json = new String(buf, encoding);
                    Scriptable post = (Scriptable) cx.evaluateString(scope, "eval(" + json + ")", "", 0, null);
                    reqtrans.setPostBody(post);
                    Object[] ids = post.getIds();
                    int idslen = ids.length;
                    for (int i = 0; i < idslen; i++) {
                        parameters.put(ids[i], post.get((String) ids[i], post));
                    }
                } else if (isXml) {
                    String xml = new String(buf, encoding);
                    int startProlog = xml.indexOf("<?xml version="), endProlog;
                    if (startProlog > -1 && (endProlog = xml.indexOf(">", startProlog + 1)) > -1) {
                        xml = new StringBuffer(xml).replace(startProlog, endProlog + 1, "").toString();
                    }
                    xml = xml.replaceAll("\\\"", "\\\\\"").replaceAll("\n", "").replaceAll("\r", "");
                    Scriptable post = (Scriptable) cx.evaluateString(scope, "new XML(\"" + xml + "\");", "", 0,
                            null);
                    reqtrans.setPostBody(post);
                }
            } catch (Exception e) {
                throw e;
            }
        }

        Scriptable sreqdata = cx.newObject(scope);
        for (Iterator i = parameters.entrySet().iterator(); i.hasNext();) {
            Map.Entry entry = (Map.Entry) i.next();
            String key = (String) entry.getKey();
            Object val = entry.getValue();

            if (val != null) {
                if (val instanceof String[]) {
                    String[] values = (String[]) val;
                    if (values.length > 0) {
                        if (values.length == 1) {
                            sreqdata.put(key, sreqdata, values[0]);
                        } else {
                            NativeArray na = new NativeArray(values);
                            ScriptRuntime.setObjectProtoAndParent(na, scope);
                            sreqdata.put(key, sreqdata, na);
                        }
                    }
                } else {
                    sreqdata.put(key, sreqdata, val);
                }
            }

        }
        reqtrans.setData(sreqdata);

    } catch (Exception ex) {
        ex.printStackTrace();
        throw ex;
    } finally {
        Context.exit();
    }
}