List of usage examples for javax.servlet.http HttpServletRequest getContentLength
public int getContentLength();
From source file:org.opengeoportal.proxy.controllers.OldDynamicOgcController.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. java 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)); copyRequestHeaders(servletRequest, proxyRequest); // Add the input entity (streamed) then execute the request. HttpResponse proxyResponse = null; InputStream servletRequestInputStream = servletRequest.getInputStream(); try { try { 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 { 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); } }
From source file:org.sakaiproject.util.Web.java
public static String snoop(PrintWriter out, boolean html, ServletConfig config, HttpServletRequest req) { // if no out, send to system out ByteArrayOutputStream ostream = null; if (out == null) { ostream = new ByteArrayOutputStream(); out = new PrintWriter(ostream); html = false;//from ww w. j a v a2 s. co m } String h1 = ""; String h1x = ""; String pre = ""; String prex = ""; String b = ""; String bx = ""; String p = ""; if (html) { h1 = "<h1>"; h1x = "</h1>"; pre = "<pre>"; prex = "</pre>"; b = "<b>"; bx = "</b>"; p = "<p>"; } Enumeration<?> e = null; out.println(h1 + "Snoop for request" + h1x); out.println(req.toString()); if (config != null) { e = config.getInitParameterNames(); if (e != null) { boolean first = true; while (e.hasMoreElements()) { if (first) { out.println(h1 + "Init Parameters" + h1x); out.println(pre); first = false; } String param = (String) e.nextElement(); out.println(" " + param + ": " + config.getInitParameter(param)); } out.println(prex); } } out.println(h1 + "Request information:" + h1x); out.println(pre); print(out, "Request method", req.getMethod()); String requestUri = req.getRequestURI(); print(out, "Request URI", requestUri); displayStringChars(out, requestUri); print(out, "Request protocol", req.getProtocol()); String servletPath = req.getServletPath(); print(out, "Servlet path", servletPath); displayStringChars(out, servletPath); String contextPath = req.getContextPath(); print(out, "Context path", contextPath); displayStringChars(out, contextPath); String pathInfo = req.getPathInfo(); print(out, "Path info", pathInfo); displayStringChars(out, pathInfo); print(out, "Path translated", req.getPathTranslated()); print(out, "Query string", req.getQueryString()); print(out, "Content length", req.getContentLength()); print(out, "Content type", req.getContentType()); print(out, "Server name", req.getServerName()); print(out, "Server port", req.getServerPort()); print(out, "Remote user", req.getRemoteUser()); print(out, "Remote address", req.getRemoteAddr()); // print(out, "Remote host", req.getRemoteHost()); print(out, "Authorization scheme", req.getAuthType()); out.println(prex); e = req.getHeaderNames(); if (e.hasMoreElements()) { out.println(h1 + "Request headers:" + h1x); out.println(pre); while (e.hasMoreElements()) { String name = (String) e.nextElement(); out.println(" " + name + ": " + req.getHeader(name)); } out.println(prex); } e = req.getParameterNames(); if (e.hasMoreElements()) { out.println(h1 + "Servlet parameters (Single Value style):" + h1x); out.println(pre); while (e.hasMoreElements()) { String name = (String) e.nextElement(); out.println(" " + name + " = " + req.getParameter(name)); } out.println(prex); } e = req.getParameterNames(); if (e.hasMoreElements()) { out.println(h1 + "Servlet parameters (Multiple Value style):" + h1x); out.println(pre); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String vals[] = (String[]) req.getParameterValues(name); if (vals != null) { out.print(b + " " + name + " = " + bx); out.println(vals[0]); for (int i = 1; i < vals.length; i++) out.println(" " + vals[i]); } out.println(p); } out.println(prex); } e = req.getAttributeNames(); if (e.hasMoreElements()) { out.println(h1 + "Request attributes:" + h1x); out.println(pre); while (e.hasMoreElements()) { String name = (String) e.nextElement(); out.println(" " + name + ": " + req.getAttribute(name)); } out.println(prex); } if (ostream != null) { out.flush(); return ostream.toString(); } return ""; }
From source file:httpmultiplexer.httpproxy.ProxyServlet.java
protected void duplicateRequest(HttpServletRequest servletRequest) 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, secondTargetUri); }// w w w . j av a2 s. co m if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) { servletRequest.setAttribute(ATTR_TARGET_HOST, secondTargetHost); } // 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()); } proxyClient.getParams().setParameter("http.socket.timeout", 1000); proxyClient.getParams().setParameter("http.connection.timeout", 1000); proxyClient.getParams().setParameter("http.connection-manager.timeout", (long) 1000); proxyClient.execute(getTargetHost(servletRequest), proxyRequest); } catch (Exception e) { _logger.error("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri() + " got error " + e.toString()); } finally { servletRequest.setAttribute(ATTR_TARGET_URI, null); servletRequest.setAttribute(ATTR_TARGET_HOST, null); // 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:io.hops.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 ww w . ja va 2 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) { 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.owasp.appsensor.block.proxy.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); }// w w w .jav a2 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) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } proxyResponse = proxyClient.execute(getTargetHost(servletRequest), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); // copying response headers to make sure SESSIONID or other Cookie which comes from remote server // will be saved in client when the proxied url was redirected to another one. // see issue [#51](https://github.com/mitre/HTTP-Proxy-Servlet/issues/51) copyResponseHeaders(proxyResponse, servletRequest, servletResponse); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //the response is already "committed" now without any body to send 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()); // 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:de.derschimi.proxyservlet.TestServlet.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 ww w. j av a 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); 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:nl.nn.adapterframework.pipes.StreamPipe.java
@Override public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException { Object result = input;/*from w ww . j ava2 s . c o m*/ String inputString; if (input instanceof String) { inputString = (String) input; } else { inputString = ""; } ParameterResolutionContext prc = new ParameterResolutionContext(inputString, session, isNamespaceAware()); Map parameters = null; ParameterList parameterList = getParameterList(); if (parameterList != null) { try { parameters = prc.getValueMap(parameterList); } catch (ParameterException e) { throw new PipeRunException(this, "Could not resolve parameters", e); } } InputStream inputStream = null; OutputStream outputStream = null; HttpServletRequest httpRequest = null; HttpServletResponse httpResponse = null; String contentType = null; String contentDisposition = null; if (parameters != null) { if (parameters.get("inputStream") != null) { inputStream = (InputStream) parameters.get("inputStream"); } if (parameters.get("outputStream") != null) { outputStream = (OutputStream) parameters.get("outputStream"); } if (parameters.get("httpRequest") != null) { httpRequest = (HttpServletRequest) parameters.get("httpRequest"); } if (parameters.get("httpResponse") != null) { httpResponse = (HttpServletResponse) parameters.get("httpResponse"); } if (parameters.get("contentType") != null) { contentType = (String) parameters.get("contentType"); } if (parameters.get("contentDisposition") != null) { contentDisposition = (String) parameters.get("contentDisposition"); } } if (inputStream == null) { if (input instanceof InputStream) { inputStream = (InputStream) input; } } try { if (httpResponse != null) { HttpSender.streamResponseBody(inputStream, contentType, contentDisposition, httpResponse, log, getLogPrefix(session)); } else if (httpRequest != null) { StringBuilder partsString = new StringBuilder("<parts>"); String firstStringPart = null; if (ServletFileUpload.isMultipartContent(httpRequest)) { log.debug(getLogPrefix(session) + "request with content type [" + httpRequest.getContentType() + "] and length [" + httpRequest.getContentLength() + "] contains multipart content"); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); List<FileItem> items = servletFileUpload.parseRequest(httpRequest); int fileCounter = 0, stringCounter = 0; log.debug(getLogPrefix(session) + "multipart request items size [" + items.size() + "]"); for (FileItem item : items) { if (item.isFormField()) { // Process regular form field (input // type="text|radio|checkbox|etc", select, etc). String fieldValue = item.getString(); if (isExtractFirstStringPart() && firstStringPart == null) { log.debug(getLogPrefix(session) + "extracting first string part [" + fieldValue + "]"); firstStringPart = fieldValue; } else { String fieldName = "part_string" + (++stringCounter > 1 ? stringCounter : ""); log.debug(getLogPrefix(session) + "setting parameter [" + fieldName + "] to [" + fieldValue + "]"); session.put(fieldName, fieldValue); partsString.append("<part type=\"string\" sessionKey=\"" + fieldName + "\" size=\"" + fieldValue.length() + "\"/>"); } } else { // Process form file field (input type="file"). String fieldName = "part_file" + (++fileCounter > 1 ? fileCounter : ""); String fileName = FilenameUtils.getName(item.getName()); InputStream is = item.getInputStream(); int size = is.available(); String mimeType = item.getContentType(); if (size > 0) { log.debug(getLogPrefix(session) + "setting parameter [" + fieldName + "] to input stream of file [" + fileName + "]"); session.put(fieldName, is); } else { log.debug(getLogPrefix(session) + "setting parameter [" + fieldName + "] to [" + null + "]"); session.put(fieldName, null); } partsString.append("<part type=\"file\" name=\"" + fileName + "\" sessionKey=\"" + fieldName + "\" size=\"" + size + "\" mimeType=\"" + mimeType + "\"/>"); } } } else { log.debug(getLogPrefix(session) + "request with content type [" + httpRequest.getContentType() + "] and length [" + httpRequest.getContentLength() + "] does NOT contain multipart content"); } partsString.append("</parts>"); if (isExtractFirstStringPart()) { result = adjustFirstStringPart(firstStringPart, session); session.put(getMultipartXmlSessionKey(), partsString.toString()); } else { result = partsString.toString(); } } else { Misc.streamToStream(inputStream, outputStream); } } catch (IOException e) { throw new PipeRunException(this, "IOException streaming input to output", e); } catch (FileUploadException e) { throw new PipeRunException(this, "FileUploadException getting multiparts from httpServletRequest", e); } return new PipeRunResult(getForward(), result); }
From source file:com.netscape.cms.servlet.connector.ConnectorServlet.java
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean running_state = CMS.isInRunningState(); if (!running_state) throw new IOException("CMS server is not ready to serve."); HttpServletRequest req = request;//from w w w . ja v a 2 s . c om HttpServletResponse resp = response; CMSRequest cmsRequest = newCMSRequest(); // set argblock cmsRequest.setHttpParams(CMS.createArgBlock(toHashtable(request))); // set http request cmsRequest.setHttpReq(request); // set http response cmsRequest.setHttpResp(response); // set servlet config. cmsRequest.setServletConfig(mConfig); // set servlet context. cmsRequest.setServletContext(mConfig.getServletContext()); char[] content = null; String encodedreq = null; String method = null; int len = -1; IPKIMessage msg = null; IPKIMessage replymsg = null; // NOTE must read all bufer before redoing handshake for // ssl client auth for client auth to work. // get request method method = req.getMethod(); // get content length len = request.getContentLength(); // get content, a base 64 encoded serialized request. if (len > 0) { InputStream in = request.getInputStream(); InputStreamReader inreader = new InputStreamReader(in, "UTF8"); BufferedReader reader = new BufferedReader(inreader, len); content = new char[len]; int done = reader.read(content, 0, len); int total = done; while (done >= 0 && total < len) { done = reader.read(content, total, len - total); total += done; } reader.close(); encodedreq = new String(content); } // force client auth handshake, validate RA and get RA's Id. // NOTE must do this after all contents are read for ssl // redohandshake to work X509Certificate peerCert; try { peerCert = getPeerCert(req); } catch (EBaseException e) { mAuthority.log(ILogger.LL_SECURITY, CMS.getLogMessage("CMSGW_HAS_NO_CLIENT_CERT")); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } if (peerCert == null) { // XXX log something here. resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // authenticate RA String RA_Id = null; String raUserId = null; IAuthToken token = null; try { token = authenticate(request); raUserId = token.getInString("userid"); RA_Id = peerCert.getSubjectDN().toString(); } catch (EInvalidCredentials e) { // already logged. resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } catch (EBaseException e) { // already logged. resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } mAuthority.log(ILogger.LL_INFO, "Remote Authority authenticated: " + peerCert.getSubjectDN()); // authorize AuthzToken authzToken = null; try { authzToken = authorize(mAclMethod, token, mAuthzResourceName, "submit"); } catch (Exception e) { // do nothing for now } if (authzToken == null) { cmsRequest.setStatus(ICMSRequest.UNAUTHORIZED); return; } // after cert validated, check http request. if (!method.equalsIgnoreCase("POST")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } if (len <= 0) { resp.sendError(HttpServletResponse.SC_LENGTH_REQUIRED); return; } // now process request. CMS.debug("ConnectorServlet: process request RA_Id=" + RA_Id); try { // decode request. msg = (IPKIMessage) mReqEncoder.decode(encodedreq); // process request replymsg = processRequest(RA_Id, raUserId, msg, token); } catch (IOException e) { CMS.debug("ConnectorServlet: service " + e.toString()); CMS.debug(e); mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString())); resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } catch (EBaseException e) { CMS.debug("ConnectorServlet: service " + e.toString()); CMS.debug(e); mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString())); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } catch (Exception e) { CMS.debug("ConnectorServlet: service " + e.toString()); CMS.debug(e); } CMS.debug("ConnectorServlet: done processRequest"); // encode reply try { String encodedrep = mReqEncoder.encode(replymsg); resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/html"); resp.setContentLength(encodedrep.length()); // send reply OutputStream out = response.getOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF8"); writer.write(encodedrep); writer.flush(); writer.close(); out.flush(); } catch (Exception e) { CMS.debug("ConnectorServlet: error writing e=" + e.toString()); } CMS.debug("ConnectorServlet: send response RA_Id=" + RA_Id); }
From source file:org.apache.karaf.cellar.http.balancer.CellarBalancerProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { String location = locations.get(new Random().nextInt(locations.size())); URI locationUri = URI.create(location); HttpHost host = URIUtils.extractHost(locationUri); LOGGER.debug("CELLAR HTTP BALANCER: proxying to"); LOGGER.debug("CELLAR HTTP BALANCER: URI: {}", locationUri); LOGGER.debug("CELLAR HTTP BALANCER: Host: {}", host); // 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(); LOGGER.debug("CELLAR HTTP BALANCER: Method: {}", method); String proxyRequestUri = rewriteUrlFromRequest(servletRequest, location); LOGGER.debug("CELLAR HTTP BALANCER: Proxy Request URI: {}", proxyRequestUri); HttpRequest proxyRequest;/* 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); LOGGER.debug("CELLAR HTTP BALANCER: copying request headers"); copyRequestHeaders(servletRequest, proxyRequest, host); LOGGER.debug("CELLAR HTTP BALANCER: set X-Forwarded header"); setXForwardedForHeader(servletRequest, proxyRequest); HttpResponse proxyResponse = null; try { // Execute the request LOGGER.debug("CELLAR HTTP BALANCER: executing proxy request"); proxyResponse = proxyClient.execute(host, proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); LOGGER.debug("CELLAR HTTP BALANCER: status code: {}", statusCode); // copying response headers to make sure SESSIONID or other Cookie which comes from remote server // will be saved in client when the proxied url was redirected to another one. // see issue [#51](https://github.com/mitre/HTTP-Proxy-Servlet/issues/51) LOGGER.debug("CELLAR HTTP BALANCER: copying response headers"); copyResponseHeaders(proxyResponse, servletRequest, servletResponse); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode, location)) { //the response is already "committed" now without any body to send 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 LOGGER.debug("CELLAR HTTP BALANCER: set response status code"); servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); // Send the content to the client LOGGER.debug("CELLAR HTTP BALANCER: copying response entity"); 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:com.dien.upload.server.UploadServlet.java
/** * This method parses the submit action, puts in session a listener where the * progress status is updated, and eventually stores the received data in * the user session.//from w w w . j a va 2 s . c o m * * returns null in the case of success or a string with the error * */ @SuppressWarnings("unchecked") protected String parsePostRequest(HttpServletRequest request, HttpServletResponse response) { try { String delay = request.getParameter(PARAM_DELAY); uploadDelay = Integer.parseInt(delay); } catch (Exception e) { } HttpSession session = request.getSession(); logger.debug("UPLOAD-SERVLET (" + session.getId() + ") new upload request received."); AbstractUploadListener listener = getCurrentListener(request); if (listener != null) { if (listener.isFrozen() || listener.isCanceled() || listener.getPercent() >= 100) { removeCurrentListener(request); } else { String error = getMessage("busy"); logger.error("UPLOAD-SERVLET (" + session.getId() + ") " + error); return error; } } // Create a file upload progress listener, and put it in the user session, // so the browser can use ajax to query status of the upload process listener = createNewListener(request); List<FileItem> uploadedItems; try { // Call to a method which the user can override checkRequest(request); // Create the factory used for uploading files, FileItemFactory factory = getFileItemFactory(request.getContentLength()); ServletFileUpload uploader = new ServletFileUpload(factory); uploader.setSizeMax(maxSize); uploader.setProgressListener(listener); // Receive the files logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsing HTTP POST request "); uploadedItems = uploader.parseRequest(request); logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsed request, " + uploadedItems.size() + " items received."); // Received files are put in session Vector<FileItem> sessionFiles = (Vector<FileItem>) getSessionFileItems(request); if (sessionFiles == null) { sessionFiles = new Vector<FileItem>(); } String error = ""; session.setAttribute(SESSION_LAST_FILES, uploadedItems); if (uploadedItems.size() > 0) { sessionFiles.addAll(uploadedItems); String msg = ""; for (FileItem i : sessionFiles) { msg += i.getFieldName() + " => " + i.getName() + "(" + i.getSize() + " bytes),"; } logger.debug("UPLOAD-SERVLET (" + session.getId() + ") puting items in session: " + msg); session.setAttribute(SESSION_FILES, sessionFiles); } else { logger.error("UPLOAD-SERVLET (" + session.getId() + ") error NO DATA received "); error += getMessage("no_data"); } return error.length() > 0 ? error : null; } catch (SizeLimitExceededException e) { RuntimeException ex = new UploadSizeLimitException(e.getPermittedSize(), e.getActualSize()); listener.setException(ex); throw ex; } catch (UploadSizeLimitException e) { listener.setException(e); throw e; } catch (UploadCanceledException e) { listener.setException(e); throw e; } catch (UploadTimeoutException e) { listener.setException(e); throw e; } catch (Exception e) { logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") Unexpected Exception -> " + e.getMessage() + "\n" + stackTraceToString(e)); e.printStackTrace(); RuntimeException ex = new UploadException(e); listener.setException(ex); throw ex; } }