1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package net.sf.urlchecker.communication.configurers;
21
22 import java.util.List;
23
24 import org.apache.commons.configuration.HierarchicalConfiguration;
25 import org.apache.commons.configuration.XMLConfiguration;
26 import org.apache.commons.httpclient.Credentials;
27 import org.apache.commons.httpclient.HttpClient;
28 import org.apache.commons.httpclient.UsernamePasswordCredentials;
29 import org.apache.commons.httpclient.auth.AuthScope;
30 import org.apache.log4j.Logger;
31
32
33
34
35
36
37
38
39
40
41
42
43
44 public class ClientConfigurer implements Configurer<HttpClient> {
45
46
47 private static final Logger LOGGER = Logger.getLogger(ClientConfigurer.class
48 .getName());
49
50
51
52
53
54
55
56
57
58 protected void configureHosts(final XMLConfiguration config,
59 final HttpClient client) {
60 if (config.containsKey("hosts.host")) {
61 final List<HierarchicalConfiguration> hosts = config
62 .configurationsAt("hosts.host");
63 if (null != hosts) {
64 LOGGER.debug("hosts:" + hosts.size());
65 for (final HierarchicalConfiguration host : hosts) {
66 final String username = host.getString("username", "admin");
67 final String password = host
68 .getString("password", "admin1");
69 final String hostName = host.getString("server",
70 "localhost");
71 final int port = host.getInt("port", 80);
72
73 final Credentials defaultcreds = new UsernamePasswordCredentials(
74 username, password);
75 client.getState().setCredentials(
76 new AuthScope(hostName, port, AuthScope.ANY_REALM),
77 defaultcreds);
78
79 }
80 }
81 }
82 }
83
84
85
86
87
88
89
90
91
92 protected void configurePreemptive(final XMLConfiguration config,
93 final HttpClient client) {
94
95 if (config.getBoolean("preemtive", false)) {
96 client.getParams().setAuthenticationPreemptive(true);
97 }
98 }
99
100
101
102
103
104
105
106
107
108 protected void configureProxy(final XMLConfiguration config,
109 final HttpClient client) {
110 if (config.containsKey("proxy")) {
111 final HierarchicalConfiguration proxy = config
112 .configurationAt("proxy");
113 if (null != proxy) {
114 final String username = proxy.getString("username", "admin");
115 final String password = proxy.getString("password", "admin1");
116 final String host = proxy.getString("server", "localhost");
117 final int port = proxy.getInt("port", 80);
118
119 final Credentials defaultcreds = new UsernamePasswordCredentials(
120 username, password);
121 client.getState().setProxyCredentials(
122 new AuthScope(host, port, AuthScope.ANY_REALM),
123 defaultcreds);
124 }
125 }
126 }
127
128
129
130
131
132
133
134
135
136 public HttpClient configureWith(XMLConfiguration config) {
137 final HttpClient subject = new HttpClient();
138 configurePreemptive(config, subject);
139 configureHosts(config, subject);
140 configureProxy(config, subject);
141 return subject;
142 }
143
144 }