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.olio.webapp.fileupload.FileUploadHandler.java

/**
 * Handles the initial fields up to the first upload field. This will
 * allow creating the database entry and obtaining the auto-generated
 * ids./*w w  w . j  ava  2 s  . c om*/
 * @return A hash table with the initial field values
 */
public Hashtable<String, String> getInitialParams(HttpServletRequest request, HttpServletResponse response) {

    // print out header for
    Enumeration enumx = request.getHeaderNames();
    String key = "";
    String listx = "";
    while (enumx.hasMoreElements()) {
        key = (String) enumx.nextElement();
        listx += "\n" + key + ":" + request.getHeader(key);
    }
    logger.fine("Incoming Header Item:" + listx);
    // enable progress bar (this managed bean that is in the session could be comp specific, but I can't create the component specific
    // session object until I have the components name.  For now use static key through backing bean).
    // Use session to allow the monitoring of the fileupload based
    HttpSession session = request.getSession();

    FileUploadStatus status = new FileUploadStatus();
    session.setAttribute(FileUploadUtil.FILE_UPLOAD_STATUS, status);
    setFileUploadStatus(status);

    // Create hashtable to hold uploaded data so it can be used by custom post extension
    Hashtable<String, String> htUpload = new Hashtable<String, String>();
    // set to set hashtable for final retrieval
    status.setUploadItems(htUpload);

    // get size of upload and set status
    long totalSizeOfUpload = request.getContentLength();
    status.setTotalUploadSize(totalSizeOfUpload);

    // Check that we have a proper file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {

        // Streaming API typically provide better performance for file uploads.
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();

        try {
            // Now we should have the componentsName and upload directory to setup remaining upload of file items
            String compName = htUpload.get(FileUploadUtil.COMPONENT_NAME);
            status.setName(compName);

            // Parse the request and return list of "FileItem" whle updating status
            FileItemIterator iter = upload.getItemIterator(request);

            status.setReadingComplete();

            while (iter.hasNext()) {
                item = iter.next();
                if (item.isFormField()) {
                    // handle a form item being uploaded
                    String itemName = item.getFieldName();

                    // process form(non-file) item200002
                    int size = formItemFound(item, htUpload);
                    updateSessionStatus(itemName, size);

                    logger.fine("Form field item:" + itemName);

                } else {
                    // At the first find of an uploaded file, stop.
                    // We need to insert our record first in order
                    // to find the id.
                    break;
                }
            }
            itemIter = iter;
        } catch (Exception e) {
            status.setUploadError(
                    "FileUpload didn't complete successfully.  Exception received:" + e.toString());
            logger.log(Level.SEVERE, "file.upload.exception", e);
        }
    }
    fileUploadStatus = status;
    requestParams = htUpload;
    return htUpload;
}

From source file:org.apache.openaz.xacml.rest.XACMLPdpServlet.java

/**
 * POST - We expect XACML requests to be posted by PEP applications. They can be in the form of XML or
 * JSON according to the XACML 3.0 Specifications for both.
 *
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *///ww w. ja  v  a2 s.  c  om
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //
    // no point in doing any work if we know from the get-go that we cannot do anything with the request
    //
    if (status.getLoadedRootPolicies().size() == 0) {
        logger.warn("Request from PEP at " + request.getRequestURI()
                + " for service when PDP has No Root Policies loaded");
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;
    }

    XACMLRest.dumpRequest(request);
    //
    // Set our no-cache header
    //
    response.setHeader("Cache-Control", "no-cache");
    //
    // They must send a Content-Type
    //
    if (request.getContentType() == null) {
        logger.warn("Must specify a Content-Type");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "no content-type given");
        return;
    }
    //
    // Limit the Content-Length to something reasonable
    //
    if (request.getContentLength() > Integer
            .parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", "32767"))) {
        String message = "Content-Length larger than server will accept.";
        logger.info(message);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
    if (request.getContentLength() <= 0) {
        String message = "Content-Length is negative";
        logger.info(message);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
    ContentType contentType = null;
    try {
        contentType = ContentType.parse(request.getContentType());
    } catch (Exception e) {
        String message = "Parsing Content-Type: " + request.getContentType() + ", error=" + e.getMessage();
        logger.error(message, e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
    //
    // What exactly did they send us?
    //
    String incomingRequestString = null;
    Request pdpRequest = null;
    if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())
            || contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType())
            || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
        //
        // Read in the string
        //
        StringBuilder buffer = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            incomingRequestString = buffer.toString();
        }
        logger.info(incomingRequestString);
        //
        // Parse into a request
        //
        try {
            if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) {
                pdpRequest = JSONRequest.load(incomingRequestString);
            } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType())
                    || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
                pdpRequest = DOMRequest.load(incomingRequestString);
            }
        } catch (Exception e) {
            logger.error("Could not parse request", e);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            return;
        }
    } else {
        String message = "unsupported content type" + request.getContentType();
        logger.error(message);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
    //
    // Did we successfully get and parse a request?
    //
    if (pdpRequest == null || pdpRequest.getRequestAttributes() == null
            || pdpRequest.getRequestAttributes().size() <= 0) {
        String message = "Zero Attributes found in the request";
        logger.error(message);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
    //
    // Run it
    //
    try {
        //
        // Get the pointer to the PDP Engine
        //
        PDPEngine myEngine = null;
        synchronized (pdpEngineLock) {
            myEngine = this.pdpEngine;
        }
        if (myEngine == null) {
            String message = "No engine loaded.";
            logger.error(message);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
            return;
        }
        //
        // Send the request and save the response
        //
        long lTimeStart, lTimeEnd;
        Response pdpResponse = null;

        // TODO - Make this unnecessary
        // TODO It seems that the PDP Engine is not thread-safe, so when a configuration change occurs in
        // the middle of processing
        // TODO a PEP Request, that Request fails (it throws a NullPointerException in the decide()
        // method).
        // TODO Using synchronize will slow down processing of PEP requests, possibly by a significant
        // amount.
        // TODO Since configuration changes are rare, it would be A Very Good Thing if we could eliminate
        // this sychronized block.
        // TODO
        // TODO This problem was found by starting one PDP then
        // TODO RestLoadTest switching between 2 configurations, 1 second apart
        // TODO both configurations contain the datarouter policy
        // TODO both configurations already have all policies cached in the PDPs config directory
        // TODO RestLoadTest started with the Datarouter test requests, 5 threads, no interval
        // TODO With that configuration this code (without the synchronized) throws a NullPointerException
        // TODO within a few seconds.
        //
        synchronized (pdpEngineLock) {
            myEngine = this.pdpEngine;
            try {
                lTimeStart = System.currentTimeMillis();
                pdpResponse = myEngine.decide(pdpRequest);
                lTimeEnd = System.currentTimeMillis();
            } catch (PDPException e) {
                String message = "Exception during decide: " + e.getMessage();
                logger.error(message);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
                return;
            }
        }
        requestLogger.info(lTimeStart + "=" + incomingRequestString);
        if (logger.isDebugEnabled()) {
            logger.debug("Request time: " + (lTimeEnd - lTimeStart) + "ms");
        }
        //
        // Convert Response to appropriate Content-Type
        //
        if (pdpResponse == null) {
            requestLogger.info(lTimeStart + "=" + "{}");
            throw new Exception("Failed to get response from PDP engine.");
        }
        //
        // Set our content-type
        //
        response.setContentType(contentType.getMimeType());
        //
        // Convert the PDP response object to a String to
        // return to our caller as well as dump to our loggers.
        //
        String outgoingResponseString = "";
        if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) {
            //
            // Get it as a String. This is not very efficient but we need to log our
            // results for auditing.
            //
            outgoingResponseString = JSONResponse.toString(pdpResponse, logger.isDebugEnabled());
            if (logger.isDebugEnabled()) {
                logger.debug(outgoingResponseString);
                //
                // Get rid of whitespace
                //
                outgoingResponseString = JSONResponse.toString(pdpResponse, false);
            }
        } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType())
                || contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) {
            //
            // Get it as a String. This is not very efficient but we need to log our
            // results for auditing.
            //
            outgoingResponseString = DOMResponse.toString(pdpResponse, logger.isDebugEnabled());
            if (logger.isDebugEnabled()) {
                logger.debug(outgoingResponseString);
                //
                // Get rid of whitespace
                //
                outgoingResponseString = DOMResponse.toString(pdpResponse, false);
            }
        }
        //
        // lTimeStart is used as an ID within the requestLogger to match up
        // request's with responses.
        //
        requestLogger.info(lTimeStart + "=" + outgoingResponseString);
        response.getWriter().print(outgoingResponseString);
    } catch (Exception e) {
        String message = "Exception executing request: " + e;
        logger.error(message, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
        return;
    }
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:cz.incad.kramerius.client.ForwardServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {//from  w w w  .j av  a2s  . com
        TypeOfCall tc = disectTypeOfCall(req);
        User user = tc.getUser((CallUserController) req.getSession().getAttribute(CallUserController.KEY));

        String urlPrefixKey = getInitParameter(URL_PREFIX_KEY);
        String prefixAddr = KConfiguration.getInstance().getConfiguration().getString(urlPrefixKey);
        if (prefixAddr == null || StringUtils.isEmptyString(prefixAddr))
            throw new RuntimeException("expecting property " + urlPrefixKey);

        String queryString = req.getQueryString();
        String requestedURI = req.getRequestURI();

        String urlModif = getInitParameter(URL_PATH_MODIF_KEY);
        if (urlModif != null) {
            URLPathModify pathModifier = getPathModifier(urlModif);
            requestedURI = pathModifier.modifyPath(requestedURI, req);
            queryString = pathModifier.modifyQuery(queryString, req);
        } else {
            URLPathModify pathModifier = getPathModifier(DefaultModify.class.getName());
            requestedURI = pathModifier.modifyPath(requestedURI, req);
            queryString = pathModifier.modifyQuery(queryString, req);
        }

        String replaceURL = prefixAddr + requestedURI;
        if (StringUtils.isAnyString(queryString)) {
            replaceURL = replaceURL + "?" + queryString;
        }
        LOGGER.info("requesting url " + replaceURL);

        JSONObject jsonObj = null;
        if (req.getContentLength() > 0) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ServletInputStream iStream = req.getInputStream();
            IOUtils.copyStreams(iStream, bos);

            String t = new String(bos.toByteArray(), Charset.forName("UTF-8"));

            if ((!t.startsWith("{")) && (!t.endsWith("}"))) {
                // hack because of jquery
                jsonObj = new JSONObject("{" + t + "}");
            } else {
                jsonObj = new JSONObject(t);
            }
        }

        ClientResponse clientResponse = null;
        if (user != null) {
            clientResponse = method(replaceURL, SupportedMethods.POST, jsonObj, user.getUserName(),
                    user.getPassword(), req.getHeader("Accept"), req.getHeader("Content-Type"));
        } else {
            clientResponse = method(replaceURL, SupportedMethods.POST, jsonObj, null, null,
                    req.getHeader("Accept"), req.getHeader("Content-Type"));
        }
        resp.setContentType(clientResponse.getType().toString());
        resp.getWriter().write(clientResponse.getEntity(String.class));
    } catch (JSONException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (InstantiationException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (IllegalAccessException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (ClassNotFoundException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.osaf.cosmo.dav.servlet.StandardRequestHandler.java

@SuppressWarnings("unchecked")
private void dumpRequest(HttpServletRequest req) {
    if (!log.isTraceEnabled())
        return;//  w w  w . j  a  v  a2 s . co m

    StringBuffer sb = new StringBuffer("\n------------------------ Dump of request -------------------\n");
    try {
        Enumeration names = req.getHeaderNames();

        sb.append("Request headers:\n");
        while (names.hasMoreElements()) {
            String key = (String) names.nextElement();
            String val = req.getHeader(key);
            sb.append("  ").append(key).append(" = \"").append(val).append("\"\n");
        }

        names = req.getParameterNames();
        String title = "Request parameters";

        sb.append(title).append(" - global info and uris:").append("\n");
        sb.append("getMethod = ").append(req.getMethod()).append("\n");
        sb.append("getRemoteAddr = ").append(req.getRemoteAddr()).append("\n");
        sb.append("getRequestURI = ").append(req.getRequestURI()).append("\n");
        sb.append("getRemoteUser = ").append(req.getRemoteUser()).append("\n");
        sb.append("getRequestedSessionId = ").append(req.getRequestedSessionId()).append("\n");
        sb.append("HttpUtils.getRequestURL(req) = ").append(req.getRequestURL()).append("\n");
        sb.append("contextPath=").append(req.getContextPath()).append("\n");
        sb.append("query=").append(req.getQueryString()).append("\n");
        sb.append("contentlen=").append(req.getContentLength()).append("\n");
        sb.append("request=").append(req).append("\n");
        sb.append(title).append(":\n");

        while (names.hasMoreElements()) {
            String key = (String) names.nextElement();
            String val = req.getParameter(key);
            sb.append("  ").append(key).append(" = \"").append(val).append("\"").append("\n");
            ;
        }
        sb.append("Request attributes:\n");
        for (Enumeration<String> e = req.getAttributeNames(); e.hasMoreElements();) {
            String key = (String) e.nextElement();
            Object val = req.getAttribute(key);
            sb.append("  ").append(key).append(" = \"").append(val).append("\"").append("\n");
            ;
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
    sb.append("------------------------ End dump of request -------------------");
    log.trace(sb);
}

From source file:com.baidu.jprotobuf.rpc.server.HttpRequestHandlerServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String context = request.getPathInfo();
    if (context == null) {
        LOGGER.warn("invalid request path.");
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;// w  ww.  j  a v a 2s  .  c  o m
    } else {
        if (context.startsWith("/")) {
            context = context.substring(1);
        }

        if (!serviceMap.containsKey(context)) {
            LOGGER.warn("invalid request path service name[" + context + "] not found.");
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }

    try {
        ServiceExporter idlServiceExporter = serviceMap.get(context);

        //to check if a get idl request 
        if (request.getParameter(ServiceExporter.INPUT_IDL_PARAMETER) != null) {

            String inputIDL = idlServiceExporter.getInputIDL();
            if (inputIDL != null) {
                response.setContentLength(inputIDL.length());
                response.getOutputStream().write(inputIDL.getBytes());

                return;
            }

        } else if (request.getParameter(ServiceExporter.OUTPUT_IDL_PARAMETER) != null) {
            String outputIDL = idlServiceExporter.getOutputIDL();
            if (outputIDL != null) {
                response.setContentLength(outputIDL.length());
                response.getOutputStream().write(outputIDL.getBytes());

                return;
            }
        }

        IDLProxyObject inputIDLProxyObject = idlServiceExporter.getInputProxyObject();
        IDLProxyObject input = null;
        if (inputIDLProxyObject != null && request.getContentLength() > 0) {
            byte[] bytes = readStream(request.getInputStream(), request.getContentLength());
            input = inputIDLProxyObject.decode(bytes);
        }

        IDLProxyObject result = idlServiceExporter.execute(input);
        if (result != null) {
            byte[] bytes = result.encode();
            response.setContentLength(bytes.length);
            response.getOutputStream().write(bytes);
        }
    } catch (Exception ex) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
    } finally {
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
}

From source file:org.unitedinternet.cosmo.dav.servlet.StandardRequestHandler.java

private void dumpRequest(HttpServletRequest req) {
    if (!LOG.isTraceEnabled()) {
        return;//from  ww  w .j ava2s . co m
    }

    StringBuffer sb = new StringBuffer("\n------------------------ Dump of request -------------------\n");
    try {
        Enumeration<String> names = req.getHeaderNames();

        sb.append("Request headers:\n");
        while (names.hasMoreElements()) {
            String key = names.nextElement();
            String val = req.getHeader(key);
            sb.append("  ").append(key).append(" = \"").append(val).append("\"\n");
        }

        names = req.getParameterNames();
        String title = "Request parameters";

        sb.append(title).append(" - global info and uris:").append("\n");
        sb.append("getMethod = ").append(req.getMethod()).append("\n");
        sb.append("getRemoteAddr = ").append(req.getRemoteAddr()).append("\n");
        sb.append("getRequestURI = ").append(req.getRequestURI()).append("\n");
        sb.append("getRemoteUser = ").append(req.getRemoteUser()).append("\n");
        sb.append("getRequestedSessionId = ").append(req.getRequestedSessionId()).append("\n");
        sb.append("HttpUtils.getRequestURL(req) = ").append(req.getRequestURL()).append("\n");
        sb.append("contextPath=").append(req.getContextPath()).append("\n");
        sb.append("query=").append(req.getQueryString()).append("\n");
        sb.append("contentlen=").append(req.getContentLength()).append("\n");
        sb.append("request=").append(req).append("\n");
        sb.append(title).append(":\n");

        while (names.hasMoreElements()) {
            String key = (String) names.nextElement();
            String val = req.getParameter(key);
            sb.append("  ").append(key).append(" = \"").append(val).append("\"").append("\n");
        }
        sb.append("Request attributes:\n");
        for (Enumeration<String> e = req.getAttributeNames(); e.hasMoreElements();) {
            String key = (String) e.nextElement();
            Object val = req.getAttribute(key);
            sb.append("  ").append(key).append(" = \"").append(val).append("\"").append("\n");
        }
    } catch (Exception e) {
        LOG.error("Error on dumpRequest class StandardRequestHandler " + e);
    }
    sb.append("------------------------ End dump of request -------------------");
    //Fix Log Forging - java fortify
    //Writing unvalidated user input to log files can allow an attacker to forge log entries or
    //inject malicious content into the logs.

    LOG.trace(sb.toString());
}

From source file:org.vuphone.vandyupon.media.incoming.event.ImageParser.java

public Notification parse(HttpServletRequest req) {
    if (req.getParameter("type").equalsIgnoreCase("eventimagepost")) {
        //get data from request

        String response = null;//w  ww . ja  v a  2  s .  c  o m
        String callback = null;
        long time, eventId = 0;
        time = System.currentTimeMillis();
        byte[] imageData = null;

        eventId = Long.parseLong(req.getParameter(EVENTID));

        response = req.getParameter("resp");
        callback = req.getParameter("callback");
        if (ServletFileUpload.isMultipartContent(req)) {
            //process the multipart request

            File temp = new File("/temp");
            if (!temp.exists()) {
                temp.mkdir();
            }

            DiskFileItemFactory factory = new DiskFileItemFactory(5000000, temp);

            ServletFileUpload ul = new ServletFileUpload(factory);
            Iterator iter = null;

            HashMap<String, String> params = new HashMap<String, String>();

            try {
                iter = ul.parseRequest(req).iterator();

                while (iter.hasNext()) {

                    FileItem item = (FileItem) iter.next();

                    if (item.isFormField())
                        params.put(item.getFieldName(), item.getString());
                    else
                        //file upload
                        imageData = item.get();
                }

            } catch (FileUploadException e) {
                e.printStackTrace();
                return null;
            }

        } else {

            eventId = Long.parseLong(req.getParameter(EVENTID));

            response = req.getParameter("resp");
            callback = req.getParameter("callback");
            imageData = new byte[req.getContentLength() + 1];
            try {
                ServletInputStream sis = req.getInputStream();
                int read = 0;
                int readSoFar = 0;
                while ((read = sis.read(imageData, readSoFar, imageData.length - readSoFar)) != -1) {
                    readSoFar += read;
                    //logger_.log(Level.SEVERE, "Read " + String.valueOf(read) + " bytes this time. So Far " + String.valueOf(readSoFar));
                }
            } catch (IOException excp) {
                logger_.log(Level.SEVERE, "Got IOException:" + excp.getMessage());
            }

        }
        ImageNotification in = new ImageNotification();
        in.setEventId(eventId);
        in.setTime(time);
        in.setBytes(imageData);
        in.setResponseType(response);
        in.setCallback(callback);
        return in;
    } else {
        return null;
    }
}

From source file:com.couchbase.capi.servlet.CAPIServlet.java

protected void handleDocumentInternal(HttpServletRequest req, HttpServletResponse resp, String databaseName,
        String documentId, String documentType) throws IOException, ServletException {

    logger.trace(String.format("Got document request in database %s document %s type %s", databaseName,
            documentId, documentType));/*ww w .j  a  v  a2  s.c o m*/

    if (!(req.getMethod().equals("GET") || req.getMethod().equals("HEAD") || req.getMethod().equals("PUT"))) {
        throw new UnsupportedOperationException(
                "Only GET/HEAD/PUT operations on documents are supported at this time");
    }

    if (req.getMethod().equals("GET") || req.getMethod().equals("HEAD")) {

        Map<String, Object> doc = null;
        if (documentType.equals("_local")) {
            doc = capiBehavior.getLocalDocument(databaseName, documentId);
        } else {
            doc = capiBehavior.getDocument(databaseName, documentId);
        }

        if (doc != null) {
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.setContentType("application/json");
            OutputStream os = resp.getOutputStream();
            mapper.writeValue(os, doc);
        } else {
            sendNotFoundResponse(resp, "missing");
            return;
        }

    } else if (req.getMethod().equals("PUT")) {

        String rev = null;

        //read the document
        InputStream is = req.getInputStream();

        int requestLength = req.getContentLength();
        byte[] buffer = new byte[requestLength];
        IOUtils.readFully(is, buffer, 0, requestLength);

        @SuppressWarnings("unchecked")
        Map<String, Object> parsedValue = (Map<String, Object>) mapper.readValue(buffer, Map.class);

        if (documentType.equals("_local)")) {
            rev = capiBehavior.storeLocalDocument(databaseName, documentId, parsedValue);
        } else {
            rev = capiBehavior.storeDocument(databaseName, documentId, parsedValue);
        }

        if (rev == null) {
            throw new ServletException("Storing document did not result in valid revision");
        }

        resp.setStatus(HttpServletResponse.SC_CREATED);
        resp.setContentType("application/json");
        OutputStream os = resp.getOutputStream();

        Map<String, Object> responseMap = new HashMap<String, Object>();
        responseMap.put("ok", true);
        responseMap.put("id", documentId);
        responseMap.put("rev", rev);
        mapper.writeValue(os, responseMap);
    }

}

From source file:org.apache.axis2.builder.MultipartFormDataBuilder.java

/**
 * @return Returns the document element.
 *///from   www  .j  a v a2s . com
public OMElement processDocument(InputStream inputStream, String contentType, MessageContext messageContext)
        throws AxisFault {
    MultipleEntryHashMap parameterMap;
    HttpServletRequest request = (HttpServletRequest) messageContext
            .getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);

    // TODO: Do check ContentLength for the max size,
    //       but it can't be configured anywhere.
    //       I think that it cant be configured at web.xml or axis2.xml.

    /**
     * When we are building a request context without the use of Servlets, we require charset encoding and content length
     * parameters to be set in the transports.
     */
    String charSetEncoding = (String) messageContext
            .getProperty(Constants.Configuration.CHARACTER_SET_ENCODING);
    Integer contentLength = 0;

    Map<String, String> transportHeaders = (Map) messageContext.getProperty(MessageContext.TRANSPORT_HEADERS);

    String contentLengthValue = (String) transportHeaders.get(HTTPConstants.HEADER_CONTENT_LENGTH);
    if (contentLengthValue != null) {
        try {
            contentLength = new Integer(contentLengthValue);
        } catch (NumberFormatException e) {
            // TODO handle this better in case we cannot find the contentLength
        }
    }

    RequestContextImpl nRequest;

    if (request == null) { // on regular transport
        if (charSetEncoding == null || contentLength == null) {
            throw new AxisFault(
                    "multipart/form-data builder could not find charset encoding or content length in messageContext TRANSPORT_HEADERS. Please set these in the respective transport in use.");
        }
        nRequest = new RequestContextImpl(inputStream, contentType, charSetEncoding, contentLength);
    } else { // from servlet transport
        nRequest = new RequestContextImpl(inputStream, request.getContentType(), request.getCharacterEncoding(),
                request.getContentLength());
    }

    try {
        parameterMap = getParameterMap(nRequest, charSetEncoding);
        return BuilderUtil.buildsoapMessage(messageContext, parameterMap, OMAbstractFactory.getSOAP12Factory());

    } catch (FileUploadException e) {
        throw AxisFault.makeFault(e);
    }

}

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

/**
 * Redirect to HTTP port./*from   w w  w . j  ava  2s .c  om*/
 */
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
    client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
    PostMethod get = new PostMethod("http://localhost:8080/gateway");

    try {
        // copy all the headers
        // Enumeration headerNames = req.getHeaderNames();
        // while (headerNames.hasMoreElements()) {
        // String headerName = (String) headerNames.nextElement();
        // logger.debug("Adding received header to tunnel request: "
        // + headerName);
        // get.addRequestHeader(headerName, req.getHeader(headerName));
        // }
        // Enumeration parameterNames = req.getParameterNames();
        // while (parameterNames.hasMoreElements()) {
        // String parameterName = (String) parameterNames.nextElement();
        // logger.debug("Adding received parameter to tunnel request: "
        // + parameterName);
        // get.getParams().setParameter(parameterName,
        // req.getParameter(parameterName));
        // }
        // Enumeration attributeNames = req.getAttributeNames();
        // while (attributeNames.hasMoreElements()) {
        // String attributeName = (String) attributeNames.nextElement();
        // logger.debug("Adding received attribute to tunnel request: "
        // + attributeName);
        // }

        String path = req.getContextPath();
        if (path == null) {
            path = "";
        }
        // System.out.println("Path: " + path);
        if (req.getPathInfo() != null) {
            path += req.getPathInfo();
        }
        // System.out.println("Path: " + path);

        int reqContentLength = req.getContentLength();
        if (reqContentLength > 0) {
            // System.out.println("Request content length: " +
            // reqContentLength);

            ByteBuffer reqBuffer = ByteBuffer.allocate(reqContentLength);
            ServletUtils.copy(req.getInputStream(), reqBuffer.asOutputStream());
            reqBuffer.flip();
            get.setRequestEntity(new InputStreamRequestEntity(reqBuffer.asInputStream(), reqContentLength,
                    "application/x-amf"));
            // get.setPath(path);
            get.addRequestHeader("Tunnel-request", path);

            client.executeMethod(get);
            // System.out.println("Response code: " + get.getStatusCode());

            if (get.getStatusCode() == HttpStatus.SC_OK) {
                resp.setContentType("application/x-amf");
                int responseLength = ((Long) get.getResponseContentLength()).intValue();
                ByteBuffer respBuffer = ByteBuffer.allocate(responseLength);
                ServletUtils.copy(get.getResponseBodyAsStream(), respBuffer.asOutputStream());
                respBuffer.flip();
                ServletUtils.copy(respBuffer.asInputStream(), resp.getOutputStream());
                resp.flushBuffer();
            } else {
                resp.sendError(get.getStatusCode());
            }

        } else {
            resp.sendError(HttpStatus.SC_BAD_REQUEST);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        get.releaseConnection();
    }
}