Java Code Examples for javax.servlet.http.HttpServletRequest.getContentType()

The following are Jave code examples for showing how to use getContentType() of the javax.servlet.http.HttpServletRequest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: lams   File: HttpPutFormContentFilter.java   View Source Code Vote up 7 votes
private boolean isFormContentType(HttpServletRequest request) {
	String contentType = request.getContentType();
	if (contentType != null) {
		try {
			MediaType mediaType = MediaType.parseMediaType(contentType);
			return (MediaType.APPLICATION_FORM_URLENCODED.includes(mediaType));
		}
		catch (IllegalArgumentException ex) {
			return false;
		}
	}
	else {
		return false;
	}
}
 
Example 2
Project: incubator-servicecomb-java-chassis   File: BodyProcessorCreator.java   View Source Code Vote up 6 votes
@Override
public Object getValue(HttpServletRequest request) throws Exception {
  Object body = request.getAttribute(RestConst.BODY_PARAMETER);
  if (body != null) {
    return convertValue(body, targetType);
  }

  // for standard HttpServletRequest, getInputStream will never return null
  // but for mocked HttpServletRequest, maybe get a null
  //  like org.apache.servicecomb.provider.springmvc.reference.ClientToHttpServletRequest
  InputStream inputStream = request.getInputStream();
  if (inputStream == null) {
    return null;
  }

  String contentType = request.getContentType();
  if (contentType != null && !contentType.toLowerCase(Locale.US).startsWith(MediaType.APPLICATION_JSON)) {
    // TODO: we should consider body encoding
    return IOUtils.toString(inputStream, "UTF-8");
  }
  return RestObjectMapper.INSTANCE.readValue(inputStream, targetType);
}
 
Example 3
Project: lams   File: RequestProcessor.java   View Source Code Vote up 6 votes
/**
 * <p>If this is a multipart request, wrap it with a special wrapper.
 * Otherwise, return the request unchanged.</p>
 *
 * @param request The HttpServletRequest we are processing
 */
protected HttpServletRequest processMultipart(HttpServletRequest request) {

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

}
 
Example 4
Project: yadaframework   File: YadaHttpUtil.java   View Source Code Vote up 6 votes
/**
 * Return the document type by checking the request content type and the extension of the request path
 * @param request
 * @return
 */
public int getRequestDocumentType(HttpServletRequest request) {
	String contentType = request.getContentType();
	int result = getDocumentType(contentType);
	if (result!=CONTENT_UNKNOWN) {
		return result;
	}
	String pathInfo = request.getPathInfo();
	if (pathInfo==null) {
		return CONTENT_DOCUMENT;
	}
	if (pathInfo.endsWith(".css")) {
		return CONTENT_CSS;
	}
	if (pathInfo.endsWith(".js")) {
		return CONTENT_JAVASCRIPT;
	}
	if (pathInfo.endsWith(".gif") 
		|| pathInfo.endsWith(".jpeg") 
		|| pathInfo.endsWith(".jpg") 
		|| pathInfo.endsWith(".png") 
		|| pathInfo.endsWith(".tiff")) {
		return CONTENT_IMAGE;
	}
	return CONTENT_DOCUMENT;
}
 
Example 5
Project: validator-web   File: HttpMessageReaderExtractor.java   View Source Code Vote up 6 votes
private MediaType getContentType(HttpServletRequest request) {
    String contentType = request.getContentType();
    if (contentType == null) {
        if (logger.isTraceEnabled()) {
            logger.trace("No Content-Type header found, defaulting to application/octet-stream");
        }
        return MediaType.APPLICATION_OCTET_STREAM;
    }
    return MediaType.parseMediaType(contentType);
}
 
Example 6
Project: OftenPorter   File: PutParamSourceHandle.java   View Source Code Vote up 5 votes
@Override
public ParamSource get(WObject wObject, Class<?> porterClass, Method porterFun) throws Exception
{
    HttpServletRequest request = wObject.getRequest().getOriginalRequest();

    String ctype = request.getContentType();
    if (ctype != null && ctype.indexOf(ContentType.APP_FORM_URLENCODED.getType()) != -1)
    {
        String encode = getEncode(ctype);

        String body = FileTool.getString(request.getInputStream());
        if(body==null){
            return null;
        }
        String[] strs = body.split("&");
        final HashMap<String, Object> paramsMap = new HashMap<>(strs.length);
        int index;
        for (String string : strs)
        {
            index = string.indexOf('=');
            if (index != -1)
            {
                paramsMap.put(string.substring(0, index),
                        URLDecoder.decode(string.substring(index + 1), encode));
            }
        }

        ParamSource paramSource = new DefaultParamSource(paramsMap, wObject.getRequest());

        return paramSource;

    }
    return null;
}
 
Example 7
Project: k8s-proxy   File: K8sReverseProxy.java   View Source Code Vote up 5 votes
private InputStreamEntity getInputStreamEntity(HttpServletRequest request) throws IOException
{
    int contentLength = request.getContentLength();

    ContentType contentType = null;
    if (request.getContentType() != null) {
        contentType = ContentType.parse(request.getContentType());
    }

    return new InputStreamEntity(request.getInputStream(), contentLength, contentType);
}
 
Example 8
Project: Equella   File: AbstractFileUpload.java   View Source Code Vote up 5 votes
public static boolean isMultipartRequest(HttpServletRequest request)
{
    String contentType = request.getContentType();
    return contentType != null && contentType.toLowerCase(Locale.ENGLISH).startsWith("multipart/");
}
 
Example 9
Project: lams   File: StandardServletMultipartResolver.java   View Source Code Vote up 5 votes
@Override
public boolean isMultipart(HttpServletRequest request) {
	// Same check as in Commons FileUpload...
	if (!"post".equals(request.getMethod().toLowerCase())) {
		return false;
	}
	String contentType = request.getContentType();
	return (contentType != null && contentType.toLowerCase().startsWith("multipart/"));
}
 
Example 10
Project: lams   File: IMSPOXRequest.java   View Source Code Vote up 5 votes
public void loadFromRequest(HttpServletRequest request) 
{
	String contentType = request.getContentType();
	if ( ! "application/xml".equals(contentType) ) {
		errorMessage = "Content Type must be application/xml";
		Log.info(errorMessage+"\n"+contentType);
		return;
	}

	setAuthHeader(request.getHeader("Authorization"));
	if ( oauth_body_hash == null ) {
		errorMessage = "Did not find oauth_body_hash";
		Log.info(errorMessage+"\n"+header);
		return;
	}

	try {
		Reader in = request.getReader();
		postBody = readPostBody(in);
	} catch(Exception e) {
		errorMessage = "Could not read message body:"+e.getMessage();
		return;
	}

	validatePostBody();
	if (errorMessage != null) return;

	parsePostBody();
}
 
Example 11
Project: hadoop   File: CheckUploadContentTypeFilter.java   View Source Code Vote up 5 votes
/**
 * Enforces the content-type to be application/octet-stream for
 * POST and PUT requests.
 *
 * @param request servlet request.
 * @param response servlet response.
 * @param chain filter chain.
 *
 * @throws IOException thrown if an IO error occurrs.
 * @throws ServletException thrown if a servet error occurrs.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain)
  throws IOException, ServletException {
  boolean contentTypeOK = true;
  HttpServletRequest httpReq = (HttpServletRequest) request;
  HttpServletResponse httpRes = (HttpServletResponse) response;
  String method = httpReq.getMethod();
  if (method.equals("PUT") || method.equals("POST")) {
    String op = httpReq.getParameter(HttpFSFileSystem.OP_PARAM);
    if (op != null && UPLOAD_OPERATIONS.contains(
        StringUtils.toUpperCase(op))) {
      if ("true".equalsIgnoreCase(httpReq.getParameter(HttpFSParametersProvider.DataParam.NAME))) {
        String contentType = httpReq.getContentType();
        contentTypeOK =
          HttpFSFileSystem.UPLOAD_CONTENT_TYPE.equalsIgnoreCase(contentType);
      }
    }
  }
  if (contentTypeOK) {
    chain.doFilter(httpReq, httpRes);
  }
  else {
    httpRes.sendError(HttpServletResponse.SC_BAD_REQUEST,
                      "Data upload requests must have content-type set to '" +
                      HttpFSFileSystem.UPLOAD_CONTENT_TYPE + "'");

  }
}
 
Example 12
Project: EasyController   File: WebUtils.java   View Source Code Vote up 5 votes
/**
 * multipart
 */
public static boolean isMultipartContent(HttpServletRequest request) {
    if (HttpMethod.POST.name().equals(request.getMethod().toUpperCase())) {
        String contentType = request.getContentType();
        if (contentType != null)
            if (contentType.toLowerCase(Locale.ENGLISH).startsWith(MULTIPART)) {
                return true;
            }
    }
    return false;
}
 
Example 13
Project: jboot   File: RequestUtils.java   View Source Code Vote up 4 votes
public static boolean isMultipartRequest(HttpServletRequest request) {
    String contentType = request.getContentType();
    return contentType != null && contentType.toLowerCase().indexOf("multipart") != -1;
}
 
Example 14
Project: datarouter   File: DefaultSignatureValidator.java   View Source Code Vote up 4 votes
private boolean isFormPost(HttpServletRequest request){
	String contentType = request.getContentType();
	boolean isFormContent = contentType != null
			&& contentType.contains(ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
	return isFormContent && "POST".equalsIgnoreCase(request.getMethod());
}
 
Example 15
Project: convertigo-engine   File: ProxyServletRequester.java   View Source Code Vote up 4 votes
private void gatherRequestInfo(ParameterShuttle infoShuttle, HttpServletRequest request) throws IOException {
		infoShuttle.sessionID = request.getSession().getId();

		infoShuttle.postFromUser = request.getMethod().equals("POST");
		if (infoShuttle.postFromUser) {
			infoShuttle.userContentType = request.getContentType();
			infoShuttle.userContentLength = request.getContentLength();
		}

/*		String query = request.getQueryString();
		if (query != null) {
			int pos = 0;

			infoShuttle.postToSite = query.startsWith(ParameterShuttle.bridgePostTag);
			if (infoShuttle.postToSite)
				pos = ParameterShuttle.bridgePostTag.length();

			if (query.startsWith(ParameterShuttle.bridgeGotoTag, pos)) {
				int p2 = query.indexOf(ParameterShuttle.bridgeThenTag, pos);

				if (p2 > -1) {
					infoShuttle.userGoto = query.substring(pos + ParameterShuttle.bridgeGotoTag.length(), p2);
					infoShuttle.userThen = query.substring(p2 + ParameterShuttle.bridgeThenTag.length());
				}
				else {
					infoShuttle.userGoto = query.substring(pos + ParameterShuttle.bridgeGotoTag.length());
				}
			}
			else if (query.startsWith(ParameterShuttle.bridgeThenTag, pos)) {
				infoShuttle.userThen = query.substring(pos + ParameterShuttle.bridgeThenTag.length());
			}
		}*/
		infoShuttle.postToSite = infoShuttle.postFromUser;//request.getParameter(Parameter.ProxyPost.getName()) != null;
		infoShuttle.userGoto = request.getParameter(Parameter.ProxyGoto.getName());
		infoShuttle.userThen = request.getParameter(Parameter.ProxyThen.getName());

		Enumeration<String> allHeaderNames = GenericUtils.cast(request.getHeaderNames());
		while (allHeaderNames.hasMoreElements()) {
			String name = (String) allHeaderNames.nextElement();
			infoShuttle.userHeaderNames.add(name.toLowerCase());
			infoShuttle.userHeaderValues.add(request.getHeader(name));
		}

		ParameterShuttle.getSelfURL(
			request.getScheme(),
			request.getServerName(),
			request.getServerPort(),
			request.getRequestURI()
		);
	}
 
Example 16
Project: lams   File: RequestParamMethodArgumentResolver.java   View Source Code Vote up 4 votes
private void assertIsMultipartRequest(HttpServletRequest request) {
	String contentType = request.getContentType();
	if (contentType == null || !contentType.toLowerCase().startsWith("multipart/")) {
		throw new MultipartException("The current request is not a multipart request");
	}
}
 
Example 17
Project: lams   File: ServletServerHttpRequest.java   View Source Code Vote up 4 votes
private boolean isFormPost(HttpServletRequest request) {
	return (request.getContentType() != null && request.getContentType().contains(FORM_CONTENT_TYPE) &&
			METHOD_POST.equalsIgnoreCase(request.getMethod()));
}
 
Example 18
Project: loc-framework   File: LocAccessLogger.java   View Source Code Vote up 4 votes
private boolean isMultipart(final HttpServletRequest request) {
  return request.getContentType() != null && request.getContentType()
      .startsWith("multipart/form-data");
}
 
Example 19
Project: careconnect-reference-implementation   File: ServerInterceptor.java   View Source Code Vote up 4 votes
@Override
public boolean incomingRequestPreProcessed(HttpServletRequest request, HttpServletResponse theResponse) {

    if (request.getMethod() != null) {

        /* KGM 3/1/2018 This is now handled by CORS headers

       if (theRequest.getMethod().equals("OPTIONS"))
            throw new MethodNotAllowedException("request must use HTTP GET");
        */

        if (request.getContentType() != null) {
           checkContentType(request.getContentType());
        }

        if (request.getQueryString() != null) {


            List<NameValuePair> params = null;
            try {
                params = URLEncodedUtils.parse(new URI("http://dummy?" + request.getQueryString()), "UTF-8");
            } catch (Exception ex) {
            }

            ListIterator paramlist = params.listIterator();
            while (paramlist.hasNext()) {
                NameValuePair param = (NameValuePair) paramlist.next();
                if (param.getName().equals("_format"))
                    checkContentType(param.getValue());

            }
        }


        // May need to re-add this at a later date (probably in conjunction with a security uplift)
        /*
        KGM 3/1/2018 disabled for crucible testing

        if (request.getMethod().equals("POST") && request.getPathInfo() != null && request.getPathInfo().contains("_search"))
            throw new MethodNotAllowedException("request must use HTTP GET");
            */
    }
    return true;
}
 
Example 20
Project: wisp   File: RequestFilter.java   View Source Code Vote up 2 votes
/**
 * 是否是上传文件
 *
 * @param request
 *
 * @return
 */
private boolean isMultipart(final HttpServletRequest request) {
    return request.getContentType() != null && request.getContentType().startsWith("multipart/form-data");
}