Example usage for javax.servlet.http HttpServletRequest getContentType

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

Introduction

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

Prototype

public String getContentType();

Source Link

Document

Returns the MIME type of the body of the request, or null if the type is not known.

Usage

From source file:com.jaspersoft.jasperserver.rest.utils.Utils.java

public boolean isMultipartContent(HttpServletRequest request) {
    if (!(RESTAbstractService.HTTP_PUT.equals(request.getMethod().toLowerCase())
            || RESTAbstractService.HTTP_POST.equals(request.getMethod().toLowerCase()))) {
        return false;
    }/*from www .ja v a 2  s . co m*/
    String contentType = request.getContentType();
    if (contentType == null) {
        return false;
    }
    if (contentType.toLowerCase().startsWith("multipart/")) {
        return true;
    }
    return false;
}

From source file:org.ngrinder.script.controller.DavSvnController.java

private void logRequest(HttpServletRequest request) {
    StringBuilder logBuffer = new StringBuilder();
    logBuffer.append('\n');
    logBuffer.append("request.getAuthType(): " + request.getAuthType());
    logBuffer.append('\n');
    logBuffer.append("request.getCharacterEncoding(): " + request.getCharacterEncoding());
    logBuffer.append('\n');
    logBuffer.append("request.getContentType(): " + request.getContentType());
    logBuffer.append('\n');
    logBuffer.append("request.getContextPath(): " + request.getContextPath());
    logBuffer.append('\n');
    logBuffer.append("request.getContentLength(): " + request.getContentLength());
    logBuffer.append('\n');
    logBuffer.append("request.getMethod(): " + request.getMethod());
    logBuffer.append('\n');
    logBuffer.append("request.getPathInfo(): " + request.getPathInfo());
    logBuffer.append('\n');
    logBuffer.append("request.getPathTranslated(): " + request.getPathTranslated());
    logBuffer.append('\n');
    logBuffer.append("request.getQueryString(): " + request.getQueryString());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteAddr(): " + request.getRemoteAddr());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteHost(): " + request.getRemoteHost());
    logBuffer.append('\n');
    logBuffer.append("request.getRemoteUser(): " + request.getRemoteUser());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURI(): " + request.getRequestURI());
    logBuffer.append('\n');
    logBuffer.append("request.getServerName(): " + request.getServerName());
    logBuffer.append('\n');
    logBuffer.append("request.getServerPort(): " + request.getServerPort());
    logBuffer.append('\n');
    logBuffer.append("request.getServletPath(): " + request.getServletPath());
    logBuffer.append('\n');
    logBuffer.append("request.getRequestURL(): " + request.getRequestURL());
    LOGGER.trace(logBuffer.toString());//from www.ja v  a  2 s.c  o m
}

From source file:org.openrdf.http.server.repository.RepositoryController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String reqMethod = request.getMethod();
    String queryStr = request.getParameter(QUERY_PARAM_NAME);

    if (METHOD_POST.equals(reqMethod)) {
        String mimeType = HttpServerUtil.getMIMEType(request.getContentType());

        if (!(Protocol.FORM_MIME_TYPE.equals(mimeType) || Protocol.SPARQL_QUERY_MIME_TYPE.equals(mimeType))) {
            throw new ClientHTTPException(SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported MIME type: " + mimeType);
        }/*from www. ja  va  2s .  c  om*/

        if (Protocol.SPARQL_QUERY_MIME_TYPE.equals(mimeType)) {
            // The query should be the entire body
            try {
                queryStr = IOUtils.toString(request.getReader());
            } catch (IOException e) {
                throw new HTTPException(HttpStatus.SC_BAD_REQUEST, "Error reading request message body", e);
            }
            if (queryStr.isEmpty())
                queryStr = null;
        }
    } else if (METHOD_DELETE.equals(reqMethod)) {
        String repId = RepositoryInterceptor.getRepositoryID(request);
        logger.info("DELETE request invoked for repository '" + repId + "'");

        if (queryStr != null) {
            logger.warn("query supplied on repository delete request, aborting delete");
            throw new HTTPException(HttpStatus.SC_BAD_REQUEST,
                    "Repository delete error: query supplied with request");
        }

        if (SystemRepository.ID.equals(repId)) {
            logger.warn("attempted delete of SYSTEM repository, aborting");
            throw new HTTPException(HttpStatus.SC_FORBIDDEN, "SYSTEM Repository can not be deleted");
        }

        try {
            // we need to forcibly close the default repository connection
            // opened for this repository by
            // the interceptor.
            RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request);
            synchronized (repositoryCon) {
                repositoryCon.close();
            }

            boolean success = repositoryManager.removeRepository(repId);
            if (success) {
                logger.info("DELETE request successfully completed");
                return new ModelAndView(EmptySuccessView.getInstance());
            } else {
                logger.error("error while attempting to delete repository '" + repId + "'");
                throw new HTTPException(HttpStatus.SC_BAD_REQUEST,
                        "could not locate repository configuration for repository '" + repId + "'.");
            }
        } catch (OpenRDFException e) {
            logger.error("error while attempting to delete repository '" + repId + "'", e);
            throw new ServerHTTPException("Repository delete error: " + e.getMessage(), e);
        }
    }

    Repository repository = RepositoryInterceptor.getRepository(request);

    int qryCode = 0;
    if (logger.isInfoEnabled() || logger.isDebugEnabled()) {
        qryCode = String.valueOf(queryStr).hashCode();
    }

    boolean headersOnly = false;
    if (METHOD_GET.equals(reqMethod)) {
        logger.info("GET query {}", qryCode);
    } else if (METHOD_HEAD.equals(reqMethod)) {
        logger.info("HEAD query {}", qryCode);
        headersOnly = true;
    } else if (METHOD_POST.equals(reqMethod)) {
        logger.info("POST query {}", qryCode);
    }

    logger.debug("query {} = {}", qryCode, queryStr);

    if (queryStr != null) {
        RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request);
        synchronized (repositoryCon) {
            Query query = getQuery(repository, repositoryCon, queryStr, request, response);

            View view;
            Object queryResult;
            FileFormatServiceRegistry<? extends FileFormat, ?> registry;

            try {
                if (query instanceof TupleQuery) {
                    TupleQuery tQuery = (TupleQuery) query;

                    queryResult = headersOnly ? null : tQuery.evaluate();
                    registry = TupleQueryResultWriterRegistry.getInstance();
                    view = TupleQueryResultView.getInstance();
                } else if (query instanceof GraphQuery) {
                    GraphQuery gQuery = (GraphQuery) query;

                    queryResult = headersOnly ? null : gQuery.evaluate();
                    registry = RDFWriterRegistry.getInstance();
                    view = GraphQueryResultView.getInstance();
                } else if (query instanceof BooleanQuery) {
                    BooleanQuery bQuery = (BooleanQuery) query;

                    queryResult = headersOnly ? null : bQuery.evaluate();
                    registry = BooleanQueryResultWriterRegistry.getInstance();
                    view = BooleanQueryResultView.getInstance();
                } else {
                    throw new ClientHTTPException(SC_BAD_REQUEST,
                            "Unsupported query type: " + query.getClass().getName());
                }
            } catch (QueryInterruptedException e) {
                logger.info("Query interrupted", e);
                throw new ServerHTTPException(SC_SERVICE_UNAVAILABLE, "Query evaluation took too long");
            } catch (QueryEvaluationException e) {
                logger.info("Query evaluation error", e);
                if (e.getCause() != null && e.getCause() instanceof HTTPException) {
                    // custom signal from the backend, throw as HTTPException
                    // directly (see SES-1016).
                    throw (HTTPException) e.getCause();
                } else {
                    throw new ServerHTTPException("Query evaluation error: " + e.getMessage());
                }
            }
            Object factory = ProtocolUtil.getAcceptableService(request, response, registry);

            Map<String, Object> model = new HashMap<String, Object>();
            model.put(QueryResultView.FILENAME_HINT_KEY, "query-result");
            model.put(QueryResultView.QUERY_RESULT_KEY, queryResult);
            model.put(QueryResultView.FACTORY_KEY, factory);
            model.put(QueryResultView.HEADERS_ONLY, headersOnly);

            return new ModelAndView(view, model);
        }
    } else {
        throw new ClientHTTPException(SC_BAD_REQUEST, "Missing parameter: " + QUERY_PARAM_NAME);
    }
}

From source file:com.krawler.esp.servlets.FileImporterServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww  w  .ja  va  2 s  . c  o  m
 * 
 * @param request
 *            servlet request
 * @param response
 *            servlet response
 */
@SuppressWarnings("static-access")
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SessionExpiredException {
    String contentType = request.getContentType();
    response.setContentType("text/html;charset=UTF-8");
    boolean isFormSubmit = false;
    String emsg = KWLErrorMsgs.errMsgImportMPX;
    if (SessionHandler.isValidSession(request, response)) {
        String resString = null;
        File f1 = null;
        FileInputStream fstream = null;
        mppparser c = null;
        JSONObject jo = null;
        int action = Integer.parseInt(request.getParameter("action"));
        try {
            switch (action) {
            case 1:
                isFormSubmit = true;
                jo = new JSONObject();
                if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
                    String docid = UUID.randomUUID().toString();
                    f1 = getfile(request, docid);
                    fstream = new FileInputStream(f1);
                    c = new mppparser();
                    String newres = c.getResourceInfo(fstream, Integer.parseInt(request.getParameter("type")));
                    JSONObject jarr = new JSONObject(newres);
                    jo.put("success", true);
                    if (jarr.getJSONArray("data").length() > 0 && request.getParameter("isres").equals("1")) // if imported file contains resources then send list
                    //for mapping with existing resources
                    {
                        jo.put("newresource", newres);
                        jo.put("docid", docid);
                        resString = jo.toString();
                    } else { // else import tasks
                        fstream = new FileInputStream(f1);// read uploded file
                        HashMap mp = importFile(fstream, docid, request); // store tasks
                        String errormsg = ((ArrayList) mp.get("errormsg")).get(0).toString();
                        jo.put("errormsg", errormsg);
                        resString = jo.toString();
                    }
                } else {
                    jo.put("success", false);
                    jo.put("msg", "Error occured at server while importing file.");
                    resString = jo.toString();
                }
                break;
            case 2:// after mapping with existing resources
                jo = new JSONObject();
                fstream = getStoredfile(request.getParameter("docid")); // read stored file
                HashMap mp = importFile(fstream, request.getParameter("docid"), request); // store tasks
                mapImportedRes(request.getParameter("val"), mp);// allocate tasks to mapped resources
                if (request.getParameter("isbaseline").equals("1")) {
                    saveBaseline(request);
                }
                String errormsg = ((ArrayList) mp.get("errormsg")).get(0).toString();
                jo.put("success", true);
                jo.put("errormsg", errormsg);
                resString = jo.toString();
                break;
            }
        } catch (com.krawler.utils.json.base.JSONException xex) {
            resString = "Problem FileImporterServlet while importing project[connection]:" + xex.toString();
            KrawlerLog.op.warn(resString);
            resString = "{\"success\":false, \"msg\":\"" + emsg + "\", \"errormsg\":\"" + resString + "\"}";
        } catch (ServiceException xex) {
            resString = "Problem FileImporterServlet while importing project[connection]:" + xex.toString();
            KrawlerLog.op.warn(resString);
            resString = "{\"success\":false, \"msg\":\"" + emsg + "\", \"errormsg\":\"" + resString + "\"}";
        } catch (MPXJException xex) {
            resString = "Problem FileImporterServlet while importing project[connection]:" + xex.toString();
            KrawlerLog.op.warn(resString);
            resString = "{\"success\":false, \"msg\":\"" + KWLErrorMsgs.errMsgImportMPXInvalidFileFormat
                    + "\", \"errormsg\":\"" + resString + "\"}";
        } catch (Exception xex) {
            resString = "Problem FileImporterServlet while importing project[connection]:" + xex.toString();
            KrawlerLog.op.warn(resString);
            resString = "{\"success\":false, \"msg\":\"" + emsg + "\", \"errormsg\":\"" + resString + "\"}";
        } finally {
            if (fstream != null)
                fstream.close();
            if (!isFormSubmit) {
                try {
                    JSONObject jbj = new com.krawler.utils.json.base.JSONObject();
                    jbj.put("valid", "true");
                    jbj.put("data", resString);
                    response.getWriter().println(jbj.toString());
                } catch (com.krawler.utils.json.base.JSONException ex) {
                    Logger.getLogger(FileImporterServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                response.getWriter().println(resString);
            }
            response.getWriter().close();
        }
    } else { //session valid if() ends here
        response.getWriter().println("{\"valid\": false}");
    }
}

From source file:org.eclipse.rdf4j.http.server.repository.statements.StatementsController.java

/**
 * Upload data to the repository./*w  ww . j a v  a  2  s  . c om*/
 */
private ModelAndView getAddDataResult(Repository repository, HttpServletRequest request,
        HttpServletResponse response, boolean replaceCurrent)
        throws IOException, ServerHTTPException, ClientHTTPException, HTTPException {
    ProtocolUtil.logRequestParameters(request);

    String mimeType = HttpServerUtil.getMIMEType(request.getContentType());

    RDFFormat rdfFormat = Rio.getParserFormatForMIMEType(mimeType).orElseThrow(
            () -> new ClientHTTPException(SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported MIME type: " + mimeType));

    ValueFactory vf = repository.getValueFactory();

    Resource[] contexts = ProtocolUtil.parseContextParam(request, CONTEXT_PARAM_NAME, vf);
    IRI baseURI = ProtocolUtil.parseURIParam(request, BASEURI_PARAM_NAME, vf);
    final boolean preserveNodeIds = ProtocolUtil.parseBooleanParam(request,
            Protocol.PRESERVE_BNODE_ID_PARAM_NAME, false);

    if (baseURI == null) {
        baseURI = vf.createIRI("foo:bar");
        logger.info("no base URI specified, using dummy '{}'", baseURI);
    }

    InputStream in = request.getInputStream();
    try (RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request)) {
        repositoryCon.begin();

        if (preserveNodeIds) {
            repositoryCon.getParserConfig().set(BasicParserSettings.PRESERVE_BNODE_IDS, true);
        }

        if (replaceCurrent) {
            repositoryCon.clear(contexts);
        }
        repositoryCon.add(in, baseURI.toString(), rdfFormat, contexts);

        repositoryCon.commit();

        return new ModelAndView(EmptySuccessView.getInstance());
    } catch (UnsupportedRDFormatException e) {
        throw new ClientHTTPException(SC_UNSUPPORTED_MEDIA_TYPE,
                "No RDF parser available for format " + rdfFormat.getName());
    } catch (RDFParseException e) {
        ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_DATA, e.getMessage());
        throw new ClientHTTPException(SC_BAD_REQUEST, errInfo.toString());
    } catch (IOException e) {
        throw new ServerHTTPException("Failed to read data: " + e.getMessage(), e);
    } catch (RepositoryException e) {
        if (e.getCause() != null && e.getCause() instanceof HTTPException) {
            // custom signal from the backend, throw as HTTPException
            // directly
            // (see SES-1016).
            throw (HTTPException) e.getCause();
        } else {
            throw new ServerHTTPException("Repository update error: " + e.getMessage(), e);
        }
    }
}

From source file:org.bibsonomy.rest.RestServlet.java

/**
 * Sends an error to the client.//from w  ww . j av a 2s .  c om
 * 
 * @param request
 *            the current {@link HttpServletRequest} object.
 * @param response
 *            the current {@link HttpServletResponse} object.
 * @param code
 *            the error code to send.
 * @param message
 *            the message to send.
 * @throws IOException
 */
private void sendError(final HttpServletRequest request, final HttpServletResponse response, final int code,
        final String message) throws IOException {
    // get renderer
    final RenderingFormat mediaType = RESTUtils.getRenderingFormatForRequest(request.getParameterMap(),
            request.getHeader(HeaderUtils.HEADER_ACCEPT), request.getContentType());
    final Renderer renderer = rendererFactory.getRenderer(mediaType);

    // send error
    response.setStatus(code);
    response.setContentType(mediaType.getMimeType());
    final ByteArrayOutputStream cachingStream = new ByteArrayOutputStream();
    final Writer writer = new OutputStreamWriter(cachingStream, Charset.forName(RESPONSE_ENCODING));
    renderer.serializeError(writer, message);
    response.setContentLength(cachingStream.size());
    response.getOutputStream().print(cachingStream.toString(RESPONSE_ENCODING));
}

From source file:org.openrdf.http.server.repository.statements.StatementsController.java

/**
 * Upload data to the repository.//  ww w  .ja v  a  2  s . c  om
 */
private ModelAndView getAddDataResult(Repository repository, HttpServletRequest request,
        HttpServletResponse response, boolean replaceCurrent)
        throws IOException, ServerHTTPException, ClientHTTPException, HTTPException {
    ProtocolUtil.logRequestParameters(request);

    String mimeType = HttpServerUtil.getMIMEType(request.getContentType());

    RDFFormat rdfFormat = Rio.getParserFormatForMIMEType(mimeType).orElseThrow(
            () -> new ClientHTTPException(SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported MIME type: " + mimeType));

    ValueFactory vf = repository.getValueFactory();

    Resource[] contexts = ProtocolUtil.parseContextParam(request, CONTEXT_PARAM_NAME, vf);
    IRI baseURI = ProtocolUtil.parseURIParam(request, BASEURI_PARAM_NAME, vf);
    final boolean preserveNodeIds = ProtocolUtil.parseBooleanParam(request,
            Protocol.PRESERVE_BNODE_ID_PARAM_NAME, false);

    if (baseURI == null) {
        baseURI = vf.createIRI("foo:bar");
        logger.info("no base URI specified, using dummy '{}'", baseURI);
    }

    InputStream in = request.getInputStream();
    try {
        RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request);
        synchronized (repositoryCon) {
            if (!repositoryCon.isActive()) {
                repositoryCon.begin();
            }

            if (preserveNodeIds) {
                repositoryCon.getParserConfig().set(BasicParserSettings.PRESERVE_BNODE_IDS, true);
            }

            if (replaceCurrent) {
                repositoryCon.clear(contexts);
            }
            repositoryCon.add(in, baseURI.toString(), rdfFormat, contexts);

            repositoryCon.commit();
        }

        return new ModelAndView(EmptySuccessView.getInstance());
    } catch (UnsupportedRDFormatException e) {
        throw new ClientHTTPException(SC_UNSUPPORTED_MEDIA_TYPE,
                "No RDF parser available for format " + rdfFormat.getName());
    } catch (RDFParseException e) {
        ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_DATA, e.getMessage());
        throw new ClientHTTPException(SC_BAD_REQUEST, errInfo.toString());
    } catch (IOException e) {
        throw new ServerHTTPException("Failed to read data: " + e.getMessage(), e);
    } catch (RepositoryException e) {
        if (e.getCause() != null && e.getCause() instanceof HTTPException) {
            // custom signal from the backend, throw as HTTPException directly
            // (see SES-1016).
            throw (HTTPException) e.getCause();
        } else {
            throw new ServerHTTPException("Repository update error: " + e.getMessage(), e);
        }
    }
}

From source file:org.sakaiproject.jsf.renderer.InputFileUploadRenderer.java

/**
 * Check for errors (both developer errors and user errors) - return a
 * user-friendly error message describing the error, or null if there are no
 * errors.//from w ww .  j  a va2  s.c  om
 */
private static String checkForErrors(FacesContext context, UIComponent component, String clientId,
        boolean atDecodeTime) {
    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();

    UIForm form = null;
    try {
        form = getForm(component);
    } catch (IllegalArgumentException e) {
        // there are more than one nested form - thats not OK!
        return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in just ONE form.  Nested forms confuse the browser.";
    }
    if (form == null || !"multipart/form-data".equals(RendererUtil.getAttribute(context, form, "enctype"))) {
        return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in a <h:form enctype=\"multipart/form-data\"> tag.";
    }

    // check tag attributes
    String directory = (String) RendererUtil.getAttribute(context, component, "directory");
    if (directory != null && directory.length() != 0) {
        // the tag is configured to persist the uploaded files to a directory.
        // check that the specified directory exists, and is writeable
        File dir = new File(directory);
        if (!dir.isDirectory() || !dir.exists()) {
            return "DEVELOPER ERROR: The directory specified on the <inputFileUpload> tag does not exist or is not writable.\n"
                    + "Check the permissions on directory:\n" + dir;
        }
    }

    FileItem item = getFileItem(context, component);
    boolean isMultipartRequest = request.getContentType() != null
            && request.getContentType().startsWith("multipart/form-data");
    boolean wasMultipartRequestFullyParsed = request.getParameter(clientId + ID_HIDDEN_ELEMENT) != null;
    String requestFilterStatus = (String) request.getAttribute("upload.status");
    Object requestFilterUploadLimit = request.getAttribute("upload.limit");
    Exception requestFilterException = (Exception) request.getAttribute("upload.exception");
    boolean wasDecodeAlreadyCalledOnTheRequest = "true"
            .equals(request.getAttribute(clientId + ATTR_REQUEST_DECODED));

    if (wasDecodeAlreadyCalledOnTheRequest && !atDecodeTime) {
        // decode() was already called on the request, and we're now at encode() time - so don't do further error checking
        // as the FileItem may no longer be valid.
        return null;
    }

    // at this point, if its not a multipart request, it doesn't have a file and there isn't an error.
    if (!isMultipartRequest)
        return null;

    // check for user errors
    if ("exception".equals(requestFilterStatus)) {
        return "An error occured while processing the uploaded file.  The error was:\n"
                + requestFilterException;
    } else if ("size_limit_exceeded".equals(requestFilterStatus)) {
        // the user tried to upload too large a file
        return "The upload size limit of " + requestFilterUploadLimit + "MB has been exceeded.";
    } else if (item == null || item.getName() == null || item.getName().length() == 0) {
        // The file item will be null if the component was previously not rendered.
        return null;
    } else if (item.getSize() == 0) {
        return "The filename '" + item.getName() + "' is invalid.  Please select a valid file.";
    }

    if (!wasMultipartRequestFullyParsed) {
        return "An error occured while processing the uploaded file.  The error was:\n"
                + "DEVELOPER ERROR: The <inputFileUpload> tag requires a <filter> in web.xml to parse the uploaded file.\n"
                + "Check that the Sakai RequestFilter is properly configured in web.xml.";
    }

    if (item.getName().indexOf("..") >= 0) {
        return "The filename '" + item.getName() + "' is invalid.  Please select a valid file.";
    }

    // everything checks out fine! The upload was parsed, and a FileItem
    // exists with a filename and non-zero length
    return null;
}

From source file:eionet.gdem.utils.FileUpload.java

/**
 * Uploads file from client to the server. Parses HttpRequestInputstream and writes bytes to the specified folder in the same
 * computer, where servlet runs/*  w  w w.  j  av  a  2  s  .c  o  m*/
 *
 * @param req request
 * @throws GDEMException If an error occurs.
 */
public File uploadFile(HttpServletRequest req) throws GDEMException {

    // helper arrays
    byte[] bt1 = new byte[4096];
    byte[] bt2 = new byte[4096];

    int[] int1 = new int[1];
    int[] int2 = new int[1];
    ServletInputStream si = null;

    try {
        si = req.getInputStream();
        String contentType = req.getContentType();
        String charEncoding = req.getCharacterEncoding();
        // +RV020508
        int contentLength = req.getContentLength();
        lenRcvd = 0;
        if (contentLength == -1) {
            throw new GDEMException("Invalid HTTP POST. Content length is unknown.");
        }
        //
        int boundaryPos;
        if ((boundaryPos = contentType.indexOf("boundary=")) != -1) {
            contentType = contentType.substring(boundaryPos + 9);
            contentType = "--" + contentType;
        } // end if

        // Find filename
        String fileName;
        while ((fileName = readLine(bt1, int1, si, charEncoding)) != null) {
            int i = fileName.indexOf("filename=");
            if (i >= 0) {
                fileName = fileName.substring(i + 10);
                i = fileName.indexOf("\"");
                if (i > 0) {
                    FileOutputStream fileOut = null;
                    boolean fWrite = false;
                    File tmpFile = new File(_folderName, getSessionId());
                    try {

                        fileName = fileName.substring(0, i);

                        fileName = getFileName(fileName);

                        // _fileName is returned by getFileName() method
                        _fileName = fileName;

                        String line2 = readLine(bt1, int1, si, charEncoding);
                        if (line2.indexOf("Content-Type") >= 0) {
                            readLine(bt1, int1, si, charEncoding);
                        }

                        fileOut = new FileOutputStream(tmpFile);

                        String helpStr = null;
                        long l = 0L;

                        // changes to true, if something is written to the output file
                        // remains false, if user has entered a wrong filename or the file's size is 0kB

                        // parse the file in the MIME message
                        while ((line2 = readLine(bt1, int1, si, charEncoding)) != null) {
                            if (line2.indexOf(contentType) == 0 && bt1[0] == 45) {
                                break;
                            }
                            if (helpStr != null && l <= 75L) {
                                fWrite = true;
                                fileOut.write(bt2, 0, int2[0]);
                                fileOut.flush();
                            } // endif
                            helpStr = readLine(bt2, int2, si, charEncoding);
                            if (helpStr == null || helpStr.indexOf(contentType) == 0 && bt2[0] == 45) {
                                break;
                            }

                            fWrite = true;
                            fileOut.write(bt1, 0, int1[0]);
                            fileOut.flush();
                        } // end while

                        byte bt0;

                        if (lineSep.length() == 1) {
                            bt0 = 2;
                        } else {
                            bt0 = 1;
                        }

                        if (helpStr != null && bt2[0] != 45 && int2[0] > lineSep.length() * bt0) {
                            fileOut.write(bt2, 0, int2[0] - lineSep.length() * bt0);
                            fWrite = true;
                        }
                        if (line2 != null && bt1[0] != 45 && int1[0] > lineSep.length() * bt0) {
                            fileOut.write(bt1, 0, int1[0] - lineSep.length() * bt0);
                            fWrite = true;
                        }
                    } finally {
                        IOUtils.closeQuietly(fileOut);
                    }
                    if (fWrite) {
                        try {
                            synchronized (fileLock) {
                                File file = new File(_folderName, fileName);
                                int n = 0;
                                while (file.exists()) {
                                    n++;
                                    fileName = genFileName(fileName, n);
                                    file = new File(_folderName, fileName);
                                }
                                setFileName(fileName);
                                try {
                                    file.delete();
                                } catch (Exception _ex) {
                                    throw new GDEMException("Error deleting temporary file: " + _ex.toString());
                                }
                                tmpFile.renameTo(file);
                                return file;
                            } // sync
                        } catch (Exception _ex) {
                            throw new GDEMException("Error renaming temporary file: " + _ex.toString());
                        }

                    } else { // end-if file = 0kb or does not exist
                        tmpFile.delete();
                        throw new GDEMException("File: " + fileName + " does not exist or contains no data.");
                    }

                }
                // break;
            } // end if (filename found)
        } // end while
          // +RV020508
        if (contentLength != lenRcvd) {
            throw new GDEMException(
                    "Canceled upload: expected " + contentLength + " bytes, received " + lenRcvd + " bytes.");
        }
    } catch (IOException e) {
        throw new GDEMException("Error uploading file: " + e.toString());
    } finally {
        IOUtils.closeQuietly(si);
    }

    return null;
}

From source file:byps.http.HActiveMessages.java

private void addIncomingStreamAsync(final BTargetId targetId, HRequestContext rctxt) throws BException {
    if (log.isDebugEnabled())
        log.debug("addIncomingStreamAsync(targetId=" + targetId + ", rctxt=" + rctxt);

    try {//from   w  ww  .  j a  v  a2s.co  m
        final HttpServletRequest request = (HttpServletRequest) (rctxt.getRequest());
        final String contentType = request.getContentType();
        final String contentDisposition = request.getHeader("Content-Disposition");
        final String contentLengthStr = request.getHeader("Content-Length");
        final long contentLength = contentLengthStr != null && contentLengthStr.length() != 0
                ? Long.parseLong(contentLengthStr)
                : -1L;
        final String totalLengthStr = request.getParameter("total");
        final long totalLength = totalLengthStr != null && totalLengthStr.length() != 0
                ? Long.parseLong(totalLengthStr)
                : -1L;
        final String partIdStr = request.getParameter("partid");
        final long partId = partIdStr != null && partIdStr.length() != 0 ? Long.parseLong(partIdStr) : -1L;
        final String lastPartStr = request.getParameter("last");
        final boolean isLastPart = lastPartStr != null && lastPartStr.length() != 0
                ? (Integer.valueOf(lastPartStr) != 0)
                : true;

        HAsyncErrorListener alsn = new HAsyncErrorListener() {
            @Override
            public void onError(AsyncEvent arg0) throws IOException {
                if (log.isDebugEnabled())
                    log.debug("AsyncErrorListener.onError(" + arg0 + ")");
                final Long streamId = targetId.getStreamId();
                InputStream is = incomingStreams.remove(streamId);
                if (is != null) {
                    is.close();
                }
            }
        };
        rctxt.addListener(alsn);

        BContentStream istrm = null;

        // Is splitted stream?
        if (partId != -1L) {

            istrm = incomingStreams.get(targetId.getStreamId());

            if (istrm == null) {

                istrm = new HIncomingSplittedStreamAsync(targetId, contentType, totalLength, contentDisposition,
                        HConstants.REQUEST_TIMEOUT_MILLIS, tempDir) {
                    public void close() throws IOException {
                        if (log.isDebugEnabled())
                            log.debug("close incoming stream " + targetId + "(");
                        Long streamId = getTargetId().getStreamId();
                        incomingStreams.remove(streamId);
                        super.close();
                        if (log.isDebugEnabled())
                            log.debug(")close");
                    }
                };

                incomingStreams.put(targetId.getStreamId(), istrm);
            }

            ((HIncomingSplittedStreamAsync) istrm).addStream(partId, contentLength, isLastPart, rctxt);

        } else {

            istrm = new HIncomingStreamAsync(targetId, contentType, contentLength, contentDisposition,
                    HConstants.REQUEST_TIMEOUT_MILLIS, tempDir, rctxt) {
                public void close() throws IOException {
                    if (log.isDebugEnabled())
                        log.debug("close incoming stream " + targetId + "(");
                    Long streamId = getTargetId().getStreamId();
                    incomingStreams.remove(streamId);
                    super.close();
                    if (log.isDebugEnabled())
                        log.debug(")close");
                }
            };

            incomingStreams.put(targetId.getStreamId(), istrm);
        }

        synchronized (this) {
            notifyAll();
        }

    } catch (Throwable e) {
        throw new BException(BExceptionC.IOERROR, "Failed to add incoming stream", e);
    }

    if (log.isDebugEnabled())
        log.debug(")addIncomingStreamAsync");
}