List of usage examples for javax.servlet.http HttpServletResponse SC_MULTIPLE_CHOICES
int SC_MULTIPLE_CHOICES
To view the source code for javax.servlet.http HttpServletResponse SC_MULTIPLE_CHOICES.
Click Source Link
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
/** * Executes the {@link org.apache.commons.httpclient.HttpMethod} passed in and sends the proxy response * back to the client via the given {@link javax.servlet.http.HttpServletResponse} * * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws java.io.IOException Can be thrown by the {@link org.apache.commons.httpclient.HttpClient}.executeMethod * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred *///from w ww. j a v a 2 s . c o m private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { if (httpServletRequest.isSecure()) { Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443)); } // Create a default HttpClient HttpClient httpClient = new HttpClient(); httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); InputStream response = httpMethodProxyRequest.getResponseBodyAsStream(); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); if (followRedirects) { if (stringLocation.contains("jsessionid")) { Cookie cookie = new Cookie("JSESSIONID", stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11)); cookie.setPath("/"); httpServletResponse.addCookie(cookie); //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL"); } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) { Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie"); String[] cookieDetails = header.getValue().split(";"); String[] nameValue = cookieDetails[0].split("="); Cookie cookie = new Cookie(nameValue[0], nameValue[1]); cookie.setPath("/"); //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath()); httpServletResponse.addCookie(cookie); } httpServletResponse.sendRedirect( stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName)); return; } } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked") || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth // proxy servlet does not support chunked encoding } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } List<Header> responseHeaders = Arrays.asList(headerArrayResponse); if (isBodyParameterGzipped(responseHeaders)) { debug("GZipped: true"); int length = 0; if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) { String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); intProxyResponseCode = HttpServletResponse.SC_OK; httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz); } else { final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody()); length = bytes.length; response = new ByteArrayInputStream(bytes); } httpServletResponse.setContentLength(length); } // Send the content to the client debug("Received status code: " + intProxyResponseCode, "Response: " + response); //httpServletResponse.getWriter().write(response); copy(response, httpServletResponse.getOutputStream()); }
From source file:io.fabric8.gateway.servlet.ProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link javax.servlet.http.HttpServletResponse} * * @param proxyDetails/*w ww . ja v a 2 s. c o m*/ * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws java.io.IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred */ private void executeProxyRequest(ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { httpMethodProxyRequest.setDoAuthentication(false); httpMethodProxyRequest.setFollowRedirects(false); // Create a default HttpClient HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect(stringLocation .replace(proxyDetails.getProxyHostAndPort() + proxyDetails.getProxyPath(), stringMyHostName)); return; } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (!ProxySupport.isHopByHopHeader(header.getName())) { if (ProxySupport.isSetCookieHeader(header)) { HttpProxyRule proxyRule = proxyDetails.getProxyRule(); String setCookie = ProxySupport.replaceCookieAttributes(header.getValue(), proxyRule.getCookiePath(), proxyRule.getCookieDomain()); httpServletResponse.setHeader(header.getName(), setCookie); } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } } // check if we got data, that is either the Content-Length > 0 // or the response code != 204 int code = httpMethodProxyRequest.getStatusCode(); boolean noData = code == HttpStatus.SC_NO_CONTENT; if (!noData) { String length = httpServletRequest.getHeader(STRING_CONTENT_LENGTH_HEADER_NAME); if (length != null && "0".equals(length.trim())) { noData = true; } } LOG.trace("Response has data? {}", !noData); if (!noData) { // Send the content to the client InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); int intNextByte; while ((intNextByte = bufferedInputStream.read()) != -1) { outputStreamClientResponse.write(intNextByte); } } }
From source file:it.geosolutions.httpproxy.HTTPProxy.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response back to the client via the given {@link HttpServletResponse} * // w w w . ja va2 s .c om * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied response back to the client * @param digest * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException Can be thrown to indicate that another error has occurred */ private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String user, String password, ProxyInfo proxyInfo) throws IOException, ServletException { if (user != null && password != null) { UsernamePasswordCredentials upc = new UsernamePasswordCredentials(user, password); httpClient.getState().setCredentials(AuthScope.ANY, upc); } httpMethodProxyRequest.setFollowRedirects(false); InputStream inputStreamServerResponse = null; ByteArrayOutputStream baos = null; try { // ////////////////////////// // Execute the request // ////////////////////////// int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); onRemoteResponse(httpMethodProxyRequest); // //////////////////////////////////////////////////////////////////////////////// // Check if the proxy response is a redirect // The following code is adapted from // org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software // //////////////////////////////////////////////////////////////////////////////// if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(Utils.LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Recieved status code: " + stringStatusCode + " but no " + Utils.LOCATION_HEADER + " header was found in the response"); } // ///////////////////////////////////////////// // Modify the redirect to go to this proxy // servlet rather that the proxied host // ///////////////////////////////////////////// String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect(stringLocation.replace( Utils.getProxyHostAndPort(proxyInfo) + proxyInfo.getProxyPath(), stringMyHostName)); return; } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // /////////////////////////////////////////////////////////////// // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. // /////////////////////////////////////////////////////////////// httpServletResponse.setIntHeader(Utils.CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // ///////////////////////////////////////////// // Pass the response code back to the client // ///////////////////////////////////////////// httpServletResponse.setStatus(intProxyResponseCode); // ///////////////////////////////////////////// // Pass response headers back to the client // ///////////////////////////////////////////// Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { // ///////////////////////// // Skip GZIP Responses // ///////////////////////// if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_ACCEPT_ENCODING) && header.getValue().toLowerCase().contains("gzip")) continue; else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_CONTENT_ENCODING) && header.getValue().toLowerCase().contains("gzip")) continue; else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_TRANSFER_ENCODING)) continue; // else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_WWW_AUTHENTICATE)) // continue; else httpServletResponse.setHeader(header.getName(), header.getValue()); } // /////////////////////////////////// // Send the content to the client // /////////////////////////////////// inputStreamServerResponse = httpMethodProxyRequest.getResponseBodyAsStream(); if (inputStreamServerResponse != null) { byte[] b = new byte[proxyConfig.getDefaultStreamByteSize()]; baos = new ByteArrayOutputStream(b.length); int read = 0; while ((read = inputStreamServerResponse.read(b)) > 0) { baos.write(b, 0, read); baos.flush(); } baos.writeTo(httpServletResponse.getOutputStream()); } } catch (HttpException e) { if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, "Error executing HTTP method ", e); } finally { try { if (inputStreamServerResponse != null) inputStreamServerResponse.close(); } catch (IOException e) { if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, "Error closing request input stream ", e); throw new ServletException(e.getMessage()); } try { if (baos != null) { baos.flush(); baos.close(); } } catch (IOException e) { if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, "Error closing response stream ", e); throw new ServletException(e.getMessage()); } httpMethodProxyRequest.releaseConnection(); } }
From source file:com.groupon.odo.Proxy.java
/** * Execute a request//from w ww . j a v a2 s . c o m * * @param httpMethodProxyRequest * @param httpServletRequest * @param httpServletResponse * @param history * @param outStream * @throws Exception */ private void executeRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, History history, OutputStream outStream) throws Exception { int intProxyResponseCode = 999; try { // Create a default HttpClient HttpClient httpClient = new HttpClient(); httpMethodProxyRequest.setFollowRedirects(false); ArrayList<String> headersToRemove = getRemoveHeaders(); httpClient.getParams().setSoTimeout(60000); httpServletRequest.setAttribute("com.groupon.odo.removeHeaders", headersToRemove); intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); } catch (Exception e) { requestInformation.get().outputString = "TIMEOUT"; logRequestHistory(httpMethodProxyRequest, httpServletResponse, history); throw e; } logger.info("Response code: {}, {}", intProxyResponseCode, HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString())); if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); processRedirect(stringStatusCode, httpMethodProxyRequest, httpServletRequest, httpServletResponse); } else { // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { httpServletResponse.setHeader(header.getName(), header.getValue()); } // there is no data for a HTTP 304 if (intProxyResponseCode != HttpServletResponse.SC_NOT_MODIFIED) { // Send the content to the client InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); int intNextByte; // Collect all of the server data while ((intNextByte = bufferedInputStream.read()) != -1) { outStream.write(intNextByte); } } } }
From source file:org.apache.hadoop.hdfs.server.namenode.CancelDelegationTokenServlet.java
@Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final UserGroupInformation ugi; final ServletContext context = getServletContext(); final Configuration conf = (Configuration) context.getAttribute(JspHelper.CURRENT_CONF); try {//w ww .ja v a2 s . c o m ugi = getUGI(req, conf); } catch (IOException ioe) { LOG.info("Request for token received with no authentication from " + req.getRemoteAddr(), ioe); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Unable to identify or authenticate user"); return; } final NameNode nn = (NameNode) context.getAttribute("name.node"); String tokenString = req.getParameter(TOKEN); if (tokenString == null) { resp.sendError(HttpServletResponse.SC_MULTIPLE_CHOICES, "Token to renew not specified"); } final Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>(); token.decodeFromUrlString(tokenString); try { ugi.doAs(new PrivilegedExceptionAction<Void>() { public Void run() throws Exception { nn.cancelDelegationToken(token); return null; } }); } catch (Exception e) { LOG.info("Exception while cancelling token. Re-throwing. ", e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }
From source file:org.apache.hadoop.hdfs.server.namenode.RenewDelegationTokenServlet.java
@Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final UserGroupInformation ugi; final ServletContext context = getServletContext(); final Configuration conf = (Configuration) context.getAttribute(JspHelper.CURRENT_CONF); try {//from www.j a va 2 s. c o m ugi = getUGI(req, conf); } catch (IOException ioe) { LOG.info("Request for token received with no authentication from " + req.getRemoteAddr(), ioe); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Unable to identify or authenticate user"); return; } final NameNode nn = (NameNode) context.getAttribute("name.node"); String tokenString = req.getParameter(TOKEN); if (tokenString == null) { resp.sendError(HttpServletResponse.SC_MULTIPLE_CHOICES, "Token to renew not specified"); } final Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>(); token.decodeFromUrlString(tokenString); try { long result = ugi.doAs(new PrivilegedExceptionAction<Long>() { public Long run() throws Exception { return nn.renewDelegationToken(token); } }); PrintStream os = new PrintStream(resp.getOutputStream()); os.println(result); os.close(); } catch (Exception e) { // transfer exception over the http String exceptionClass = e.getClass().getCanonicalName(); String exceptionMsg = e.getLocalizedMessage(); String strException = exceptionClass + ";" + exceptionMsg; LOG.info("Exception while renewing token. Re-throwing. s=" + strException, e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, strException); } }
From source file:org.apache.sling.servlets.get.impl.helpers.JsonRendererServlet.java
@Override protected void doGet(SlingHttpServletRequest req, SlingHttpServletResponse resp) throws IOException { // Access and check our data final Resource r = req.getResource(); if (ResourceUtil.isNonExistingResource(r)) { throw new ResourceNotFoundException("No data to render."); }/* ww w . jav a 2 s.co m*/ int maxRecursionLevels = 0; try { maxRecursionLevels = getMaxRecursionLevel(req); } catch (IllegalArgumentException iae) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.getMessage()); return; } resp.setContentType(req.getResponseContentType()); resp.setCharacterEncoding("UTF-8"); // We check the tree to see if the nr of nodes isn't bigger than the allowed nr. boolean allowDump = true; int allowedLevel = 0; final boolean tidy = isTidy(req); final boolean harray = hasSelector(req, HARRAY); ResourceTraversor traversor = null; try { traversor = new ResourceTraversor(maxRecursionLevels, maximumResults, r, tidy); allowedLevel = traversor.collectResources(); if (allowedLevel != -1) { allowDump = false; } } catch (final JSONException e) { reportException(e); } try { // Dump the resource if we can if (allowDump) { if (tidy || harray) { final JSONRenderer.Options opt = renderer.options().withIndent(tidy ? INDENT_SPACES : 0) .withArraysForChildren(harray); resp.getWriter().write(renderer.prettyPrint(traversor.getJSONObject(), opt)); } else { // If no rendering options, use the plain toString() method, for // backwards compatibility. Output might be slightly different // with prettyPrint and no options resp.getWriter().write(traversor.getJSONObject().toString()); } } else { // We are not allowed to do the dump. // Send a 300 String tidyUrl = (tidy) ? "tidy." : ""; resp.setStatus(HttpServletResponse.SC_MULTIPLE_CHOICES); JSONWriter writer = new JSONWriter(resp.getWriter()); writer.array(); while (allowedLevel >= 0) { writer.value( r.getResourceMetadata().getResolutionPath() + "." + tidyUrl + allowedLevel + ".json"); allowedLevel--; } writer.endArray(); } } catch (JSONException je) { reportException(je); } }
From source file:org.chorusbdd.chorus.tools.webagent.jettyhandler.TestSuiteHandler.java
@Override protected void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response, XMLStreamWriter writer) throws IOException { String suiteId = baseRequest.getParameter("suiteId"); if (suiteId == null) { response.setStatus(HttpServletResponse.SC_MULTIPLE_CHOICES); response.getWriter().append("Must specify a suite using parameter suiteId"); } else {//w w w. jav a2s. c o m WebAgentTestSuite s = cache.getSuite(suiteId); if (s == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().append("Could not find a test suite " + suiteId); } else { try { handleForSuite(response, s); } catch (PropertyException pe) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); log.error("Failed to serialize test suite to xml, PropertyException, probably your Marshaller " + "implementation does not support the property com.sun.xml.internal.bind.xmlHeaders", pe); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); //client may not see this if we have already written output log.error("Failed to serialize test suite to xml", e); } } } }
From source file:org.codeartisans.proxilet.Proxilet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response back to the client via the given * {@link HttpServletResponse}.//w w w. j a v a 2 s . c om * * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied response back to the client * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException Can be thrown to indicate that another error has occurred */ private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { // Create a default HttpClient HttpClient httpClient; httpClient = createClientWithLogin(); httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // String response = httpMethodProxyRequest.getResponseBodyAsString(); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */ ) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(HEADER_LOCATION).getValue(); if (stringLocation == null) { throw new ServletException("Received status code: " + stringStatusCode + " but no " + HEADER_LOCATION + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); if (followRedirects) { httpServletResponse .sendRedirect(stringLocation.replace(getProxyHostAndPort() + proxyPath, stringMyHostName)); return; } } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(HEADER_CONTENT_LENGTH, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked") || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip")) { // proxy servlet does not support chunked encoding } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } List<Header> responseHeaders = Arrays.asList(headerArrayResponse); // FIXME We should handle both String and bytes response in the same way: String response = null; byte[] bodyBytes = null; if (isBodyParameterGzipped(responseHeaders)) { LOGGER.trace("GZipped: true"); if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) { response = httpMethodProxyRequest.getResponseHeader(HEADER_LOCATION).getValue(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); intProxyResponseCode = HttpServletResponse.SC_OK; httpServletResponse.setHeader(HEADER_LOCATION, response); httpServletResponse.setContentLength(response.length()); } else { bodyBytes = ungzip(httpMethodProxyRequest.getResponseBody()); httpServletResponse.setContentLength(bodyBytes.length); } } if (httpServletResponse.getContentType() != null && httpServletResponse.getContentType().contains("text")) { LOGGER.trace("Received status code: {} Response: {}", intProxyResponseCode, response); } else { LOGGER.trace("Received status code: {} [Response is not textual]", intProxyResponseCode); } // Send the content to the client if (response != null) { httpServletResponse.getWriter().write(response); } else if (bodyBytes != null) { httpServletResponse.getOutputStream().write(bodyBytes); } else { IOUtils.copy(httpMethodProxyRequest.getResponseBodyAsStream(), httpServletResponse.getOutputStream()); } }
From source file:org.jboss.orion.openshift.server.proxy.JsonProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link javax.servlet.http.HttpServletResponse} * * @param proxyDetails//from ww w . j av a2s .co m * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws java.io.IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred */ private void executeProxyRequest(ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { httpMethodProxyRequest.setDoAuthentication(false); httpMethodProxyRequest.setFollowRedirects(false); // Create a default HttpClient HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest); // Execute the request int intProxyResponseCode = 500; try { intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); } catch (Exception e) { e.printStackTrace(); } // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect(stringLocation .replace(proxyDetails.getProxyHostAndPort() + proxyDetails.getProxyPath(), stringMyHostName)); return; } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (!ProxySupport.isHopByHopHeader(header.getName())) { if (ProxySupport.isSetCookieHeader(header)) { HttpProxyRule proxyRule = proxyDetails.getProxyRule(); String setCookie = ProxySupport.replaceCookieAttributes(header.getValue(), proxyRule.getCookiePath(), proxyRule.getCookieDomain()); httpServletResponse.setHeader(header.getName(), setCookie); } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } } // check if we got data, that is either the Content-Length > 0 // or the response code != 204 int code = httpMethodProxyRequest.getStatusCode(); boolean noData = code == HttpStatus.SC_NO_CONTENT; if (!noData) { String length = httpServletRequest.getHeader(STRING_CONTENT_LENGTH_HEADER_NAME); if (length != null && "0".equals(length.trim())) { noData = true; } } if (!noData) { // Send the content to the client InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); int intNextByte; while ((intNextByte = bufferedInputStream.read()) != -1) { outputStreamClientResponse.write(intNextByte); } } }