List of usage examples for javax.servlet.http HttpServletRequest getContentLength
public int getContentLength();
From source file:com.couchbase.capi.servlet.CAPIServlet.java
protected void handlePreReplicate(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("pre replicate 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 commitopaque = (String) parsedValue.get("commitopaque"); String vbucketUUID = capiBehavior.getVBucketUUID("default", bucket, vbucket); if ((vbopaque != null) && (!vbopaque.equals(vbucketUUID))) { logger.debug("returning 400"); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); }//from ww w.j av a 2s . c o m if ((commitopaque != null) && (!commitopaque.equals(vbucketUUID))) { logger.debug("returning 400"); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); } OutputStream os = resp.getOutputStream(); resp.setContentType("application/json"); Map<String, Object> responseMap = new HashMap<String, Object>(); responseMap.put("vbopaque", vbucketUUID); mapper.writeValue(os, responseMap); }
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 www . jav a2 s . c o 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:com.aspectran.web.activity.request.multipart.MultipartFormDataParser.java
/** * Creates a RequestContext needed by Jakarta Commons Upload. * /* w w w . j a v a 2 s .c o m*/ * @param req the HTTP request. * @return a new request context. */ private RequestContext createRequestContext(final HttpServletRequest req) { return new RequestContext() { @Override public String getCharacterEncoding() { return req.getCharacterEncoding(); } @Override public String getContentType() { return req.getContentType(); } @Override @Deprecated public int getContentLength() { return req.getContentLength(); } @Override public InputStream getInputStream() throws IOException { return req.getInputStream(); } }; }
From source file:com.reachcall.pretty.http.ProxyServlet.java
@Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Match match = (Match) req.getAttribute("match"); HttpPut method = new HttpPut(match.toURL()); copyHeaders(req, method);/* w w w . j a v a2 s.c o m*/ method.setEntity(new InputStreamEntity(req.getInputStream(), req.getContentLength())); this.execute(match, method, req, resp); }
From source file:org.wso2.carbon.attachment.mgt.ui.fileupload.AttachmentUploadServlet.java
/** * Get the inputstream from the request and generate a file from t at the tmp directory. *///from w ww. j a v a2 s . c o m private File generateTemporaryFile(HttpServletRequest request) throws ServletException, IOException { log.warn( "This code can be improved if reviewed thoroughly. Here we get the file from input stream and create" + " a temp file at \"tmp\" directory. May be we can avoid this file creation."); String contentType = request.getContentType(); if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) { DataInputStream inputStream = new DataInputStream(request.getInputStream()); //we are taking the length of Content type data int formDataLength = request.getContentLength(); byte dataBytes[] = new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0; //this loop converting the uploaded file into byte code while (totalBytesRead < formDataLength) { byteRead = inputStream.read(dataBytes, totalBytesRead, formDataLength); totalBytesRead += byteRead; } String file = new String(dataBytes); //for saving the file name String saveFile = file.substring(file.indexOf("filename=\"") + 10); saveFile = saveFile.substring(0, saveFile.indexOf("\n")); saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\"")); int lastIndex = contentType.lastIndexOf("="); String boundary = contentType.substring(lastIndex + 1, contentType.length()); int pos; //extracting the index of file pos = file.indexOf("filename=\""); pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; int boundaryLocation = file.indexOf(boundary, pos) - 4; int startPos = ((file.substring(0, pos)).getBytes()).length; int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length; //TODO log.warn("Hard-coded directory path:" + "\"tmp/\""); File tmpFile = new File("tmp" + File.separator + saveFile); FileOutputStream fileOut = new FileOutputStream(tmpFile); fileOut.write(dataBytes, startPos, (endPos - startPos)); fileOut.flush(); IOUtils.closeQuietly(fileOut); IOUtils.closeQuietly(inputStream); return tmpFile; } else { throw new ServletException("Content type of the request is not multipart/form-data"); } }
From source file:org.primeframework.mvc.parameter.RequestBodyWorkflowTest.java
@Test public void parse() throws IOException, ServletException { HttpServletRequest request = createStrictMock(HttpServletRequest.class); expect(request.getParameterMap()).andReturn(new HashMap<>()); expect(request.getContentType()).andReturn("application/x-www-form-urlencoded"); String body = "param1=value1¶m2=value2¶m+space+key=param+space+value¶m%2Bencoded%2Bkey=param%2Bencoded%2Bvalue"; expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes())); expect(request.getContentLength()).andReturn(body.getBytes().length); expect(request.getCharacterEncoding()).andReturn("UTF-8"); replay(request);/*from w ww. j a va2s .c om*/ WorkflowChain chain = createStrictMock(WorkflowChain.class); chain.continueWorkflow(); replay(chain); HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request); RequestBodyWorkflow workflow = new RequestBodyWorkflow(wrapper); workflow.perform(chain); @SuppressWarnings("unchecked") Map<String, String[]> actual = wrapper.getParameterMap(); Map<String, String[]> expected = MapBuilder.<String, String[]>map().put("param1", new String[] { "value1" }) .put("param2", new String[] { "value2" }) .put("param space key", new String[] { "param space value" }) .put("param+encoded+key", new String[] { "param+encoded+value" }).done(); assertParameterMapsEquals(actual, expected); verify(request, chain); }
From source file:com.jaspersoft.jasperserver.rest.utils.Utils.java
/** * Extract the attachments from the request and put the in the list of * input attachments of the service./*ww w . j ava 2s . c o m*/ * * The method returns the currenst HttpServletRequest if the message is not * multipart, otherwise it returns a MultipartHttpServletRequest * * * @param service * @param hRequest */ public HttpServletRequest extractAttachments(LegacyRunReportService service, HttpServletRequest hRequest) { //Check whether we're dealing with a multipart request MultipartResolver resolver = new CommonsMultipartResolver(); // handles the PUT multipart requests if (isMultipartContent(hRequest) && hRequest.getContentLength() != -1) { MultipartHttpServletRequest mreq = resolver.resolveMultipart(hRequest); if (mreq != null && mreq.getFileMap().size() != 0) { Iterator iterator = mreq.getFileNames(); String fieldName = null; while (iterator.hasNext()) { fieldName = (String) iterator.next(); MultipartFile file = mreq.getFile(fieldName); if (file != null) { DataSource ds = new MultipartFileDataSource(file); service.getInputAttachments().put(fieldName, ds); } } if (log.isDebugEnabled()) { log.debug(service.getInputAttachments().size() + " attachments were extracted from the PUT"); } return mreq; } // handles the POST multipart requests else { if (hRequest instanceof DefaultMultipartHttpServletRequest) { DefaultMultipartHttpServletRequest dmServletRequest = (DefaultMultipartHttpServletRequest) hRequest; Iterator iterator = ((DefaultMultipartHttpServletRequest) hRequest).getFileNames(); String fieldName = null; while (iterator.hasNext()) { fieldName = (String) iterator.next(); MultipartFile file = dmServletRequest.getFile(fieldName); if (file != null) { DataSource ds = new MultipartFileDataSource(file); service.getInputAttachments().put(fieldName, ds); } } } } } if (log.isDebugEnabled()) { log.debug(service.getInputAttachments().size() + " attachments were extracted from the POST"); } return hRequest; }
From source file:com.nominanuda.web.http.ServletHelper.java
public HttpRequest copyRequest(HttpServletRequest servletRequest, boolean stripContextPath) throws IOException { final InputStream is = getServletRequestBody(servletRequest); String method = servletRequest.getMethod(); String uri = getRequestLineURI(servletRequest, stripContextPath); String ct = servletRequest.getContentType(); @SuppressWarnings("unused") String charenc = getCharacterEncoding(servletRequest); String cenc = getContentEncoding(servletRequest); long contentLength = servletRequest.getContentLength(); HttpRequest req;/*from ww w. j ava2 s . com*/ if (is == null) { req = new BasicHttpRequest(method, uri); } else { req = new BasicHttpEntityEnclosingRequest(method, uri); HttpEntity entity = buildEntity(servletRequest, is, contentLength, ct, cenc); if (entity != null) { ((BasicHttpEntityEnclosingRequest) req).setEntity(entity); } } Enumeration<?> names = servletRequest.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); Enumeration<?> vals = servletRequest.getHeaders(name); while (vals.hasMoreElements()) { String value = (String) vals.nextElement(); req.addHeader(name, value); } } return req; }
From source file:org.primeframework.mvc.parameter.RequestBodyWorkflowTest.java
@Test public void singleFiles() throws IOException, ServletException { String body = FileUtils.readFileToString( new File("src/test/java/org/primeframework/mvc/servlet/http-test-body-single-file.txt")); HttpServletRequest request = EasyMock.createStrictMock(HttpServletRequest.class); EasyMock.expect(request.getParameterMap()).andReturn(new HashMap<>()); EasyMock.expect(request.getContentType()).andReturn("multipart/form-data, boundary=AaB03x").times(2); EasyMock.expect(request.getInputStream()).andReturn(new MockServletInputStream(body.getBytes())); EasyMock.expect(request.getCharacterEncoding()).andReturn("UTF-8"); EasyMock.expect(request.getContentLength()).andReturn(body.length()); final Capture<Map<String, List<FileInfo>>> capture = new Capture<>(); request.setAttribute(eq(RequestKeys.FILE_ATTRIBUTE), capture(capture)); EasyMock.replay(request);/* ww w . j a v a 2 s . com*/ final AtomicBoolean run = new AtomicBoolean(false); MockWorkflowChain chain = new MockWorkflowChain(() -> { Map<String, List<FileInfo>> files = capture.getValue(); assertEquals(files.size(), 1); try { assertEquals(FileUtils.readFileToString(files.get("userfile").get(0).file), "test"); } catch (IOException e) { throw new RuntimeException(e); } run.set(true); }); HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request); RequestBodyWorkflow workflow = new RequestBodyWorkflow(wrapper); workflow.perform(chain); assertTrue(run.get()); assertEquals(wrapper.getParameter("field1"), "value1"); assertEquals(wrapper.getParameter("field2"), "value2"); EasyMock.verify(request); }
From source file:com.kolich.curacao.mappers.request.types.body.MemoryBufferingRequestBodyMapper.java
@Override public final T resolve(@Nullable final Annotation annotation, @Nonnull final CuracaoContext ctx) throws Exception { // This mapper, and all of its children, only handles parameters // annotated with request body. If it's anything else, immediately // return null. if (!(annotation instanceof RequestBody)) { return null; }//from ww w. j a va 2 s.c om final RequestBody rb = (RequestBody) annotation; // If this request context already has a copy of the request body // in memory, then we should not attempt to "re-buffer" it. We can // use what's already been fetched over the wire from the client. byte[] body = ctx.getBody(); if (body == null) { // No pre-buffered body was attached to the request context. We // should attempt to buffer one. final HttpServletRequest request = ctx.request_; final long maxLength = (rb.maxSizeInBytes() > 0L) ? // If the RequestBody annotation specified a maximum body // size in bytes, then we should honor that here. rb.maxSizeInBytes() : // Otherwise, default to what's been globally configured in // the app configuration. DEFAULT_MAX_REQUEST_BODY_SIZE_BYTES; // Sigh, blocking I/O (for now). try (final InputStream is = request.getInputStream()) { long contentLength = request.getContentLength(); if (contentLength != -1L) { // Content-Length was specified, check to make sure it's not // larger than the maximum request body size supported. if (maxLength > 0 && contentLength > maxLength) { throw new RequestTooLargeException( "Incoming request " + "body was too large to buffer into memory: " + contentLength + "-bytes > " + maxLength + "-bytes maximum."); } } else { // Content-Length was not specified on the request. contentLength = (maxLength <= 0) ? // Default to copy as much as data as we can if the // config does not place a limit on the maximum size // of the request body to buffer in memory. Long.MAX_VALUE : // No Content-Length was specified. Default the max // number of bytes to the max request body size. maxLength; } // Note we're using a limited input stream that intentionally // limits the number of bytes read by reading N-bytes, then // stops. This prevents us from filling up too many buffers // which could lead to bringing down the JVM with too many // requests and not enough memory. body = toByteArray(limit(is, contentLength)); // Cache the freshly buffered body byte[] array to the request // context for other mappers to pick up if needed. ctx.setBody(body); } } return resolveWithBody(rb, ctx, body); }