1 package be
.nikiroo
.utils
;
3 import java
.net
.Authenticator
;
4 import java
.net
.PasswordAuthentication
;
7 * Simple proxy helper to select a default internet proxy.
13 * Use the proxy described by this string:
15 * <li><tt>((user(:pass)@)proxy:port)</tt></li>
16 * <li>System proxy is noted <tt>:</tt></li>
20 * <li><tt></tt> → do not use any proxy</li>
21 * <li><tt>:</tt> → use the system proxy</li>
22 * <li><tt>user@prox.com</tt> → use the proxy "prox.com" with default port
23 * and user "user"</li>
24 * <li><tt>prox.com:8080</tt> → use the proxy "prox.com" on port 8080</li>
25 * <li><tt>user:pass@prox.com:8080</tt> → use "prox.com" on port 8080
26 * authenticated as "user" with password "pass"</li>
27 * <li><tt>user:pass@:</tt> → use the system proxy authenticated as user
28 * "user" with password "pass"</li>
34 static public void use(String proxy
) {
35 if (proxy
!= null && !proxy
.isEmpty()) {
37 String password
= null;
40 if (proxy
.contains("@")) {
41 int pos
= proxy
.indexOf("@");
42 user
= proxy
.substring(0, pos
);
43 proxy
= proxy
.substring(pos
+ 1);
44 if (user
.contains(":")) {
45 pos
= user
.indexOf(":");
46 password
= user
.substring(pos
+ 1);
47 user
= user
.substring(0, pos
);
51 if (proxy
.equals(":")) {
53 } else if (proxy
.contains(":")) {
54 int pos
= proxy
.indexOf(":");
56 port
= Integer
.parseInt(proxy
.substring(0, pos
));
57 proxy
= proxy
.substring(pos
+ 1);
58 } catch (Exception e
) {
63 Proxy
.useSystemProxy(user
, password
);
65 Proxy
.useProxy(proxy
, port
, user
, password
);
71 * Use the system proxy.
73 static public void useSystemProxy() {
74 useSystemProxy(null, null);
78 * Use the system proxy with the given login/password, for authenticated
82 * the user name or login
86 static public void useSystemProxy(String user
, String password
) {
87 System
.setProperty("java.net.useSystemProxies", "true");
95 * the proxy host name or IP address
99 static public void useProxy(String host
, int port
) {
100 useProxy(host
, port
, null, null);
104 * Use the given proxy with the given login/password, for authenticated
108 * the user name or login
112 * the proxy host name or IP address
116 * the user name or login
120 static public void useProxy(String host
, int port
, String user
,
122 System
.setProperty("http.proxyHost", host
);
123 System
.setProperty("http.proxyPort", Integer
.toString(port
));
124 auth(user
, password
);
128 * Select the default authenticator for proxy requests.
131 * the user name or login
135 static private void auth(final String user
, final String password
) {
136 if (user
!= null && password
!= null) {
137 Authenticator proxy
= new Authenticator() {
139 protected PasswordAuthentication
getPasswordAuthentication() {
140 if (getRequestorType() == RequestorType
.PROXY
) {
141 return new PasswordAuthentication(user
,
142 password
.toCharArray());
147 Authenticator
.setDefault(proxy
);