View Javadoc

1   package com.atlassian.sal.core.net;
2   
3   import java.net.URI;
4   
5   import org.apache.commons.httpclient.HostConfiguration;
6   import org.apache.commons.httpclient.HttpClient;
7   import org.apache.commons.httpclient.HttpsURL;
8   import org.apache.commons.httpclient.protocol.Protocol;
9   
10  class HttpClientProtocolConfig
11  {
12      /**
13       * Configures httpClient to use the default SSL protocols for the given url
14       *
15       * @param httpClient httpClient to configure
16       * @param url url to use the protocols with
17       */
18      static void configureProtocol(final HttpClient httpClient, final String url)
19      {
20          changeHostConfigurationProtocol(httpClient, url, CustomSSLProtocolSocketFactory.DEFAULT_PROTOCOLS);
21      }
22  
23      /**
24       * Change httpClient protocol configuration to use different ssl protocols.
25       * The httpClient must have been configured before using the configureProtocol method.
26       *
27       * @param httpClient httpClient to configure
28       * @param sslProtocols url to use the protocols with
29       */
30      static void changeHostConfigurationProtocol(final HttpClient httpClient, final String sslProtocols)
31      {
32          final HostConfiguration hostConfiguration = httpClient.getHostConfiguration();
33  
34          String host = hostConfiguration.getHost();
35          int port = hostConfiguration.getPort();
36          String scheme = hostConfiguration.getProtocol().getScheme();
37  
38          changeHostConfigurationProtocol(hostConfiguration, host, port, scheme, sslProtocols);
39      }
40  
41      private static void changeHostConfigurationProtocol(final HttpClient httpClient, final String remoteUrl, final String sslProtocols)
42      {
43          URI url = URI.create(remoteUrl);
44          String host = url.getHost();
45          int port = url.getPort();
46          String scheme = url.getScheme();
47  
48          changeHostConfigurationProtocol(httpClient.getHostConfiguration(), host, port, scheme, sslProtocols);
49      }
50  
51      private static void changeHostConfigurationProtocol(HostConfiguration hostConfiguration, String host, int port, String scheme, String sslProtocols)
52      {
53          if ("https".equals(scheme))
54          {
55              Protocol customHttpsProtocol = new Protocol("https", new CustomSSLProtocolSocketFactory(sslProtocols), HttpsURL.DEFAULT_PORT);
56              hostConfiguration.setHost(host, port, customHttpsProtocol);
57          } else
58          {
59              hostConfiguration.setHost(host, port);
60          }
61      }
62  }