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.mob.forum.util.legacy.commons.fileupload.FileUploadBase.java

/**
 * Utility method that determines whether the request contains multipart
 * content./*from w ww.  j av a 2  s.c om*/
 *
 * @param req The servlet request to be evaluated. Must be non-null.
 *
 * @return <code>true</code> if the request is multipart;
 *         <code>false</code> otherwise.
 *
 * @deprecated Use the method on <code>ServletFileUpload</code> instead.
 */
public static final boolean isMultipartContent(HttpServletRequest req) {
    if (!"post".equals(req.getMethod().toLowerCase())) {
        return false;
    }
    String contentType = req.getContentType();
    if (contentType == null) {
        return false;
    }
    if (contentType.toLowerCase().startsWith(MULTIPART)) {
        return true;
    }
    return false;
}

From source file:com.jaspersoft.jasperserver.rest.RESTUtils.java

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

From source file:com.pureinfo.srm.RequestUtils.java

public static PureProperties parse(HttpServletRequest _request) throws PureException {
    logger.debug("enti");
    PureProperties props = new PureProperties();

    Enumeration names = _request.getParameterNames();
    logger.debug("enti11111111111#" + names.hasMoreElements());
    while (names.hasMoreElements()) {
        String sName = (String) names.nextElement();
        String[] values = _request.getParameterValues(sName);
        if (values.length == 1) {
            props.setProperty(sName, values[0]);
        } else {//from  ww  w . j a  v a  2 s . c  o m
            props.setProperty(sName, values);
        }

    }

    String sContentType = _request.getContentType();
    if (sContentType != null && sContentType.startsWith("multipart/form-data")) {
        logger.debug("enti111");
        DiskFileUpload upload = new DiskFileUpload();
        List items;
        try {
            items = upload.parseRequest(_request);
        } catch (FileUploadException ex) {
            throw new PureException(PureException.UNKNOWN, "upload error", ex);
        }
        logger.debug("enti111111111111" + items.size());
        for (Iterator iter = items.iterator(); iter.hasNext();) {
            FileItem item = (FileItem) iter.next();
            if (item.getName() == null) {
                props.setProperty(item.getFieldName(), item.getString());
            } else {
                props.setProperty(item.getFieldName(), item);
            }
            logger.debug("name:" + item.getFieldName() + "-value:" + props.getProperty(item.getFieldName()));
        }
    }

    return props;
}

From source file:com.extjs.djn.ioc.servlet.BaseDirectJNgineServlet.java

private static RequestType getFromRequestContentType(HttpServletRequest request) {
    assert request != null;

    String contentType = request.getContentType();
    String contentTypeLowercase = "";
    if (contentType != null) {
        contentTypeLowercase = contentType.toLowerCase();
    }//from   w w  w . j  a v  a2  s  .c  o  m

    String pathInfo = request.getPathInfo();

    if (!StringUtils.isEmpty(pathInfo) && pathInfo.startsWith(PollRequestProcessor.PATHINFO_POLL_PREFIX)) {
        return RequestType.POLL;
    } else if (contentTypeLowercase.startsWith("application/json")) {
        return RequestType.JSON;
    } else if (contentTypeLowercase.startsWith("application/x-www-form-urlencoded")
            && request.getMethod().toLowerCase().equals("post")) {
        return RequestType.FORM_SIMPLE_POST;
    } else if (ServletFileUpload.isMultipartContent(request)) {
        return RequestType.FORM_UPLOAD_POST;
    } else {
        String requestInfo = ServletUtils.getDetailedRequestInformation(request);
        RequestException ex = RequestException.forRequestFormatNotRecognized();
        logger.error("Error during file uploader: " + ex.getMessage() + "\nAdditional request information: "
                + requestInfo, ex);
        throw ex;
    }
}

From source file:org.opendatakit.odktables.util.ServiceUtils.java

@SuppressWarnings({ "rawtypes", "unused" })
public static void examineRequest(ServletContext sc, HttpServletRequest req) {
    Log logger = LogFactory.getLog(ServiceUtils.class);

    Enumeration headers = req.getHeaderNames();
    StringBuilder b = new StringBuilder();
    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        Enumeration fieldValues = req.getHeaders(headerName);
        while (fieldValues.hasMoreElements()) {
            String fieldValue = (String) fieldValues.nextElement();
            b.append(headerName).append(": ").append(fieldValue).append("\n");
        }// w  w w. j av a  2 s .co  m
    }

    String contentType = req.getContentType();
    logger.info("Content type: " + contentType);

    String charEncoding = req.getCharacterEncoding();
    logger.info("Character encoding: " + charEncoding);

    String headerSet = b.toString();
    logger.info("Headers: " + headerSet);

    Cookie[] cookies = req.getCookies();
    logger.info("Cookies: " + cookies);

    String method = req.getMethod();
    logger.info("Method: " + method);

    String ctxtPath = req.getContextPath();
    logger.info("Context Path: " + ctxtPath);

    String pathInfo = req.getPathInfo();
    logger.info("Path Info: " + pathInfo);

    String query = req.getQueryString();
    logger.info("Query String: " + query);

    String ace = req.getHeader(ApiConstants.ACCEPT_CONTENT_ENCODING_HEADER);
    boolean sessionId = req.isRequestedSessionIdValid();
}

From source file:com.easyjf.web.core.FrameworkEngine.java

/**
 * ?requestform//from  ww w. j  av  a  2 s  . c o m
 * 
 * @param request
 * @param formName
 * @return ??Form
 */
public static WebForm creatWebForm(HttpServletRequest request, String formName, Module module) {
    Map textElement = new HashMap();
    Map fileElement = new HashMap();
    String contentType = request.getContentType();
    String reMethod = request.getMethod();
    if ((contentType != null) && (contentType.startsWith("multipart/form-data"))
            && (reMethod.equalsIgnoreCase("post"))) {
        //  multipart/form-data
        File file = new File(request.getSession().getServletContext().getRealPath("/temp"));
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(webConfig.getUploadSizeThreshold());
        factory.setRepository(file);
        ServletFileUpload sf = new ServletFileUpload(factory);
        sf.setSizeMax(webConfig.getMaxUploadFileSize());
        sf.setHeaderEncoding(request.getCharacterEncoding());
        List reqPars = null;
        try {
            reqPars = sf.parseRequest(request);
            for (int i = 0; i < reqPars.size(); i++) {
                FileItem it = (FileItem) reqPars.get(i);
                if (it.isFormField()) {
                    textElement.put(it.getFieldName(), it.getString(request.getCharacterEncoding()));// ??
                } else {
                    fileElement.put(it.getFieldName(), it);// ???
                }
            }
        } catch (Exception e) {
            logger.error(e);
        }
    } else if ((contentType != null) && contentType.equals("text/xml")) {
        StringBuffer buffer = new StringBuffer();
        try {
            String s = request.getReader().readLine();
            while (s != null) {
                buffer.append(s + "\n");
                s = request.getReader().readLine();
            }
        } catch (Exception e) {
            logger.error(e);
        }
        textElement.put("xml", buffer.toString());
    } else {
        textElement = request2map(request);
    }
    // logger.debug("????");
    WebForm wf = findForm(formName);
    wf.setValidate(module.isValidate());// ?validate?Form
    if (wf != null) {
        wf.setFileElement(fileElement);
        wf.setTextElement(textElement);
    }
    return wf;
}

From source file:com.softwarementors.extjs.djn.servlet.DirectJNgineServlet.java

private static RequestType getFromRequestContentType(HttpServletRequest request) {
    assert request != null;

    String contentType = request.getContentType();
    String pathInfo = request.getPathInfo();

    if (!StringUtils.isEmpty(pathInfo) && pathInfo.startsWith(PollRequestProcessor.PATHINFO_POLL_PREFIX)) {
        return RequestType.POLL;
    } else if (StringUtils.startsWithCaseInsensitive(contentType, "application/json")) {
        return RequestType.JSON;
    } else if (StringUtils.startsWithCaseInsensitive(contentType, "application/x-www-form-urlencoded")
            && request.getMethod().equalsIgnoreCase("post")) {
        return RequestType.FORM_SIMPLE_POST;
    } else if (ServletFileUpload.isMultipartContent(request)) {
        return RequestType.FORM_UPLOAD_POST;
    } else if (RequestRouter.isSourceRequest(pathInfo)) {
        return RequestType.SOURCE;
    } else {//from w ww. j a  v a 2 s . c  o m
        String requestInfo = ServletUtils.getDetailedRequestInformation(request);
        RequestException ex = RequestException.forRequestFormatNotRecognized();
        logger.error("Error during file uploader: " + ex.getMessage() + "\nAdditional request information: "
                + requestInfo, ex);
        throw ex;
    }
}

From source file:org.springframework.http.server.reactive.ServletServerHttpRequest.java

private static HttpHeaders initHeaders(HttpServletRequest request) {
    HttpHeaders headers = new HttpHeaders();
    for (Enumeration<?> names = request.getHeaderNames(); names.hasMoreElements();) {
        String name = (String) names.nextElement();
        for (Enumeration<?> values = request.getHeaders(name); values.hasMoreElements();) {
            headers.add(name, (String) values.nextElement());
        }//from   w  w w . ja  va 2s  .  co  m
    }
    MediaType contentType = headers.getContentType();
    if (contentType == null) {
        String requestContentType = request.getContentType();
        if (StringUtils.hasLength(requestContentType)) {
            contentType = MediaType.parseMediaType(requestContentType);
            headers.setContentType(contentType);
        }
    }
    if (contentType != null && contentType.getCharset() == null) {
        String encoding = request.getCharacterEncoding();
        if (StringUtils.hasLength(encoding)) {
            Charset charset = Charset.forName(encoding);
            Map<String, String> params = new LinkedCaseInsensitiveMap<>();
            params.putAll(contentType.getParameters());
            params.put("charset", charset.toString());
            headers.setContentType(new MediaType(contentType.getType(), contentType.getSubtype(), params));
        }
    }
    if (headers.getContentLength() == -1) {
        int contentLength = request.getContentLength();
        if (contentLength != -1) {
            headers.setContentLength(contentLength);
        }
    }
    return headers;
}

From source file:org.opendaylight.sloth.filter.SlothSecurityFilter.java

private static Request getRequest(HttpServletRequest httpServletRequest, String externalJson) {
    LOG.info(String.format("create request, method: %s, request-url: %s, query-string: %s",
            httpServletRequest.getMethod(), httpServletRequest.getRequestURI(),
            httpServletRequest.getQueryString()));
    RequestBuilder requestBuilder = new RequestBuilder();
    requestBuilder.setMethod(HttpType.valueOf(httpServletRequest.getMethod()))
            .setRequestUrl(httpServletRequest.getRequestURI())
            .setQueryString(httpServletRequest.getQueryString());
    if (externalJson == null || externalJson.isEmpty()) {
        try {/*from w w  w  .j  a  v  a 2s .  c o m*/
            if (httpServletRequest.getContentType() != null
                    && Objects.equals(httpServletRequest.getContentType(), JSON_CONTENT_TYPE)) {
                requestBuilder.setJsonBody(IOUtils.toString(httpServletRequest.getReader()));
            }
        } catch (IOException e) {
            LOG.error("failed to get json body from http servlet request: " + e.getMessage());
        }
    } else {
        requestBuilder.setJsonBody(externalJson);
    }
    return requestBuilder.build();
}

From source file:org.jaffa.presentation.portlet.CustomRequestProcessor.java

/**
 * <p>Populate the properties of the specified JavaBean from the specified
 * HTTP request, based on matching each parameter name (plus an optional
 * prefix and/or suffix) against the corresponding JavaBeans "property
 * setter" methods in the bean's class. Suitable conversion is done for
 * argument types as described under <code>setProperties</code>.</p>
 *
 * <p>If you specify a non-null <code>prefix</code> and a non-null
 * <code>suffix</code>, the parameter name must match <strong>both</strong>
 * conditions for its value(s) to be used in populating bean properties.
 * If the request's content type is "multipart/form-data" and the
 * method is "POST", the <code>HttpServletRequest</code> object will be wrapped in
 * a <code>MultipartRequestWrapper</code object.</p>
 *
 * @param bean The JavaBean whose properties are to be set
 * @param prefix The prefix (if any) to be prepend to bean property
 *               names when looking for matching parameters
 * @param suffix The suffix (if any) to be appended to bean property
 *               names when looking for matching parameters
 * @param request The HTTP request whose parameters are to be used
 *                to populate bean properties
 *
 * @exception ServletException if an exception is thrown while setting
 *            property values//from   w w  w .  j  ava2 s . co  m
 */
protected static void customRequestUtilsPopulate(Object bean, String prefix, String suffix,
        HttpServletRequest request, ActionMapping mapping) throws ServletException {

    // Build a list of relevant request parameters from this request
    HashMap properties = new HashMap();
    // Iterator of parameter names
    Enumeration names = null;
    // Map for multipart parameters
    Map multipartParameters = null;

    String contentType = request.getContentType();
    String method = request.getMethod();
    boolean isMultipart = false;

    if ((contentType != null) && (contentType.startsWith("multipart/form-data"))
            && (method.equalsIgnoreCase("POST"))) {

        // Get the ActionServletWrapper from the form bean
        ActionServletWrapper servlet;
        if (bean instanceof ActionForm) {
            servlet = ((ActionForm) bean).getServletWrapper();
        } else {
            throw new ServletException(
                    "bean that's supposed to be " + "populated from a multipart request is not of type "
                            + "\"org.apache.struts.action.ActionForm\", but type " + "\""
                            + bean.getClass().getName() + "\"");
        }

        // Obtain a MultipartRequestHandler
        MultipartRequestHandler multipartHandler = getMultipartHandler(request);

        // Set the multipart request handler for our ActionForm.
        // If the bean isn't an ActionForm, an exception would have been
        // thrown earlier, so it's safe to assume that our bean is
        // in fact an ActionForm.
        ((ActionForm) bean).setMultipartRequestHandler(multipartHandler);

        if (multipartHandler != null) {
            isMultipart = true;
            // Set servlet and mapping info
            servlet.setServletFor(multipartHandler);
            multipartHandler.setMapping((ActionMapping) request.getAttribute(Globals.MAPPING_KEY));
            // Initialize multipart request class handler
            multipartHandler.handleRequest(request);
            //stop here if the maximum length has been exceeded
            Boolean maxLengthExceeded = (Boolean) request
                    .getAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);
            if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) {
                // *** Jaffa-customization: Do not just terminate form population. Instead throw a ServletException ***
                //return;
                throw new ServletException(
                        "The size of the file being uploaded exceeds the maximum allowed " + ModuleUtils
                                .getInstance().getModuleConfig(request).getControllerConfig().getMaxFileSize());
            }
            //retrieve form values and put into properties
            multipartParameters = getAllParametersForMultipartRequest(request, multipartHandler);
            names = Collections.enumeration(multipartParameters.keySet());
        }
    }

    if (!isMultipart) {
        names = request.getParameterNames();
    }

    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        String stripped = name;
        if (prefix != null) {
            if (!stripped.startsWith(prefix)) {
                continue;
            }
            stripped = stripped.substring(prefix.length());
        }
        if (suffix != null) {
            if (!stripped.endsWith(suffix)) {
                continue;
            }
            stripped = stripped.substring(0, stripped.length() - suffix.length());
        }
        Object parameterValue = null;
        if (isMultipart) {
            parameterValue = multipartParameters.get(name);
        } else {
            parameterValue = request.getParameterValues(name);
        }

        // Populate parameters, except "standard" struts attributes
        // such as 'org.apache.struts.action.CANCEL'
        if (!(stripped.startsWith("org.apache.struts."))) {
            properties.put(stripped, parameterValue);
        }
    }

    // *** Jaffa-customization: Reset the bean ***
    try {
        if (log.isDebugEnabled())
            log.debug("Calling FormBean reset()");
        ((ActionForm) bean).reset(mapping, request);
    } catch (Exception e) {
        throw new ServletException("FormBean.reset", e);
    }

    // Set the corresponding properties of our bean
    try {
        BeanUtils.populate(bean, properties);
    } catch (Exception e) {
        throw new ServletException("BeanUtils.populate", e);
    }

}