List of usage examples for javax.servlet.http HttpServletRequest getContentLength
public int getContentLength();
From source file:com.meikai.common.web.servlet.FCKeditorUploadServlet.java
/** * Manage the Upload requests.<br> * * The servlet accepts commands sent in the following format:<br> * simpleUploader?Type=ResourceType<br><br> * It store the file (renaming it in case a file with the same name exists) and then return an HTML file * with a javascript command in it.//from w ww.j a va 2s . co m * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (debug) System.out.println("--- BEGIN DOPOST ---"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); // edit check user uploader file size int contextLength = request.getContentLength(); int fileSize = (int) (((float) contextLength) / ((float) (1024))); String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (fileSize < 30240) { String typeStr = request.getParameter("Type"); String currentPath = ""; String currentDirPath = getServletContext().getRealPath(currentPath); currentPath = request.getContextPath() + currentPath; // edit end ++++++++++++++++ if (debug) System.out.println(currentDirPath); if (enabled) { DiskFileUpload upload = new DiskFileUpload(); try { List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = FckeditorUtil.getNameWithoutExtension(fileName); String ext = FckeditorUtil.getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); fileUrl = currentPath + "/" + fileName; if (FckeditorUtil.extIsAllowed(allowedExtensions, deniedExtensions, typeStr, ext)) { int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; fileUrl = currentPath + "/" + newName; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); // ? if (logger.isInfoEnabled()) { logger.info("..."); } } else { retVal = "202"; errorMessage = ""; if (debug) System.out.println("Invalid file type: " + ext); } } catch (Exception ex) { if (debug) ex.printStackTrace(); retVal = "203"; } } else { retVal = "1"; errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file"; } } else { retVal = "204"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:com.adaptris.core.http.jetty.MessageConsumer.java
@Override public AdaptrisMessage createMessage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { AdaptrisMessage msg = null;/*from www .ja va2 s . co m*/ OutputStream out = null; try { logHeaders(request); if (getEncoder() != null) { msg = getEncoder().readMessage(request); } else { msg = defaultIfNull(getMessageFactory()).newMessage(); out = msg.getOutputStream(); if (request.getContentLength() == -1) { IOUtils.copy(request.getInputStream(), out); } else { StreamUtil.copyStream(request.getInputStream(), out, request.getContentLength()); } out.flush(); } msg.setContentEncoding(request.getCharacterEncoding()); addParamMetadata(msg, request); addHeaderMetadata(msg, request); } catch (CoreException e) { IOException ioe = new IOException(e.getMessage()); ioe.initCause(e); throw ioe; } finally { IOUtils.closeQuietly(out); } return msg; }
From source file:org.apache.struts.extras.SecureJakartaStreamMultiPartRequest.java
/** * Get the request content length.// ww w . jav a 2s.c o m * * @param request * @return */ private long getRequestSize(HttpServletRequest request) { long requestSize = 0; if (request != null) requestSize = request.getContentLength(); return requestSize; }
From source file:com.wadpam.guja.oauth2.web.Oauth2ClientAuthenticationFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { LOGGER.debug("Oauth2 client authentication"); HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; // Either the Authorize header or json body is used to provide the client credentials String authHeader = request.getHeader(OAuth2Filter.HEADER_AUTHORIZATION); ClientCredentials credentials = null; if (request.getContentLength() > 0 && (request.getContentType().startsWith(MediaType.APPLICATION_JSON) || request.getContentType().startsWith(MediaType.APPLICATION_FORM_URLENCODED))) { HttpBodyRequestWrapper wrappedRequest = new HttpBodyRequestWrapper(request); if (request.getContentType().startsWith(MediaType.APPLICATION_JSON)) { // Parse JSON body credentials = objectMapper.readValue(wrappedRequest.getBody(), ClientCredentials.class); } else if (request.getContentType().startsWith(MediaType.APPLICATION_FORM_URLENCODED)) { // Parse the form encoded request body. Remember to URL decode the parameters Map<String, String> formParams = Splitter.on("&").trimResults().withKeyValueSeparator("=") .split(wrappedRequest.getBody()); formParams = Maps.transformValues(formParams, new Function<String, String>() { @Override//from w w w . j av a 2 s. c om public String apply(String value) { try { return URLDecoder.decode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { LOGGER.error("Not possible to URL decode {}", e); return value; } } }); LOGGER.debug("URL decoded form body {}", formParams); credentials = new ClientCredentials(); credentials.setClient_id(formParams.get("client_id")); credentials.setClient_secret((formParams.get("client_secret"))); } // Must wrap the request request = wrappedRequest; } // Check for duplicate authentication methods - invalid request if (null != authHeader && null != credentials && null != credentials.getClient_id() && null != credentials.getClient_secret()) { LOGGER.info("Bad request - duplicate client authentication credentials"); // Multiple authentication credentials (400, "invalid_request") errorMessage(response, HttpServletResponse.SC_BAD_REQUEST, ERROR_INVALID_REQUEST); return; } // check for header if (null != authHeader) { LOGGER.debug("{}: {}", OAuth2Filter.HEADER_AUTHORIZATION, authHeader); int beginIndex = authHeader.indexOf(PREFIX_BASIC_AUTHENTICATION); if (-1 < beginIndex) { String baString = authHeader.substring(beginIndex + PREFIX_BASIC_AUTHENTICATION.length()); String storedBaString = getBasicAuthenticationString(); LOGGER.debug("{} equals? {}", baString, storedBaString); if (!baString.equals(storedBaString)) { LOGGER.info("Unauthorized - invalid client credentials"); // Unauthorized (401, "invalid_client") response.setHeader(HEADER_WWW_AUTHENTICATE, PREFIX_BEARER); // TODO What should be returned errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT); return; } } else { // Unsupported client authentication method (401, "invalid_client") LOGGER.info("Unauthorized - client authentication method not supported"); response.setHeader(HEADER_WWW_AUTHENTICATE, PREFIX_BEARER); // TODO What should be returned errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT); return; } } else if (null != credentials) { // Check JSON LOGGER.debug(String.format("%s: %s, %s", PREFIX_BASIC_AUTHENTICATION, credentials.getClient_id(), credentials.getClient_secret())); if (null == credentials.getClient_id() && null == credentials.getClient_secret()) { // No client authentication included (401, "invalid_client") LOGGER.info("Unauthorized - no client credentials found"); errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT); return; } else if (null == credentials.getClient_id() ^ null == credentials.getClient_secret()) { LOGGER.info("Bad request - missing required parameter"); // Missing client authentication parameter (400, "invalid_request") errorMessage(response, HttpServletResponse.SC_BAD_REQUEST, ERROR_INVALID_REQUEST); return; } else if (!isCredentialsValid(credentials.getClient_id(), credentials.getClient_secret())) { LOGGER.info("Unauthorized - invalid client credentials"); // Unauthorized (401, "invalid_client") errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT); return; } } else { // No client authentication included (401, "invalid_client") LOGGER.info("Unauthorized - no client credentials found"); errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT); return; } chain.doFilter(request, response); }
From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java
@Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); HttpServletRequest request = context.getRequest(); MultiValueMap<String, String> headers = this.helper.buildZuulRequestHeaders(request); MultiValueMap<String, String> params = this.helper.buildZuulRequestQueryParams(request); String verb = getVerb(request); InputStream requestEntity = getRequestBody(request); if (request.getContentLength() < 0) { context.setChunkedRequestBody(); }// www . j a va2s . c om String uri = this.helper.buildZuulRequestURI(request); this.helper.addIgnoredHeaders(); try { CloseableHttpResponse response = forward(this.httpClient, verb, uri, request, headers, params, requestEntity); setResponse(response); } catch (Exception ex) { context.set(ERROR_STATUS_CODE, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); context.set("error.exception", ex); } return null; }
From source file:org.opendatakit.aggregate.parser.MultiPartFormData.java
/** * Construct a mult-part form data container by parsing a multi part form * request into a set of multipartformitems. The information are stored in * items and are indexed by either the field name or the file name (or both) * provided in the http submission/*w w w . java 2 s . co m*/ * * @param req * an HTTP request from a multipart form * * @throws FileUploadException * @throws IOException */ public MultiPartFormData(HttpServletRequest req) throws FileUploadException, IOException { simpleFieldNameMap = new HashMap<String, String>(); fieldNameMap = new HashMap<String, MultiPartFormItem>(); fileNameMap = new HashMap<String, MultiPartFormItem>(); fileNameWithoutExtensionNameMap = new HashMap<String, MultiPartFormItem>(); ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); int size = req.getContentLength(); if (size > 0) { upload.setFileSizeMax(size); } else { upload.setFileSizeMax(ParserConsts.FILE_SIZE_MAX); } List<MultiPartFormItem> fileNameList = new ArrayList<MultiPartFormItem>(); FileItemIterator items = upload.getItemIterator(req); while (items.hasNext()) { FileItemStream item = items.next(); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); BufferedInputStream formStream = new BufferedInputStream(item.openStream()); // TODO: determine ways to possibly improve efficiency int nextByte = formStream.read(); while (nextByte != -1) { byteStream.write(nextByte); nextByte = formStream.read(); } formStream.close(); if (item.isFormField()) { simpleFieldNameMap.put(item.getFieldName(), byteStream.toString()); } else { MultiPartFormItem data = new MultiPartFormItem(item.getFieldName(), item.getName(), item.getContentType(), byteStream); String fieldName = item.getFieldName(); if (fieldName != null) { fieldNameMap.put(fieldName, data); } String fileName = item.getName(); if (fileName != null && fileName.length() != 0) { fileNameList.add(data); } } } // Find the common prefix to the filenames being uploaded... // Deal with Windows backslash file separator... boolean first = true; String[] commonPath = null; int commonPrefix = 0; for (MultiPartFormItem e : fileNameList) { String fullFilePath = e.getFilename(); if (first) { commonPath = fullFilePath.split("[/\\\\]"); commonPrefix = commonPath.length - 1; // everything but // filename... first = false; } else { String[] path = fullFilePath.split("[/\\\\]"); int pathPrefix = path.length - 1; // everything but // filename... if (pathPrefix < commonPrefix) commonPrefix = pathPrefix; for (int i = 0; i < commonPrefix; ++i) { if (!commonPath[i].equals(path[i])) { commonPrefix = i; break; } } } } // and now go back through the attachments, adjusting the filename // and building the filename mapping. for (MultiPartFormItem e : fileNameList) { String fullFilePath = e.getFilename(); String[] filePath = fullFilePath.split("[/\\\\]"); StringBuilder b = new StringBuilder(); first = true; // start at the first entry after the common prefix... for (int i = commonPrefix; i < filePath.length; ++i) { if (!first) { b.append("/"); } first = false; b.append(filePath[i]); } // and construct the filename with common directory prefix // stripped. String fileName = b.toString(); e.setFilename(fileName); if (fileName != null) { // TODO: possible bug in ODK collect truncating file extension // may need to remove this code after ODK collect is fixed int indexOfExtension = fileName.lastIndexOf("."); if (indexOfExtension > 0) { fileNameWithoutExtensionNameMap.put(fileName.substring(0, indexOfExtension), e); } fileNameMap.put(fileName, e); } } }
From source file:com.ultrapower.eoms.common.plugin.ajaxupload.AjaxMultiPartRequest.java
/** * Creates a RequestContext needed by Jakarta Commons Upload. * //from w ww.ja v a 2 s . co 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.ejbca.ui.web.protocol.OCSPServlet.java
/** * Reads the request bytes and verifies min and max size of the request. If an error occurs it throws a MalformedRequestException. * Can get request bytes both from a HTTP GET and POST request * /*from w w w . j a va2s. c o m*/ * @param request * @param response * @return the request bytes or null if an error occured. * @throws IOException In case there is no stream to read * @throws MalformedRequestException */ private byte[] checkAndGetRequestBytes(HttpServletRequest request, HttpMethod httpMethod) throws IOException, MalformedRequestException { final byte[] ret; // Get the request data final int n = request.getContentLength(); // Expect n might be -1 for HTTP GET requests if (log.isDebugEnabled()) { log.debug(">checkAndGetRequestBytes. Received " + httpMethod.name() + " request with content length: " + n + " from " + request.getRemoteAddr()); } if (n > LimitLengthASN1Reader.MAX_REQUEST_SIZE) { String msg = intres.getLocalizedMessage("ocsp.toolarge", LimitLengthASN1Reader.MAX_REQUEST_SIZE, n); log.info(msg); throw new MalformedRequestException(msg); } // So we passed basic tests, now we can read the bytes, but still keep an eye on the size // we can not fully trust the sent content length. if (HttpMethod.POST.equals(httpMethod)) { final ServletInputStream in = request.getInputStream(); // ServletInputStream does not have to be closed, container handles this LimitLengthASN1Reader limitLengthASN1Reader = new LimitLengthASN1Reader(in, n); try { ret = limitLengthASN1Reader.readFirstASN1Object(); if (n > ret.length) { // The client is sending more data than the OCSP request. It might be slightly broken or trying to bog down the server on purpose. // In the interest of not breaking existing systems that might have slightly broken clients we just log for a warning for now. String msg = intres.getLocalizedMessage("ocsp.additionaldata", ret.length, n); log.warn(msg); } } finally { limitLengthASN1Reader.close(); } } else if (HttpMethod.GET.equals(httpMethod)) { // GET request final StringBuffer url = request.getRequestURL(); // RFC2560 A.1.1 says that request longer than 255 bytes SHOULD be sent by POST, we support GET for longer requests anyway. if (url.length() <= LimitLengthASN1Reader.MAX_REQUEST_SIZE) { final String decodedRequest; try { // We have to extract the pathInfo manually, to avoid multiple slashes being converted to a single // According to RFC 2396 2.2 chars only have to encoded if they conflict with the purpose, so // we can for example expect both '/' and "%2F" in the request. final String fullServletpath = request.getContextPath() + request.getServletPath(); final int paramIx = Math.max(url.indexOf(fullServletpath), 0) + fullServletpath.length() + 1; final String requestString = paramIx < url.length() ? url.substring(paramIx) : ""; decodedRequest = URLDecoder.decode(requestString, "UTF-8").replaceAll(" ", "+"); } catch (Exception e) { String msg = intres.getLocalizedMessage("ocsp.badurlenc"); log.info(msg); throw new MalformedRequestException(e); } if (decodedRequest != null && decodedRequest.length() > 0) { if (log.isDebugEnabled()) { // Don't log the request if it's too long, we don't want to cause denial of service by filling log files or buffers. if (decodedRequest.length() < 2048) { log.debug("decodedRequest: " + decodedRequest); } else { log.debug("decodedRequest too long to log: " + decodedRequest.length()); } } try { ret = Base64.decode(decodedRequest.getBytes()); } catch (Exception e) { String msg = intres.getLocalizedMessage("ocsp.badurlenc"); log.info(msg); throw new MalformedRequestException(e); } } else { String msg = intres.getLocalizedMessage("ocsp.missingreq"); log.info(msg); throw new MalformedRequestException(msg); } } else { String msg = intres.getLocalizedMessage("ocsp.toolarge", LimitLengthASN1Reader.MAX_REQUEST_SIZE, url.length()); log.info(msg); throw new MalformedRequestException(msg); } } else { // Strange, an unknown method String msg = intres.getLocalizedMessage("ocsp.unknownmethod", request.getMethod()); log.info(msg); throw new MalformedRequestException(msg); } // Make a final check that we actually received something if (ret == null || ret.length == 0) { String msg = intres.getLocalizedMessage("ocsp.emptyreq", request.getRemoteAddr()); log.info(msg); throw new MalformedRequestException(msg); } return ret; }
From source file:org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter.java
@Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); HttpServletRequest request = context.getRequest(); MultiValueMap<String, String> headers = this.helper.buildZuulRequestHeaders(request); MultiValueMap<String, String> params = this.helper.buildZuulRequestQueryParams(request); String verb = getVerb(request); InputStream requestEntity = getRequestBody(request); if (request.getContentLength() < 0) { context.setChunkedRequestBody(); }/*from w w w . ja v a 2 s . c om*/ String uri = this.helper.buildZuulRequestURI(request); this.helper.addIgnoredHeaders(); try { HttpResponse response = forward(this.httpClient, verb, uri, request, headers, params, requestEntity); setResponse(response); } catch (Exception ex) { throw new ZuulRuntimeException(ex); } return null; }
From source file:com.couchbase.capi.servlet.CAPIServlet.java
protected void handleCommitForCheckpoint(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // read the request InputStream is = req.getInputStream(); int requestLength = req.getContentLength(); byte[] buffer = new byte[requestLength]; IOUtils.readFully(is, buffer, 0, requestLength); @SuppressWarnings("unchecked") Map<String, Object> parsedValue = (Map<String, Object>) mapper.readValue(buffer, Map.class); logger.trace("commit for checkpoint parsed value is " + parsedValue); int vbucket = (Integer) parsedValue.get("vb"); String bucket = (String) parsedValue.get("bucket"); String bucketUUID = (String) parsedValue.get("bucketUUID"); String vbopaque = (String) parsedValue.get("vbopaque"); String vbucketUUID = capiBehavior.getVBucketUUID("default", bucket, vbucket); Map<String, Object> responseMap = new HashMap<String, Object>(); responseMap.put("vbopaque", vbucketUUID); if ((vbopaque != null) && (!vbopaque.equals(vbucketUUID))) { logger.debug("returning 400"); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else {/*from w w w.j a v a 2s . c om*/ // add the commit opaque responseMap.put("commitopaque", vbucketUUID); } OutputStream os = resp.getOutputStream(); resp.setContentType("application/json"); mapper.writeValue(os, responseMap); }