Example usage for org.apache.commons.httpclient HttpClient getParams

List of usage examples for org.apache.commons.httpclient HttpClient getParams

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient getParams.

Prototype

public HttpClientParams getParams() 

Source Link

Usage

From source file:org.jetbrains.plugins.github.api.GithubApiUtil.java

@NotNull
private static HttpClient getHttpClient(@Nullable GithubAuthData.BasicAuth basicAuth, boolean useProxy) {
    final HttpClient client = new HttpClient();
    HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
    params.setConnectionTimeout(CONNECTION_TIMEOUT); //set connection timeout (how long it takes to connect to
    // remote host)
    params.setSoTimeout(CONNECTION_TIMEOUT); //set socket timeout (how long it takes to retrieve data from remote
    // host)/*w  ww .java2  s.c  o m*/

    client.getParams().setContentCharset("UTF-8");
    // Configure proxySettings if it is required
    final HttpConfigurable proxySettings = HttpConfigurable.getInstance();
    if (useProxy && proxySettings.USE_HTTP_PROXY && !StringUtil.isEmptyOrSpaces(proxySettings.PROXY_HOST)) {
        client.getHostConfiguration().setProxy(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT);
        if (proxySettings.PROXY_AUTHENTICATION) {
            client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    proxySettings.getProxyLogin(), proxySettings.getPlainProxyPassword()));
        }
    }
    if (basicAuth != null) {
        client.getParams().setCredentialCharset("UTF-8");
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(basicAuth.getLogin(), basicAuth.getPassword()));
    }
    return client;
}

From source file:org.jetbrains.tfsIntegration.webservice.WebServiceHelper.java

private static void setupHttpClient(Credentials credentials, URI serverUri, HttpClient httpClient) {
    setCredentials(httpClient, credentials, serverUri);
    setProxy(httpClient);// w ww. j a va  2 s  .  c  o m
    httpClient.getParams().setSoTimeout(SOCKET_TIMEOUT);
    if (Registry.is("tfs.set.connection.timeout", false)) {
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(SOCKET_TIMEOUT);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(SOCKET_TIMEOUT);
    }
}

From source file:org.jetbrains.tfsIntegration.webservice.WebServiceHelper.java

private static void setCredentials(final @NotNull HttpClient httpClient, final @NotNull Credentials credentials,
        final @NotNull URI serverUri) {
    if (credentials.getType() == Credentials.Type.Alternate) {
        HostParams parameters = httpClient.getHostConfiguration().getParams();
        Collection<Header> headers = (Collection<Header>) parameters.getParameter(HostParams.DEFAULT_HEADERS);

        if (headers == null) {
            headers = new ArrayList<Header>();
            parameters.setParameter(HostParams.DEFAULT_HEADERS, headers);
        }/*from www .  j a  va 2 s. co m*/

        Header authHeader = ContainerUtil.find(headers, new Condition<Header>() {
            @Override
            public boolean value(Header header) {
                return header.getName().equals(HTTPConstants.HEADER_AUTHORIZATION);
            }
        });

        if (authHeader == null) {
            authHeader = new Header(HTTPConstants.HEADER_AUTHORIZATION, "");
            headers.add(authHeader);
        }

        authHeader.setValue(BasicScheme.authenticate(
                new UsernamePasswordCredentials(credentials.getUserName(), credentials.getPassword()),
                "UTF-8"));
    } else {
        final NTCredentials ntCreds = new NTCredentials(credentials.getUserName(), credentials.getPassword(),
                serverUri.getHost(), credentials.getDomain());
        httpClient.getState().setCredentials(AuthScope.ANY, ntCreds);
        httpClient.getParams().setBooleanParameter(USE_NATIVE_CREDENTIALS,
                credentials.getType() == Credentials.Type.NtlmNative);
    }
}

From source file:org.jivesoftware.community.http.impl.HttpClientManagerImpl.java

public HttpClient getClient(URL url,
        com.sun.syndication.fetcher.impl.HttpClientFeedFetcher.CredentialSupplier credentialSupplier,
        int timeout) {
    HttpClient client = new HttpClient();
    HttpConnectionManager conManager = client.getHttpConnectionManager();

    if (JiveGlobals.getProperty("http.proxyHost") != null
            && JiveGlobals.getProperty("http.proxyPort") != null) {
        client.getHostConfiguration().setProxy(JiveGlobals.getProperty("http.proxyHost"),
                Integer.parseInt(JiveGlobals.getProperty("http.proxyPort")));
        if (JiveGlobals.getProperty("http.proxyUsername") != null
                && JiveGlobals.getProperty("http.proxyPassword") != null) {
            HttpState state = new HttpState();
            state.setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(JiveGlobals.getProperty("http.proxyUserName"),
                            JiveGlobals.getProperty("http.proxyPassword")));
            client.setState(state);//from  ww  w.ja v a 2  s.c o  m
        }
    }
    if (timeout > 0) {
        conManager.getParams().setParameter("http.connection.timeout", Integer.valueOf(timeout));
        conManager.getParams().setParameter("http.socket.timeout", Integer.valueOf(timeout));
    }
    if (isHTTPS(url)) {
        int port = url.getPort() <= -1 ? 443 : url.getPort();
        Protocol myhttps = new Protocol("https", new DummySSLSocketFactory(), port);
        Protocol.registerProtocol("https", myhttps);
        client.getHostConfiguration().setHost(url.getHost(), port, myhttps);
    } else {
        int port = url.getPort() <= -1 ? 80 : url.getPort();
        client.getHostConfiguration().setHost(url.getHost(), port);
    }
    if (url.getUserInfo() != null && credentialSupplier == null)
        credentialSupplier = new BasicAuthCredentials(url.getUserInfo());

    if (credentialSupplier != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(new AuthScope(url.getHost(), -1, AuthScope.ANY_REALM),
                credentialSupplier.getCredentials(null, url.getHost()));
    }
    return client;
}

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 w  w w. j a va2  s.  c  om
 * 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.openfire.crowd.CrowdManager.java

private CrowdManager() {
    try {//from w w w.ja v  a2 s .co m
        // loading crowd.properties file
        CrowdProperties crowdProps = new CrowdProperties();

        MultiThreadedHttpConnectionManager threadedConnectionManager = new MultiThreadedHttpConnectionManager();
        HttpClient hc = new HttpClient(threadedConnectionManager);

        HttpClientParams hcParams = hc.getParams();
        hcParams.setAuthenticationPreemptive(true);

        HttpConnectionManagerParams hcConnectionParams = hc.getHttpConnectionManager().getParams();
        hcConnectionParams.setDefaultMaxConnectionsPerHost(crowdProps.getHttpMaxConnections());
        hcConnectionParams.setMaxTotalConnections(crowdProps.getHttpMaxConnections());
        hcConnectionParams.setConnectionTimeout(crowdProps.getHttpConnectionTimeout());
        hcConnectionParams.setSoTimeout(crowdProps.getHttpSocketTimeout());

        crowdServer = new URI(crowdProps.getCrowdServerUrl()).resolve("rest/usermanagement/latest/");

        // setting BASIC authentication in place for connection with Crowd
        HttpState httpState = hc.getState();
        Credentials crowdCreds = new UsernamePasswordCredentials(crowdProps.getApplicationName(),
                crowdProps.getApplicationPassword());
        httpState.setCredentials(new AuthScope(crowdServer.getHost(), crowdServer.getPort()), crowdCreds);

        // setting Proxy config in place if needed
        if (StringUtils.isNotBlank(crowdProps.getHttpProxyHost()) && crowdProps.getHttpProxyPort() > 0) {
            hc.getHostConfiguration().setProxy(crowdProps.getHttpProxyHost(), crowdProps.getHttpProxyPort());

            if (StringUtils.isNotBlank(crowdProps.getHttpProxyUsername())
                    || StringUtils.isNotBlank(crowdProps.getHttpProxyPassword())) {
                Credentials proxyCreds = new UsernamePasswordCredentials(crowdProps.getHttpProxyUsername(),
                        crowdProps.getHttpProxyPassword());
                httpState.setProxyCredentials(
                        new AuthScope(crowdProps.getHttpProxyHost(), crowdProps.getHttpProxyPort()),
                        proxyCreds);
            }
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("HTTP Client config");
            LOG.debug(crowdServer.toString());
            LOG.debug("Max connections:" + hcConnectionParams.getMaxTotalConnections());
            LOG.debug("Socket timeout:" + hcConnectionParams.getSoTimeout());
            LOG.debug("Connect timeout:" + hcConnectionParams.getConnectionTimeout());
            LOG.debug("Proxy host:" + crowdProps.getHttpProxyHost() + ":" + crowdProps.getHttpProxyPort());
            LOG.debug("Crowd application name:" + crowdProps.getApplicationName());
        }

        client = hc;
    } catch (Exception e) {
        LOG.error("Failure to load the Crowd manager", e);
    }
}

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
 *///w  w  w. jav  a  2  s.c om
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 ww  .j a  v  a  2s.  co 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//from  w  w  w . ja  v a  2  s .  c  om
 * @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/*from  ww  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;
}