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.eclipse.leshan.standalone.servlet.ClientServlet.java

private LwM2mResponse writeRequest(Client client, String target, HttpServletRequest req,
        HttpServletResponse resp) throws IOException {
    Map<String, String> parameters = new HashMap<String, String>();
    String contentType = HttpFields.valueParameters(req.getContentType(), parameters);

    if ("text/plain".equals(contentType)) {
        String content = IOUtils.toString(req.getInputStream(), parameters.get("charset"));
        int rscId = Integer.valueOf(target.substring(target.lastIndexOf("/") + 1));
        return server.send(client, new WriteRequest(target,
                new LwM2mResource(rscId, Value.newStringValue(content)), ContentFormat.TEXT, true), TIMEOUT);

    } else if ("application/json".equals(contentType)) {
        String content = IOUtils.toString(req.getInputStream(), parameters.get("charset"));
        LwM2mNode node = null;/*ww  w  . j  a  v a2  s.  co m*/
        try {
            node = gson.fromJson(content, LwM2mNode.class);
        } catch (JsonSyntaxException e) {
            throw new IllegalArgumentException("unable to parse json to tlv:" + e.getMessage(), e);
        }
        return server.send(client, new WriteRequest(target, node, null, true), TIMEOUT);

    } else {
        throw new IllegalArgumentException(
                "content type " + req.getContentType() + " not supported for write requests");
    }
}

From source file:com.xpn.xwiki.web.XWikiPortlet.java

protected HttpServletRequest processMultipart(HttpServletRequest request) {
    if (!"POST".equalsIgnoreCase(request.getMethod())) {
        return (request);
    }/*from w  w w. j  a  va  2  s .c o  m*/

    String contentType = request.getContentType();

    if ((contentType != null) && contentType.startsWith("multipart/form-data")) {
        return (new MultipartRequestWrapper(request));
    } else {
        return (request);
    }
}

From source file:org.vast.ows.server.WPSServlet.java

/**
 * Parse and process HTTP POST request/*from   w w w .  j av  a 2s .  co m*/
 */
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    OWSRequest query = null;
    log.info("POST REQUEST from IP " + req.getRemoteAddr());

    //  get request URL
    String requestURL = req.getRequestURL().toString();

    if (req.getContentType().equalsIgnoreCase("text/xml")) {
        try {
            InputStream xmlRequest = new PostRequestFilter(new BufferedInputStream(req.getInputStream()));
            DOMHelper dom = new DOMHelper(xmlRequest, false);
            query = (OWSRequest) owsUtils.readXMLQuery(dom, dom.getBaseElement());

            // setup response stream
            resp.setContentType("text/xml");
            query.setHttpResponse(resp);
            query.setPostServer(requestURL);

            if (query instanceof GetCapabilitiesRequest)
                processQuery((GetCapabilitiesRequest) query);
            else
                throw new ServletException("WPS accepts requests of content type 'text/xml' only for the"
                        + "GetCapabilities request");
        }

        catch (WPSException e) {
            try {
                resp.sendError(500, e.getMessage());
            } catch (IOException e1) {
                e.printStackTrace();
            }
        } catch (OWSException e) {
            try {
                resp.sendError(400, e.getMessage());
            } catch (IOException e1) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            throw new ServletException(internalErrorMsg, e);
        } finally {
            try {
                resp.getOutputStream().flush();
                resp.getOutputStream().close();
            } catch (IOException e) {
                throw new ServletException(e);
            }
        }
    }

    else if (req.getContentType().equalsIgnoreCase("application/soap+xml")) {

        try {
            InputStream soapRequest = new PostRequestFilter(new BufferedInputStream(req.getInputStream()));
            query = wpsUtils.extractWPSRequest(soapRequest);

            // setup response stream
            resp.setContentType(req.getContentType());
            query.setHttpResponse(resp);
            query.setPostServer(requestURL);

            if (query instanceof GetCapabilitiesRequest)
                processQuery((GetCapabilitiesRequest) query);
            else if (query instanceof DescribeProcessRequest)
                processQuery((DescribeProcessRequest) query);
            else if (query instanceof DescribeProcessRequest)
                processQuery((ExecuteProcessRequest) query);
        } catch (WPSException e) {
            try {
                resp.sendError(500, e.getMessage());
            } catch (IOException e1) {
                e.printStackTrace();
            }
        } catch (SOAPException e) {
            try {
                resp.sendError(500, e.getMessage());
            } catch (IOException e1) {
                e.printStackTrace();
            }
        } catch (OWSException e) {
            try {
                resp.sendError(400, "Invalid request or unrecognized version");
            } catch (IOException e1) {
                e.printStackTrace();
            }
        } catch (DOMHelperException e) {
            try {
                resp.sendError(400, "Invalid XML request. Please check request format");
            } catch (IOException e1) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            throw new ServletException(internalErrorMsg, e);
        } finally {
            try {
                resp.getOutputStream().close();
            } catch (IOException e) {
                throw new ServletException(e);
            }
        }
    }
}

From source file:org.iqvis.nvolv3.request.filter.LoggingFilter.java

@SuppressWarnings("unused")
private void logRequest(final HttpServletRequest request) {
    StringBuilder msg = new StringBuilder();
    msg.append(REQUEST_PREFIX);/*w  ww.  ja  va 2s  .c  o  m*/
    if (request instanceof RequestWrapper) {
        msg.append("request id=").append(((RequestWrapper) request).getId()).append("; ");
    }
    HttpSession session = request.getSession(false);
    if (session != null) {
        msg.append("session id=").append(session.getId()).append("; ");
    }
    if (request.getContentType() != null) {
        msg.append("content type=").append(request.getContentType()).append("; ");
    }
    msg.append("uri=").append(request.getRequestURI());
    if (request.getQueryString() != null) {
        msg.append('?').append(request.getQueryString());
    }

    if (request instanceof RequestWrapper && !isMultipart(request)) {
        RequestWrapper requestWrapper = (RequestWrapper) request;
        try {
            String charEncoding = requestWrapper.getCharacterEncoding() != null
                    ? requestWrapper.getCharacterEncoding()
                    : "UTF-8";
            msg.append("; payload=").append(new String(requestWrapper.toByteArray(), charEncoding));
        } catch (UnsupportedEncodingException e) {
            logger.warn("Failed to parse request payload", e);
        }

    }
    logger.debug(msg.toString());
}

From source file:org.apache.asterix.api.http.servlet.QueryServiceServlet.java

private RequestParameters getRequestParameters(HttpServletRequest request) throws IOException {
    final String contentTypeParam = request.getContentType();
    int sep = contentTypeParam.indexOf(';');
    final String contentType = sep < 0 ? contentTypeParam.trim() : contentTypeParam.substring(0, sep).trim();
    RequestParameters param = new RequestParameters();
    if (MediaType.JSON.str().equals(contentType)) {
        try {//from ww w . j av  a2 s.  co  m
            JsonNode jsonRequest = new ObjectMapper().readTree(getRequestBody(request));
            param.statement = jsonRequest.get(Parameter.STATEMENT.str()).asText();
            param.format = toLower(getOptText(jsonRequest, Parameter.FORMAT.str()));
            param.pretty = getOptBoolean(jsonRequest, Parameter.PRETTY.str(), false);
            param.clientContextID = getOptText(jsonRequest, Parameter.CLIENT_ID.str());
        } catch (JsonParseException | JsonMappingException e) {
            // if the JSON parsing fails, the statement is empty and we get an empty statement error
            GlobalConfig.ASTERIX_LOGGER.log(Level.SEVERE, e.getMessage(), e);
        }
    } else {
        param.statement = request.getParameter(Parameter.STATEMENT.str());
        if (param.statement == null) {
            param.statement = getRequestBody(request);
        }
        param.format = toLower(request.getParameter(Parameter.FORMAT.str()));
        param.pretty = Boolean.parseBoolean(request.getParameter(Parameter.PRETTY.str()));
        param.clientContextID = request.getParameter(Parameter.CLIENT_ID.str());
    }
    return param;
}

From source file:org.apache.flume.sink.solr.morphline.BlobHandler.java

private Map<String, String> getHeaders(HttpServletRequest request) {
    if (LOGGER.isDebugEnabled()) {
        Map requestHeaders = new HashMap();
        Enumeration iter = request.getHeaderNames();
        while (iter.hasMoreElements()) {
            String name = (String) iter.nextElement();
            requestHeaders.put(name, request.getHeader(name));
        }//from   ww  w . j a  v  a  2s . c o m
        LOGGER.debug("requestHeaders: {}", requestHeaders);
    }
    Map<String, String> headers = new HashMap();
    if (request.getContentType() != null) {
        headers.put(Metadata.CONTENT_TYPE, request.getContentType());
    }
    Enumeration iter = request.getParameterNames();
    while (iter.hasMoreElements()) {
        String name = (String) iter.nextElement();
        headers.put(name, request.getParameter(name));
    }
    return headers;
}

From source file:com.ultrapower.eoms.common.plugin.ajaxupload.AjaxMultiPartRequest.java

/**
 * Creates a RequestContext needed by Jakarta Commons Upload.
 * /*from   ww w  .j  av a 2  s . c  o m*/
 * @param req
 *            the request.
 * @return a new request context.
 */
private RequestContext createRequestContext(final HttpServletRequest req) {
    return new RequestContext() {
        public String getCharacterEncoding() {
            return req.getCharacterEncoding();
        }

        public String getContentType() {
            return req.getContentType();
        }

        public int getContentLength() {
            return req.getContentLength();
        }

        public InputStream getInputStream() throws IOException {
            return req.getInputStream();
        }
    };
}

From source file:org.ow2.petals.binding.restproxy.in.AbstractRESTService.java

/**
 * @throws RESTException/*ww w  .j a va 2  s . c  om*/
 * 
 */
public void process(String path, String endpointName, QName serviceName, QName interfaceName,
        HttpServletRequest request, HttpServletResponse response) throws RESTException {
    Message out = null;
    Message message = new MessageImpl();

    String contentType = HTTPUtils.getContentType(request.getContentType());

    if (contentType == null) {
        contentType = org.ow2.petals.messaging.framework.Constants.MimeTypes.TYPE_RAW;
        this.logger.debug("Content type is null, setting default : " + contentType);
    } else {
        this.logger.debug("Initial content type is : " + contentType);
    }

    String encoding = this.getEncoding(request);
    this.logger.debug("Char encoding is : " + encoding);

    ReaderRegistry readers = EngineFactory.getEngine().getComponent(ReaderRegistry.class);
    if ((readers != null) && (readers.get(contentType) != null)) {
        try {
            message = readers.get(contentType).read(request.getInputStream(), encoding);
        } catch (ReaderException e) {
            throw new RESTException(e);
        } catch (IOException e) {
            throw new RESTException(e);
        }

        // add some additional properties which are common to all
        message.putAll(this.createProperties(path, request));

        try {
            message.put(org.ow2.petals.messaging.framework.message.Constants.OPERATION,
                    QName.valueOf(request.getMethod().toUpperCase()));
            message.put(org.ow2.petals.messaging.framework.message.Constants.SERVICE, serviceName);
            message.put(org.ow2.petals.messaging.framework.message.Constants.INTERFACE, interfaceName);
            // FIXME = This should be in the context and not iin the code
            message.put(org.ow2.petals.messaging.framework.message.Constants.PROTOCOL, "jbi");
            MessagingEngine messagingEngine = EngineFactory.getEngine().getComponent(MessagingEngine.class);
            if (messagingEngine != null) {
                out = messagingEngine.send(message);
            } else {
                // TODO = error
                out = null;
            }
        } catch (MessagingException e) {
            throw new RESTException(e);
        }

        if (out != null) {
            this.writeResponse(out, response);
        } else {
            throw new RESTException("No message response...");
        }
    } else {
        throw new RESTException("Can not find a valid reader for type '" + contentType + "'");
    }
}

From source file:it.unipmn.di.dcs.sharegrid.web.servlet.MultipartRequestWrapper.java

/** Performs initializations stuff. */
@SuppressWarnings("unchecked") // ServletFileUpload#parseRequest() does not return generic type.
private void init(HttpServletRequest request, long maxSize, long maxFileSize, int thresholdSize,
        String repositoryPath) {/* w  ww.  j a v a 2s  .  com*/
    if (!ServletFileUpload.isMultipartContent(request)) {
        String errorText = "Content-Type is not multipart/form-data but '" + request.getContentType() + "'";

        MultipartRequestWrapper.Log.severe(errorText);

        throw new FacesException(errorText);
    } else {
        this.params = new HashMap<String, String[]>();
        this.fileItems = new HashMap<String, FileItem>();

        DiskFileItemFactory factory = null;
        ServletFileUpload upload = null;

        //factory = new DiskFileItemFactory();
        factory = MultipartRequestWrapper.CreateDiskFileItemFactory(request.getSession().getServletContext(),
                thresholdSize, new File(repositoryPath));
        //factory.setRepository(new File(repositoryPath));
        //factory.setSizeThreshold(thresholdSize);

        upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxSize);
        upload.setFileSizeMax(maxFileSize);

        String charset = request.getCharacterEncoding();
        if (charset != null) {
            charset = ServletConstants.DefaultCharset;
        }
        upload.setHeaderEncoding(charset);

        List<FileItem> itemList = null;
        try {
            //itemList = (List<FileItem>) upload.parseRequest(request);
            itemList = (List<FileItem>) upload.parseRequest(request);
        } catch (FileUploadException fue) {
            MultipartRequestWrapper.Log.severe(fue.getMessage());
            throw new FacesException(fue);
        } catch (ClassCastException cce) {
            // This shouldn't happen!
            MultipartRequestWrapper.Log.severe(cce.getMessage());
            throw new FacesException(cce);
        }

        MultipartRequestWrapper.Log.fine("parametercount = " + itemList.size());

        for (FileItem item : itemList) {
            String key = item.getFieldName();

            //            {
            //               String value = item.getString();
            //               if (value.length() > 100) {
            //                  value = value.substring(0, 100) + " [...]";
            //               }
            //               MultipartRequestWrapper.Log.fine(
            //                  "Parameter : '" + key + "'='" + value + "' isFormField="
            //                  + item.isFormField() + " contentType='" + item.getContentType() + "'"
            //               );
            //            }
            if (item.isFormField()) {
                Object inStock = this.params.get(key);
                if (inStock == null) {
                    String[] values = null;
                    try {
                        // TODO: enable configuration of  'accept-charset'
                        values = new String[] { item.getString(ServletConstants.DefaultCharset) };
                    } catch (UnsupportedEncodingException uee) {
                        MultipartRequestWrapper.Log.warning("Caught: " + uee);

                        values = new String[] { item.getString() };
                    }
                    this.params.put(key, values);
                } else if (inStock instanceof String[]) {
                    // two or more parameters
                    String[] oldValues = (String[]) inStock;
                    String[] values = new String[oldValues.length + 1];

                    int i = 0;
                    while (i < oldValues.length) {
                        values[i] = oldValues[i];
                        i++;
                    }

                    try {
                        // TODO: enable configuration of  'accept-charset'
                        values[i] = item.getString(ServletConstants.DefaultCharset);
                    } catch (UnsupportedEncodingException uee) {
                        MultipartRequestWrapper.Log.warning("Caught: " + uee);

                        values[i] = item.getString();
                    }
                    this.params.put(key, values);
                } else {
                    MultipartRequestWrapper.Log
                            .severe("Program error. Unsupported class: " + inStock.getClass().getName());
                }
            } else {
                //String fieldName = item.getFieldName();
                //String fileName = item.getName();
                //String contentType = item.getContentType();
                //boolean isInMemory = item.isInMemory();
                //long sizeInBytes = item.getSize();
                //...
                this.fileItems.put(key, item);
            }
        }
    }
}

From source file:net.sf.j2ep.requesthandlers.EntityEnclosingRequestHandler.java

/**
 * Will set the input stream and the Content-Type header to match this request.
 * Will also set the other headers send in the request.
 * /*from  w  w  w. j  av a2 s  .c  o m*/
 * @throws IOException An exception is throws when there is a problem getting the input stream
 * @see net.sf.j2ep.model.RequestHandler#process(javax.servlet.http.HttpServletRequest, java.lang.String)
 */
public HttpMethod process(HttpServletRequest request, String url) throws IOException {

    EntityEnclosingMethod method = null;

    if (request.getMethod().equalsIgnoreCase("POST")) {
        method = new PostMethod(url);
    } else if (request.getMethod().equalsIgnoreCase("PUT")) {
        method = new PutMethod(url);
    }

    setHeaders(method, request);

    InputStreamRequestEntity stream;
    stream = new InputStreamRequestEntity(request.getInputStream());
    method.setRequestEntity(stream);
    method.setRequestHeader("Content-type", request.getContentType());

    return method;

}