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:org.primeframework.mvc.parameter.RequestBodyWorkflowTest.java

@Test
public void containerDrainedBody() throws IOException, ServletException {
    HttpServletRequest request = createStrictMock(HttpServletRequest.class);
    expect(request.getParameterMap()).andReturn(new HashMap<>());
    expect(request.getContentType()).andReturn("application/x-www-form-urlencoded");
    expect(request.getInputStream()).andReturn(new MockServletInputStream(new byte[0]));
    expect(request.getContentLength()).andReturn(0);
    expect(request.getCharacterEncoding()).andReturn("UTF-8");
    replay(request);/*w  w  w  .j a va2 s .c  om*/

    WorkflowChain chain = createStrictMock(WorkflowChain.class);
    chain.continueWorkflow();
    replay(chain);

    // This is the assert since the request would be unwrapped if the body contained parameters
    RequestBodyWorkflow workflow = new RequestBodyWorkflow(request);
    workflow.perform(chain);

    verify(request, chain);
}

From source file:org.springframework.integration.http.DefaultInboundRequestMapper.java

private Object createPayloadFromRequest(HttpServletRequest request) throws Exception {
    Object payload = null;//from  w w  w. j a  v  a  2  s .  c o  m
    String contentType = request.getContentType() != null ? request.getContentType() : "";
    if (request instanceof MultipartHttpServletRequest) {
        payload = this.createPayloadFromMultipartRequest((MultipartHttpServletRequest) request);
    } else if (contentType.startsWith("multipart/form-data")) {
        throw new IllegalArgumentException("Content-Type of 'multipart/form-data' requires a MultipartResolver."
                + " Try configuring a MultipartResolver within the ApplicationContext.");
    } else if (request.getMethod().equals("GET")) {
        if (logger.isDebugEnabled()) {
            logger.debug("received GET request, using parameter map as payload");
        }
        payload = this.createPayloadFromParameterMap(request);
    } else if (contentType.startsWith("application/x-www-form-urlencoded")) {
        if (logger.isDebugEnabled()) {
            logger.debug("received " + request.getMethod()
                    + " request with form data, using parameter map as payload");
        }
        payload = createPayloadFromParameterMap(request);
    } else if (contentType.startsWith("text")) {
        if (logger.isDebugEnabled()) {
            logger.debug("received " + request.getMethod() + " request, creating payload with text content");
        }
        payload = createPayloadFromTextContent(request);
    } else if (contentType.startsWith("application/x-java-serialized-object")) {
        payload = createPayloadFromSerializedObject(request);
    } else {
        payload = createPayloadFromInputStream(request);
    }
    return payload;
}

From source file:org.apache.solr.servlet.SolrRequestParsers.java

public HttpRequestContentStream(HttpServletRequest req) throws IOException {
    this.req = req;

    contentType = req.getContentType();
    // name = ???
    // sourceInfo = ???

    String v = req.getHeader("Content-Length");
    if (v != null) {
        size = Long.valueOf(v);//w  w  w  .j  a va2 s. c o  m
    }
}

From source file:org.apache.shindig.social.opensocial.hibernate.utils.HttpLogFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    req = new BufferedServletRequestWrapper(req);
    try {/*from  w  w w . j  ava  2 s .c  o m*/
        JSONObject json = new JSONObject();
        json.put("requestURI", req.getRequestURI());
        json.put("contentType", req.getContentType());
        json.put("method", req.getMethod());
        Map<String, String> headerMap = new HashMap<String, String>();
        Enumeration headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            String headerValue = req.getHeader(headerName);
            headerMap.put(headerName, headerValue);
        }
        json.put("headerMap", headerMap);
        InputStream in = req.getInputStream();
        String body = IOUtils.toString(in, "UTF-8");
        json.put("body", body);

        json.put("parameterMap", req.getParameterMap());
        json.put("timestamp", new Date().getTime());
        //
        String serialized = JsonSerializer.serialize(json);
        logger.info(serialized);
    } catch (Throwable e) {
        logger.error("Couldn't output a log.", e);
    }
    chain.doFilter(req, response);
}

From source file:org.primeframework.mvc.parameter.RequestBodyWorkflowTest.java

@Test
public void parseCombine() throws IOException, ServletException {
    Map<String, String[]> oldParams = new HashMap<>();
    oldParams.put("param1", new String[] { "oldvalue1", "oldvalue2" });
    oldParams.put("param2", new String[] { "oldvalue3" });

    String body = "param1=value1&param1=value2&param2=value3";
    HttpServletRequest request = createStrictMock(HttpServletRequest.class);
    expect(request.getParameterMap()).andReturn(oldParams);
    expect(request.getContentType()).andReturn("application/x-www-form-urlencoded");
    expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes()));
    expect(request.getContentLength()).andReturn(body.getBytes().length);
    expect(request.getCharacterEncoding()).andReturn("UTF-8");
    replay(request);/* w  w w .  j  a  va 2s  . c  o  m*/

    WorkflowChain chain = createStrictMock(WorkflowChain.class);
    chain.continueWorkflow();
    replay(chain);

    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request);
    RequestBodyWorkflow workflow = new RequestBodyWorkflow(wrapper);
    workflow.perform(chain);

    @SuppressWarnings("unchecked")
    Map<String, String[]> actual = wrapper.getParameterMap();
    Map<String, String[]> expected = MapBuilder.<String, String[]>map()
            .put("param1", new String[] { "oldvalue1", "oldvalue2", "value1", "value2" })
            .put("param2", new String[] { "oldvalue3", "value3" }).done();
    assertParameterMapsEquals(actual, expected);

    verify(request, chain);
}

From source file:org.primeframework.mvc.parameter.RequestBodyWorkflowTest.java

@Test
public void parseMultiple() throws IOException, ServletException {
    String body = "param1=value1&param1=value2&param2=value3";
    HttpServletRequest request = createStrictMock(HttpServletRequest.class);
    expect(request.getParameterMap()).andReturn(new HashMap<>());
    expect(request.getContentType()).andReturn("application/x-www-form-urlencoded");
    expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes()));
    expect(request.getContentLength()).andReturn(body.getBytes().length);
    expect(request.getCharacterEncoding()).andReturn("UTF-8");
    replay(request);/* w  w w .  jav  a2  s. c  om*/

    WorkflowChain chain = createStrictMock(WorkflowChain.class);
    chain.continueWorkflow();
    replay(chain);

    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request);
    RequestBodyWorkflow workflow = new RequestBodyWorkflow(wrapper);
    workflow.perform(chain);

    @SuppressWarnings("unchecked")
    Map<String, String[]> actual = wrapper.getParameterMap();
    Map<String, String[]> expected = MapBuilder.<String, String[]>map()
            .put("param1", new String[] { "value1", "value2" }).put("param2", new String[] { "value3" }).done();
    assertParameterMapsEquals(actual, expected);

    verify(request, chain);
}

From source file:org.primeframework.mvc.parameter.RequestBodyWorkflowTest.java

@Test
public void parse() throws IOException, ServletException {
    HttpServletRequest request = createStrictMock(HttpServletRequest.class);
    expect(request.getParameterMap()).andReturn(new HashMap<>());
    expect(request.getContentType()).andReturn("application/x-www-form-urlencoded");
    String body = "param1=value1&param2=value2&param+space+key=param+space+value&param%2Bencoded%2Bkey=param%2Bencoded%2Bvalue";
    expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes()));
    expect(request.getContentLength()).andReturn(body.getBytes().length);
    expect(request.getCharacterEncoding()).andReturn("UTF-8");
    replay(request);//w  w  w.  j av  a2 s .  c  om

    WorkflowChain chain = createStrictMock(WorkflowChain.class);
    chain.continueWorkflow();
    replay(chain);

    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request);
    RequestBodyWorkflow workflow = new RequestBodyWorkflow(wrapper);
    workflow.perform(chain);

    @SuppressWarnings("unchecked")
    Map<String, String[]> actual = wrapper.getParameterMap();
    Map<String, String[]> expected = MapBuilder.<String, String[]>map().put("param1", new String[] { "value1" })
            .put("param2", new String[] { "value2" })
            .put("param space key", new String[] { "param space value" })
            .put("param+encoded+key", new String[] { "param+encoded+value" }).done();
    assertParameterMapsEquals(actual, expected);

    verify(request, chain);
}

From source file:org.dspace.app.webui.servlet.BatchMetadataImportServlet.java

/**
 * Respond to a post request for metadata bulk importing via csv
 *
 * @param context a DSpace Context object
 * @param request the HTTP request/*from  w  ww  . j a  v  a  2 s.  c  o  m*/
 * @param response the HTTP response
 *
 * @throws ServletException
 * @throws IOException
 * @throws SQLException
 * @throws AuthorizeException
 */
protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException, AuthorizeException {
    // First, see if we have a multipart request (uploading a metadata file)
    String contentType = request.getContentType();
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) {
        String message = null;

        // Process the file uploaded
        try {
            // Wrap multipart request to get the submission info
            FileUploadRequest wrapper = new FileUploadRequest(request);
            File f = wrapper.getFile("file");

            int colId = Integer.parseInt(wrapper.getParameter("collection"));
            Collection collection = Collection.find(context, colId);

            String inputType = wrapper.getParameter("inputType");

            try {
                ItemImport.processUploadableImport(f, new Collection[] { collection }, inputType, context);

                request.setAttribute("has-error", "false");

            } catch (Exception e) {
                request.setAttribute("has-error", "true");
                message = e.getMessage();
                e.printStackTrace();
            }
        } catch (FileSizeLimitExceededException e) {
            request.setAttribute("has-error", "true");
            message = e.getMessage();
            e.printStackTrace();
        } catch (Exception e) {
            request.setAttribute("has-error", "true");
            message = e.getMessage();
            e.printStackTrace();
        }

        //Get all the possible data loaders from the Spring configuration
        BTEBatchImportService dls = new DSpace().getSingletonService(BTEBatchImportService.class);
        List<String> inputTypes = dls.getFileDataLoaders();

        request.setAttribute("input-types", inputTypes);

        //Get all collections
        List<Collection> collections = null;
        String colIdS = request.getParameter("colId");
        if (colIdS != null) {
            collections = new ArrayList<Collection>();
            collections.add(Collection.find(context, Integer.parseInt(colIdS)));

        } else {
            collections = Arrays.asList(Collection.findAll(context));
        }

        request.setAttribute("collections", collections);

        request.setAttribute("message", message);

        // Show the upload screen
        JSPManager.showJSP(request, response, "/dspace-admin/batchmetadataimport.jsp");

    } else {
        request.setAttribute("has-error", "true");

        // Show the upload screen
        JSPManager.showJSP(request, response, "/dspace-admin/batchmetadataimport.jsp");
    }
}

From source file:org.vosao.servlet.FormSendServlet.java

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

    String message = null;/*  w  w w .  j  av  a  2  s  . co  m*/
    Map<String, String> parameters = new HashMap<String, String>();
    List<FileItem> files = new ArrayList<FileItem>();
    try {
        if (request.getContentType().startsWith("multipart/form-data")) {
            ServletFileUpload upload = new ServletFileUpload();
            upload.setFileSizeMax(MAX_SIZE);
            upload.setHeaderEncoding("UTF-8");
            FileItemIterator iter;
            try {
                iter = upload.getItemIterator(request);
                InputStream stream = null;
                while (iter.hasNext()) {
                    FileItemStream item = iter.next();
                    stream = item.openStream();
                    if (item.isFormField()) {
                        parameters.put(item.getFieldName(), Streams.asString(stream, "UTF-8"));
                    } else {
                        files.add(new FileItem(item, StreamUtil.readFileStream(stream)));
                    }
                }
            } catch (FileUploadException e) {
                logger.error(e.getMessage());
                throw new UploadException(Messages.get("request_parsing_error"));
            }
        } else {
            for (Object key : request.getParameterMap().keySet()) {
                String paramName = (String) key;
                parameters.put(paramName, request.getParameter(paramName));
            }
        }
        message = processForm(parameters, files, request);
    } catch (UploadException e) {
        message = createMessage("error", e.getMessage());
        logger.error(message);
    } catch (Exception e) {
        message = createMessage("error", e.getMessage());
        logger.error(message);
        e.printStackTrace();
    }
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    response.setStatus(200);
    response.getWriter().write(message);
}

From source file:com.climate.oada.controller.OADAAPIController.java

@Override
public List<IResource> updateResources(@RequestHeader(value = "Authorization") String accessToken,
        String resources, HttpServletRequest request, HttpServletResponse response) {
    Long userId = extractUserId(accessToken);
    String inContentType = request.getContentType();
    if (OADA_FIELDS_CONTENT_TYPE.equalsIgnoreCase(inContentType)) {
        /*/*from  ww w.j ava 2  s.c  o  m*/
         * We assume that fields are nothing but a geospatial boundary
         * (specified in WKT / WKB / GeoJSON) along with some some metadata.
         *
         * Parse json via jackson.
         */
        List<LandUnit> lus = processFields(resources);
        for (LandUnit lu : lus) {
            lu.setUserId(userId);
            getFieldsResourceDAO().insert(lu);
        }
    }
    return null;
}