List of usage examples for javax.servlet.http HttpServletRequest getContentLength
public int getContentLength();
From source file:io.hops.hopsworks.api.kibana.ProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { //initialize request attributes from caches if unset by a subclass by this point if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) { servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); }//from w w w . java 2 s . com if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) { servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); } // 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; //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()); } HttpHost httpHost = getTargetHost(servletRequest); proxyResponse = proxyClient.execute(httpHost, 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, servletRequest, 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()); } //Note: Don't need to close servlet outputStream: // http://stackoverflow.com/questions/1159168/should-one-call-close-on //-httpservletresponse-getoutputstream-getwriter } }
From source file:org.webdavaccess.servlet.WebdavServlet.java
/** * MKCOL Method.// w ww. j av a2 s . c o m * * @param req * HttpServletRequest * @param resp * HttpServletResponse * @throws IOException * if an error in the underlying store occurs */ protected void doMkcol(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getContentLength() > 0) { resp.sendError(WebdavStatus.SC_NOT_IMPLEMENTED); } else { if (!readOnly) { // not readonly String path = getRelativePath(req); String parentPath = getParentPath(path); String lockOwner = "doMkcol" + System.nanoTime() + req.toString(); if (fResLocks.lock(path, lockOwner, true, 0)) { try { if (parentPath != null && fStore.isFolder(parentPath)) { boolean isFolder = fStore.isFolder(path); if (!fStore.objectExists(path)) { try { fStore.createFolder(path); resp.setStatus(WebdavStatus.SC_CREATED); } catch (ObjectAlreadyExistsException e) { String methodsAllowed = determineMethodsAllowed(true, isFolder); resp.addHeader("Allow", methodsAllowed); resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED); } } else { // object already exists String methodsAllowed = determineMethodsAllowed(true, isFolder); resp.addHeader("Allow", methodsAllowed); resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED); } } else { resp.sendError(WebdavStatus.SC_CONFLICT); } } catch (AccessDeniedException e) { log.error("WebdavServer not authenticated: ", e); resp.sendError(WebdavStatus.SC_FORBIDDEN); } catch (WebdavException e) { log.error("WebdavServer internal error: ", e); resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); } finally { fResLocks.unlock(path, lockOwner); } } else { log.error("WebdavServer unable to lock resource " + lockOwner); resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); } } else { log.error("WebdavServer not authenticated for write"); resp.sendError(WebdavStatus.SC_FORBIDDEN); } } }
From source file:com.google.gwt.jolokia.server.servlet.ProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // initialize request attributes from caches if unset by a subclass by // this point if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) { servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); }//from w ww . j a va 2 s. c om if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) { servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); } // 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; // 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); //debugProxyRequest(proxyRequest); HttpResponse proxyResponse = null; try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } proxyResponse = proxyClient.execute(getTargetHost(servletRequest), 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, servletRequest, 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()); // Note: Don't need to close servlet outputStream: // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter } }
From source file:org.red5.server.net.rtmpt.RTMPTServlet.java
/** * Main entry point for the servlet./*from ww w. ja va 2s .c o m*/ * * @param req * Request object * @param resp * Response object * @throws IOException * I/O exception */ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (applicationContext == null) { ServletContext ctx = getServletContext(); applicationContext = WebApplicationContextUtils.getWebApplicationContext(ctx); if (applicationContext == null) { applicationContext = (WebApplicationContext) ctx .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); } log.debug("Application context: {}", applicationContext); // ensure we have a connection manager if (manager == null) { log.warn("Class instance connection manager was null, looking up in application context"); manager = (RTMPConnManager) applicationContext.getBean("rtmpConnManager"); if (manager == null) { log.warn("Connection manager was null in context, getting class instance"); manager = RTMPConnManager.getInstance(); if (manager == null) { log.error("Connection manager is still null, this is bad"); } } } } log.debug("Request - method: {} content type: {} path: {}", new Object[] { req.getMethod(), req.getContentType(), req.getServletPath() }); // allow only POST requests with valid content length if (!REQUEST_METHOD.equals(req.getMethod()) || req.getContentLength() == 0) { // Bad request - return simple error page handleBadRequest("Bad request, only RTMPT supported.", resp); return; } // decide whether or not to enforce request content checks if (enforceContentTypeCheck && !CONTENT_TYPE.equals(req.getContentType())) { handleBadRequest(String.format("Bad request, unsupported content type: %s.", req.getContentType()), resp); return; } // get the uri String uri = req.getRequestURI().trim(); log.debug("URI: {}", uri); // get the path String path = req.getServletPath(); // since the only current difference in the type of request that we are interested in is the 'second' character, we can double // the speed of this entry point by using a switch on the second character. char p = path.charAt(1); switch (p) { case 'o': // OPEN_REQUEST handleOpen(req, resp); break; case 'c': // CLOSE_REQUEST setRequestInfo(req); handleClose(req, resp); requestInfo.remove(); break; case 's': // SEND_REQUEST setRequestInfo(req); handleSend(req, resp); requestInfo.remove(); break; case 'i': // IDLE_REQUEST setRequestInfo(req); handleIdle(req, resp); requestInfo.remove(); break; case 'f': // HTTPIdent request (ident and ident2) //if HTTPIdent is requested send back some Red5 info //http://livedocs.adobe.com/flashmediaserver/3.0/docs/help.html?content=08_xmlref_011.html String ident = "<fcs><Company>Red5</Company><Team>Red5 Server</Team></fcs>"; // handle ident2 slightly different to appease osx clients if (uri.charAt(uri.length() - 1) == '2') { // check for pre-configured ident2 value if (ident2 != null) { ident = ident2; } else { // just send 404 back if no ident2 value is set resp.setStatus(HttpServletResponse.SC_NOT_FOUND); resp.setHeader("Connection", "Keep-Alive"); resp.setHeader("Cache-Control", "no-cache"); resp.flushBuffer(); break; } } resp.setStatus(HttpServletResponse.SC_OK); resp.setHeader("Connection", "Keep-Alive"); resp.setHeader("Cache-Control", "no-cache"); resp.setContentType(CONTENT_TYPE); resp.setContentLength(ident.length()); resp.getWriter().write(ident); resp.flushBuffer(); break; default: handleBadRequest(String.format("RTMPT command %s is not supported.", path), resp); } // clear thread local reference Red5.setConnectionLocal(null); }
From source file:org.exist.http.SOAPServer.java
public void doPost(DBBroker broker, HttpServletRequest request, HttpServletResponse response, String path) throws BadRequestException, PermissionDeniedException, NotFoundException, IOException { /*//w w w .j av a 2 s. c o m * Example incoming SOAP Request * <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <SOAP-ENV:Body> <echo xmlns="http://localhost:8080/exist/servlet/db/echo.xqws"> <arg1>adam</arg1> </echo> </SOAP-ENV:Body> </SOAP-ENV:Envelope> */ // 1) Read the incoming SOAP request final InputStream is = request.getInputStream(); final byte[] buf = new byte[request.getContentLength()]; int bytes = 0; int offset = 0; final int max = 4096; while ((bytes = is.read(buf, offset, max)) != -1) { offset += bytes; } // 2) Create an XML Document from the SOAP Request Document soapRequest = null; try { soapRequest = BuildXMLDocument(buf); } catch (final Exception e) { LOG.debug(e.getMessage()); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, formatXPathException(null, path, new XPathException( "Unable to construct an XML document from the SOAP Request, probably an invalid request: " + e.getMessage(), e)), "text/html", ENCODING); return; } try { final StringWriter out = new StringWriter(); broker.getSerializer().serialize((ElementImpl) soapRequest.getDocumentElement(), out); //System.out.println(out.toString()); } catch (final SAXException e) { LOG.error("Error during serialization.", e); } // 3) Validate the SOAP Request //TODO: validate the SOAP Request // 4) Extract the function call from the SOAP Request final NodeList nlBody = soapRequest.getDocumentElement().getElementsByTagNameNS(Namespaces.SOAP_ENVELOPE, "Body"); if (nlBody == null) { LOG.error("Style Parameter wrapped not supported yet"); } final Node nSOAPBody = nlBody.item(0); // DW: can return NULL ! case: style ParameterWrapped final NodeList nlBodyChildren = nSOAPBody.getChildNodes(); Node nSOAPFunction = null; for (int i = 0; i < nlBodyChildren.getLength(); i++) { Node bodyChild = nlBodyChildren.item(i); if (bodyChild.getNodeType() == Node.ELEMENT_NODE) { nSOAPFunction = bodyChild; break; } } // Check the namespace for the function in the SOAP document is the same as the request path? final String funcNamespace = nSOAPFunction.getNamespaceURI(); if (funcNamespace != null) { if (!funcNamespace.equals(request.getRequestURL().toString())) { //function in SOAP request has an invalid namespace response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, "SOAP Function call has invalid namespace, got: " + funcNamespace + " but expected: " + request.getRequestURL().toString(), "text/html", ENCODING); return; } } else { //function in SOAP request has no namespace response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, "SOAP Function call has no namespace, expected: " + request.getRequestURL().toString(), "text/html", ENCODING); return; } // 4.5) Detemine encoding style final String encodingStyle = ((org.w3c.dom.Element) nSOAPFunction).getAttributeNS(Namespaces.SOAP_ENVELOPE, "encodingStyle"); boolean isRpcEncoded = (encodingStyle != null && "http://schemas.xmlsoap.org/soap/encoding/".equals(encodingStyle)); // As this detection is a "quirk" which is not always available, let's use a better one... if (!isRpcEncoded) { final NodeList nlSOAPFunction = nSOAPFunction.getChildNodes(); for (int i = 0; i < nlSOAPFunction.getLength(); i++) { final Node functionChild = nlSOAPFunction.item(i); if (functionChild.getNodeType() == Node.ELEMENT_NODE) { if (((org.w3c.dom.Element) functionChild).hasAttributeNS(Namespaces.SCHEMA_INSTANCE_NS, "type")) { isRpcEncoded = true; break; } } } } // 5) Execute the XQWS function indicated by the SOAP request try { //Get the internal description for the function requested by SOAP (should be in the cache) final XQWSDescription description = getXQWSDescription(broker, path, request); //Create an XQuery to call the XQWS function final CompiledXQuery xqCallXQWS = XQueryExecuteXQWSFunction(broker, nSOAPFunction, description, request, response); //xqCallXQWS final XQuery xqueryService = broker.getXQueryService(); final Sequence xqwsResult = xqueryService.execute(xqCallXQWS, null); // 6) Create a SOAP Response describing the Result String funcName = nSOAPFunction.getLocalName(); if (funcName == null) { funcName = nSOAPFunction.getNodeName(); } final byte[] result = description.getSOAPResponse(funcName, xqwsResult, request, isRpcEncoded); // 7) Send the SOAP Response to the http servlet response response.setContentType(MimeType.XML_LEGACY_TYPE.getName()); final ServletOutputStream os = response.getOutputStream(); final BufferedOutputStream bos = new BufferedOutputStream(os); bos.write(result); bos.close(); os.close(); } catch (final XPathException xpe) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, formatXPathException(null, path, xpe), "text/html", ENCODING); } catch (final SAXException saxe) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, formatXPathException(null, path, new XPathException( "SAX exception while transforming node: " + saxe.getMessage(), saxe)), "text/html", ENCODING); } catch (final TransformerConfigurationException tce) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, formatXPathException(null, path, new XPathException("SAX exception while transforming node: " + tce.getMessage(), tce)), "text/html", ENCODING); } }
From source file:com.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java
private void uploadMultipart(HttpServletRequest req, HttpServletResponse resp, OutputStream repoItemOutputStrem) throws IOException { log.info("Multipart detected"); ServletFileUpload upload = new ServletFileUpload(); try {// w w w . j a v a2 s .co m // Parse the request FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); try (InputStream stream = item.openStream()) { if (item.isFormField()) { // TODO What to do with this? log.info("Form field {} with value {} detected.", name, Streams.asString(stream)); } else { // TODO Must we support multiple files uploading? log.info("File field {} with file name detected.", name, item.getName()); log.info("Start to receive bytes (estimated bytes)", Integer.toString(req.getContentLength())); int bytes = IOUtils.copy(stream, repoItemOutputStrem); resp.setStatus(SC_OK); log.info("Bytes received: {}", Integer.toString(bytes)); } } } } catch (FileUploadException e) { throw new IOException(e); } }
From source file:org.kurento.repository.internal.http.RepositoryHttpServlet.java
private void uploadMultipart(HttpServletRequest req, HttpServletResponse resp, OutputStream repoItemOutputStrem) throws IOException { log.debug("Multipart detected"); ServletFileUpload upload = new ServletFileUpload(); try {//from w w w .j ava2 s . c o m // Parse the request FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); try (InputStream stream = item.openStream()) { if (item.isFormField()) { // TODO What to do with this? log.debug("Form field {} with value {} detected.", name, Streams.asString(stream)); } else { // TODO Must we support multiple files uploading? log.debug("File field {} with file name detected.", name, item.getName()); log.debug("Start to receive bytes (estimated bytes)", Integer.toString(req.getContentLength())); int bytes = IOUtils.copy(stream, repoItemOutputStrem); resp.setStatus(SC_OK); log.debug("Bytes received: {}", Integer.toString(bytes)); } } } } catch (FileUploadException e) { throw new IOException(e); } }
From source file:ORG.oclc.os.SRW.SRWServlet.java
@Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { MessageContext msgContext = createMessageContext(getEngine(), request, response); if (!srwInfo.setSRWStuff(request, response, msgContext)) { servletLog.error("srwInfo.setSRWStuff failed!"); return;/* w ww . j a va2s .c o m*/ } if (log.isDebugEnabled()) log.debug("in doPut: got APP request for " + request.getRequestURI()); SRWDatabase db = (SRWDatabase) msgContext.getProperty("db"); if (log.isDebugEnabled()) log.debug("adding to database " + db); if (log.isDebugEnabled()) log.debug("adding to database " + db.dbname); InputStream is = request.getInputStream(); int len, offset = 0, totlen = request.getContentLength(); byte[] b = new byte[totlen]; while (totlen > 0) { len = is.read(b, offset, totlen); totlen -= len; offset += len; } db.replace(b); if (db.httpHeaderSetter != null) db.httpHeaderSetter.setPutResponseHeaders(new String(b, "UTF-8"), request, response); response.setStatus(200); return; }
From source file:httpmultiplexer.httpproxy.ProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // duplicate request before processing it HttpServletRequest duplicatedServletRequest; duplicatedServletRequest = servletRequest; // send another request to second target host duplicateRequest(duplicatedServletRequest); //initialize request attributes from caches if unset by a subclass by this point if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) { servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); }/* www .j a va2 s . c o m*/ if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) { servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); } // 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; //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) { _logger.info("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } proxyResponse = proxyClient.execute(getTargetHost(servletRequest), 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()); } //Note: Don't need to close servlet outputStream: // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter } }
From source file:org.opengeoportal.proxy.controllers.DynamicOgcController.java
@SuppressWarnings("deprecation") private void doProxy(String remoteUrl, 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 try {//from w w w . j a v a 2 s . com this.targetUri = new URI(remoteUrl); } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //Need to handle https, but think about "restricted" layers for now. Some institutions don't really have good protection for restricted layers. Does this open up potential for security //problems for those folks? if (servletRequest.getScheme().equals("https")) { //actually, what matters the most is if the remote url is https } BasicHttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest( servletRequest.getMethod(), rewriteUrlFromRequest(servletRequest)); //HttpGet httpget = new HttpGet(rewriteUrlFromRequest(servletRequest)); copyRequestHeaders(servletRequest, proxyRequest); // Add the input entity (streamed) then execute the request. HttpResponse proxyResponse = null; InputStream servletRequestInputStream = servletRequest.getInputStream(); CloseableHttpClient proxyClient = ogpHttpClient.getCloseableHttpClient(); try { try { //proxyRequest.setEntity(new InputStreamEntity(servletRequestInputStream)); proxyRequest.setEntity( new InputStreamEntity(servletRequestInputStream, servletRequest.getContentLength())); // Execute the request logger.debug("proxy " + servletRequest.getMethod() + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); } finally { IOUtils.closeQuietly(servletRequestInputStream); } // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); logger.info("Status from remote server: " + Integer.toString(statusCode)); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { 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; throw new RuntimeException(e); } }