From: Niki Roo Date: Sun, 24 Mar 2019 17:29:01 +0000 (+0100) Subject: Merge branch 'master' of github.com:nikiroo/nikiroo-utils X-Git-Url: http://git.nikiroo.be/?p=nikiroo-utils.git;a=commitdiff_plain;h=5644a84eee241f6c831f06e0bbf29650f0b82cc2;hp=40fe10ff099d9dabce950f456e983cf75a31f06b Merge branch 'master' of github.com:nikiroo/nikiroo-utils --- diff --git a/changelog.md b/changelog.md index 37cbe4b..1236039 100644 --- a/changelog.md +++ b/changelog.md @@ -5,6 +5,7 @@ - Serial: fix b64/not b64 error - Serial: perf improvement - Base64: perf improvement +- new: Proxy selector ## Version 4.5.1 diff --git a/src/be/nikiroo/utils/Proxy.java b/src/be/nikiroo/utils/Proxy.java new file mode 100755 index 0000000..fa59c73 --- /dev/null +++ b/src/be/nikiroo/utils/Proxy.java @@ -0,0 +1,92 @@ +package be.nikiroo.utils; + +import java.net.Authenticator; +import java.net.PasswordAuthentication; + +/** + * Simple proxy helper to select a default internet proxy. + * + * @author niki + */ +public class Proxy { + /** + * Use the system proxy. + */ + static public void useSystemProxy() { + useSystemProxy(null, null); + } + + /** + * Use the system proxy with the given login/password, for authenticated + * proxies. + * + * @param user + * the user name or login + * @param password + * the password + */ + static public void useSystemProxy(String user, String password) { + System.setProperty("java.net.useSystemProxies", "true"); + auth(user, password); + } + + /** + * Use the give proxy. + * + * @param host + * the proxy host name or IP address + * @param port + * the port to use + */ + static public void useProxy(String host, int port) { + useProxy(host, port, null, null); + } + + /** + * Use the given proxy with the given login/password, for authenticated + * proxies. + * + * @param user + * the user name or login + * @param password + * the password + * @param host + * the proxy host name or IP address + * @param port + * the port to use + * @param user + * the user name or login + * @param password + * the password + */ + static public void useProxy(String host, int port, String user, + String password) { + System.setProperty("http.proxyHost", "proxy.stluc.ucl.ac.be"); + System.setProperty("http.proxyPort", "8080"); + auth(user, password); + } + + /** + * Select the default authenticator for proxy requests. + * + * @param user + * the user name or login + * @param password + * the password + */ + static private void auth(final String user, final String password) { + if (user != null && password != null) { + Authenticator proxy = new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + if (getRequestorType() == RequestorType.PROXY) { + return new PasswordAuthentication(user, + password.toCharArray()); + } + return null; + } + }; + Authenticator.setDefault(proxy); + } + } +}