List of usage examples for javax.servlet.http HttpServletRequest getContentType
public String getContentType();
null
if the type is not known. From source file:org.brutusin.rpc.http.RpcServlet.java
/** * * @param request//from w ww . ja v a 2 s . c om * @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"); }
From source file:de.adorsys.oauth.authdispatcher.FixedServletUtils.java
/** * Creates a new HTTP request from the specified HTTP servlet request. * * @param sr The servlet request. Must not be * {@code null}.// ww w . j av a2 s.c om * @param maxEntityLength The maximum entity length to accept, -1 for * no limit. * * @return The HTTP request. * * @throws IllegalArgumentException The the servlet request method is * not GET, POST, PUT or DELETE or the * content type header value couldn't * be parsed. * @throws IOException For a POST or PUT body that * couldn't be read due to an I/O * exception. */ public static HTTPRequest createHTTPRequest(final HttpServletRequest sr, final long maxEntityLength) throws IOException { HTTPRequest.Method method = HTTPRequest.Method.valueOf(sr.getMethod().toUpperCase()); String urlString = reconstructRequestURLString(sr); URL url; try { url = new URL(urlString); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid request URL: " + e.getMessage() + ": " + urlString, e); } HTTPRequest request = new HTTPRequest(method, url); try { request.setContentType(sr.getContentType()); } catch (ParseException e) { throw new IllegalArgumentException("Invalid Content-Type header value: " + e.getMessage(), e); } Enumeration<String> headerNames = sr.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); request.setHeader(headerName, sr.getHeader(headerName)); } if (method.equals(HTTPRequest.Method.GET) || method.equals(HTTPRequest.Method.DELETE)) { request.setQuery(sr.getQueryString()); } else if (method.equals(HTTPRequest.Method.POST) || method.equals(HTTPRequest.Method.PUT)) { if (maxEntityLength > 0 && sr.getContentLength() > maxEntityLength) { throw new IOException("Request entity body is too large, limit is " + maxEntityLength + " chars"); } Map<String, String[]> parameterMap = sr.getParameterMap(); StringBuilder builder = new StringBuilder(); if (!parameterMap.isEmpty()) { for (Entry<String, String[]> entry : parameterMap.entrySet()) { String key = entry.getKey(); String[] value = entry.getValue(); if (value.length > 0 && value[0] != null) { String encoded = URLEncoder.encode(value[0], "UTF-8"); builder = builder.append(key).append('=').append(encoded).append('&'); } } String queryString = StringUtils.substringBeforeLast(builder.toString(), "&"); request.setQuery(queryString); } else { // read body StringBuilder body = new StringBuilder(256); BufferedReader reader = sr.getReader(); char[] cbuf = new char[256]; int readChars; while ((readChars = reader.read(cbuf)) != -1) { body.append(cbuf, 0, readChars); if (maxEntityLength > 0 && body.length() > maxEntityLength) { throw new IOException( "Request entity body is too large, limit is " + maxEntityLength + " chars"); } } reader.close(); request.setQuery(body.toString()); } } return request; }
From source file:com.groupon.odo.HttpUtilities.java
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same standard POST data * as was sent in the given {@link HttpServletRequest} * * @param methodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a * standard POST request * @param httpServletRequest The {@link HttpServletRequest} that contains the POST data to * be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} * @param history The {@link com.groupon.odo.proxylib.models.History} log for this request *///from w w w. ja va 2 s . c o m @SuppressWarnings("unchecked") public static void handleStandardPost(EntityEnclosingMethod methodProxyRequest, HttpServletRequest httpServletRequest, History history) throws Exception { String deserialisedMessages = ""; byte[] requestByteArray = null; // Create a new StringBuffer with the data to be passed StringBuilder requestBody = new StringBuilder(); InputStream body = httpServletRequest.getInputStream(); java.util.Scanner s = new java.util.Scanner(body).useDelimiter("\\A"); if (httpServletRequest.getContentType() != null && httpServletRequest.getContentType().contains(STRING_CONTENT_TYPE_FORM_URLENCODED)) { // Get the client POST data as a Map if content type is: application/x-www-form-urlencoded // We do this manually since some data is not properly parseable by the servlet request Map<String, String[]> mapPostParameters = HttpUtilities.mapUrlEncodedParameters(httpServletRequest); // Iterate the parameter names for (String stringParameterName : mapPostParameters.keySet()) { // Iterate the values for each parameter name String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName); for (String stringParameterValue : stringArrayParameterValues) { // Create a NameValuePair and store in list // add an & if there is already data if (requestBody.length() > 0) { requestBody.append("&"); } requestBody.append(stringParameterName); // not everything has a value so lets check if (stringParameterValue.length() > 0) { requestBody.append("="); requestBody.append(stringParameterValue); } } } } else if (httpServletRequest.getContentType() != null && httpServletRequest.getContentType().contains(STRING_CONTENT_TYPE_MESSAGEPACK)) { /** * Convert input stream to bytes for it to be read by the deserializer * Unpack and iterate the list to see the contents */ MessagePack msgpack = new MessagePack(); requestByteArray = IOUtils.toByteArray(body); ByteArrayInputStream byteArrayIS = new ByteArrayInputStream(requestByteArray); Unpacker unpacker = msgpack.createUnpacker(byteArrayIS); for (Value message : unpacker) { deserialisedMessages += message; deserialisedMessages += "\n"; } } else { // just set the request body to the POST body if (s.hasNext()) { requestBody.append(s.next()); } } // Set the proxy request data StringRequestEntity stringEntity = new StringRequestEntity(requestBody.toString(), null, null); // set post body in history object history.setRequestPostData(requestBody.toString()); // set post body in proxy request object methodProxyRequest.setRequestEntity(stringEntity); /** * Set the history to have decoded messagepack. Pass the byte data back to request */ if (httpServletRequest.getContentType() != null && httpServletRequest.getContentType().contains(STRING_CONTENT_TYPE_MESSAGEPACK)) { history.setRequestPostData(deserialisedMessages); ByteArrayRequestEntity byteRequestEntity = new ByteArrayRequestEntity(requestByteArray); methodProxyRequest.setRequestEntity(byteRequestEntity); } }
From source file:de.adorsys.oauth.server.FixedServletUtils.java
/** * Creates a new HTTP request from the specified HTTP servlet request. * * @param servletRequest The servlet request. Must not be * {@code null}./*from w ww.ja v a2 s . c o m*/ * @param maxEntityLength The maximum entity length to accept, -1 for * no limit. * * @return The HTTP request. * * @throws IllegalArgumentException The the servlet request method is * not GET, POST, PUT or DELETE or the * content type header value couldn't * be parsed. * @throws IOException For a POST or PUT body that * couldn't be read due to an I/O * exception. */ public static HTTPRequest createHTTPRequest(final HttpServletRequest servletRequest, final long maxEntityLength) throws IOException { HTTPRequest.Method method = HTTPRequest.Method.valueOf(servletRequest.getMethod().toUpperCase()); String urlString = reconstructRequestURLString(servletRequest); URL url; try { url = new URL(urlString); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid request URL: " + e.getMessage() + ": " + urlString, e); } HTTPRequest request = new HTTPRequest(method, url); try { request.setContentType(servletRequest.getContentType()); } catch (ParseException e) { throw new IllegalArgumentException("Invalid Content-Type header value: " + e.getMessage(), e); } Enumeration<String> headerNames = servletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); request.setHeader(headerName, servletRequest.getHeader(headerName)); } if (method.equals(HTTPRequest.Method.GET) || method.equals(HTTPRequest.Method.DELETE)) { request.setQuery(servletRequest.getQueryString()); } else if (method.equals(HTTPRequest.Method.POST) || method.equals(HTTPRequest.Method.PUT)) { if (maxEntityLength > 0 && servletRequest.getContentLength() > maxEntityLength) { throw new IOException("Request entity body is too large, limit is " + maxEntityLength + " chars"); } Map<String, String[]> parameterMap = servletRequest.getParameterMap(); StringBuilder builder = new StringBuilder(); if (!parameterMap.isEmpty()) { for (Entry<String, String[]> entry : parameterMap.entrySet()) { String key = entry.getKey(); String[] value = entry.getValue(); if (value.length > 0 && value[0] != null) { String encoded = URLEncoder.encode(value[0], "UTF-8"); builder = builder.append(key).append('=').append(encoded).append('&'); } } String queryString = StringUtils.substringBeforeLast(builder.toString(), "&"); request.setQuery(queryString); } else { // read body StringBuilder body = new StringBuilder(256); BufferedReader reader = servletRequest.getReader(); reader.reset(); char[] cbuf = new char[256]; int readChars; while ((readChars = reader.read(cbuf)) != -1) { body.append(cbuf, 0, readChars); if (maxEntityLength > 0 && body.length() > maxEntityLength) { throw new IOException( "Request entity body is too large, limit is " + maxEntityLength + " chars"); } } reader.reset(); // reader.close(); request.setQuery(body.toString()); } } return request; }
From source file:org.cruxframework.crux.core.server.rest.spi.HttpUtil.java
public static HttpHeaders extractHttpHeaders(HttpServletRequest request) { HttpHeaders headers = new HttpHeaders(); MultivaluedMap<String, String> requestHeaders = extractRequestHeaders(request); headers.setRequestHeaders(requestHeaders); List<MediaType> acceptableMediaTypes = extractAccepts(requestHeaders); List<String> acceptableLanguages = extractLanguages(requestHeaders); headers.setAcceptableMediaTypes(acceptableMediaTypes); headers.setAcceptableLanguages(acceptableLanguages); headers.setLanguage(requestHeaders.getFirst(HttpHeaderNames.CONTENT_LANGUAGE)); String contentType = request.getContentType(); if (contentType != null) { headers.setMediaType(MediaType.valueOf(contentType)); }/* w w w . ja v a 2 s .c o m*/ Map<String, Cookie> cookies = extractCookies(request); headers.setCookies(cookies); return headers; }
From source file:com.news.util.UploadFileUtil.java
public static String upload(HttpServletRequest request, String paramName, String fileName) { String result = ""; File file;//from w ww . j a v a 2 s.c o m int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; String filePath = ""; ///opt/apache-tomcat-7.0.59/webapps/noithat //filePath = getServletContext().getRealPath("") + File.separator + "test-upload" + File.separator; filePath = File.separator + File.separator + "opt" + File.separator + File.separator; filePath += "apache-tomcat-7.0.59" + File.separator + File.separator + "webapps"; filePath += File.separator + File.separator + "noithat"; filePath += File.separator + File.separator + "upload" + File.separator + File.separator; filePath += "images" + File.separator; //filePath = "E:" + File.separator; // Verify the content type String contentType = request.getContentType(); System.out.println("contentType=" + contentType); if (contentType != null && (contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("c:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); System.out.println("fileItems.size()=" + fileItems.size()); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField() && fi.getFieldName().equals(paramName)) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); int dotPos = fi.getName().lastIndexOf("."); if (dotPos < 0) { fileName += ".jpg"; } else { fileName += fi.getName().substring(dotPos); } boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); System.out.println("Uploaded Filename: " + filePath + fileName + "<br>"); result = fileName; } } } catch (Exception ex) { ex.printStackTrace(); } } return result; }
From source file:org.imsglobal.lti2.LTI2Util.java
@SuppressWarnings({ "unchecked", "unused" }) public static Object getSettings(HttpServletRequest request, String scope, JSONObject link_settings, JSONObject binding_settings, JSONObject proxy_settings, String link_url, String binding_url, String proxy_url) {//from w w w . ja v a2 s .c om // Check to see if we are doing the bubble String bubbleStr = request.getParameter("bubble"); String acceptHdr = request.getHeader("Accept"); String contentHdr = request.getContentType(); if (bubbleStr != null && bubbleStr.equals("all") && acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) < 0) { return "Simple format does not allow bubble=all"; } if (SCOPE_LtiLink.equals(scope) || SCOPE_ToolProxyBinding.equals(scope) || SCOPE_ToolProxy.equals(scope)) { // All good } else { return "Bad Setttings Scope=" + scope; } boolean bubble = bubbleStr != null && "GET".equals(request.getMethod()); boolean distinct = bubbleStr != null && "distinct".equals(bubbleStr); boolean bubbleAll = bubbleStr != null && "all".equals(bubbleStr); // Check our output format boolean acceptComplex = acceptHdr == null || acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) >= 0; if (distinct && link_settings != null && scope.equals(SCOPE_LtiLink)) { Iterator<String> i = link_settings.keySet().iterator(); while (i.hasNext()) { String key = (String) i.next(); if (binding_settings != null) binding_settings.remove(key); if (proxy_settings != null) proxy_settings.remove(key); } } if (distinct && binding_settings != null && scope.equals(SCOPE_ToolProxyBinding)) { Iterator<String> i = binding_settings.keySet().iterator(); while (i.hasNext()) { String key = (String) i.next(); if (proxy_settings != null) proxy_settings.remove(key); } } // Lets get this party started... JSONObject jsonResponse = null; if ((distinct || bubbleAll) && acceptComplex) { jsonResponse = new JSONObject(); jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.TOOLSETTINGS_CONTEXT); JSONArray graph = new JSONArray(); boolean started = false; if (link_settings != null && SCOPE_LtiLink.equals(scope)) { JSONObject cjson = new JSONObject(); cjson.put(LTI2Constants.JSONLD_ID, link_url); cjson.put(LTI2Constants.TYPE, SCOPE_LtiLink); cjson.put(LTI2Constants.CUSTOM, link_settings); graph.add(cjson); started = true; } if (binding_settings != null && (started || SCOPE_ToolProxyBinding.equals(scope))) { JSONObject cjson = new JSONObject(); cjson.put(LTI2Constants.JSONLD_ID, binding_url); cjson.put(LTI2Constants.TYPE, SCOPE_ToolProxyBinding); cjson.put(LTI2Constants.CUSTOM, binding_settings); graph.add(cjson); started = true; } if (proxy_settings != null && (started || SCOPE_ToolProxy.equals(scope))) { JSONObject cjson = new JSONObject(); cjson.put(LTI2Constants.JSONLD_ID, proxy_url); cjson.put(LTI2Constants.TYPE, SCOPE_ToolProxy); cjson.put(LTI2Constants.CUSTOM, proxy_settings); graph.add(cjson); } jsonResponse.put(LTI2Constants.GRAPH, graph); } else if (distinct) { // Simple format output jsonResponse = proxy_settings; if (SCOPE_LtiLink.equals(scope)) { jsonResponse.putAll(binding_settings); jsonResponse.putAll(link_settings); } else if (SCOPE_ToolProxyBinding.equals(scope)) { jsonResponse.putAll(binding_settings); } } else { // bubble not specified jsonResponse = new JSONObject(); jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.TOOLSETTINGS_CONTEXT); JSONObject theSettings = null; String endpoint = null; if (SCOPE_LtiLink.equals(scope)) { endpoint = link_url; theSettings = link_settings; } else if (SCOPE_ToolProxyBinding.equals(scope)) { endpoint = binding_url; theSettings = binding_settings; } if (SCOPE_ToolProxy.equals(scope)) { endpoint = proxy_url; theSettings = proxy_settings; } if (acceptComplex) { JSONArray graph = new JSONArray(); JSONObject cjson = new JSONObject(); cjson.put(LTI2Constants.JSONLD_ID, endpoint); cjson.put(LTI2Constants.TYPE, scope); cjson.put(LTI2Constants.CUSTOM, theSettings); graph.add(cjson); jsonResponse.put(LTI2Constants.GRAPH, graph); } else { jsonResponse = theSettings; } } return jsonResponse; }
From source file:org.wso2.carbon.bpmn.rest.common.utils.Utils.java
public static byte[] processMultiPartFile(HttpServletRequest httpServletRequest, String contentMessage) throws IOException { //Content-Type: multipart/form-data; boundary="----=_Part_2_1843361794.1448198281814" String encoding = httpServletRequest.getCharacterEncoding(); if (encoding == null) { encoding = DEFAULT_ENCODING;/*from ww w. ja va 2 s . c o m*/ httpServletRequest.setCharacterEncoding(encoding); } byte[] requestBodyArray = IOUtils.toByteArray(httpServletRequest.getInputStream()); if (requestBodyArray == null || requestBodyArray.length == 0) { throw new ActivitiIllegalArgumentException("No :" + contentMessage + "was found in request body."); } String requestContentType = httpServletRequest.getContentType(); StringBuilder contentTypeString = new StringBuilder(); contentTypeString.append("Content-Type: " + requestContentType); contentTypeString.append("\r"); contentTypeString.append(System.getProperty("line.separator")); byte[] contentTypeArray = contentTypeString.toString().getBytes(encoding); byte[] aggregatedRequestBodyByteArray = new byte[contentTypeArray.length + requestBodyArray.length]; System.arraycopy(contentTypeArray, 0, aggregatedRequestBodyByteArray, 0, contentTypeArray.length); System.arraycopy(requestBodyArray, 0, aggregatedRequestBodyByteArray, contentTypeArray.length, requestBodyArray.length); boolean debugEnabled = log.isDebugEnabled(); int index = requestContentType.indexOf("boundary"); if (index <= 0) { throw new ActivitiIllegalArgumentException("boundary tag not found in the request header."); } String boundaryString = requestContentType.substring(index + "boundary=".length()); boundaryString = boundaryString.replaceAll("\"", "").trim(); if (debugEnabled) { log.debug("----------Content-Type:-----------\n" + httpServletRequest.getContentType()); log.debug("\n\n\n\n"); log.debug("\n\n\n\n----------Aggregated Request Body:-----------\n" + new String(aggregatedRequestBodyByteArray)); log.debug("boundaryString:" + boundaryString); } byte[] boundary = boundaryString.getBytes(encoding); ByteArrayInputStream content = new ByteArrayInputStream(aggregatedRequestBodyByteArray); MultipartStream multipartStream = new MultipartStream(content, boundary, aggregatedRequestBodyByteArray.length, null); boolean nextPart = multipartStream.skipPreamble(); if (debugEnabled) { log.debug(nextPart); } ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] byteArray = null; // Get first file in the map, ignore possible other files while (nextPart) { // if (debugEnabled) { String header = multipartStream.readHeaders(); printHeaders(header); } multipartStream.readBodyData(byteArrayOutputStream); byteArray = byteArrayOutputStream.toByteArray(); nextPart = multipartStream.readBoundary(); } return byteArray; }
From source file:be.solidx.hot.test.nio.http.GetServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println(req.getContentType()); resp.getWriter().write(req.getParameter("name") + " " + req.getParameter("age")); }
From source file:com.du.order.dist.log.LoggingFilter.java
private boolean isMultipart(final HttpServletRequest request) { return request.getContentType() != null && request.getContentType().startsWith("multipart/form-data"); }