Example usage for javax.servlet.http HttpServletRequest getInputStream

List of usage examples for javax.servlet.http HttpServletRequest getInputStream

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getInputStream.

Prototype

public ServletInputStream getInputStream() throws IOException;

Source Link

Document

Retrieves the body of the request as binary data using a ServletInputStream .

Usage

From source file:com.groupdocs.ui.servlets.ViewDocument.java

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

    response.addHeader("Content-Type", "application/json");
    ViewDocumentParameters params = new ObjectMapper().readValue(request.getInputStream(),
            ViewDocumentParameters.class);

    ViewDocumentResponse result = new ViewDocumentResponse();
    FileData fileData = ViewerUtils.factoryFileData(params.getPath());
    DocumentInfoContainer docInfo = null;

    try {//  ww w . j a v a2 s  .c  o m
        result.setDocumentDescription(
                (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false));
    } catch (ParseException x) {
        throw new ServletException(x);
    }

    if (params.getUseHtmlBasedEngine()) {
        try {
            docInfo = ViewerUtils.getViewerHtmlHandler()
                    .getDocumentInfo(new DocumentInfoOptions(params.getPath()));
        } catch (Exception x) {
            throw new ServletException(x);
        }

        result.setPageCss(new String[0]);
        result.setLic(true);
        result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
        result.setPdfPrintUrl(GetPdfPrintUrl(params));
        result.setUrl(GetFileUrl(params));
        result.setPath(params.getPath());
        result.setName(params.getPath());
        result.setDocType(docInfo.getDocumentType());
        result.setFileType(docInfo.getFileType());

        HtmlOptions htmlOptions = new HtmlOptions();
        htmlOptions.setResourcesEmbedded(true);

        htmlOptions.setHtmlResourcePrefix("/GetResourceForHtml?documentPath=" + params.getPath()
                + "&pageNumber={page-number}&resourceName=");

        if (!DotNetToJavaStringHelper.isNullOrEmpty(params.getPreloadPagesCount().toString())
                && params.getPreloadPagesCount().intValue() > 0) {
            htmlOptions.setPageNumber(1);
            htmlOptions.setCountPagesToConvert(params.getPreloadPagesCount().intValue());
        }

        String[] cssList = null;

        RefObject<ArrayList<String>> tempRef_cssList = new RefObject<ArrayList<String>>(cssList);

        List<PageHtml> htmlPages = GetHtmlPages(params.getPath(), htmlOptions);
        cssList = tempRef_cssList.argValue;

        ArrayList<String> pagesContent = new ArrayList<String>();
        for (PageHtml page : htmlPages) {
            pagesContent.add(page.getHtmlContent());
        }
        String[] htmlContent = pagesContent.toArray(new String[0]);
        result.setPageHtml(htmlContent);
        result.setPageCss(new String[] { String.join(" ", temp_cssList) });

        for (int i = 0; i < result.getPageHtml().length; i++) {
            String html = result.getPageHtml()[i];
            int indexOfScript = html.indexOf("script");
            if (indexOfScript > 0) {
                result.getPageHtml()[i] = html.substring(0, indexOfScript);
            }
        }

    } else {

        try {
            docInfo = ViewerUtils.getViewerImageHandler()
                    .getDocumentInfo(new DocumentInfoOptions(params.getPath()));
        } catch (Exception x) {
            throw new ServletException(x);
        }

        int maxWidth = 0;
        int maxHeight = 0;
        for (PageData pageData : docInfo.getPages()) {
            if (pageData.getHeight() > maxHeight) {
                maxHeight = pageData.getHeight();
                maxWidth = pageData.getWidth();
            }
        }

        fileData.setDateCreated(new Date());
        fileData.setDateModified(docInfo.getLastModificationDate());
        fileData.setPageCount(docInfo.getPages().size());
        fileData.setPages(docInfo.getPages());
        fileData.setMaxWidth(maxWidth);
        fileData.setMaxHeight(maxHeight);

        result.setPageCss(new String[0]);
        result.setLic(true);
        result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
        result.setPdfPrintUrl(GetPdfPrintUrl(params));
        result.setUrl(GetFileUrl(params.getPath(), true, false, params.getFileDisplayName(),
                params.getWatermarkText(), params.getWatermarkColor(), params.getWatermarkPostion(),
                params.getWatermarkWidth(), params.getIgnoreDocumentAbsence(), params.getUseHtmlBasedEngine(),
                params.getSupportPageRotation()));
        result.setPath(params.getPath());
        result.setName(params.getPath());

        result.setDocType(docInfo.getDocumentType());
        result.setFileType(docInfo.getFileType());

        int[] pageNumbers = new int[docInfo.getPages().size()];
        int count = 0;
        for (PageData page : docInfo.getPages()) {

            pageNumbers[count] = page.getNumber();
            count++;
        }
        String applicationHost = request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort();
        String[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, params);

        result.setImageUrls(imageUrls);

    }

    new ObjectMapper().writeValue(response.getOutputStream(), result);

}

From source file:com.amazon.dtasdk.v2.signature.Request.java

/**
 * Creates a Request from an HttpServletRequest. Useful for verifying the signature of a request.
 * //  w  ww .j  av a2s  .  c om
 * NOTE: This consumes the body of the request which can cause issues when you try and read it again.
 * 
 * @param httpServletRequest
 *            the HttpServletRequest to copy
 * @throws IOException
 *             on invalid url or body copying
 */
public Request(HttpServletRequest httpServletRequest) throws IOException {
    url = getFullURL(httpServletRequest);
    method = Method.valueOf(httpServletRequest.getMethod());

    Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        headers.put(name, httpServletRequest.getHeader(name));
    }
    headers.put(CONTENT_TYPE_HEADER, httpServletRequest.getContentType());
    body = IOUtils.toString(httpServletRequest.getInputStream());
}

From source file:net.buffalo.service.BuffaloWorker.java

public void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("invoking buffalo worker");
    }// w  ww  .  j a va2s.c o  m

    String requestService = getWorkerRelativePath();
    ServiceRepository repository = ServiceRepositoryUtil
            .getServiceRepository(RequestContext.getContext().getServletContext());

    Object service = repository.get(requestService);
    response.setHeader("content-type", "text/xml;charset=" + OUTPUT_ENCODING);
    try {
        ServletInputStream inputStream = request.getInputStream();
        BuffaloInvoker.getInstance().invoke(service, inputStream,
                new OutputStreamWriter(response.getOutputStream(), OUTPUT_ENCODING));
    } catch (Throwable ex) {
        LOGGER.error("An exception occured when invoking a service: ", ex);
        StringWriter writer = new StringWriter();
        ex.printStackTrace(new PrintWriter(writer));
        StringBuffer faultString = new StringBuffer();
        faultString.append("An exception occured when invoking a service. \n");
        faultString.append(writer.toString());
        throw new ServiceInvocationException(faultString.toString(), ex);
    }
}

From source file:com.bstek.dorado.view.resolver.ViewServiceResolver.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    XmlEscapeWriter writer = new XmlEscapeWriter(getWriter(request, response));

    JsonBuilder jsonBuilder = new JsonBuilder(writer);
    ServletInputStream in = request.getInputStream();
    DoradoContext context = DoradoContext.getCurrent();
    try {/* ww w.java 2 s  . co m*/
        String contentType = request.getContentType();
        if (contentType != null && contentType.contains(JAVASCRIPT_TOKEN)) {
            Reader reader = new InputStreamReader(in, Constants.DEFAULT_CHARSET);
            StringBuffer buf = new StringBuffer();
            char[] cs = new char[BUFFER_SIZE];
            for (int n; (n = reader.read(cs)) > 0;) {
                buf.append(new String(cs, 0, n));
            }

            ObjectNode objectNode = (ObjectNode) JsonUtils.getObjectMapper().readTree(buf.toString());

            processTask(writer, objectNode, context);
        } else if (contentType != null && contentType.contains(XML_TOKEN)) {
            Document document = getXmlDocumentBuilder(context)
                    .loadDocument(new InputStreamResource(in, request.getRequestURI()));

            writer.append("<?xml version=\"1.0\" encoding=\"" + Constants.DEFAULT_CHARSET + "\"?>\n");
            writer.append("<result>\n");

            Writer escapeWriter = new XmlEscapeWriter(writer);
            for (Element element : DomUtils.getChildElements(document.getDocumentElement())) {
                writer.append("<request>\n");
                writer.append("<response type=\"json\"><![CDATA[\n");
                writer.setEscapeEnabled(true);

                String textContent = DomUtils.getTextContent(element);

                ObjectNode objectNode = (ObjectNode) JsonUtils.getObjectMapper().readTree(textContent);
                try {
                    processTask(escapeWriter, objectNode, context);
                    writer.setEscapeEnabled(false);

                    writer.append("\n]]></response>\n");
                } catch (Exception e) {
                    Throwable t = e;
                    while (t.getCause() != null) {
                        t = t.getCause();
                    }
                    writer.setEscapeEnabled(false);

                    writer.append("\n]]></response>\n");
                    if (t instanceof ClientRunnableException) {
                        writer.append("<exception type=\"runnable\"><![CDATA[");
                        writer.setEscapeEnabled(true);
                        writer.append("(function(){").append(((ClientRunnableException) t).getScript())
                                .append("})");
                    } else {
                        writer.append("<exception><![CDATA[\n");
                        writer.setEscapeEnabled(true);
                        outputException(jsonBuilder, e);
                    }
                    writer.setEscapeEnabled(false);
                    writer.append("\n]]></exception>\n");
                    logger.error(e, e);
                }
                writer.append("</request>\n");
            }

            writer.append("</result>");
        }
    } catch (Exception e) {
        in.close();

        Throwable t = e;
        while (t.getCause() != null) {
            t = t.getCause();
        }

        if (t instanceof ClientRunnableException) {
            response.setContentType("text/runnable");
            writer.append("(function(){").append(((ClientRunnableException) t).getScript()).append("})");
        } else {
            response.setContentType("text/dorado-exception");
            outputException(jsonBuilder, e);
        }

        logger.error(e, e);
    } finally {
        writer.flush();
        writer.close();
    }
}

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

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

    // read the request
    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);
    logger.trace("commit for checkpoint parsed value is " + parsedValue);

    int vbucket = (Integer) parsedValue.get("vb");
    String bucket = (String) parsedValue.get("bucket");
    String bucketUUID = (String) parsedValue.get("bucketUUID");
    String vbopaque = (String) parsedValue.get("vbopaque");

    String vbucketUUID = capiBehavior.getVBucketUUID("default", bucket, vbucket);
    Map<String, Object> responseMap = new HashMap<String, Object>();
    responseMap.put("vbopaque", vbucketUUID);

    if ((vbopaque != null) && (!vbopaque.equals(vbucketUUID))) {
        logger.debug("returning 400");
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {// w w  w .j ava2 s .  c  o m
        // add the commit opaque
        responseMap.put("commitopaque", vbucketUUID);
    }

    OutputStream os = resp.getOutputStream();
    resp.setContentType("application/json");
    mapper.writeValue(os, responseMap);
}

From source file:communicator.doSignIn.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww w.  j av  a 2  s.  c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = null;
    JSONObject outputObject = new JSONObject();
    try {
        /* TODO output your page here. You may use following sample code. */

        out = response.getWriter();
        JSONObject signInRequestObject = new JSONObject(IOUtils.toString(request.getInputStream()));
        signInRequestObject = signInRequestObject.getJSONObject(Constants.JSON_SIGNIN_KEY);

        System.out.println(signInRequestObject.toString());

        /**
         * Check For all the keys are present or not.
         */
        JSONObject mJSONObjec = Constants.checkForAllKeys(signInRequestObject, Constants.signInRequestParams);
        System.out.println(mJSONObjec.toString());

        if (mJSONObjec.getString(Constants.JSON_STATUS).compareToIgnoreCase(Constants.JSON_FAILURE) == 0) {
            System.out.println("IF LOOP");
            out.println(mJSONObjec);
            out.close();
            return;
        }

        String emailAddress = signInRequestObject.getString(Constants.JSON_EMAIL_ADDRESS);
        String password = signInRequestObject.getString(Constants.JSON_PASSWORD);//"123456789";

        UserDb mUserDb = userDbFacade.getThisUser(emailAddress, password);

        if (mUserDb == null) {

            try {
                outputObject.put(Constants.JSON_STATUS, Constants.JSON_FAILURE);
                outputObject.put(Constants.JSON_MSG, Constants.JSON_USER_NOT_REGISTERED);
            } catch (JSONException ex1) {
                Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1);
            }

            out.println(outputObject.toString());

        } else {

            Gson gson = new Gson();
            //String json = gson.toJson(mUserDb);

            try {
                outputObject.put(Constants.JSON_STATUS, Constants.JSON_SUCCESS);
                outputObject.put(Constants.JSON_MSG, Constants.JSON_SUCCESS);
                outputObject.put(Constants.JSON_PROFILE, new JSONObject(gson.toJson(mUserDb)));

                out.println(outputObject);
                out.close();
                return;

            } catch (JSONException ex1) {
                Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1);
            }

        }

    } catch (JSONException ex) {

        outputObject = new JSONObject();
        try {
            outputObject.put(Constants.JSON_STATUS, Constants.JSON_FAILURE);
            outputObject.put(Constants.JSON_MSG, Constants.JSON_EXCEPTION);
        } catch (JSONException ex1) {
            Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1);
        }

        out.println(outputObject.toString());
        Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}

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

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

    // read the request
    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);
    logger.trace("pre replicate parsed value is " + parsedValue);

    int vbucket = (Integer) parsedValue.get("vb");
    String bucket = (String) parsedValue.get("bucket");
    String bucketUUID = (String) parsedValue.get("bucketUUID");
    String vbopaque = (String) parsedValue.get("vbopaque");
    String commitopaque = (String) parsedValue.get("commitopaque");

    String vbucketUUID = capiBehavior.getVBucketUUID("default", bucket, vbucket);

    if ((vbopaque != null) && (!vbopaque.equals(vbucketUUID))) {
        logger.debug("returning 400");
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }//w  w w  . ja  va 2 s. co  m
    if ((commitopaque != null) && (!commitopaque.equals(vbucketUUID))) {
        logger.debug("returning 400");
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

    OutputStream os = resp.getOutputStream();
    resp.setContentType("application/json");
    Map<String, Object> responseMap = new HashMap<String, Object>();
    responseMap.put("vbopaque", vbucketUUID);
    mapper.writeValue(os, responseMap);
}

From source file:com.viewer.servlets.ViewDocument.java

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

    response.addHeader("Content-Type", "application/json");
    ViewDocumentParameters params = new ObjectMapper().readValue(request.getInputStream(),
            ViewDocumentParameters.class);

    ViewDocumentResponse result = new ViewDocumentResponse();
    FileData fileData = ViewerUtils.factoryFileData(params.getPath());
    DocumentInfoContainer docInfo = null;

    try {//from   w  w w .j  a va 2s.co m
        result.setDocumentDescription(
                (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false));
    } catch (ParseException x) {
        throw new ServletException(x);
    }

    if (params.getUseHtmlBasedEngine()) {
        try {
            docInfo = ViewerUtils.getViewerHtmlHandler()
                    .getDocumentInfo(new DocumentInfoOptions(params.getPath()));
        } catch (Exception x) {
            throw new ServletException(x);
        }

        result.setPageCss(new String[0]);
        result.setLic(true);
        result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
        result.setPdfPrintUrl(GetPdfPrintUrl(params));
        result.setUrl(GetFileUrl(params));
        result.setPath(params.getPath());
        result.setName(params.getPath());
        try {
            result.setDocumentDescription(
                    (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false));
        } catch (ParseException x) {
            throw new ServletException(x);
        }
        result.setDocType(docInfo.getDocumentType());
        result.setFileType(docInfo.getFileType());

        HtmlOptions htmlOptions = new HtmlOptions();
        htmlOptions.setResourcesEmbedded(true);

        htmlOptions.setHtmlResourcePrefix("/GetResourceForHtml?documentPath=" + params.getPath()
                + "&pageNumber={page-number}&resourceName=");

        if (!DotNetToJavaStringHelper.isNullOrEmpty(params.getPreloadPagesCount().toString())
                && params.getPreloadPagesCount().intValue() > 0) {
            htmlOptions.setPageNumber(1);
            htmlOptions.setCountPagesToConvert(params.getPreloadPagesCount().intValue());
        }

        String[] cssList = null;

        RefObject<ArrayList<String>> tempRef_cssList = new RefObject<ArrayList<String>>(cssList);

        List<PageHtml> htmlPages;
        try {
            htmlPages = GetHtmlPages(params.getPath(), htmlOptions);
            cssList = tempRef_cssList.argValue;

            ArrayList<String> pagesContent = new ArrayList<String>();
            for (PageHtml page : htmlPages) {
                pagesContent.add(page.getHtmlContent());
            }
            String[] htmlContent = pagesContent.toArray(new String[0]);
            result.setPageHtml(htmlContent);
            result.setPageCss(new String[] { String.join(" ", temp_cssList) });

            for (int i = 0; i < result.getPageHtml().length; i++) {
                String html = result.getPageHtml()[i];
                int indexOfScript = html.indexOf("script");
                if (indexOfScript > 0) {
                    result.getPageHtml()[i] = html.substring(0, indexOfScript);
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } else {

        try {
            docInfo = ViewerUtils.getViewerImageHandler()
                    .getDocumentInfo(new DocumentInfoOptions(params.getPath()));
        } catch (Exception x) {
            throw new ServletException(x);
        }

        int maxWidth = 0;
        int maxHeight = 0;
        for (PageData pageData : docInfo.getPages()) {
            if (pageData.getHeight() > maxHeight) {
                maxHeight = pageData.getHeight();
                maxWidth = pageData.getWidth();
            }
        }

        fileData.setDateCreated(new Date());
        fileData.setDateModified(docInfo.getLastModificationDate());
        fileData.setPageCount(docInfo.getPages().size());
        fileData.setPages(docInfo.getPages());
        fileData.setMaxWidth(maxWidth);
        fileData.setMaxHeight(maxHeight);

        result.setPageCss(new String[0]);
        result.setLic(true);
        result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
        result.setPdfPrintUrl(GetPdfPrintUrl(params));
        result.setUrl(GetFileUrl(params.getPath(), true, false, params.getFileDisplayName(),
                params.getWatermarkText(), params.getWatermarkColor(), params.getWatermarkPostion(),
                params.getWatermarkWidth(), params.getIgnoreDocumentAbsence(), params.getUseHtmlBasedEngine(),
                params.getSupportPageRotation()));
        result.setPath(params.getPath());
        result.setName(params.getPath());

        result.setDocType(docInfo.getDocumentType());
        result.setFileType(docInfo.getFileType());

        int[] pageNumbers = new int[docInfo.getPages().size()];
        int count = 0;
        for (PageData page : docInfo.getPages()) {

            pageNumbers[count] = page.getNumber();
            count++;
        }
        String applicationHost = request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort();
        String[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, params);

        result.setImageUrls(imageUrls);

    }

    new ObjectMapper().writeValue(response.getOutputStream(), result);

}

From source file:com.sap.dirigible.runtime.registry.RepositoryServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String repositoryPath = null;
    final OutputStream out = response.getOutputStream();
    try {//from   w  w w.j  av a 2 s.c om
        repositoryPath = extractRepositoryPath(request);
        IEntity entity = getEntity(repositoryPath, request);
        byte[] data;
        if (entity == null) {
            ByteArrayOutputStream buff = new ByteArrayOutputStream();
            IOUtils.copy(request.getInputStream(), buff);
            data = buff.toByteArray();
            String contentType = request.getContentType();
            if (contentType == null) {
                contentType = "text/plain"; //$NON-NLS-1$
            }
            boolean isBinary = ContentTypeHelper.isBinary(contentType);
            getRepository(request).createResource(repositoryPath, data, isBinary, contentType);
        } else {
            if (entity instanceof IResource) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        THERE_IS_AN_EXISTING_RESOURCE_AT_THE_SAME_LOCATION_USE_PUT_METHOD_FOR_UPDATE);
            } else if (entity instanceof ICollection) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        THERE_IS_AN_EXISTING_COLLECTION_AT_THE_SAME_LOCATION);
            }
        }
    } catch (IllegalArgumentException ex) {
        logger.error(String.format(REQUEST_PROCESSING_FAILED_S, repositoryPath) + ex.getMessage());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
    } catch (MissingResourceException ex) {
        logger.error(String.format(REQUEST_PROCESSING_FAILED_S, repositoryPath) + ex.getMessage());
        response.sendError(HttpServletResponse.SC_NO_CONTENT, ex.getMessage());
    } finally {
        out.flush();
        out.close();
    }

}

From source file:org.motechproject.mobile.web.OXDFormUploadServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  w  w.  ja  v  a2  s.c om
 * 
 * @param request
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
@RequestMapping(method = RequestMethod.POST)
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    long startTime = System.currentTimeMillis();

    IMPService impService = (IMPService) appCtx.getBean("impService");
    StudyProcessor studyProcessor = (StudyProcessor) appCtx.getBean("studyProcessor");

    InputStream input = request.getInputStream();
    OutputStream output = response.getOutputStream();

    ZOutputStream zOutput = null; // Wrap the streams for compression

    // Wrap the streams so for logical types
    DataInputStream dataInput = null;
    DataOutputStream dataOutput = null;

    // Set the MIME type so clients don't misinterpret
    response.setContentType("application/octet-stream");

    try {
        zOutput = new ZOutputStream(output, JZlib.Z_BEST_COMPRESSION);
        dataInput = new DataInputStream(input);
        dataOutput = new DataOutputStream(zOutput);

        if (rawUploadLog.isInfoEnabled()) {
            byte[] rawPayload = IOUtils.toByteArray(dataInput);
            String hexEncodedPayload = Hex.encodeHexString(rawPayload);
            rawUploadLog.info(hexEncodedPayload);
            // Replace the original input stream with one using read payload
            dataInput.close();
            dataInput = new DataInputStream(new ByteArrayInputStream(rawPayload));
        }

        String name = dataInput.readUTF();
        String password = dataInput.readUTF();
        String serializer = dataInput.readUTF();
        String locale = dataInput.readUTF();

        byte action = dataInput.readByte();

        // TODO Authentication of usename and password. Possible M6
        // enhancement
        log.info("uploading: name=" + name + ", password=" + password + ", serializer=" + serializer
                + ", locale=" + locale + ", action=" + action);

        EpihandyXformSerializer serObj = new EpihandyXformSerializer();
        serObj.addDeserializationListener(studyProcessor);

        try {
            Map<Integer, String> formVersionMap = formService.getXForms();
            serObj.deserializeStudiesWithEvents(dataInput, formVersionMap);
        } catch (FormNotFoundException fne) {
            String msg = "failed to deserialize forms: ";
            log.error(msg + fne.getMessage());
            dataOutput.writeByte(ResponseHeader.STATUS_FORMS_STALE);
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        } catch (Exception e) {
            String msg = "failed to deserialize forms";
            log.error(msg, e);
            dataOutput.writeByte(ResponseHeader.STATUS_ERROR);
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        String[][] studyForms = studyProcessor.getConvertedStudies();
        int numForms = studyProcessor.getNumForms();

        log.debug("upload contains: studies=" + studyForms.length + ", forms=" + numForms);

        // Starting processing here, only process until we run out of time
        int processedForms = 0;
        int faultyForms = 0;
        if (studyForms != null && numForms > 0) {
            formprocessing: for (int i = 0; i < studyForms.length; i++) {
                for (int j = 0; j < studyForms[i].length; j++, processedForms++) {

                    if (maxProcessingTime > 0 && System.currentTimeMillis() - startTime > maxProcessingTime)
                        break formprocessing;

                    try {
                        studyForms[i][j] = impService.processXForm(studyForms[i][j]);
                    } catch (Exception ex) {
                        log.error("processing form failed", ex);
                        studyForms[i][j] = ex.getMessage();
                    }
                    if (!impService.getFormProcessSuccess().equalsIgnoreCase(studyForms[i][j])) {
                        faultyForms++;
                    }
                }
            }
        }

        // Write out usual upload response
        dataOutput.writeByte(ResponseHeader.STATUS_SUCCESS);

        dataOutput.writeInt(processedForms);
        dataOutput.writeInt(faultyForms);

        for (int s = 0; s < studyForms.length; s++) {
            for (int f = 0; f < studyForms[s].length; f++) {
                if (!impService.getFormProcessSuccess().equalsIgnoreCase(studyForms[s][f])) {
                    dataOutput.writeByte((byte) s);
                    dataOutput.writeShort((short) f);
                    dataOutput.writeUTF(studyForms[s][f]);
                }
            }
        }

        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        log.error("failure during upload", e);
    } finally {
        if (dataOutput != null)
            dataOutput.flush();
        if (zOutput != null)
            zOutput.finish();
        response.flushBuffer();
    }
}