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

The following examples show how to use javax.servlet.http.HttpServletRequest#getContentType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestSdcIpcTarget.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  String appId = req.getHeader(Constants.X_SDC_APPLICATION_ID_HEADER);
  String contentType = req.getContentType();
  if (contentType == null || !contentType.equals(Constants.APPLICATION_BINARY)) {
    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
  } else if (appId == null || !appId.equals("appId")) {
    resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
  } else {
    compressedData = req.getHeader(Constants.X_SDC_COMPRESSION_HEADER) != null &&
                     req.getHeader(Constants.X_SDC_COMPRESSION_HEADER).equals(Constants.SNAPPY_COMPRESSION);
    InputStream is = req.getInputStream();
    while (is.read() > 1);
    resp.setStatus(HttpServletResponse.SC_OK);
  }
}
 
Example 2
Source File: RequestUtils.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
/**
 *   是否multipart/form-data or application/octet-stream表单提交方式
 * @param request
 * @return
 */
public static final boolean isMultipartContent(HttpServletRequest request) {
	if (!RestConst.POST_METHOD.equalsIgnoreCase(request.getMethod())) {
		return false;
	}
	String contentType = request.getContentType();
	if (contentType == null) {
		return false;
	}
	contentType = contentType.toLowerCase(Locale.ENGLISH);
	if (contentType.startsWith(RestConst.MULTIPART) 
			|| MediaType.APPLICATION_OCTET_STREAM.equals(contentType)) {
		return true;
	}
	return false;
}
 
Example 3
Source File: AccessServlet.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/** construct from the req */
public AccessServletInfo(HttpServletRequest req)
{
	m_options = new Properties();
	String type = req.getContentType();

	Enumeration e = req.getParameterNames();
	while (e.hasMoreElements())
	{
		String key = (String) e.nextElement();
		String[] values = req.getParameterValues(key);
		if (values.length == 1)
		{
			m_options.put(key, values[0]);
		}
		else
		{
			StringBuilder buf = new StringBuilder();
			for (int i = 0; i < values.length; i++)
			{
				buf.append(values[i] + FORM_VALUE_DELIMETER);
			}
			m_options.put(key, buf.toString());
		}
	}
}
 
Example 4
Source File: HttpProxy.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
private HttpEntity createEntity(HttpServletRequest servletRequest) throws IOException {
    final String contentType = servletRequest.getContentType();
    // body with 'application/x-www-form-urlencoded' is handled by tomcat therefore we cannot
    // obtain it through input stream and need some workaround
    if (ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType)) {
        List<NameValuePair> entries = new ArrayList<>();
        // obviously that we also copy params from url, but we cannot differentiate its
        Enumeration<String> names = servletRequest.getParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            entries.add(new BasicNameValuePair(name, servletRequest.getParameter(name)));
        }
        return new UrlEncodedFormEntity(entries, servletRequest.getCharacterEncoding());
    }

    // Add the input entity (streamed)
    //  note: we don't bother ensuring we close the servletInputStream since the container handles it
    return new InputStreamEntity(servletRequest.getInputStream(),
            servletRequest.getContentLength(),
            ContentType.create(contentType));
}
 
Example 5
Source File: HttpUtil.java    From AthenaServing with Apache License 2.0 6 votes vote down vote up
/**
 * 获取请求参数
 *
 * @param request
 * @return
 */
public static String findParameters(HttpServletRequest request) {
    String contentType = request.getContentType();
    String result = "";
    if (null == contentType) {
        return result;
    }
    if (contentType.toLowerCase().contains("application/x-www-form-urlencoded")) {
        //当为application/x-www-form-urlencoded协议
        result = getBodyString(request);
    } else if (contentType.toLowerCase().contains("application/json")) {
        //当为application/json协议
    } else if (contentType.toLowerCase().contains("multipart/form-data")) {
        //当为multipart/form-data协议
        result = getBodyString(request);
    }
    return result;
}
 
Example 6
Source File: RequestAuth.java    From java-unified-sdk with Apache License 2.0 5 votes vote down vote up
private RequestAuth(HttpServletRequest req) {
  if (req.getContentType() != null && req.getContentType().startsWith("text/plain")) {
    // TODO
  } else {
    appId = getHeaders(req, "x-lc-id", "x-avoscloud-application-id", "x-uluru-application-id");
    appKey =
        getHeaders(req, "x-lc-key", "x-avoscloud-application-key", "x-uluru-application-key");
    masterKey = getHeaders(req, "x-avoscloud-master-key", "x-uluru-master-key");
    if (appKey != null && appKey.indexOf(",master") > 0) {
      masterKey = appKey.substring(0, appKey.indexOf(",master"));
      appKey = null;
    }
    prod = getHeaders(req, "x-lc-prod", "x-avoscloud-application-production",
        "x-uluru-application-production");
    if ("false".equals(prod)) {
      prod = "0";
    }
    sessionToken =
        getHeaders(req, "x-lc-session", "x-uluru-session-token", "x-avoscloud-session-token");
    sign = getHeaders(req, "x-lc-sign", "x-avoscloud-request-sign");

    // 放在这里只能算是一个side effect
    String remoteAddress = getHeaders(req, "x-real-ip", "x-forwarded-for");
    if (StringUtil.isEmpty(remoteAddress)) {
      remoteAddress = req.getRemoteAddr();
    }
    EngineRequestContext.setSessionToken(sessionToken);
    EngineRequestContext.setRemoteAddress(remoteAddress);
  }
}
 
Example 7
Source File: RpcServlet.java    From Brutusin-RPC with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param request
 * @return
 */
private static boolean isMultipartContent(HttpServletRequest request) {
    String method = request.getMethod().toUpperCase();
    if (!method.equals("POST") && !method.equals("PUT")) {
        return false;
    }
    String contentType = request.getContentType();
    if (contentType == null) {
        return false;
    }
    return contentType.toLowerCase(Locale.ENGLISH).startsWith("multipart");
}
 
Example 8
Source File: SolrRequestParsers.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public HttpRequestContentStream( HttpServletRequest req ) {
  this.req = req;
  
  contentType = req.getContentType();
  // name = ???
  // sourceInfo = ???
  
  String v = req.getHeader( "Content-Length" );
  if( v != null ) {
    size = Long.valueOf( v );
  }
}
 
Example 9
Source File: AbstractCrudController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Deserializes a payload from the request, handles JSON/XML payloads
 *
 * @param request HttpServletRequest from current session
 * @return Parsed entity or null if invalid type
 */
protected T deserialize( HttpServletRequest request ) throws IOException
{
    String type = request.getContentType();
    type = !StringUtils.isEmpty( type ) ? type : MediaType.APPLICATION_JSON_VALUE;

    // allow type to be overridden by path extension
    if ( request.getPathInfo().endsWith( ".json" ) )
    {
        type = MediaType.APPLICATION_JSON_VALUE;
    }
    else if ( request.getPathInfo().endsWith( ".xml" ) )
    {
        type = MediaType.APPLICATION_XML_VALUE;
    }

    if ( isCompatibleWith( type, MediaType.APPLICATION_JSON ) )
    {
        return renderService.fromJson( request.getInputStream(), getEntityClass() );
    }
    else if ( isCompatibleWith( type, MediaType.APPLICATION_XML ) )
    {
        return renderService.fromXml( request.getInputStream(), getEntityClass() );
    }

    return null;
}
 
Example 10
Source File: RequestHelper.java    From bird-java with MIT License 5 votes vote down vote up
/**
 * 是否是Multipart请求
 *
 * @param request 请求
 * @return is multipart
 */
public static boolean isMultipartContent(HttpServletRequest request) {
    String contentType = request.getContentType();
    if (contentType == null) {
        return false;
    }
    return contentType.toLowerCase(Locale.ENGLISH).startsWith(WebConstant.MULTIPART);
}
 
Example 11
Source File: XsymFilter.java    From HongsCORE with MIT License 5 votes vote down vote up
@Override
public void doFilter(Core core, ActionHelper hlpr, FilterChain chain)
    throws IOException, ServletException
{
    HttpServletResponse rsp = hlpr.getResponse();
    HttpServletRequest  req = hlpr.getRequest( );
    String act = ActionDriver.getRecentPath(req);
    String ctt = req.getContentType();

    do {
        if (ctt == null) {
            break;
        }

        /**
         * 非 JSON 已在 Dict 中兼容
         */
        ctt = ctt.split( ";", 2 )[0];
        if (! ctt.endsWith("/json")) {
            break;
        }

        /**
         * 检查当前动作是否可以忽略
         */
        if (ignore != null && ignore.ignore(act)) {
            break;
        }

        doChange(hlpr.getRequestData());
    }
    while (false);

    chain.doFilter(req , rsp);
}
 
Example 12
Source File: ReportTableFacadeController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Deserializes a payload from the request, handles JSON/XML payloads
 *
 * @param request HttpServletRequest from current session
 * @return Parsed entity or null if invalid type
 */
protected ReportTable deserialize( HttpServletRequest request ) throws IOException
{
    String type = request.getContentType();
    type = !StringUtils.isEmpty( type ) ? type : MediaType.APPLICATION_JSON_VALUE;

    // allow type to be overridden by path extension
    if ( request.getPathInfo().endsWith( ".json" ) )
    {
        type = MediaType.APPLICATION_JSON_VALUE;
    }
    else if ( request.getPathInfo().endsWith( ".xml" ) )
    {
        type = MediaType.APPLICATION_XML_VALUE;
    }

    if ( isCompatibleWith( type, MediaType.APPLICATION_JSON ) )
    {
        return renderService.fromJson( request.getInputStream(), ReportTable.class );
    }
    else if ( isCompatibleWith( type, MediaType.APPLICATION_XML ) )
    {
        return renderService.fromXml( request.getInputStream(), ReportTable.class );
    }

    return null;
}
 
Example 13
Source File: PutAwareStandardServletMultiPartResolver.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method that determines whether the request contains multipart content.
 *
 * @param request
 *     The servlet request to be evaluated. Must be non-null.
 * @return <code>true</code> if the request is multipart; {@code false} otherwise.
 * @see org.apache.commons.fileupload.servlet.ServletFileUpload#isMultipartContent(HttpServletRequest)
 */
public static final boolean isMultipartContent(HttpServletRequest request) {
    final String method = request.getMethod().toLowerCase();
    if (!method.equalsIgnoreCase("post") && !method.equalsIgnoreCase("put")) {
        return false;
    }

    String contentType = request.getContentType();
    return StringUtils.startsWithIgnoreCase(contentType, "multipart/");
}
 
Example 14
Source File: RequestData.java    From sample.ferret with Apache License 2.0 5 votes vote down vote up
public RequestData(final HttpServletRequest request) {
    method = request.getMethod();
    uri = request.getRequestURI();
    protocol = request.getProtocol();
    servletPath = request.getServletPath();
    pathInfo = request.getPathInfo();
    pathTranslated = request.getPathTranslated();
    characterEncoding = request.getCharacterEncoding();
    queryString = request.getQueryString();
    contentLength = request.getContentLength();
    contentType = request.getContentType();
    serverName = request.getServerName();
    serverPort = request.getServerPort();
    remoteUser = request.getRemoteUser();
    remoteAddress = request.getRemoteAddr();
    remoteHost = request.getRemoteHost();
    remotePort = request.getRemotePort();
    localAddress = request.getLocalAddr();
    localHost = request.getLocalName();
    localPort = request.getLocalPort();
    authorizationScheme = request.getAuthType();
    preferredClientLocale = request.getLocale();
    allClientLocales = Collections.list(request.getLocales());
    contextPath = request.getContextPath();
    userPrincipal = request.getUserPrincipal();
    requestHeaders = getRequestHeaders(request);
    cookies = getCookies(request.getCookies());
    requestAttributes = getRequestAttributes(request);
}
 
Example 15
Source File: UploadUtils.java    From jeecg with Apache License 2.0 4 votes vote down vote up
/**
 * 上传验证,并初始化文件目录
 * 
 * @param request
 */
private String validateFields(HttpServletRequest request) {
	String errorInfo = "true";
	// boolean errorFlag = true;
	// 获取内容类型
	String contentType = request.getContentType();
	int contentLength = request.getContentLength();
	// 文件保存目录路径
	savePath = request.getSession().getServletContext().getRealPath("/") + basePath + "/";
	// 文件保存目录URL
	saveUrl = request.getContextPath() + "/" + basePath + "/";
	File uploadDir = new File(savePath);
	if (contentType == null || !contentType.startsWith("multipart")) {
		// TODO
		org.jeecgframework.core.util.LogUtil.info("请求不包含multipart/form-data流");
		errorInfo = "请求不包含multipart/form-data流";
	} else if (maxSize < contentLength) {
		// TODO
		org.jeecgframework.core.util.LogUtil.info("上传文件大小超出文件最大大小");
		errorInfo = "上传文件大小超出文件最大大小[" + maxSize + "]";
	} else if (!ServletFileUpload.isMultipartContent(request)) {
		// TODO
		errorInfo = "请选择文件";
	} else if (!uploadDir.isDirectory()) {// 检查目录
		// TODO
		errorInfo = "上传目录[" + savePath + "]不存在";
	} else if (!uploadDir.canWrite()) {
		// TODO
		errorInfo = "上传目录[" + savePath + "]没有写权限";
	} else if (!extMap.containsKey(dirName)) {
		// TODO
		errorInfo = "目录名不正确";
	} else {
		// .../basePath/dirName/
		// 创建文件夹
		savePath += dirName + "/";
		saveUrl += dirName + "/";
		File saveDirFile = new File(savePath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}
		// .../basePath/dirName/yyyyMMdd/
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());
		savePath += ymd + "/";
		saveUrl += ymd + "/";
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		// 获取上传临时路径
		tempPath = request.getSession().getServletContext().getRealPath("/") + tempPath + "/";
		File file = new File(tempPath);
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	return errorInfo;
}
 
Example 16
Source File: LongWaitStatusServlet.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (FrameworkUtils.getMaxInactiveInterval() == 0) {
        FrameworkUtils.setMaxInactiveInterval(request.getSession().getMaxInactiveInterval());
    }
    String id = request.getParameter(PROP_WAITING_ID);
    if (id == null) {
        if (request.getContentType() != null && request.getContentType().startsWith
                (FrameworkConstants.ContentTypes.TYPE_APPLICATION_JSON)) {
            Gson gson = new Gson();
            LongWaitStatusRequest longWaitStatusRequest = gson.fromJson(request.getReader(),
                                                                        LongWaitStatusRequest.class);
            id = longWaitStatusRequest.getWaitId();
        }
    }

    LongWaitStatusResponse longWaitResponse = new LongWaitStatusResponse();
    longWaitResponse.setWaitId(id);
    if (id == null) {
        longWaitResponse.setStatus(LongWaitStatus.Status.UNKNOWN.name());
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } else {
        LongWaitStatusStoreService longWaitStatusStoreService =
                FrameworkServiceDataHolder.getInstance().getLongWaitStatusStoreService();
        if (longWaitStatusStoreService == null) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } else {
            LongWaitStatus longWaitStatus = null;
            try {
                longWaitStatus = longWaitStatusStoreService.getWait(id);
            } catch (FrameworkException e) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
            if (longWaitStatus == null) {
                longWaitResponse.setStatus(LongWaitStatus.Status.COMPLETED.name());
            } else {
                if (longWaitStatus.getStatus() != null) {
                    if (longWaitStatus.getStatus() == LongWaitStatus.Status.UNKNOWN) {
                        longWaitResponse.setStatus(LongWaitStatus.Status.COMPLETED.name());
                    } else {
                        longWaitResponse.setStatus(longWaitStatus.getStatus().name());
                    }
                } else {
                    longWaitResponse.setStatus(LongWaitStatus.Status.COMPLETED.name());
                }
            }
        }
    }

    response.setContentType(FrameworkConstants.ContentTypes.TYPE_APPLICATION_JSON);
    String json = new Gson().toJson(longWaitResponse);
    try (PrintWriter out = response.getWriter()) {
        out.print(json);
        out.flush();
    }
}
 
Example 17
Source File: CommandProxyServlet.java    From Scribengin with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void onResponseFailure(HttpServletRequest request, HttpServletResponse response, 
                                  Response proxyResponse, Throwable failure){
  //System.err.println("Response Failure!");
  this.setForwardingUrl();
  
  HttpClient c = null;
  try {
    c = this.createHttpClient();
  } catch (ServletException e1) {
    e1.printStackTrace();
  }
  
  final Request proxyRequest =  c.newRequest(this.forwardingUrl)
      .method(request.getMethod())
      .version(HttpVersion.fromString(request.getProtocol()));
  
  boolean hasContent = request.getContentLength() > 0 || request.getContentType() != null;
  for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();){
      String headerName = headerNames.nextElement();
      if (HttpHeader.TRANSFER_ENCODING.is(headerName))
          hasContent = true;
      for (Enumeration<String> headerValues = request.getHeaders(headerName); headerValues.hasMoreElements();){
          String headerValue = headerValues.nextElement();
          if (headerValue != null)
              proxyRequest.header(headerName, headerValue);
      }
  }

  // Add proxy headers
  addViaHeader(proxyRequest);
  addXForwardedHeaders(proxyRequest, request);

  final AsyncContext asyncContext = request.getAsyncContext();
  // We do not timeout the continuation, but the proxy request
  asyncContext.setTimeout(0);
  proxyRequest.timeout(getTimeout(), TimeUnit.MILLISECONDS);

  if (hasContent)
    try {
      proxyRequest.content(proxyRequestContent(proxyRequest, request));
    } catch (IOException e) {
      e.printStackTrace();
    }

  customizeProxyRequest(proxyRequest, request);

  proxyRequest.send(new ProxyResponseListener(request, response));
}
 
Example 18
Source File: CORSFilter.java    From para with Apache License 2.0 4 votes vote down vote up
/**
 * Determines the request type.
 * @param request req
 * @return CORS request type
 */
public CORSRequestType checkRequestType(final HttpServletRequest request) {
	CORSRequestType requestType = CORSRequestType.INVALID_CORS;
	if (request == null) {
		throw new IllegalArgumentException(
				"HttpServletRequest object is null");
	}
	String originHeader = request.getHeader(REQUEST_HEADER_ORIGIN);
	// Section 6.1.1 and Section 6.2.1
	if (originHeader != null) {
		if (originHeader.isEmpty()) {
			requestType = CORSRequestType.INVALID_CORS;
		} else if (!isValidOrigin(originHeader)) {
			requestType = CORSRequestType.INVALID_CORS;
		} else {
			String method = StringUtils.trimToEmpty(request.getMethod());
			if (HTTP_METHODS.contains(method)) {
				if ("OPTIONS".equals(method)) {
					String accessControlRequestMethodHeader
							= request.getHeader(REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
					if (StringUtils.isNotBlank(accessControlRequestMethodHeader)) {
						requestType = CORSRequestType.PRE_FLIGHT;
					} else if (StringUtils.isWhitespace(accessControlRequestMethodHeader)) {
						requestType = CORSRequestType.INVALID_CORS;
					} else {
						requestType = CORSRequestType.ACTUAL;
					}
				} else if ("GET".equals(method) || "HEAD".equals(method)) {
					requestType = CORSRequestType.SIMPLE;
				} else if ("POST".equals(method)) {
					String contentType = request.getContentType();
					if (contentType != null) {
						contentType = contentType.toLowerCase().trim();
						if (SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES
								.contains(contentType)) {
							requestType = CORSRequestType.SIMPLE;
						} else {
							requestType = CORSRequestType.ACTUAL;
						}
					}
				} else if (COMPLEX_HTTP_METHODS.contains(method)) {
					requestType = CORSRequestType.ACTUAL;
				}
			}
		}
	} else {
		requestType = CORSRequestType.NOT_CORS;
	}

	return requestType;
}
 
Example 19
Source File: UpdateServlet.java    From database with GNU General Public License v2.0 3 votes vote down vote up
@Override
protected void doPut(final HttpServletRequest req,
        final HttpServletResponse resp) throws IOException {

    if (!isWritable(getServletContext(), req, resp)) {
        // Service must be writable.
        return;
    }

    final String queryStr = req.getParameter(QueryServlet.ATTR_QUERY);

    final String contentType = req.getContentType();

    if (contentType == null) {

        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);

    }

    if (queryStr == null) {

        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);

    }

    doUpdateWithQuery(req, resp);

}
 
Example 20
Source File: RESTServlet.java    From database with GNU General Public License v2.0 3 votes vote down vote up
static boolean hasMimeType(final HttpServletRequest req,
           final String mimeType) {

       final String contentType = req.getContentType();
       
       return contentType != null
               && mimeType.equals(new MiniMime(contentType).getMimeType());
       
}