List of usage examples for javax.servlet.http HttpServletRequest getContentLength
public int getContentLength();
From source file:org.ocpsoft.rewrite.servlet.config.proxy.ProxyServlet.java
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { /*//from w ww . j ava2 s . c o m * Note: we won't transfer the protocol version because I'm not sure it would truly be compatible */ String method = servletRequest.getMethod(); HttpRequest proxyRequest; /* * Spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. */ if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, targetUri); /* * Add the input entity (streamed) note: we don't bother ensuring we close the servletInputStream since the * container handles it */ eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else proxyRequest = new BasicHttpRequest(method, targetUri); copyRequestHeaders(servletRequest, proxyRequest); try { /* * Execute the request */ if (doLog) { logger.debug("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUriObj), proxyRequest); /* * Process the response */ int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { /* * just to be sure, but is probably a no-op */ EntityUtils.consume(proxyResponse.getEntity()); return; } /* * Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the * reason along too. noinspection deprecation */ servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); /* * Send the content to the client */ copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { /* * abort request, according to best practice with HttpClient */ if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; // noinspection ConstantConditions if (e instanceof IOException) throw (IOException) e; throw new RuntimeException(e); } }
From source file:uk.co.bubobubo.web.HttpClientProxy.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest;/* w w w .j a va2 s .c om*/ //spec: RFC 2616, sec 4.3: either these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else proxyRequest = new BasicHttpRequest(method, proxyRequestUri); copyRequestHeaders(servletRequest, proxyRequest); try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } proxyRequest.removeHeaders("authorization"); if (targetUri.getUserInfo() != null && !targetUri.getUserInfo().equalsIgnoreCase("") && !targetUri.getUserInfo().equalsIgnoreCase(":")) { Credentials credentials = new UsernamePasswordCredentials(targetUri.getUserInfo().split(":")[0], targetUri.getUserInfo().split(":")[1]); proxyClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); } HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //just to be sure, but is probably a no-op EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; if (e instanceof IOException) throw (IOException) e; throw new RuntimeException(e); } }
From source file:snoopware.api.ProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest;/*from ww w. j a va 2 s. c o m*/ //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else { proxyRequest = new BasicHttpRequest(method, proxyRequestUri); } copyRequestHeaders(servletRequest, proxyRequest); try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURL().toString() + " -- " + proxyRequest.getRequestLine().getUri()); } HttpResponse proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //just to be sure, but is probably a no-op EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is deprecated but // it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) { throw (RuntimeException) e; } if (e instanceof ServletException) { throw (ServletException) e; } //noinspection ConstantConditions if (e instanceof IOException) { throw (IOException) e; } throw new RuntimeException(e); } }
From source file:com.codeabovelab.dm.gateway.proxy.common.HttpProxy.java
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))); }//from w w w . j a va 2 s. com 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)); }
From source file:com.funambol.transport.http.server.Sync4jServlet.java
/** * Returns the content of HTTP request.// w w w. java2 s.c o m * Uncompresses the request if the Content-Encoding is gzip or deflate. * Updates the Content-Length with the length of the uncompressed request. * * @param httpRequest the HttpServletRequest * @param contentEncoding the content encoding * @param requestTime the time in which the request is arrived to servlet * @param sessionId the session identifier * * @return requestData the uncompressed request content * @throws java.io.IOException if an error occurs */ private byte[] getRequestContent(HttpServletRequest httpRequest, String contentEncoding, long requestTime, String sessionId) throws IOException { byte[] requestData = null; InputStream in = null; try { in = httpRequest.getInputStream(); int contentLength = httpRequest.getContentLength(); if (contentLength <= 0) { contentLength = SIZE_INPUT_BUFFER; } if (logMessages) { // // Read the compressed request data to log it // requestData = IOTools.readContent(in, contentLength); logRequest(httpRequest, requestData, requestTime, sessionId); // // Create a new InputStream to pass at the decompressor // in = new ByteArrayInputStream(requestData); } if (contentEncoding != null) { if (contentEncoding.equals(COMPRESSION_TYPE_GZIP)) { if (log.isTraceEnabled()) { log.trace("Reading the request using: " + COMPRESSION_TYPE_GZIP); } in = new GZIPInputStream(in); } else if (contentEncoding.equals(COMPRESSION_TYPE_DEFLATE)) { if (log.isTraceEnabled()) { log.trace("Reading the request using: " + COMPRESSION_TYPE_DEFLATE); } in = new InflaterInputStream(in); } String uncompressedContentLength = httpRequest.getHeader("Uncompressed-Content-Length"); if (uncompressedContentLength != null) { contentLength = Integer.parseInt(uncompressedContentLength); } else { contentLength = SIZE_INPUT_BUFFER; } } if (!logMessages || contentEncoding != null) { requestData = IOTools.readContent(in, contentLength); } } finally { if (in != null) { in.close(); } } return requestData; }
From source file:com.ecyrd.jspwiki.attachment.AttachmentServlet.java
/** * {@inheritDoc}/*ww w .j a v a2 s . com*/ */ public void doPut(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { String errorPage = m_engine.getURL(WikiContext.ERROR, "", null, false); // If something bad happened, Upload should be able to take care of most stuff String p = new String(req.getPathInfo().getBytes("ISO-8859-1"), "UTF-8"); DavPath path = new DavPath(p); try { InputStream data = req.getInputStream(); WikiContext context = m_engine.createContext(req, WikiContext.UPLOAD); String wikipage = path.get(0); errorPage = context.getURL(WikiContext.UPLOAD, wikipage); String changeNote = null; // FIXME: Does not quite work boolean created = executeUpload(context, data, path.getName(), errorPage, wikipage, changeNote, req.getContentLength()); if (created) res.sendError(HttpServletResponse.SC_CREATED); else res.sendError(HttpServletResponse.SC_OK); } catch (ProviderException e) { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (RedirectException e) { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }
From source file:org.dspace.app.xmlui.cocoon.servlet.multipart.DSpaceMultipartParser.java
public Hashtable getParts(HttpServletRequest request) throws IOException, MultipartException { this.parts = new Hashtable(); // Copy all parameters coming from the request URI to the parts table. // This happens when a form's action attribute has some parameters Enumeration names = request.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String[] values = request.getParameterValues(name); Vector v = new Vector(values.length); for (int i = 0; i < values.length; i++) { v.add(values[i]);//from w w w .ja v a 2 s . c om } this.parts.put(name, v); } // upload progress bar support this.session = request.getSession(); this.hasSession = this.session != null; if (this.hasSession) { this.uploadStatus = new Hashtable(); this.uploadStatus.put("started", Boolean.FALSE); this.uploadStatus.put("finished", Boolean.FALSE); this.uploadStatus.put("sent", new Integer(0)); this.uploadStatus.put("total", new Integer(request.getContentLength())); this.uploadStatus.put("filename", ""); this.uploadStatus.put("error", Boolean.FALSE); this.uploadStatus.put("uploadsdone", new Integer(0)); this.session.setAttribute(UPLOAD_STATUS_SESSION_ATTR, this.uploadStatus); } parseParts(request.getContentLength(), request.getContentType(), request.getInputStream()); if (this.hasSession) { this.uploadStatus.put("finished", Boolean.TRUE); } return this.parts; }
From source file:kornell.server.ProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest;//from w w w . ja v a 2s . co m //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else proxyRequest = new BasicHttpRequest(method, proxyRequestUri); copyRequestHeaders(servletRequest, proxyRequest); setXForwardedForHeader(servletRequest, proxyRequest); HttpResponse proxyResponse = null; try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUriObj), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //the response is already "committed" now without any body to send //TODO copy response headers? return; } // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; //noinspection ConstantConditions if (e instanceof IOException) throw (IOException) e; throw new RuntimeException(e); } finally { // make sure the entire entity was consumed, so the connection is released if (proxyResponse != null) consumeQuietly(proxyResponse.getEntity()); if (proxyResponse != null) closeQuietly(servletResponse.getOutputStream()); } }
From source file:org.redhat.jboss.httppacemaker.ProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible String method = servletRequest.getMethod(); // FIXME: the rewriteUrlFromRequest() method adds an extra trailing "slash", remove by the replace String proxyRequestUri = rewriteUrlFromRequest(servletRequest).replaceAll("/$", ""); HttpRequest proxyRequest;/*from ww w. j ava2 s . c o m*/ //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else proxyRequest = new BasicHttpRequest(method, proxyRequestUri); copyRequestHeaders(servletRequest, proxyRequest); if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } sendProxyRequestToBackend(proxyRequest, servletRequest, servletResponse); }
From source file:fedora.server.rest.RestUtil.java
/** * Retrieves the contents of the HTTP Request. * @return InputStream from the request// ww w. ja v a 2 s . c o m */ public RequestContent getRequestContent(HttpServletRequest request, HttpHeaders headers) throws Exception { RequestContent rContent = null; // See if the request is a multi-part file upload request if (ServletFileUpload.isMultipartContent(request)) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request, use the first available File item FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { rContent = new RequestContent(); rContent.contentStream = item.openStream(); rContent.mimeType = item.getContentType(); FileItemHeaders itemHeaders = item.getHeaders(); if (itemHeaders != null) { String contentLength = itemHeaders.getHeader("Content-Length"); if (contentLength != null) { rContent.size = Integer.parseInt(contentLength); } } break; } } } else { // If the content stream was not been found as a multipart, // try to use the stream from the request directly if (rContent == null) { if (request.getContentLength() > 0) { rContent = new RequestContent(); rContent.contentStream = request.getInputStream(); rContent.size = request.getContentLength(); } else { String transferEncoding = request.getHeader("Transfer-Encoding"); if (transferEncoding != null && transferEncoding.contains("chunked")) { BufferedInputStream bis = new BufferedInputStream(request.getInputStream()); bis.mark(2); if (bis.read() > 0) { bis.reset(); rContent = new RequestContent(); rContent.contentStream = bis; } } } } } // Attempt to set the mime type and size if not already set if (rContent != null) { if (rContent.mimeType == null) { MediaType mediaType = headers.getMediaType(); if (mediaType != null) { rContent.mimeType = mediaType.toString(); } } if (rContent.size == 0) { List<String> lengthHeaders = headers.getRequestHeader("Content-Length"); if (lengthHeaders != null && lengthHeaders.size() > 0) { rContent.size = Integer.parseInt(lengthHeaders.get(0)); } } } return rContent; }