merge with master
[fanfix.git] / src / be / nikiroo / utils / Proxy.java
1 package be.nikiroo.utils;
2
3 import java.net.Authenticator;
4 import java.net.PasswordAuthentication;
5
6 /**
7 * Simple proxy helper to select a default internet proxy.
8 *
9 * @author niki
10 */
11 public class Proxy {
12 /**
13 * Use the system proxy.
14 */
15 static public void useSystemProxy() {
16 useSystemProxy(null, null);
17 }
18
19 /**
20 * Use the system proxy with the given login/password, for authenticated
21 * proxies.
22 *
23 * @param user
24 * the user name or login
25 * @param password
26 * the password
27 */
28 static public void useSystemProxy(String user, String password) {
29 System.setProperty("java.net.useSystemProxies", "true");
30 auth(user, password);
31 }
32
33 /**
34 * Use the give proxy.
35 *
36 * @param host
37 * the proxy host name or IP address
38 * @param port
39 * the port to use
40 */
41 static public void useProxy(String host, int port) {
42 useProxy(host, port, null, null);
43 }
44
45 /**
46 * Use the given proxy with the given login/password, for authenticated
47 * proxies.
48 *
49 * @param user
50 * the user name or login
51 * @param password
52 * the password
53 * @param host
54 * the proxy host name or IP address
55 * @param port
56 * the port to use
57 * @param user
58 * the user name or login
59 * @param password
60 * the password
61 */
62 static public void useProxy(String host, int port, String user,
63 String password) {
64 System.setProperty("http.proxyHost", "proxy.stluc.ucl.ac.be");
65 System.setProperty("http.proxyPort", "8080");
66 auth(user, password);
67 }
68
69 /**
70 * Select the default authenticator for proxy requests.
71 *
72 * @param user
73 * the user name or login
74 * @param password
75 * the password
76 */
77 static private void auth(final String user, final String password) {
78 if (user != null && password != null) {
79 Authenticator proxy = new Authenticator() {
80 @Override
81 protected PasswordAuthentication getPasswordAuthentication() {
82 if (getRequestorType() == RequestorType.PROXY) {
83 return new PasswordAuthentication(user,
84 password.toCharArray());
85 }
86 return null;
87 }
88 };
89 Authenticator.setDefault(proxy);
90 }
91 }
92 }