1 package com.atlassian.httpclient.apache.httpcomponents.proxy;
2
3 import com.atlassian.fugue.Option;
4 import com.atlassian.fugue.Options;
5 import com.google.common.collect.Iterables;
6 import com.google.common.collect.Lists;
7 import org.apache.commons.lang3.StringUtils;
8 import org.apache.http.HttpHost;
9 import org.apache.http.auth.AuthScope;
10 import org.apache.http.auth.Credentials;
11 import org.apache.http.auth.NTCredentials;
12 import org.apache.http.auth.UsernamePasswordCredentials;
13
14 import java.net.ProxySelector;
15
16
17
18
19 @SuppressWarnings("StaticPseudoFunctionalStyleMethod")
20 public class SystemPropertiesProxyConfig extends ProxyConfig {
21 private static final Iterable<String> SUPPORTED_SCHEMAS = Lists.newArrayList("http", "https");
22
23 Iterable<HttpHost> getProxyHosts() {
24 return Options.flatten(Options.filterNone(
25 Iterables.transform(SUPPORTED_SCHEMAS, SystemPropertiesProxyConfig::getProxy)));
26 }
27
28 @SuppressWarnings("ConstantConditions")
29 @Override
30 public Iterable<AuthenticationInfo> getAuthenticationInfo() {
31 return Iterables.transform(getProxyHosts(), httpHost -> {
32 final AuthScope authScope = new AuthScope(httpHost);
33 final Option<Credentials> credentials = credentialsForScheme(httpHost.getSchemeName());
34 return new AuthenticationInfo(authScope, credentials);
35 });
36 }
37
38 @Override
39 public ProxySelector toProxySelector() {
40
41 return ProxySelector.getDefault();
42 }
43
44 private static Option<HttpHost> getProxy(final String schemeName) {
45 String proxyHost = System.getProperty(schemeName + ".proxyHost");
46 if (proxyHost != null) {
47 return Option.some(new HttpHost(proxyHost, Integer.parseInt(System.getProperty(schemeName + ".proxyPort")), schemeName));
48 } else {
49 return Option.none();
50 }
51 }
52
53 private static Option<Credentials> credentialsForScheme(final String schemeName) {
54 final String username = System.getProperty(schemeName + ".proxyUser");
55 if (username != null) {
56 final String proxyPassword = System.getProperty(schemeName + ".proxyPassword");
57 final String proxyAuth = System.getProperty(schemeName + ".proxyAuth");
58 if (proxyAuth == null || proxyAuth.equalsIgnoreCase("basic")) {
59 return Option.<Credentials>some(new UsernamePasswordCredentials(username, proxyPassword));
60 } else if (proxyAuth.equalsIgnoreCase("digest") || proxyAuth.equalsIgnoreCase("ntlm")) {
61 String ntlmDomain = System.getProperty(schemeName + ".proxyNtlmDomain");
62 String ntlmWorkstation = System.getProperty(schemeName + ".proxyNtlmWorkstation");
63 return Option.<Credentials>some(new NTCredentials(username, proxyPassword,
64 StringUtils.defaultString(ntlmWorkstation), StringUtils.defaultString(ntlmDomain)));
65 } else {
66 return Option.none();
67 }
68 } else {
69 return Option.none();
70 }
71 }
72
73 }