List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection
public abstract void releaseConnection();
From source file:org.jboss.web.loadbalancer.Loadbalancer.java
protected void handleRequest(HttpServletRequest request, HttpServletResponse response, HttpMethod method) throws ServletException, IOException { boolean reschedule = false; try {/* ww w . j a v a 2 s . c o m*/ HttpClient client = prepareServerRequest(request, response, method); int tries = 0; while (tries < MAX_RETRIES) { try { client.executeMethod(method); break; } catch (IOException ex) { try { method.releaseConnection(); } catch (Exception e) { //ignore } tries++; log.info("Connect retry no. " + tries); if (log.isDebugEnabled()) log.debug(ex); } } if (tries < MAX_RETRIES) { parseServerResponse(request, response, client, method); } else { log.error("Max retries reached - giving up. Host will be marked down"); // Inform Scheduler of node problems scheduler.setNodeDown(request, response, client, method); reschedule = true; } } finally { try { method.releaseConnection(); } catch (Exception e) { //ignore } } // try again? if (reschedule) { String redirectURI = request.getRequestURI(); if (request.getQueryString() != null) { redirectURI += "?" + request.getQueryString(); } response.sendRedirect(redirectURI); } }
From source file:org.jbpm.process.workitem.rest.RESTWorkItemHandler.java
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { // extract required parameters String urlStr = (String) workItem.getParameter("Url"); String method = (String) workItem.getParameter("Method"); if (urlStr == null) { throw new IllegalArgumentException("Url is a required parameter"); }/*from w w w . ja v a 2 s. com*/ if (method == null || method.trim().length() == 0) { method = "GET"; } Map<String, Object> params = workItem.getParameters(); // optional timeout config parameters, defaulted to 60 seconds Integer connectTimeout = (Integer) params.get("ConnectTimeout"); if (connectTimeout == null) connectTimeout = 60000; Integer readTimeout = (Integer) params.get("ReadTimeout"); if (readTimeout == null) readTimeout = 60000; HttpClient httpclient = new HttpClient(); httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectTimeout); httpclient.getHttpConnectionManager().getParams().setSoTimeout(readTimeout); HttpMethod theMethod = null; if ("GET".equals(method)) { theMethod = new GetMethod(urlStr); } else if ("POST".equals(method)) { theMethod = new PostMethod(urlStr); setBody(theMethod, params); } else if ("PUT".equals(method)) { theMethod = new PutMethod(urlStr); setBody(theMethod, params); } else if ("DELETE".equals(method)) { theMethod = new DeleteMethod(urlStr); } else { throw new IllegalArgumentException("Method " + method + " is not supported"); } doAuthorization(httpclient, theMethod, params); try { int responseCode = httpclient.executeMethod(theMethod); Map<String, Object> results = new HashMap<String, Object>(); if (responseCode >= 200 && responseCode < 300) { theMethod.getResponseBody(); postProcessResult(theMethod.getResponseBodyAsString(), results); results.put("StatusMsg", "request to endpoint " + urlStr + " successfully completed " + theMethod.getStatusText()); } else { logger.warn("Unsuccessful response from REST server (status {}, endpoint {}, response {}", responseCode, urlStr, theMethod.getResponseBodyAsString()); results.put("StatusMsg", "endpoint " + urlStr + " could not be reached: " + theMethod.getResponseBodyAsString()); } results.put("Status", responseCode); // notify manager that work item has been completed manager.completeWorkItem(workItem.getId(), results); } catch (Exception e) { handleException(e); } finally { theMethod.releaseConnection(); } }
From source file:org.jbpm.process.workitem.rest.RESTWorkItemHandler.java
protected void doAuthorization(HttpClient httpclient, HttpMethod method, Map<String, Object> params) { if (type == null) { return;/* w w w . j av a 2 s . com*/ } String u = (String) params.get("Username"); String p = (String) params.get("Password"); if (u == null || p == null) { u = this.username; p = this.password; } if (u == null) { throw new IllegalArgumentException("Could not find username"); } if (p == null) { throw new IllegalArgumentException("Could not find password"); } if (type == AuthenticationType.BASIC) { httpclient.getState().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials(u, p)); method.setDoAuthentication(true); } else if (type == AuthenticationType.FORM_BASED) { String authUrlStr = (String) params.get("AuthUrl"); if (authUrlStr == null) { authUrlStr = authUrl; } if (authUrlStr == null) { throw new IllegalArgumentException("Could not find authentication url"); } try { httpclient.executeMethod(method); } catch (IOException e) { throw new RuntimeException("Could not execute request for form-based authentication", e); } finally { method.releaseConnection(); } PostMethod authMethod = new PostMethod(authUrlStr); NameValuePair[] data = { new NameValuePair("j_username", u), new NameValuePair("j_password", p) }; authMethod.setRequestBody(data); try { httpclient.executeMethod(authMethod); } catch (IOException e) { throw new RuntimeException("Could not initialize form-based authentication", e); } finally { authMethod.releaseConnection(); } } else { throw new RuntimeException("Unknown AuthenticationType " + type); } }
From source file:org.jetbrains.tfsIntegration.webservice.WebServiceHelper.java
public static void httpGet(final URI serverUri, final String downloadUrl, final OutputStream outputStream, Credentials credentials, final HttpClient httpClient) throws TfsException, IOException { TFSVcs.assertTrue(downloadUrl != null); setupHttpClient(credentials, serverUri, httpClient); HttpMethod method = new GetMethod(downloadUrl); try {/*from w ww. ja va 2 s . c o m*/ int statusCode = httpClient.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { StreamUtil.copyStreamContent(getInputStream(method), outputStream); } else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) { throw new OperationFailedException(method.getResponseBodyAsString()); } else { throw TfsExceptionManager.createHttpTransportErrorException(statusCode, null); } } finally { // enforce connection release since GZipInputStream may not trigger underlying AutoCloseInputStream.close() method.releaseConnection(); } }
From source file:org.jivesoftware.openfire.clearspace.ClearspaceManager.java
/** * Makes a rest request of any type at the specified urlSuffix. The urlSuffix should be of the * form /userService/users./*from ww w. j a va 2 s . c o m*/ * If CS throws an exception it handled and transalated to a Openfire exception if possible. * This is done using the check fault method that tries to throw the best maching exception. * * @param type Must be GET or DELETE * @param urlSuffix The url suffix of the rest request * @param xmlParams The xml with the request params, must be null if type is GET or DELETE only * @return The response as a xml doc. * @throws ConnectionException Thrown if there are issues perfoming the request. * @throws Exception Thrown if the response from Clearspace contains an exception. */ public Element executeRequest(HttpType type, String urlSuffix, String xmlParams) throws ConnectionException, Exception { if (Log.isDebugEnabled()) { Log.debug("Outgoing REST call [" + type + "] to " + urlSuffix + ": " + xmlParams); } String wsUrl = getConnectionURI() + WEBSERVICES_PATH + urlSuffix; String secret = getSharedSecret(); HttpClient client = new HttpClient(); HttpMethod method; // Configures the authentication client.getParams().setAuthenticationPreemptive(true); Credentials credentials = new UsernamePasswordCredentials(OPENFIRE_USERNAME, secret); AuthScope scope = new AuthScope(host, port, AuthScope.ANY_REALM); client.getState().setCredentials(scope, credentials); // Creates the method switch (type) { case GET: method = new GetMethod(wsUrl); break; case POST: PostMethod pm = new PostMethod(wsUrl); StringRequestEntity requestEntity = new StringRequestEntity(xmlParams); pm.setRequestEntity(requestEntity); method = pm; break; case PUT: PutMethod pm1 = new PutMethod(wsUrl); StringRequestEntity requestEntity1 = new StringRequestEntity(xmlParams); pm1.setRequestEntity(requestEntity1); method = pm1; break; case DELETE: method = new DeleteMethod(wsUrl); break; default: throw new IllegalArgumentException(); } method.setRequestHeader("Accept", "text/xml"); method.setDoAuthentication(true); try { // Executes the request client.executeMethod(method); // Parses the result String body = method.getResponseBodyAsString(); if (Log.isDebugEnabled()) { Log.debug("Outgoing REST call results: " + body); } // Checks the http status if (method.getStatusCode() != 200) { if (method.getStatusCode() == 401) { throw new ConnectionException("Invalid password to connect to Clearspace.", ConnectionException.ErrorType.AUTHENTICATION); } else if (method.getStatusCode() == 404) { throw new ConnectionException("Web service not found in Clearspace.", ConnectionException.ErrorType.PAGE_NOT_FOUND); } else if (method.getStatusCode() == 503) { throw new ConnectionException("Web service not avaible in Clearspace.", ConnectionException.ErrorType.SERVICE_NOT_AVAIBLE); } else { throw new ConnectionException( "Error connecting to Clearspace, http status code: " + method.getStatusCode(), new HTTPConnectionException(method.getStatusCode()), ConnectionException.ErrorType.OTHER); } } else if (body.contains("Clearspace Upgrade Console")) { //TODO Change CS to send a more standard error message throw new ConnectionException("Clearspace is in an update state.", ConnectionException.ErrorType.UPDATE_STATE); } Element response = localParser.get().parseDocument(body).getRootElement(); // Check for exceptions checkFault(response); // Since there is no exception, returns the response return response; } catch (DocumentException e) { throw new ConnectionException("Error parsing the response of Clearspace.", e, ConnectionException.ErrorType.OTHER); } catch (HttpException e) { throw new ConnectionException("Error performing http request to Clearspace", e, ConnectionException.ErrorType.OTHER); } catch (UnknownHostException e) { throw new ConnectionException("Unknown Host " + getConnectionURI() + " trying to connect to Clearspace", e, ConnectionException.ErrorType.UNKNOWN_HOST); } catch (IOException e) { throw new ConnectionException("Error peforming http request to Clearspace.", e, ConnectionException.ErrorType.OTHER); } finally { method.releaseConnection(); } }
From source file:org.jivesoftware.util.HttpClientWithTimeoutFeedFetcher.java
/** * @see com.sun.syndication.fetcher.FeedFetcher#retrieveFeed(java.net.URL) *///from w w w . j a v a 2 s.c o m public SyndFeed retrieveFeed(URL feedUrl) throws IllegalArgumentException, IOException, FeedException, FetcherException { if (feedUrl == null) { throw new IllegalArgumentException("null is not a valid URL"); } // TODO Fix this //System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); HttpClient client = new HttpClient(); HttpConnectionManager conManager = client.getHttpConnectionManager(); conManager.getParams().setParameter("http.connection.timeout", 3000); conManager.getParams().setParameter("http.socket.timeout", 3000); if (getCredentialSupplier() != null) { client.getState().setAuthenticationPreemptive(true); // TODO what should realm be here? Credentials credentials = getCredentialSupplier().getCredentials(null, feedUrl.getHost()); if (credentials != null) { client.getState().setCredentials(null, feedUrl.getHost(), credentials); } } System.setProperty("httpclient.useragent", "Openfire Admin Console: v" + XMPPServer.getInstance().getServerInfo().getVersion().getVersionString()); String urlStr = feedUrl.toString(); FeedFetcherCache cache = getFeedInfoCache(); if (cache != null) { // retrieve feed HttpMethod method = new GetMethod(urlStr); method.addRequestHeader("Accept-Encoding", "gzip"); try { if (isUsingDeltaEncoding()) { method.setRequestHeader("A-IM", "feed"); } // get the feed info from the cache // Note that syndFeedInfo will be null if it is not in the cache SyndFeedInfo syndFeedInfo = cache.getFeedInfo(feedUrl); if (syndFeedInfo != null) { method.setRequestHeader("If-None-Match", syndFeedInfo.getETag()); if (syndFeedInfo.getLastModified() instanceof String) { method.setRequestHeader("If-Modified-Since", (String) syndFeedInfo.getLastModified()); } } method.setFollowRedirects(true); int statusCode = client.executeMethod(method); fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr); handleErrorCodes(statusCode); SyndFeed feed = getFeed(syndFeedInfo, urlStr, method, statusCode); syndFeedInfo = buildSyndFeedInfo(feedUrl, urlStr, method, feed, statusCode); cache.setFeedInfo(new URL(urlStr), syndFeedInfo); // the feed may have been modified to pick up cached values // (eg - for delta encoding) feed = syndFeedInfo.getSyndFeed(); return feed; } finally { method.releaseConnection(); } } else { // cache is not in use HttpMethod method = new GetMethod(urlStr); try { method.setFollowRedirects(true); int statusCode = client.executeMethod(method); fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr); handleErrorCodes(statusCode); return getFeed(null, urlStr, method, statusCode); } finally { method.releaseConnection(); } } }
From source file:org.josso.gl2.gateway.reverseproxy.ReverseProxyValve.java
/** * Intercepts Http request and redirects it to the configured SSO partner application. * * @param request The servlet request to be processed * @param response The servlet response to be created * @exception IOException if an input/output error occurs * @exception javax.servlet.ServletException if a servlet error occurs *//*from w ww . j a va2 s. c o m*/ public int invoke(Request request, Response response) throws IOException, ServletException { if (debug >= 1) log("ReverseProxyValve Acting."); ProxyContextConfig[] contexts = _rpc.getProxyContexts(); // Create an instance of HttpClient. HttpClient client = new HttpClient(); HttpServletRequest hsr = (HttpServletRequest) request.getRequest(); String uri = hsr.getRequestURI(); String uriContext = null; StringTokenizer st = new StringTokenizer(uri.substring(1), "/"); while (st.hasMoreTokens()) { String token = st.nextToken(); uriContext = "/" + token; break; } if (uriContext == null) uriContext = uri; // Obtain the target host from the String proxyForwardHost = null; String proxyForwardUri = null; for (int i = 0; i < contexts.length; i++) { if (contexts[i].getContext().equals(uriContext)) { log("Proxy context mapped to host/uri: " + contexts[i].getForwardHost() + contexts[i].getForwardUri()); proxyForwardHost = contexts[i].getForwardHost(); proxyForwardUri = contexts[i].getForwardUri(); break; } } if (proxyForwardHost == null) { log("URI '" + uri + "' can't be mapped to host"); //valveContext.invokeNext(request, response); return Valve.INVOKE_NEXT; } if (proxyForwardUri == null) { // trim the uri context before submitting the http request int uriTrailStartPos = uri.substring(1).indexOf("/") + 1; proxyForwardUri = uri.substring(uriTrailStartPos); } else { int uriTrailStartPos = uri.substring(1).indexOf("/") + 1; proxyForwardUri = proxyForwardUri + uri.substring(uriTrailStartPos); } // log ("Proxy request mapped to " + "http://" + proxyForwardHost + proxyForwardUri); HttpMethod method; // to be moved to a builder which instantiates and build concrete methods. if (hsr.getMethod().equals(METHOD_GET)) { // Create a method instance. HttpMethod getMethod = new GetMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); method = getMethod; } else if (hsr.getMethod().equals(METHOD_POST)) { // Create a method instance. PostMethod postMethod = new PostMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); postMethod.setRequestBody(hsr.getInputStream()); method = postMethod; } else if (hsr.getMethod().equals(METHOD_HEAD)) { // Create a method instance. HeadMethod headMethod = new HeadMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); method = headMethod; } else if (hsr.getMethod().equals(METHOD_PUT)) { method = new PutMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); } else throw new java.lang.UnsupportedOperationException("Unknown method : " + hsr.getMethod()); // copy incoming http headers to reverse proxy request Enumeration hne = hsr.getHeaderNames(); while (hne.hasMoreElements()) { String hn = (String) hne.nextElement(); // Map the received host header to the target host name // so that the configured virtual domain can // do the proper handling. if (hn.equalsIgnoreCase("host")) { method.addRequestHeader("Host", proxyForwardHost); continue; } Enumeration hvals = hsr.getHeaders(hn); while (hvals.hasMoreElements()) { String hv = (String) hvals.nextElement(); method.addRequestHeader(hn, hv); } } // Add Reverse-Proxy-Host header String reverseProxyHost = getReverseProxyHost(request); method.addRequestHeader(Constants.JOSSO_REVERSE_PROXY_HEADER, reverseProxyHost); if (debug >= 1) log("Sending " + Constants.JOSSO_REVERSE_PROXY_HEADER + " " + reverseProxyHost); // DO NOT follow redirects ! method.setFollowRedirects(false); // By default the httpclient uses HTTP v1.1. We are downgrading it // to v1.0 so that the target server doesn't set a reply using chunked // transfer encoding which doesn't seem to be handled properly. // Check how to make chunked transfer encoding work. client.getParams().setVersion(new HttpVersion(1, 0)); // Execute the method. int statusCode = -1; try { // execute the method. statusCode = client.executeMethod(method); } catch (HttpRecoverableException e) { log("A recoverable exception occurred " + e.getMessage()); } catch (IOException e) { log("Failed to connect."); e.printStackTrace(); } // Check that we didn't run out of retries. if (statusCode == -1) { log("Failed to recover from exception."); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Release the connection. method.releaseConnection(); HttpServletResponse sres = (HttpServletResponse) response.getResponse(); // First thing to do is to copy status code to response, otherwise // catalina will do it as soon as we set a header or some other part of the response. sres.setStatus(method.getStatusCode()); // copy proxy response headers to client response Header[] responseHeaders = method.getResponseHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header responseHeader = responseHeaders[i]; String name = responseHeader.getName(); String value = responseHeader.getValue(); // Adjust the URL in the Location, Content-Location and URI headers on HTTP redirect responses // This is essential to avoid by-passing the reverse proxy because of HTTP redirects on the // backend servers which stay behind the reverse proxy switch (method.getStatusCode()) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_SEE_OTHER: case HttpStatus.SC_TEMPORARY_REDIRECT: if ("Location".equalsIgnoreCase(name) || "Content-Location".equalsIgnoreCase(name) || "URI".equalsIgnoreCase(name)) { // Check that this redirect must be adjusted. if (value.indexOf(proxyForwardHost) >= 0) { String trail = value.substring(proxyForwardHost.length()); value = getReverseProxyHost(request) + trail; if (debug >= 1) log("Adjusting redirect header to " + value); } } break; } //end of switch sres.addHeader(name, value); } // Sometimes this is null, when no body is returned ... if (responseBody != null && responseBody.length > 0) sres.getOutputStream().write(responseBody); sres.getOutputStream().flush(); if (debug >= 1) log("ReverseProxyValve finished."); return Valve.END_PIPELINE; }
From source file:org.josso.tc50.gateway.reverseproxy.ReverseProxyValve.java
/** * Intercepts Http request and redirects it to the configured SSO partner application. * * @param request The servlet request to be processed * @param response The servlet response to be created * @param valveContext The valve _context used to invoke the next valve * in the current processing pipeline/*from w w w .j a v a 2s. c o m*/ * @exception IOException if an input/output error occurs * @exception javax.servlet.ServletException if a servlet error occurs */ public void invoke(Request request, Response response, ValveContext valveContext) throws IOException, javax.servlet.ServletException { if (debug >= 1) log("ReverseProxyValve Acting."); ProxyContextConfig[] contexts = _rpc.getProxyContexts(); // Create an instance of HttpClient. HttpClient client = new HttpClient(); HttpServletRequest hsr = (HttpServletRequest) request.getRequest(); String uri = hsr.getRequestURI(); String uriContext = null; StringTokenizer st = new StringTokenizer(uri.substring(1), "/"); while (st.hasMoreTokens()) { String token = st.nextToken(); uriContext = "/" + token; break; } if (uriContext == null) uriContext = uri; // Obtain the target host from the String proxyForwardHost = null; String proxyForwardUri = null; for (int i = 0; i < contexts.length; i++) { if (contexts[i].getContext().equals(uriContext)) { log("Proxy context mapped to host/uri: " + contexts[i].getForwardHost() + contexts[i].getForwardUri()); proxyForwardHost = contexts[i].getForwardHost(); proxyForwardUri = contexts[i].getForwardUri(); break; } } if (proxyForwardHost == null) { log("URI '" + uri + "' can't be mapped to host"); valveContext.invokeNext(request, response); return; } if (proxyForwardUri == null) { // trim the uri context before submitting the http request int uriTrailStartPos = uri.substring(1).indexOf("/") + 1; proxyForwardUri = uri.substring(uriTrailStartPos); } else { int uriTrailStartPos = uri.substring(1).indexOf("/") + 1; proxyForwardUri = proxyForwardUri + uri.substring(uriTrailStartPos); } // log ("Proxy request mapped to " + "http://" + proxyForwardHost + proxyForwardUri); HttpMethod method; // to be moved to a builder which instantiates and build concrete methods. if (hsr.getMethod().equals(METHOD_GET)) { // Create a method instance. HttpMethod getMethod = new GetMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); method = getMethod; } else if (hsr.getMethod().equals(METHOD_POST)) { // Create a method instance. PostMethod postMethod = new PostMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); postMethod.setRequestBody(hsr.getInputStream()); method = postMethod; } else if (hsr.getMethod().equals(METHOD_HEAD)) { // Create a method instance. HeadMethod headMethod = new HeadMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); method = headMethod; } else if (hsr.getMethod().equals(METHOD_PUT)) { method = new PutMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); } else throw new java.lang.UnsupportedOperationException("Unknown method : " + hsr.getMethod()); // copy incoming http headers to reverse proxy request Enumeration hne = hsr.getHeaderNames(); while (hne.hasMoreElements()) { String hn = (String) hne.nextElement(); // Map the received host header to the target host name // so that the configured virtual domain can // do the proper handling. if (hn.equalsIgnoreCase("host")) { method.addRequestHeader("Host", proxyForwardHost); continue; } Enumeration hvals = hsr.getHeaders(hn); while (hvals.hasMoreElements()) { String hv = (String) hvals.nextElement(); method.addRequestHeader(hn, hv); } } // Add Reverse-Proxy-Host header String reverseProxyHost = getReverseProxyHost(request); method.addRequestHeader(Constants.JOSSO_REVERSE_PROXY_HEADER, reverseProxyHost); if (debug >= 1) log("Sending " + Constants.JOSSO_REVERSE_PROXY_HEADER + " " + reverseProxyHost); // DO NOT follow redirects ! method.setFollowRedirects(false); // By default the httpclient uses HTTP v1.1. We are downgrading it // to v1.0 so that the target server doesn't set a reply using chunked // transfer encoding which doesn't seem to be handled properly. // Check how to make chunked transfer encoding work. client.getParams().setVersion(new HttpVersion(1, 0)); // Execute the method. int statusCode = -1; try { // execute the method. statusCode = client.executeMethod(method); } catch (HttpRecoverableException e) { log("A recoverable exception occurred " + e.getMessage()); } catch (IOException e) { log("Failed to connect."); e.printStackTrace(); } // Check that we didn't run out of retries. if (statusCode == -1) { log("Failed to recover from exception."); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Release the connection. method.releaseConnection(); HttpServletResponse sres = (HttpServletResponse) response.getResponse(); // First thing to do is to copy status code to response, otherwise // catalina will do it as soon as we set a header or some other part of the response. sres.setStatus(method.getStatusCode()); // copy proxy response headers to client response Header[] responseHeaders = method.getResponseHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header responseHeader = responseHeaders[i]; String name = responseHeader.getName(); String value = responseHeader.getValue(); // Adjust the URL in the Location, Content-Location and URI headers on HTTP redirect responses // This is essential to avoid by-passing the reverse proxy because of HTTP redirects on the // backend servers which stay behind the reverse proxy switch (method.getStatusCode()) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_SEE_OTHER: case HttpStatus.SC_TEMPORARY_REDIRECT: if ("Location".equalsIgnoreCase(name) || "Content-Location".equalsIgnoreCase(name) || "URI".equalsIgnoreCase(name)) { // Check that this redirect must be adjusted. if (value.indexOf(proxyForwardHost) >= 0) { String trail = value.substring(proxyForwardHost.length()); value = getReverseProxyHost(request) + trail; if (debug >= 1) log("Adjusting redirect header to " + value); } } break; } //end of switch sres.addHeader(name, value); } // Sometimes this is null, when no body is returned ... if (responseBody != null && responseBody.length > 0) sres.getOutputStream().write(responseBody); sres.getOutputStream().flush(); if (debug >= 1) log("ReverseProxyValve finished."); return; }
From source file:org.josso.tc55.gateway.reverseproxy.ReverseProxyValve.java
/** * Intercepts Http request and redirects it to the configured SSO partner application. * * @param request The servlet request to be processed * @param response The servlet response to be created * in the current processing pipeline/* w w w. j a v a 2 s.com*/ * @exception IOException if an input/output error occurs * @exception javax.servlet.ServletException if a servlet error occurs */ public void invoke(Request request, Response response) throws IOException, javax.servlet.ServletException { if (container.getLogger().isDebugEnabled()) container.getLogger().debug("ReverseProxyValve Acting."); ProxyContextConfig[] contexts = _rpc.getProxyContexts(); // Create an instance of HttpClient. HttpClient client = new HttpClient(); HttpServletRequest hsr = (HttpServletRequest) request.getRequest(); String uri = hsr.getRequestURI(); String uriContext = null; StringTokenizer st = new StringTokenizer(uri.substring(1), "/"); while (st.hasMoreTokens()) { String token = st.nextToken(); uriContext = "/" + token; break; } if (uriContext == null) uriContext = uri; // Obtain the target host from the String proxyForwardHost = null; String proxyForwardUri = null; for (int i = 0; i < contexts.length; i++) { if (contexts[i].getContext().equals(uriContext)) { log("Proxy context mapped to host/uri: " + contexts[i].getForwardHost() + contexts[i].getForwardUri()); proxyForwardHost = contexts[i].getForwardHost(); proxyForwardUri = contexts[i].getForwardUri(); break; } } if (proxyForwardHost == null) { log("URI '" + uri + "' can't be mapped to host"); getNext().invoke(request, response); return; } if (proxyForwardUri == null) { // trim the uri context before submitting the http request int uriTrailStartPos = uri.substring(1).indexOf("/") + 1; proxyForwardUri = uri.substring(uriTrailStartPos); } else { int uriTrailStartPos = uri.substring(1).indexOf("/") + 1; proxyForwardUri = proxyForwardUri + uri.substring(uriTrailStartPos); } // log ("Proxy request mapped to " + "http://" + proxyForwardHost + proxyForwardUri); HttpMethod method; // to be moved to a builder which instantiates and build concrete methods. if (hsr.getMethod().equals(METHOD_GET)) { // Create a method instance. HttpMethod getMethod = new GetMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); method = getMethod; } else if (hsr.getMethod().equals(METHOD_POST)) { // Create a method instance. PostMethod postMethod = new PostMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); postMethod.setRequestBody(hsr.getInputStream()); method = postMethod; } else if (hsr.getMethod().equals(METHOD_HEAD)) { // Create a method instance. HeadMethod headMethod = new HeadMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); method = headMethod; } else if (hsr.getMethod().equals(METHOD_PUT)) { method = new PutMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); } else throw new java.lang.UnsupportedOperationException("Unknown method : " + hsr.getMethod()); // copy incoming http headers to reverse proxy request Enumeration hne = hsr.getHeaderNames(); while (hne.hasMoreElements()) { String hn = (String) hne.nextElement(); // Map the received host header to the target host name // so that the configured virtual domain can // do the proper handling. if (hn.equalsIgnoreCase("host")) { method.addRequestHeader("Host", proxyForwardHost); continue; } Enumeration hvals = hsr.getHeaders(hn); while (hvals.hasMoreElements()) { String hv = (String) hvals.nextElement(); method.addRequestHeader(hn, hv); } } // Add Reverse-Proxy-Host header String reverseProxyHost = getReverseProxyHost(request); method.addRequestHeader(Constants.JOSSO_REVERSE_PROXY_HEADER, reverseProxyHost); if (container.getLogger().isDebugEnabled()) container.getLogger().debug("Sending " + Constants.JOSSO_REVERSE_PROXY_HEADER + " " + reverseProxyHost); // DO NOT follow redirects ! method.setFollowRedirects(false); // By default the httpclient uses HTTP v1.1. We are downgrading it // to v1.0 so that the target server doesn't set a reply using chunked // transfer encoding which doesn't seem to be handled properly. // Check how to make chunked transfer encoding work. client.getParams().setVersion(new HttpVersion(1, 0)); // Execute the method. int statusCode = -1; try { // execute the method. statusCode = client.executeMethod(method); } catch (HttpRecoverableException e) { log("A recoverable exception occurred " + e.getMessage()); } catch (IOException e) { log("Failed to connect."); e.printStackTrace(); } // Check that we didn't run out of retries. if (statusCode == -1) { log("Failed to recover from exception."); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Release the connection. method.releaseConnection(); HttpServletResponse sres = (HttpServletResponse) response.getResponse(); // First thing to do is to copy status code to response, otherwise // catalina will do it as soon as we set a header or some other part of the response. sres.setStatus(method.getStatusCode()); // copy proxy response headers to client response Header[] responseHeaders = method.getResponseHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header responseHeader = responseHeaders[i]; String name = responseHeader.getName(); String value = responseHeader.getValue(); // Adjust the URL in the Location, Content-Location and URI headers on HTTP redirect responses // This is essential to avoid by-passing the reverse proxy because of HTTP redirects on the // backend servers which stay behind the reverse proxy switch (method.getStatusCode()) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_SEE_OTHER: case HttpStatus.SC_TEMPORARY_REDIRECT: if ("Location".equalsIgnoreCase(name) || "Content-Location".equalsIgnoreCase(name) || "URI".equalsIgnoreCase(name)) { // Check that this redirect must be adjusted. if (value.indexOf(proxyForwardHost) >= 0) { String trail = value.substring(proxyForwardHost.length()); value = getReverseProxyHost(request) + trail; if (container.getLogger().isDebugEnabled()) container.getLogger().debug("Adjusting redirect header to " + value); } } break; } //end of switch sres.addHeader(name, value); } // Sometimes this is null, when no body is returned ... if (responseBody != null && responseBody.length > 0) sres.getOutputStream().write(responseBody); sres.getOutputStream().flush(); if (container.getLogger().isDebugEnabled()) container.getLogger().debug("ReverseProxyValve finished."); return; }
From source file:org.josso.tc60.gateway.reverseproxy.ReverseProxyValve.java
/** * Intercepts Http request and redirects it to the configured SSO partner application. * * @param request The servlet request to be processed * @param response The servlet response to be created * in the current processing pipeline// w w w . j av a 2 s . c o m * @exception IOException if an input/output error occurs * @exception javax.servlet.ServletException if a servlet error occurs */ public void invoke(Request request, Response response) throws IOException, javax.servlet.ServletException { if (container.getLogger().isDebugEnabled()) container.getLogger().debug("ReverseProxyValve Acting."); ProxyContextConfig[] contexts = _rpc.getProxyContexts(); // Create an instance of HttpClient. HttpClient client = new HttpClient(); HttpServletRequest hsr = (HttpServletRequest) request.getRequest(); String uri = hsr.getRequestURI(); String uriContext = null; StringTokenizer st = new StringTokenizer(uri.substring(1), "/"); while (st.hasMoreTokens()) { String token = st.nextToken(); uriContext = "/" + token; break; } if (uriContext == null) uriContext = uri; // Obtain the target host from the String proxyForwardHost = null; String proxyForwardUri = null; for (int i = 0; i < contexts.length; i++) { if (contexts[i].getContext().equals(uriContext)) { log("Proxy context mapped to host/uri: " + contexts[i].getForwardHost() + contexts[i].getForwardUri()); proxyForwardHost = contexts[i].getForwardHost(); proxyForwardUri = contexts[i].getForwardUri(); break; } } if (proxyForwardHost == null) { log("URI '" + uri + "' can't be mapped to host"); getNext().invoke(request, response); return; } if (proxyForwardUri == null) { // trim the uri context before submitting the http request int uriTrailStartPos = uri.substring(1).indexOf("/") + 1; proxyForwardUri = uri.substring(uriTrailStartPos); } else { int uriTrailStartPos = uri.substring(1).indexOf("/") + 1; proxyForwardUri = proxyForwardUri + uri.substring(uriTrailStartPos); } // log ("Proxy request mapped to " + "http://" + proxyForwardHost + proxyForwardUri); HttpMethod method; // to be moved to a builder which instantiates and build concrete methods. if (hsr.getMethod().equals(METHOD_GET)) { // Create a method instance. HttpMethod getMethod = new GetMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); method = getMethod; } else if (hsr.getMethod().equals(METHOD_POST)) { // Create a method instance. PostMethod postMethod = new PostMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); postMethod.setRequestBody(hsr.getInputStream()); method = postMethod; } else if (hsr.getMethod().equals(METHOD_HEAD)) { // Create a method instance. HeadMethod headMethod = new HeadMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); method = headMethod; } else if (hsr.getMethod().equals(METHOD_PUT)) { method = new PutMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); } else throw new java.lang.UnsupportedOperationException("Unknown method : " + hsr.getMethod()); // copy incoming http headers to reverse proxy request Enumeration hne = hsr.getHeaderNames(); while (hne.hasMoreElements()) { String hn = (String) hne.nextElement(); // Map the received host header to the target host name // so that the configured virtual domain can // do the proper handling. if (hn.equalsIgnoreCase("host")) { method.addRequestHeader("Host", proxyForwardHost); continue; } Enumeration hvals = hsr.getHeaders(hn); while (hvals.hasMoreElements()) { String hv = (String) hvals.nextElement(); method.addRequestHeader(hn, hv); } } // Add Reverse-Proxy-Host header String reverseProxyHost = getReverseProxyHost(request); method.addRequestHeader(Constants.JOSSO_REVERSE_PROXY_HEADER, reverseProxyHost); if (container.getLogger().isDebugEnabled()) container.getLogger().debug("Sending " + Constants.JOSSO_REVERSE_PROXY_HEADER + " " + reverseProxyHost); // DO NOT follow redirects ! method.setFollowRedirects(false); // By default the httpclient uses HTTP v1.1. We are downgrading it // to v1.0 so that the target server doesn't set a reply using chunked // transfer encoding which doesn't seem to be handled properly. client.getParams().setVersion(new HttpVersion(1, 0)); // Execute the method. int statusCode = -1; try { // execute the method. statusCode = client.executeMethod(method); } catch (HttpRecoverableException e) { log("A recoverable exception occurred " + e.getMessage()); } catch (IOException e) { log("Failed to connect."); e.printStackTrace(); } // Check that we didn't run out of retries. if (statusCode == -1) { log("Failed to recover from exception."); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Release the connection. method.releaseConnection(); HttpServletResponse sres = (HttpServletResponse) response.getResponse(); // First thing to do is to copy status code to response, otherwise // catalina will do it as soon as we set a header or some other part of the response. sres.setStatus(method.getStatusCode()); // copy proxy response headers to client response Header[] responseHeaders = method.getResponseHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header responseHeader = responseHeaders[i]; String name = responseHeader.getName(); String value = responseHeader.getValue(); // Adjust the URL in the Location, Content-Location and URI headers on HTTP redirect responses // This is essential to avoid by-passing the reverse proxy because of HTTP redirects on the // backend servers which stay behind the reverse proxy switch (method.getStatusCode()) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_SEE_OTHER: case HttpStatus.SC_TEMPORARY_REDIRECT: if ("Location".equalsIgnoreCase(name) || "Content-Location".equalsIgnoreCase(name) || "URI".equalsIgnoreCase(name)) { // Check that this redirect must be adjusted. if (value.indexOf(proxyForwardHost) >= 0) { String trail = value.substring(proxyForwardHost.length()); value = getReverseProxyHost(request) + trail; if (container.getLogger().isDebugEnabled()) container.getLogger().debug("Adjusting redirect header to " + value); } } break; } //end of switch sres.addHeader(name, value); } // Sometimes this is null, when no body is returned ... if (responseBody != null && responseBody.length > 0) sres.getOutputStream().write(responseBody); sres.getOutputStream().flush(); if (container.getLogger().isDebugEnabled()) container.getLogger().debug("ReverseProxyValve finished."); return; }