Example usage for org.apache.commons.fileupload FileItem getInputStream

List of usage examples for org.apache.commons.fileupload FileItem getInputStream

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getInputStream.

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Returns an java.io.InputStream InputStream that can be used to retrieve the contents of the file.

Usage

From source file:org.codelabor.system.file.web.controller.xplatform.FileController.java

@RequestMapping("/upload-test")
public String upload(Model model, HttpServletRequest request, ServletContext context) throws Exception {
    logger.debug("upload-teset");
    DataSetList outputDataSetList = new DataSetList();
    VariableList outputVariableList = new VariableList();

    try {/*from   www.ja v a 2 s  .  c  o m*/

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
        logger.debug("paramMap: {}", paramMap.toString());

        String mapId = (String) paramMap.get("mapId");
        RepositoryType acceptedRepositoryType = repositoryType;
        String requestedRepositoryType = (String) paramMap.get("repositoryType");
        if (StringUtils.isNotEmpty(requestedRepositoryType)) {
            acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType);
        }

        if (isMultipart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(sizeThreshold);
            factory.setRepository(new File(tempRepositoryPath));
            factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(context));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(fileSizeMax);
            upload.setSizeMax(requestSizeMax);
            upload.setHeaderEncoding(characterEncoding);
            upload.setProgressListener(new FileUploadProgressListener());

            List<FileItem> fileItemList = upload.parseRequest(request);
            Iterator<FileItem> iter = fileItemList.iterator();

            while (iter.hasNext()) {
                FileItem fileItem = iter.next();
                logger.debug("fileItem: {}", fileItem.toString());
                FileDTO fileDTO = null;
                if (fileItem.isFormField()) {
                    paramMap.put(fileItem.getFieldName(), fileItem.getString(characterEncoding));
                } else {
                    if (fileItem.getName() == null || fileItem.getName().length() == 0)
                        continue;
                    // set DTO
                    fileDTO = new FileDTO();
                    fileDTO.setMapId(mapId);
                    fileDTO.setRealFilename(FilenameUtils.getName(fileItem.getName()));
                    if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) {
                        fileDTO.setUniqueFilename(uniqueFilenameGenerationService.getNextStringId());
                    }
                    fileDTO.setContentType(fileItem.getContentType());
                    fileDTO.setRepositoryPath(realRepositoryPath);
                    logger.debug("fileDTO: {}", fileDTO.toString());
                    UploadUtils.processFile(acceptedRepositoryType, fileItem.getInputStream(), fileDTO);
                }
                if (fileDTO != null)
                    fileManager.insertFile(fileDTO);
            }
        } else {
        }
        XplatformUtils.setSuccessMessage(
                messageSource.getMessage("info.success", new Object[] {}, forcedLocale), outputVariableList);
        logger.debug("success");
    } catch (Exception e) {
        logger.error("fail");
        e.printStackTrace();
        logger.error(e.getMessage());
        throw new XplatformException(messageSource.getMessage("error.failure", new Object[] {}, forcedLocale),
                e);
    }
    model.addAttribute(OUTPUT_DATA_SET_LIST, outputDataSetList);
    model.addAttribute(OUTPUT_VARIABLE_LIST, outputVariableList);
    return VIEW_NAME;

}

From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java

/**
 * ??  .</br> ? ? ?? ?  , (: ?) ? mapId  . ?
 *  ?? ? repositoryType ,  ?/*from   w  w  w. ja va 2  s.com*/
 * org.codelabor.system.file.RepositoryType .
 * 
 * @param request
 *            
 * @param response
 *            ?
 * @throws Exception
 *             
 */
@SuppressWarnings("unchecked")
protected void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap: {}", paramMap.toString());

    String mapId = (String) paramMap.get("mapId");
    RepositoryType acceptedRepositoryType = repositoryType;
    String requestedRepositoryType = (String) paramMap.get("repositoryType");
    if (StringUtils.isNotEmpty(requestedRepositoryType)) {
        acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType);
    }

    if (isMultipart) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(sizeThreshold);
        factory.setRepository(new File(tempRepositoryPath));
        factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(this.getServletContext()));

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(fileSizeMax);
        upload.setSizeMax(requestSizeMax);
        upload.setHeaderEncoding(characterEncoding);
        upload.setProgressListener(new FileUploadProgressListener());
        try {
            List<FileItem> fileItemList = upload.parseRequest(request);
            Iterator<FileItem> iter = fileItemList.iterator();

            while (iter.hasNext()) {
                FileItem fileItem = iter.next();
                logger.debug("fileItem: {}", fileItem.toString());
                FileDTO fileDTO = null;
                if (fileItem.isFormField()) {
                    paramMap.put(fileItem.getFieldName(), fileItem.getString(characterEncoding));
                } else {
                    if (fileItem.getName() == null || fileItem.getName().length() == 0)
                        continue;
                    // set DTO
                    fileDTO = new FileDTO();
                    fileDTO.setMapId(mapId);
                    fileDTO.setRealFilename(FilenameUtils.getName(fileItem.getName()));
                    if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) {
                        fileDTO.setUniqueFilename(getUniqueFilename());
                    }
                    fileDTO.setContentType(fileItem.getContentType());
                    fileDTO.setRepositoryPath(realRepositoryPath);
                    logger.debug("fileDTO: {}", fileDTO.toString());
                    UploadUtils.processFile(acceptedRepositoryType, fileItem.getInputStream(), fileDTO);
                }
                if (fileDTO != null)
                    fileManager.insertFile(fileDTO);
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw e;
        }
    } else {
        paramMap = RequestUtils.getParameterMap(request);
    }
    try {
        processParameters(paramMap);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        throw e;
    }
    dispatch(request, response, forwardPathUpload);
}

From source file:org.coodex.concrete.attachments.server.UploadByFormResource.java

@Path("/{clientId}/{tokenId}")
@POST/*from   w  w  w .j a  va  2  s.c o  m*/
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA })
@Produces(MediaType.APPLICATION_JSON)
public void uploadByForm(@Suspended final AsyncResponse asyncResponse,
        @Context final HttpServletRequest request, @PathParam("clientId") final String clientId,
        @PathParam("tokenId") final String tokenId) {

    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {

            try {
                ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
                List<FileItem> items = uploadHandler.parseRequest(request);
                List<AttachmentEntityInfo> result = new ArrayList<AttachmentEntityInfo>();
                for (FileItem item : items) {
                    if (!item.isFormField()) {
                        if (!Common.isBlank(item.getName())) {
                            AttachmentInfo attachmentInfo = new AttachmentInfo();
                            attachmentInfo.setName(item.getName());
                            attachmentInfo.setOwner(clientId);
                            attachmentInfo.setSize(item.getSize());
                            attachmentInfo.setContentType(item.getContentType());
                            result.add(saveToRepo(clientId, tokenId, attachmentInfo, item.getInputStream()));
                        }
                    }
                }
                asyncResponse.resume(result);
            } catch (Throwable t) {
                asyncResponse.resume(t);
            }
        }
    });
    t.setPriority(AttachmentServiceHelper.ATTACHMENT_PROFILE.getInt("upload.priority", 5));
    t.start();
}

From source file:org.craftercms.cstudio.publishing.servlet.FileUploadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    if (ServletFileUpload.isMultipartContent(request)) {
        ServletFileUpload servletFileUpload = createServletFileUpload();
        List<FileItem> fileItemsList = null;
        Map<String, String> parameters = new HashMap<String, String>(11);
        Map<String, InputStream> files = new HashMap<String, InputStream>(11);
        try {//from  w w w.j  a  va 2  s. c  om
            fileItemsList = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : fileItemsList) {
                if (fileItem.isFormField()) {
                    parameters.put(fileItem.getFieldName(), fileItem.getString());
                } else {
                    files.put(fileItem.getFieldName(), fileItem.getInputStream());
                }
            }

            if (LOGGER.isDebugEnabled()) {

                StringBuilder parametersLog = new StringBuilder("Request Parameters : ");

                for (Entry<String, String> entry : parameters.entrySet()) {

                    String key = entry.getKey();
                    String value = entry.getValue();

                    if (key.equals(PARAM_PASSWORD)) {
                        value = "********";
                    }
                    parametersLog.append(" " + key + " = " + value);
                }

                LOGGER.debug(parametersLog.toString());
            }

            String password = parameters.get(PARAM_PASSWORD);
            if (password != null && password.equalsIgnoreCase(this.password)) {
                deployFiles(parameters, files);
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                if (LOGGER.isWarnEnabled()) {
                    LOGGER.warn(
                            "Illegal publish request received. Password parameter does not match configured password for deployer.");
                }
            }
        } catch (Exception e) {
            handleErrorCase(files, response, e);
        }
    }
}

From source file:org.cvit.cabig.dmr.cmef.server.NewModelResource.java

private org.cvit.cabig.dmr.cmef.domain.File storeFile(FileItem item) {
    if (item.getName() == null || item.getName().equals("")) {
        return null;
    }//from ww  w.  j  av a2 s  .  co  m
    InputStream is;
    try {
        is = item.getInputStream();
    } catch (IOException e) {
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL,
                "Exception uploading files: " + e.getMessage(), e);
    }
    return storeFile(item.getName(), is);
}

From source file:org.danann.cernunnos.runtime.web.CernunnosPortlet.java

@SuppressWarnings("unchecked")
private void runScript(URL u, PortletRequest req, PortletResponse res, RuntimeRequestResponse rrr) {

    // Choose the right Task...
    Task k = getTask(u);//w  w  w. j a  va  2s. c o m

    // Basic, guaranteed request attributes...
    rrr.setAttribute(WebAttributes.REQUEST, req);
    rrr.setAttribute(WebAttributes.RESPONSE, res);

    // Also let's check the request for multi-part form 
    // data & convert to request attributes if we find any...
    List<InputStream> streams = new LinkedList<InputStream>();
    if (req instanceof ActionRequest && PortletFileUpload.isMultipartContent((ActionRequest) req)) {

        if (log.isDebugEnabled()) {
            log.debug("Multipart form data detected (preparing to process).");
        }

        try {
            final DiskFileItemFactory fac = new DiskFileItemFactory();
            final PortletFileUpload pfu = new PortletFileUpload(fac);
            final long maxSize = pfu.getFileSizeMax(); // FixMe!!
            pfu.setFileSizeMax(maxSize);
            pfu.setSizeMax(maxSize);
            fac.setSizeThreshold((int) (maxSize + 1L));
            List<FileItem> items = pfu.parseRequest((ActionRequest) req);
            for (FileItem f : items) {
                if (log.isDebugEnabled()) {
                    log.debug("Processing file upload:  name='" + f.getName() + "',fieldName='"
                            + f.getFieldName() + "'");
                }
                InputStream inpt = f.getInputStream();
                rrr.setAttribute(f.getFieldName(), inpt);
                rrr.setAttribute(f.getFieldName() + "_FileItem", f);
                streams.add(inpt);
            }
        } catch (Throwable t) {
            String msg = "Cernunnos portlet failed to process multipart " + "form data from the request.";
            throw new RuntimeException(msg, t);
        }

    } else {

        if (log.isDebugEnabled()) {
            log.debug("Multipart form data was not detected.");
        }
    }

    // Anything that should be included from the spring_context?
    if (spring_context != null && spring_context.containsBean("requestAttributes")) {
        Map<String, Object> requestAttributes = (Map<String, Object>) spring_context
                .getBean("requestAttributes");
        for (Map.Entry entry : requestAttributes.entrySet()) {
            rrr.setAttribute((String) entry.getKey(), entry.getValue());
        }
    }

    runner.run(k, rrr);

    // Clean up resources...
    if (streams.size() > 0) {
        try {
            for (InputStream inpt : streams) {
                inpt.close();
            }
        } catch (Throwable t) {
            String msg = "Cernunnos portlet failed to release resources.";
            throw new RuntimeException(msg, t);
        }
    }

}

From source file:org.danann.cernunnos.runtime.web.CernunnosServlet.java

@SuppressWarnings("unchecked")
private void runScript(URL u, HttpServletRequest req, HttpServletResponse res, RuntimeRequestResponse rrr)
        throws ServletException {

    try {/*from  w  w w  .j a  v  a 2s  . c o  m*/
        // Choose the right Task...
        Task k = getTask(u);

        // Basic, guaranteed request attributes...
        rrr.setAttribute(WebAttributes.REQUEST, req);
        rrr.setAttribute(WebAttributes.RESPONSE, res);

        // Also let's check the request for multi-part form 
        // data & convert to request attributes if we find any...
        List<InputStream> streams = new LinkedList<InputStream>();
        if (ServletFileUpload.isMultipartContent(req)) {

            log.debug("Miltipart form data detected (preparing to process).");

            try {
                final DiskFileItemFactory fac = new DiskFileItemFactory();
                final ServletFileUpload sfu = new ServletFileUpload(fac);
                final long maxSize = sfu.getFileSizeMax(); // FixMe!!
                sfu.setFileSizeMax(maxSize);
                sfu.setSizeMax(maxSize);
                fac.setSizeThreshold((int) (maxSize + 1L));
                List<FileItem> items = sfu.parseRequest(req);
                for (FileItem f : items) {
                    if (log.isDebugEnabled()) {
                        log.debug("Processing file upload:  name='" + f.getName() + "',fieldName='"
                                + f.getFieldName() + "'");
                    }
                    InputStream inpt = f.getInputStream();
                    rrr.setAttribute(f.getFieldName(), inpt);
                    rrr.setAttribute(f.getFieldName() + "_FileItem", f);
                    streams.add(inpt);
                }
            } catch (Throwable t) {
                String msg = "Cernunnos servlet failed to process multipart " + "form data from the request.";
                throw new RuntimeException(msg, t);
            }

        } else {
            log.debug("Miltipart form data was not detected.");
        }

        // Anything that should be included from the spring_context?
        if (spring_context != null && spring_context.containsBean("requestAttributes")) {
            Map<String, Object> requestAttributes = (Map<String, Object>) spring_context
                    .getBean("requestAttributes");
            for (Map.Entry entry : requestAttributes.entrySet()) {
                rrr.setAttribute((String) entry.getKey(), entry.getValue());
            }
        }

        runner.run(k, rrr);

        // Clean up resources...
        if (streams.size() > 0) {
            try {
                for (InputStream inpt : streams) {
                    inpt.close();
                }
            } catch (Throwable t) {
                String msg = "Cernunnos servlet failed to release resources.";
                throw new RuntimeException(msg, t);
            }
        }

    } catch (Exception ex) {

        // Something went wrong in the Cernunnos script.  

        if (log.isFatalEnabled()) {
            log.fatal("An error occurred during the run", ex);
        }

        throw new ServletException("An error occurred during the run", ex);
    }

}

From source file:org.dataconservancy.dcs.access.server.BagUploadServlet.java

@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(req)) {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Error: Request type not supported.");
        return;//from   w  ww.j  a  v  a  2s .c  om
    }

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List<FileItem> items = upload.parseRequest(req);

        String bagUrl = null;

        for (FileItem item : items) {
            if (item.getFieldName() != null && item.getFieldName().equals("bagUrl")) {
                bagUrl = item.getString();
            }
        }

        if (bagUrl == null) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing required paremeter: depositurl");
            return;
        }

        for (FileItem item : items) {
            String name = item.getName();

            if (item.isFormField() || name == null || name.isEmpty()) {
                continue;
            }

            String property = "java.io.tmpdir";

            String tempDir = System.getProperty(property);

            File dir = new File(tempDir);
            String path = dir.getAbsoluteFile() + "/" + item.getName();

            IOUtils.copy(item.getInputStream(), new FileOutputStream(path));
            getSIPfile(bagUrl, path, resp);
        }
    } catch (IOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error: " + e.getMessage());
        return;
    } catch (FileUploadException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error: " + e.getMessage());
        return;
    } catch (InvalidXmlException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.dataconservancy.dcs.access.server.FileUploadServlet.java

@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(req)) {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Error: Request type not supported.");
        return;//w  w  w  .  j a v  a  2 s .  c  om
    }

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List<FileItem> items = upload.parseRequest(req);

        String depositurl = null;

        for (FileItem item : items) {
            if (item.getFieldName() != null && item.getFieldName().equals("depositurl")) {
                depositurl = item.getString();
            }
        }

        if (depositurl == null) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing required paremeter: depositurl");
            return;
        }

        for (FileItem item : items) {
            String name = item.getName();

            if (item.isFormField() || name == null || name.isEmpty()) {
                continue;
            }

            uploadfile(depositurl, name, item.getInputStream(), resp);
        }
    } catch (IOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error: " + e.getMessage());
        return;
    } catch (FileUploadException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error: " + e.getMessage());
        return;
    }
}

From source file:org.deegree.services.controller.OGCFrontController.java

/**
 * Handles HTTP POST requests./*from  w ww .j a  v  a2 s  .c o  m*/
 * <p>
 * An HTTP POST request specifies parameters in the request body. OGC service specifications use three different
 * ways to encode the parameters:
 * <ul>
 * <li><b>KVP</b>: Parameters are given as <code>key=value</code> pairs which are separated using the &amp;
 * character. This is equivalent to standard HTTP GET requests, except that the parameters are not part of the query
 * string, but the POST body. In this case, the <code>content-type</code> field in the header must be
 * <code>application/x-www-form-urlencoded</code>.</li>
 * <li><b>XML</b>: The POST body contains an XML document. In this case, the <code>content-type</code> field in the
 * header has to be <code>text/xml</code>, but the implementation does not rely on this in order to be more tolerant
 * to clients.</li>
 * <li><b>SOAP</b>: TODO</li>
 * <li><b>Multipart</b>: TODO</li>
 * </ul>
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpResponseBuffer responseBuffer = createHttpResponseBuffer(request, response);

    try {
        logHeaders(request);
        addHeaders(responseBuffer);
        responseBuffer = handleCompression(responseBuffer);

        LOG.debug("doPost(), contentType: '" + request.getContentType() + "'");

        long entryTime = System.currentTimeMillis();
        try {
            // check if content-type implies that it's a KVP request
            String contentType = request.getContentType();
            boolean isKVP = false;
            if (contentType != null) {
                isKVP = request.getContentType().startsWith("application/x-www-form-urlencoded");
            }
            List<FileItem> multiParts = checkAndRetrieveMultiparts(request);
            InputStream is = request.getInputStream();

            if (isKVP) {
                String queryString = readPostBodyAsString(is);
                LOG.debug("Treating POST input stream as KVP parameters. Raw input: '" + queryString + "'.");
                Map<String, String> normalizedKVPParams = null;
                String encoding = request.getCharacterEncoding();
                if (encoding == null) {
                    LOG.debug("Request has no further encoding information. Defaulting to '" + DEFAULT_ENCODING
                            + "'.");
                    normalizedKVPParams = KVPUtils.getNormalizedKVPMap(queryString, DEFAULT_ENCODING);
                } else {
                    LOG.debug("Client encoding information :" + encoding);
                    normalizedKVPParams = KVPUtils.getNormalizedKVPMap(queryString, encoding);
                }
                dispatchKVPRequest(normalizedKVPParams, request, responseBuffer, multiParts, entryTime);
            } else {
                // if( handle multiparts, get first body from multipart (?)
                // body->requestDoc

                InputStream requestInputStream = null;
                if (multiParts != null && multiParts.size() > 0) {
                    for (int i = 0; i < multiParts.size() && requestInputStream == null; ++i) {
                        FileItem item = multiParts.get(i);
                        if (item != null) {
                            LOG.debug("Using multipart item: " + i + " with contenttype: "
                                    + item.getContentType() + " as the request.");
                            requestInputStream = item.getInputStream();
                        }
                    }
                } else {
                    requestInputStream = is;
                }
                if (requestInputStream == null) {
                    String msg = "Could not create a valid inputstream from request "
                            + ((multiParts != null && multiParts.size() > 0) ? "without" : "with")
                            + " multiparts.";
                    LOG.error(msg);
                    throw new IOException(msg);
                }

                String dummySystemId = "HTTP Post request from " + request.getRemoteAddr() + ":"
                        + request.getRemotePort();
                XMLStreamReader xmlStream = XMLInputFactoryUtils.newSafeInstance()
                        .createXMLStreamReader(dummySystemId, requestInputStream);
                // skip to start tag of root element
                XMLStreamUtils.nextElement(xmlStream);
                if (isSOAPRequest(xmlStream)) {
                    dispatchSOAPRequest(xmlStream, request, responseBuffer, multiParts);
                } else {
                    dispatchXMLRequest(xmlStream, request, responseBuffer, multiParts);
                }
            }
        } catch (Throwable e) {
            LOG.debug("Handling HTTP-POST request took: " + (System.currentTimeMillis() - entryTime)
                    + " ms before sending exception.");
            LOG.debug(e.getMessage(), e);
            OWSException ex = new OWSException(e.getLocalizedMessage(), "InvalidRequest");
            OWS ows = null;
            try {
                ows = determineOWSByPath(request);
            } catch (OWSException e2) {
                sendException(ows, e2, responseBuffer, null);
                return;
            }
            sendException(ows, ex, responseBuffer, null);
        }
        LOG.debug("Handling HTTP-POST request with status 'success' took: "
                + (System.currentTimeMillis() - entryTime) + " ms.");
    } finally {
        instance.CONTEXT.remove();
        responseBuffer.flushBuffer();
        if (mainConfig.isValidateResponses() != null && mainConfig.isValidateResponses()) {
            validateResponse(responseBuffer);
        }
    }
}