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:petascope.wcs2.Wcs2Servlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) {

    long startTime = System.currentTimeMillis();

    setServletURL(req);/*from   ww  w.  j  av  a2 s  . c  o  m*/
    meta.clearCache();

    String request = null;
    try {
        try {
            request = IOUtils.toString(req.getReader());

            log.trace("POST request length: " + req.getContentLength());
            log.trace("GET query string: " + req.getQueryString());
            log.trace("POST request body:\n" + request + "\n----------------------------------------\n");

            Map<String, String> params = buildParameterDictionary(request);
            if (params.containsKey("request")) {
                request = params.get("request");
            }
            request = StringUtil.urldecode(request, req.getContentType());
            if (request == null || request.length() == 0) {
                if (req.getQueryString() != null && req.getQueryString().length() > 0) {
                    request = req.getQueryString();
                    request = StringUtil.urldecode(request, req.getContentType());
                } else {
                    printUsage(res, request);
                    return;
                }
            }

            log.debug("Petascope Request: \n------START REQUEST--------\n" + request
                    + "\n------END REQUEST------\n");

            handleWcs2Request(request, res, req);
        } catch (WCSException e) {
            throw e;
        } catch (PetascopeException e) {
            throw new WCSException(e.getExceptionCode(), e.getMessage());
        } catch (SecoreException e) {
            throw new WCSException(e.getExceptionCode(), e);
        } catch (Exception e) {
            log.error("Runtime error : {}", e.getMessage());
            throw new WCSException(ExceptionCode.RuntimeError, "Runtime error while processing request", e);
        }
    } catch (WCSException e) {
        printError(res, request, e);
    }
    long elapsedTimeMillis = System.currentTimeMillis() - startTime;
    log.debug("Total Petascope Processing Time : " + elapsedTimeMillis);
}

From source file:helma.servlet.AbstractServletClient.java

protected void parseParameters(HttpServletRequest request, RequestTrans reqtrans, String encoding)
        throws IOException {
    // check if there are any parameters before we get started
    String queryString = request.getQueryString();
    String contentType = request.getContentType();
    boolean isFormPost = "post".equals(request.getMethod().toLowerCase()) && contentType != null
            && contentType.toLowerCase().startsWith("application/x-www-form-urlencoded");

    if (queryString == null && !isFormPost) {
        return;/*from  www.j a va  2  s  . co m*/
    }

    HashMap parameters = new HashMap();

    // Parse any query string parameters from the request
    if (queryString != null) {
        parseParameters(parameters, queryString.getBytes(), encoding, false);
        if (!parameters.isEmpty()) {
            reqtrans.setParameters(parameters, false);
            parameters.clear();
        }
    }

    // Parse any posted parameters in the input stream
    if (isFormPost) {
        int max = request.getContentLength();
        if (max > totalUploadLimit * 1024) {
            throw new IOException("Exceeded Upload limit");
        }
        int len = 0;
        byte[] buf = new byte[max];
        ServletInputStream is = request.getInputStream();

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

            if (next < 0) {
                break;
            }

            len += next;
        }

        // is.close();
        parseParameters(parameters, buf, encoding, true);
        if (!parameters.isEmpty()) {
            reqtrans.setParameters(parameters, true);
            parameters.clear();
        }
    }
}

From source file:org.sakaiproject.blti.ServiceServlet.java

@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String contentType = request.getContentType();
    if (contentType != null && contentType.startsWith("application/json")) {
        doPostJSON(request, response);//from   w w w  . j a va2  s.  c om
    } else if (contentType != null && contentType.startsWith("application/xml")) {
        doPostXml(request, response);
    } else {
        doPostForm(request, response);
    }
}

From source file:controller.FacebookServlet.java

public boolean doFilePost(HttpServletRequest request) {
    System.out.println("Do file post");
    DiskFileItemFactory fileUpload = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(fileUpload);
    if (request.getContentType() == null) {
        System.out.println("Content type null");
        return false;
    }//  ww  w  . j ava2 s  . c om
    if (!request.getContentType().startsWith("multipart/form-data")) {
        System.out.println("No comea com multipart");
        return false;
    }
    String diretorio = "C:\\Users\\BBEIRIGO\\Documents\\NetBeansProjects\\WebServiceFacebook\\src\\main\\webapp\\photos";

    System.out.println("DIRETORIO:" + diretorio);
    String filename = "file";
    String path = diretorio;
    List list;
    try {
        list = sfu.parseRequest(request);

        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            FileItem item = (FileItem) iterator.next();
            if (!item.isFormField()) {
                System.out.println("FIELD NAME:" + item.getFieldName());
                filename = item.getName();
                if ((filename != null) && (!filename.equals(""))) {
                    filename = (new File(filename)).getName();
                    item.write(new File(path + "/" + filename));
                }
            }
        }
    } catch (FileUploadException ex) {
        Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(FacebookServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    return true;
}

From source file:org.seasar.struts.action.S2RequestProcessor.java

@Override
protected void processPopulate(HttpServletRequest request, HttpServletResponse response, ActionForm form,
        ActionMapping mapping) throws ServletException {

    if (form == null) {
        return;//from  w ww . j  a  va2 s.c o  m
    }
    form.setServlet(servlet);
    String contentType = request.getContentType();
    String method = request.getMethod();
    form.setMultipartRequestHandler(null);
    MultipartRequestHandler multipartHandler = null;
    if (contentType != null && contentType.startsWith("multipart/form-data")
            && method.equalsIgnoreCase("POST")) {
        multipartHandler = getMultipartHandler(mapping.getMultipartClass());
        if (multipartHandler != null) {
            multipartHandler.setServlet(servlet);
            multipartHandler.setMapping(mapping);
            multipartHandler.handleRequest(request);
            Boolean maxLengthExceeded = (Boolean) request
                    .getAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
            if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) {
                form.setMultipartRequestHandler(multipartHandler);
                processExecuteConfig(request, response, mapping);
                return;
            }
            SingletonS2ContainerFactory.getContainer().getExternalContext().setRequest(request);
        }
    }
    processExecuteConfig(request, response, mapping);
    form.reset(mapping, request);
    Map<String, Object> params = getAllParameters(request, multipartHandler);
    S2ActionMapping actionMapping = (S2ActionMapping) mapping;
    for (Iterator<String> i = params.keySet().iterator(); i.hasNext();) {
        String name = i.next();
        try {
            setProperty(actionMapping.getActionForm(), name, params.get(name));
        } catch (Throwable t) {
            throw new IllegalPropertyRuntimeException(actionMapping.getActionFormBeanDesc().getBeanClass(),
                    name, t);
        }
    }
}

From source file:com.krawler.spring.importFunctionality.ImportUtil.java

/**
 * @param request/*w  ww.ja va  2 s  .c om*/
 * @return
 * @throws IOException
 */
public static JSONObject getMappingCSVHeader(HttpServletRequest request) throws IOException {
    String contentType = request.getContentType();
    CsvReader csvReader = null;
    JSONObject jtemp1 = new JSONObject();
    JSONObject jobj = new JSONObject();
    JSONObject jsnobj = new JSONObject();
    String delimiterType = request.getParameter("delimiterType");
    String str = "";
    {
        FileInputStream fstream = null;
        try {
            if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {

                String fileid = UUID.randomUUID().toString();
                fileid = fileid.replaceAll("-", ""); // To append UUID without "-" [SK]
                //                    String Module = request.getParameter("type")==null?"":"_"+request.getParameter("type");
                String f1 = uploadDocument(request, fileid);

                if (f1.length() != 0) {
                    String destinationDirectory = storageHandlerImpl.GetDocStorePath() + "importplans";
                    File csv = new File(destinationDirectory + "/" + f1);
                    fstream = new FileInputStream(csv);
                    csvReader = new CsvReader(new InputStreamReader(fstream), delimiterType);

                    csvReader.readHeaders();

                    int cols = csvReader.getHeaderCount();
                    for (int k = 0; k < csvReader.getHeaderCount(); k++) {
                        jtemp1 = new JSONObject();
                        if (!StringUtil.isNullOrEmpty(csvReader.getHeader(k).trim())) {
                            jtemp1.put("header", csvReader.getHeader(k));
                            jtemp1.put("index", k);
                            jobj.append("Header", jtemp1);
                        }
                    }

                    if (jobj.isNull("Header")) {
                        jsnobj.put("success", "true");

                        str = jsnobj.toString();
                    } else {
                        jobj.append("success", "true");
                        jobj.append("FileName", f1);
                        jobj.put("name", f1);
                        jobj.put("delimiterType", delimiterType);
                        jobj.put("cols", cols);
                        str = jobj.toString();
                    }
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ImportHandler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(ImportHandler.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            csvReader.close();
            fstream.close();
        }
    }
    return jobj;
}

From source file:org.dspace.app.webui.servlet.admin.EditItemServlet.java

protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException, AuthorizeException {
    // First, see if we have a multipart request (uploading a new bitstream)
    String contentType = request.getContentType();

    if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) {
        // This is a multipart request, so it's a file upload
        processUploadBitstream(context, request, response);

        return;//  w  w  w.j av  a2  s.  c o  m
    }

    /*
     * Then we check for a "cancel" button - if it's been pressed, we simply
     * return to the "find by handle/id" page
     */
    if (request.getParameter("submit_cancel") != null) {
        JSPManager.showJSP(request, response, "/tools/get-item-id.jsp");

        return;
    }

    /*
     * Respond to submitted forms. Each form includes an "action" parameter
     * indicating what needs to be done (from the constants above.)
     */
    int action = UIUtil.getIntParameter(request, "action");

    Item item = Item.find(context, UIUtil.getIntParameter(request, "item_id"));

    String handle = HandleManager.findHandle(context, item);

    // now check to see if person can edit item
    checkEditAuthorization(context, item);

    request.setAttribute("item", item);
    request.setAttribute("handle", handle);

    switch (action) {
    case START_DELETE:

        // Show "delete item" confirmation page
        JSPManager.showJSP(request, response, "/tools/confirm-delete-item.jsp");

        break;

    case CONFIRM_DELETE:

        // Delete the item - if "cancel" was pressed this would be
        // picked up above
        // FIXME: Don't know if this does all it should - remove Handle?
        Collection[] collections = item.getCollections();

        // Remove item from all the collections it's in
        for (int i = 0; i < collections.length; i++) {
            collections[i].removeItem(item);
        }

        JSPManager.showJSP(request, response, "/tools/get-item-id.jsp");
        context.complete();

        break;

    case UPDATE_ITEM:
        processUpdateItem(context, request, response, item);

        break;

    case START_WITHDRAW:

        // Show "withdraw item" confirmation page
        JSPManager.showJSP(request, response, "/tools/confirm-withdraw-item.jsp");

        break;

    case CONFIRM_WITHDRAW:

        // Withdraw the item
        item.withdraw();
        JSPManager.showJSP(request, response, "/tools/get-item-id.jsp");
        context.complete();

        break;

    case REINSTATE:
        item.reinstate();
        JSPManager.showJSP(request, response, "/tools/get-item-id.jsp");
        context.complete();

        break;

    case START_MOVE_ITEM:
        if (AuthorizeManager.isAdmin(context, item)) {
            // Display move collection page with fields of collections and communities
            Collection[] allNotLinkedCollections = item.getCollectionsNotLinked();
            Collection[] allLinkedCollections = item.getCollections();

            // get only the collection where the current user has the right permission
            List<Collection> authNotLinkedCollections = new ArrayList<Collection>();
            for (Collection c : allNotLinkedCollections) {
                if (AuthorizeManager.authorizeActionBoolean(context, c, Constants.ADD)) {
                    authNotLinkedCollections.add(c);
                }
            }

            List<Collection> authLinkedCollections = new ArrayList<Collection>();
            for (Collection c : allLinkedCollections) {
                if (AuthorizeManager.authorizeActionBoolean(context, c, Constants.REMOVE)) {
                    authLinkedCollections.add(c);
                }
            }

            Collection[] notLinkedCollections = new Collection[authNotLinkedCollections.size()];
            notLinkedCollections = authNotLinkedCollections.toArray(notLinkedCollections);
            Collection[] linkedCollections = new Collection[authLinkedCollections.size()];
            linkedCollections = authLinkedCollections.toArray(linkedCollections);

            request.setAttribute("linkedCollections", linkedCollections);
            request.setAttribute("notLinkedCollections", notLinkedCollections);

            JSPManager.showJSP(request, response, "/tools/move-item.jsp");
        } else {
            throw new ServletException("You must be an administrator to move an item");
        }

        break;

    case CONFIRM_MOVE_ITEM:
        if (AuthorizeManager.isAdmin(context, item)) {
            Collection fromCollection = Collection.find(context,
                    UIUtil.getIntParameter(request, "collection_from_id"));
            Collection toCollection = Collection.find(context,
                    UIUtil.getIntParameter(request, "collection_to_id"));

            Boolean inheritPolicies = false;
            if (request.getParameter("inheritpolicies") != null) {
                inheritPolicies = true;
            }

            if (fromCollection == null || toCollection == null) {
                throw new ServletException("Missing or incorrect collection IDs for moving item");
            }

            item.move(fromCollection, toCollection, inheritPolicies);

            showEditForm(context, request, response, item);

            context.complete();
        } else {
            throw new ServletException("You must be an administrator to move an item");
        }

        break;

    default:

        // Erm... weird action value received.
        log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(request)));
        JSPManager.showIntegrityError(request, response);
    }
}

From source file:it.eng.spago.dispatching.httpchannel.AdapterHTTP.java

/**
 * Sets the http request data./*from  w w  w. j av  a 2  s.  c om*/
 * 
 * @param request the request
 * @param requestContainer the request container
 */
private void setHttpRequestData(HttpServletRequest request, RequestContainer requestContainer) {
    requestContainer.setAttribute(HTTP_REQUEST_AUTH_TYPE, request.getAuthType());
    requestContainer.setAttribute(HTTP_REQUEST_CHARACTER_ENCODING, request.getCharacterEncoding());
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_LENGTH, String.valueOf(request.getContentLength()));
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_TYPE, request.getContentType());
    requestContainer.setAttribute(HTTP_REQUEST_CONTEXT_PATH, request.getContextPath());
    requestContainer.setAttribute(HTTP_REQUEST_METHOD, request.getMethod());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_INFO, request.getPathInfo());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_TRANSLATED, request.getPathTranslated());
    requestContainer.setAttribute(HTTP_REQUEST_PROTOCOL, request.getProtocol());
    requestContainer.setAttribute(HTTP_REQUEST_QUERY_STRING, request.getQueryString());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_ADDR, request.getRemoteAddr());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_HOST, request.getRemoteHost());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_USER, request.getRemoteUser());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID, request.getRequestedSessionId());
    requestContainer.setAttribute(HTTP_REQUEST_REQUEST_URI, request.getRequestURI());
    requestContainer.setAttribute(HTTP_REQUEST_SCHEME, request.getScheme());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_NAME, request.getServerName());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_PORT, String.valueOf(request.getServerPort()));
    requestContainer.setAttribute(HTTP_REQUEST_SERVLET_PATH, request.getServletPath());
    if (request.getUserPrincipal() != null)
        requestContainer.setAttribute(HTTP_REQUEST_USER_PRINCIPAL, request.getUserPrincipal());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_COOKIE,
            String.valueOf(request.isRequestedSessionIdFromCookie()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_URL,
            String.valueOf(request.isRequestedSessionIdFromURL()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_VALID,
            String.valueOf(request.isRequestedSessionIdValid()));
    requestContainer.setAttribute(HTTP_REQUEST_SECURE, String.valueOf(request.isSecure()));
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        String headerValue = request.getHeader(headerName);
        requestContainer.setAttribute(headerName, headerValue);
    } // while (headerNames.hasMoreElements())
    requestContainer.setAttribute(HTTP_SESSION_ID, request.getSession().getId());
    requestContainer.setAttribute(Constants.HTTP_IS_XML_REQUEST, "FALSE");
}

From source file:org.nunux.poc.portal.ProxyServlet.java

/**
 * Sets up the given {@link PostMethod} to send the same content POST data
 * (JSON, XML, etc.) as was sent in the given {@link HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link PostMethod} that we are
 * configuring to send a standard POST request
 * @param httpServletRequest The {@link HttpServletRequest} that contains
 * the POST data to be sent via the {@link PostMethod}
 *//*from  ww  w  . j  a  va2  s.  c  o m*/
private void handleContentPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws IOException, ServletException {
    StringBuilder content = new StringBuilder();
    BufferedReader reader = httpServletRequest.getReader();
    for (;;) {
        String line = reader.readLine();
        if (line == null) {
            break;
        }
        content.append(line);
    }

    String contentType = httpServletRequest.getContentType();
    String postContent = content.toString();

    if (contentType.startsWith("text/x-gwt-rpc")) {
        String clientHost = httpServletRequest.getLocalName();
        if (clientHost.equals("127.0.0.1")) {
            clientHost = "localhost";
        }

        int clientPort = httpServletRequest.getLocalPort();
        String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : "");
        String serverUrl = stringProxyHost + ((intProxyPort != 80) ? ":" + intProxyPort : "")
                + httpServletRequest.getServletPath();
        //debug("Replacing client (" + clientUrl + ") with server (" + serverUrl + ")");
        postContent = postContent.replace(clientUrl, serverUrl);
    }

    String encoding = httpServletRequest.getCharacterEncoding();
    debug("POST Content Type: " + contentType + " Encoding: " + encoding, "Content: " + postContent);
    StringRequestEntity entity;
    try {
        entity = new StringRequestEntity(postContent, contentType, encoding);
    } catch (UnsupportedEncodingException e) {
        throw new ServletException(e);
    }
    // Set the proxy request POST data
    postMethodProxyRequest.setRequestEntity(entity);
}

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

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    ModelAndView result;//from  ww  w  .j  a v  a  2  s. c  om

    Repository repository = RepositoryInterceptor.getRepository(request);

    String reqMethod = request.getMethod();

    if (METHOD_GET.equals(reqMethod)) {
        logger.info("GET statements");
        result = getExportStatementsResult(repository, request, response);
    } else if (METHOD_HEAD.equals(reqMethod)) {
        logger.info("HEAD statements");
        result = getExportStatementsResult(repository, request, response);
    } else if (METHOD_POST.equals(reqMethod)) {
        String mimeType = HttpServerUtil.getMIMEType(request.getContentType());

        if (Protocol.TXN_MIME_TYPE.equals(mimeType)) {
            logger.info("POST transaction to repository");
            result = getTransactionResultResult(repository, request, response);
        } else if (Protocol.SPARQL_UPDATE_MIME_TYPE.equals(mimeType)
                || request.getParameterMap().containsKey(Protocol.UPDATE_PARAM_NAME)) {
            logger.info("POST SPARQL update request to repository");
            result = getSparqlUpdateResult(repository, request, response);
        } else {
            logger.info("POST data to repository");
            result = getAddDataResult(repository, request, response, false);
        }
    } else if ("PUT".equals(reqMethod)) {
        logger.info("PUT data in repository");
        result = getAddDataResult(repository, request, response, true);
    } else if ("DELETE".equals(reqMethod)) {
        logger.info("DELETE data from repository");
        result = getDeleteDataResult(repository, request, response);
    } else {
        throw new ClientHTTPException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                "Method not allowed: " + reqMethod);
    }

    return result;
}