diff -r 3bff97f36acc .hgtags --- a/.hgtags Tue Mar 26 12:16:28 2013 +0100 +++ b/.hgtags Tue Mar 26 12:52:42 2013 +0100 @@ -941,3 +941,8 @@ c78d6484d78ea8dd1faa3ceb5e90898a78fa3adb javaee7_base f9c322a6c6f20740ac785b2da18d4c8013f6251f release73_base a1020f3273f1d09077d8003451dc7148ea81403a sspatch_platform_1 +0f3db632e5712cbcd04d8818f10917d14b854228 system_proxy_reload_in_core +0f3db632e5712cbcd04d8818f10917d14b854228 system_proxy_reload_in_core +0000000000000000000000000000000000000000 system_proxy_reload_in_core +0000000000000000000000000000000000000000 system_proxy_reload_in_core +d717d0d73743fd59c0084480e655eb63e3dcce8f system_proxy_reload_in_core diff -r 3bff97f36acc cnd.modelimpl/run.sh --- a/cnd.modelimpl/run.sh Tue Mar 26 12:16:28 2013 +0100 +++ b/cnd.modelimpl/run.sh Tue Mar 26 12:52:42 2013 +0100 @@ -194,7 +194,6 @@ DEBUG="${DEBUG},suspend=${SUSPEND},address=${DBGPORT}" fi -##DEFS="-J-Dnetbeans.system_http_proxy=webcache:8080" DEFS="" DEFS="${DEFS} ${CONSOLE}" DEFS="${DEFS} ${PARSERRORS}" diff -r 3bff97f36acc core.network/build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/build.xml Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,5 @@ + + + Builds, tests, and runs the project org.netbeans.core.network + + diff -r 3bff97f36acc core.network/manifest.mf --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/manifest.mf Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,6 @@ +Manifest-Version: 1.0 +OpenIDE-Module: org.netbeans.core.network +OpenIDE-Module-Localizing-Bundle: org/netbeans/core/network/Bundle.properties +OpenIDE-Module-Provides: org.netbeans.core.ProxySettings.Reloader +OpenIDE-Module-Specification-Version: 1.0 + diff -r 3bff97f36acc core.network/nbproject/project.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/nbproject/project.properties Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,3 @@ +is.autoload=true +javac.source=1.6 +javac.compilerargs=-Xlint -Xlint:-serial diff -r 3bff97f36acc core.network/nbproject/project.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/nbproject/project.xml Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,95 @@ + + + org.netbeans.modules.apisupport.project + + + org.netbeans.core.network + + + org.netbeans.core + + + + 2 + 3.40 + + + + org.netbeans.libs.jna + + + + 1 + 1.26 + + + + org.netbeans.modules.keyring + + + + 1.15 + + + + org.openide.awt + + + + 7.56 + + + + org.openide.dialogs + + + + 7.29 + + + + org.openide.filesystems + + + + 8.6 + + + + org.openide.util + + + + 8.30 + + + + org.openide.util.lookup + + + + 8.20 + + + + + + unit + + org.netbeans.insane + + + + org.netbeans.libs.junit4 + + + + org.netbeans.modules.nbjunit + + + + + + + + diff -r 3bff97f36acc core.network/src/org/netbeans/core/network/Bundle.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/src/org/netbeans/core/network/Bundle.properties Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,1 @@ +OpenIDE-Module-Name=Core Network Settings diff -r 3bff97f36acc core.network/src/org/netbeans/core/network/proxy/NbProxySelector.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/src/org/netbeans/core/network/proxy/NbProxySelector.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,428 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2013 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2011 Sun + * Microsystems, Inc. All Rights Reserved. + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + */ + +package org.netbeans.core.network.proxy; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.*; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.prefs.PreferenceChangeEvent; +import java.util.prefs.PreferenceChangeListener; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; +import org.netbeans.core.ProxySettings; +import org.openide.util.lookup.ServiceProvider; + +/** + * + * @author Jiri Rechtacek + */ +@ServiceProvider(service = ProxySelector.class, position = 1000) +public final class NbProxySelector extends ProxySelector { + + private final ProxySelector original; + private static final Logger LOG = Logger.getLogger (NbProxySelector.class.getName ()); + private static Object useSystemProxies; + private static final String DEFAULT_PROXY_SELECTOR_CLASS_NAME = "sun.net.spi.DefaultProxySelector"; + + /** Creates a new instance of NbProxySelector */ + public NbProxySelector() { + original = ProxySelector.getDefault(); + LOG.log(Level.FINE, "java.net.useSystemProxies has been set to {0}", useSystemProxies()); + if (original.getClass().getName().equals(DEFAULT_PROXY_SELECTOR_CLASS_NAME) || original == null) { + NetworkProxyReloader.reloadNetworkProxy(); + } + ProxySettings.addPreferenceChangeListener(new ProxySettingsListener()); + copySettingsToSystem(); + } + + @Override + public List select(URI uri) { + List res = new ArrayList (); + int proxyType = ProxySettings.getProxyType (); + switch (proxyType) { + case ProxySettings.DIRECT_CONNECTION: + res = Collections.singletonList (Proxy.NO_PROXY); + break; + case ProxySettings.AUTO_DETECT_PROXY: + if (!useSystemProxies ()) { + String protocol = uri.getScheme (); + assert protocol != null : "Invalid scheme of uri " + uri + ". Scheme cannot be null!"; + if (dontUseProxy (ProxySettings.getSystemNonProxyHosts(), uri.getHost ())) { + res.add (Proxy.NO_PROXY); + break; + } + if (protocol.toLowerCase (Locale.US).startsWith("http")) { + String ports = ProxySettings.getSystemHttpPort(); + if (ports != null && ports.length () > 0 && ProxySettings.getSystemHttpHost().length () > 0) { + int porti = Integer.parseInt(ports); + Proxy p = new Proxy (Proxy.Type.HTTP, new InetSocketAddress (ProxySettings.getSystemHttpHost(), porti)); + res.add (p); + } + } else { // supposed SOCKS + String ports = ProxySettings.getSystemSocksPort(); + String hosts = ProxySettings.getSystemSocksHost(); + if (ports != null && ports.length () > 0 && hosts.length () > 0) { + int porti = Integer.parseInt(ports); + Proxy p = new Proxy (Proxy.Type.SOCKS, new InetSocketAddress (hosts, porti)); + res.add (p); + } + } + if (original != null) { + res.addAll (original.select (uri)); + } + } + break; + case ProxySettings.MANUAL_SET_PROXY: + String protocol = uri.getScheme (); + assert protocol != null : "Invalid scheme of uri " + uri + ". Scheme cannot be null!"; + + // handling nonProxyHosts first + if (dontUseProxy (ProxySettings.getNonProxyHosts (), uri.getHost ())) { + res.add (Proxy.NO_PROXY); + break; + } + if (protocol.toLowerCase (Locale.US).startsWith("http")) { + String hosts = ProxySettings.getHttpHost (); + String ports = ProxySettings.getHttpPort (); + if (ports != null && ports.length () > 0 && hosts.length () > 0) { + int porti = Integer.parseInt(ports); + Proxy p = new Proxy (Proxy.Type.HTTP, new InetSocketAddress (hosts, porti)); + res.add (p); + } else { + LOG.log(Level.FINE, "Incomplete HTTP Proxy [{0}/{1}] found in ProxySelector[Type: {2}] for uri {3}. ", new Object[]{hosts, ports, ProxySettings.getProxyType (), uri}); + if (original != null) { + LOG.log(Level.FINEST, "Fallback to the default ProxySelector which returns {0}", original.select (uri)); + res.addAll (original.select (uri)); + } + } + } else { // supposed SOCKS + String ports = ProxySettings.getSocksPort (); + String hosts = ProxySettings.getSocksHost (); + if (ports != null && ports.length () > 0 && hosts.length () > 0) { + int porti = Integer.parseInt(ports); + Proxy p = new Proxy (Proxy.Type.SOCKS, new InetSocketAddress (hosts, porti)); + res.add (p); + } else { + LOG.log(Level.FINE, "Incomplete SOCKS Server [{0}/{1}] found in ProxySelector[Type: {2}] for uri {3}. ", new Object[]{hosts, ports, ProxySettings.getProxyType (), uri}); + if (original != null) { + LOG.log(Level.FINEST, "Fallback to the default ProxySelector which returns {0}", original.select (uri)); + res.addAll (original.select (uri)); + } + } + } + res.add (Proxy.NO_PROXY); + break; + case ProxySettings.AUTO_DETECT_PAC: + if (!useSystemProxies ()) { + ProxyAutoConfig pac = ProxyAutoConfig.get(getPacFile()); + assert pac != null : "Instance of ProxyAutoConfig found for " + getPacFile(); + if (pac == null) { + LOG.log(Level.FINEST, "No instance of ProxyAutoConfig({0}) for URI {1}", new Object[]{getPacFile(), uri}); + res.add(Proxy.NO_PROXY); + } + if (pac.getPacURI().getHost() == null) { + LOG.log(Level.FINEST, "Identifying proxy for URI {0}---{1}, PAC LOCAL URI: {2}", //NOI18N + new Object[] { uri.toString(), uri.getHost(), pac.getPacURI().toString() }); + res.addAll(pac.findProxyForURL(uri)); + } else if (pac.getPacURI().getHost().equals(uri.getHost())) { + // don't proxy PAC files + res.add(Proxy.NO_PROXY); + } else { + LOG.log(Level.FINEST, "Identifying proxy for URI {0}---{1}, PAC URI: {2}---{3}", //NOI18N + new Object[] { uri.toString(), uri.getHost(), pac.getPacURI().toString(), pac.getPacURI().getHost() }); + res.addAll(pac.findProxyForURL(uri)); + } + } + + if (original != null) { + res.addAll (original.select (uri)); + } + + res.add (Proxy.NO_PROXY); + break; + case ProxySettings.MANUAL_SET_PAC: + // unused branch - never can setup PAC file from NetBeans + + ProxyAutoConfig pac = ProxyAutoConfig.get(getPacFile()); + assert pac != null : "Instance of ProxyAutoConfig found for " + getPacFile(); + if (pac == null) { + LOG.log(Level.FINEST, "No instance of ProxyAutoConfig({0}) for URI {1}", new Object[]{getPacFile(), uri}); + res.add(Proxy.NO_PROXY); + } + if (pac.getPacURI().getHost() == null) { + LOG.log(Level.FINEST, "Identifying proxy for URI {0}---{1}, PAC LOCAL URI: {2}", //NOI18N + new Object[] { uri.toString(), uri.getHost(), pac.getPacURI().toString() }); + res.addAll(pac.findProxyForURL(uri)); + } else if (pac.getPacURI().getHost().equals(uri.getHost())) { + // don't proxy PAC files + res.add(Proxy.NO_PROXY); + } else { + LOG.log(Level.FINEST, "Identifying proxy for URI {0}---{1}, PAC URI: {2}---{3}", //NOI18N + new Object[] { uri.toString(), uri.getHost(), pac.getPacURI().toString(), pac.getPacURI().getHost() }); + res.addAll(pac.findProxyForURL(uri)); // NOI18N + } + res.add (Proxy.NO_PROXY); + break; + default: + assert false : "Invalid proxy type: " + proxyType; + } + LOG.log(Level.FINEST, "NbProxySelector[Type: {0}, Use HTTP for all protocols: {1}] returns {2} for URI {3}", + new Object[]{ProxySettings.getProxyType (), ProxySettings.useProxyAllProtocols (), res, uri}); + return res; + } + + @Override + public void connectFailed (URI arg0, SocketAddress arg1, IOException arg2) { + LOG.log (Level.INFO, "connectionFailed(" + arg0 + ", " + arg1 +")", arg2); + } + + // several modules listenes on these properties and propagates it futher + private class ProxySettingsListener implements PreferenceChangeListener { + @Override + public void preferenceChange(PreferenceChangeEvent evt) { + if (evt.getKey ().startsWith ("proxy") || evt.getKey ().startsWith ("useProxy")) { + copySettingsToSystem (); + } + } + } + + private void copySettingsToSystem () { + String host = null, port = null, nonProxyHosts = null; + String socksHost = null, socksPort = null; + String httpsHost = null, httpsPort = null; + int proxyType = ProxySettings.getProxyType (); + switch (proxyType) { + case ProxySettings.DIRECT_CONNECTION: + host = null; + port = null; + httpsHost = null; + httpsPort = null; + nonProxyHosts = null; + socksHost = null; + socksPort = null; + break; + case ProxySettings.AUTO_DETECT_PROXY: + host = ProxySettings.getSystemHttpHost(); + port = ProxySettings.getSystemHttpPort(); + httpsHost = ProxySettings.getSystemHttpsHost(); + httpsPort = ProxySettings.getSystemHttpsPort(); + socksHost = ProxySettings.getSystemSocksHost(); + socksPort = ProxySettings.getSystemSocksPort(); + nonProxyHosts = ProxySettings.getSystemNonProxyHosts(); + break; + case ProxySettings.MANUAL_SET_PROXY: + host = ProxySettings.getHttpHost (); + port = ProxySettings.getHttpPort (); + httpsHost = ProxySettings.getHttpsHost (); + httpsPort = ProxySettings.getHttpsPort (); + nonProxyHosts = ProxySettings.getNonProxyHosts (); + socksHost = ProxySettings.getSocksHost (); + socksPort = ProxySettings.getSocksPort (); + break; + case ProxySettings.AUTO_DETECT_PAC: + host = null; + port = null; + httpsHost = null; + httpsPort = null; + nonProxyHosts = null; + socksHost = null; + socksPort = null; + break; + case ProxySettings.MANUAL_SET_PAC: + host = null; + port = null; + httpsHost = null; + httpsPort = null; + nonProxyHosts = ProxySettings.getNonProxyHosts(); + socksHost = null; + socksPort = null; + break; + default: + assert false : "Invalid proxy type: " + proxyType; + } + setOrClearProperty ("http.proxyHost", host, false); + setOrClearProperty ("http.proxyPort", port, true); + setOrClearProperty ("http.nonProxyHosts", nonProxyHosts, false); + setOrClearProperty ("https.proxyHost", httpsHost, false); + setOrClearProperty ("https.proxyPort", httpsPort, true); + setOrClearProperty ("https.nonProxyHosts", nonProxyHosts, false); + setOrClearProperty ("socksProxyHost", socksHost, false); + setOrClearProperty ("socksProxyPort", socksPort, true); + LOG.log (Level.FINE, "Set System''s http.proxyHost/Port/NonProxyHost to {0}/{1}/{2}", new Object[]{host, port, nonProxyHosts}); + LOG.log (Level.FINE, "Set System''s https.proxyHost/Port to {0}/{1}", new Object[]{httpsHost, httpsPort}); + LOG.log (Level.FINE, "Set System''s socksProxyHost/Port to {0}/{1}", new Object[]{socksHost, socksPort}); + } + + private void setOrClearProperty (String key, String value, boolean isInteger) { + assert key != null; + if (value == null || value.length () == 0) { + System.clearProperty (key); + } else { + if (isInteger) { + try { + Integer.parseInt (value); + } catch (NumberFormatException nfe) { + LOG.log (Level.INFO, nfe.getMessage(), nfe); + } + } + System.setProperty (key, value); + } + } + + // package-private for unit-testing + static boolean dontUseProxy (String nonProxyHosts, String host) { + if (host == null) { + return false; + } + + // try IP adress first + if (dontUseIp (nonProxyHosts, host)) { + return true; + } else { + return dontUseHostName (nonProxyHosts, host); + } + + } + + private static boolean dontUseHostName (String nonProxyHosts, String host) { + if (host == null) { + return false; + } + + boolean dontUseProxy = false; + StringTokenizer st = new StringTokenizer (nonProxyHosts, "|", false); + while (st.hasMoreTokens () && !dontUseProxy) { + String token = st.nextToken ().trim(); + int star = token.indexOf ("*"); + if (star == -1) { + dontUseProxy = token.equals (host); + if (dontUseProxy) { + LOG.log(Level.FINEST, "NbProxySelector[Type: {0}]. Host {1} found in nonProxyHosts: {2}", new Object[]{ProxySettings.getProxyType (), host, nonProxyHosts}); + } + } else { + String start = token.substring (0, star - 1 < 0 ? 0 : star - 1); + String end = token.substring (star + 1 > token.length () ? token.length () : star + 1); + + //Compare left of * if and only if * is not first character in token + boolean compareStart = star > 0; // not first character + //Compare right of * if and only if * is not the last character in token + boolean compareEnd = star < (token.length() - 1); // not last character + dontUseProxy = (compareStart && host.startsWith(start)) || (compareEnd && host.endsWith(end)); + + if (dontUseProxy) { + LOG.log(Level.FINEST, "NbProxySelector[Type: {0}]. Host {1} found in nonProxyHosts: {2}", new Object[]{ProxySettings.getProxyType (), host, nonProxyHosts}); + } + } + } + return dontUseProxy; + } + + private static boolean dontUseIp (String nonProxyHosts, String host) { + if (host == null) { + return false; + } + + String ip = null; + try { + ip = InetAddress.getByName (host).getHostAddress (); + } catch (UnknownHostException ex) { + LOG.log (Level.FINE, ex.getLocalizedMessage (), ex); + } + + if (ip == null) { + return false; + } + + boolean dontUseProxy = false; + StringTokenizer st = new StringTokenizer (nonProxyHosts, "|", false); + while (st.hasMoreTokens () && !dontUseProxy) { + String nonProxyHost = st.nextToken ().trim(); + int star = nonProxyHost.indexOf ("*"); + if (star == -1) { + dontUseProxy = nonProxyHost.equals (ip); + if (dontUseProxy) { + LOG.log(Level.FINEST, "NbProxySelector[Type: {0}]. Host''s IP {1} found in nonProxyHosts: {2}", new Object[]{ProxySettings.getProxyType (), ip, nonProxyHosts}); + } + } else { + // match with given dotted-quad IP + try { + dontUseProxy = Pattern.matches (nonProxyHost, ip); + if (dontUseProxy) { + LOG.log(Level.FINEST, "NbProxySelector[Type: {0}]. Host''s IP{1} found in nonProxyHosts: {2}", new Object[]{ProxySettings.getProxyType (), ip, nonProxyHosts}); + } + } catch (PatternSyntaxException pse) { + // may ignore it here + } + } + } + return dontUseProxy; + } + + // NetProperties is JDK vendor specific, access only by reflection + static boolean useSystemProxies () { + if (useSystemProxies == null) { + try { + Class clazz = Class.forName ("sun.net.NetProperties"); + Method getBoolean = clazz.getMethod ("getBoolean", String.class); + useSystemProxies = getBoolean.invoke (null, "java.net.useSystemProxies"); + } catch (Exception x) { + LOG.log (Level.FINEST, "Cannot get value of java.net.useSystemProxies bacause " + x.getMessage(), x); + } + } + return useSystemProxies != null && "true".equalsIgnoreCase (useSystemProxies.toString ()); + } + + static boolean usePAC() { + String pacFile = ProxySettings.getSystemPac(); + return pacFile != null; + } + + private static String getPacFile() { + return ProxySettings.getSystemPac(); + } +} diff -r 3bff97f36acc core.network/src/org/netbeans/core/network/proxy/NetworkProxyReloader.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/src/org/netbeans/core/network/proxy/NetworkProxyReloader.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,230 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2013 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2013 Sun Microsystems, Inc. + */ +package org.netbeans.core.network.proxy; + +import org.netbeans.core.ProxySettings; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.prefs.Preferences; +import org.netbeans.core.network.proxy.fallback.FallbackNetworkProxy; +import org.netbeans.core.network.proxy.gnome.GnomeNetworkProxy; +import org.netbeans.core.network.proxy.kde.KdeNetworkProxy; +import org.netbeans.core.network.proxy.mac.MacNetworkProxy; +import org.netbeans.core.network.proxy.windows.WindowsNetworkProxy; +import org.openide.util.NbPreferences; +import org.openide.util.Utilities; +import org.openide.util.lookup.ServiceProvider; + +/** + * This class allows user to reload system network proxy settings. + * + * @author lfischme + */ +@ServiceProvider(service = ProxySettings.Reloader.class, position = 1000) +public class NetworkProxyReloader extends ProxySettings.Reloader { + + private final static Logger LOGGER = Logger.getLogger(NetworkProxyReloader.class.getName()); + + private final static String COMMA = ","; //NOI18N + + private final static String GNOME = "gnome"; //NOI18N + private final static String KDE = "kde"; //NOI18N + private final static String RUNNING_ENV_SYS_PROPERTY = "netbeans.running.environment"; //NOI18N + + private static final NetworkProxyResolver NETWORK_PROXY_RESOLVER = getNetworkProxyResolver(); + private static final NetworkProxyResolver FALLBACK_NETWORK_PROXY_RESOLVER = getFallbackProxyResolver(); + /** + * Reloads system proxy network settings. + * + * The first it tries to retrieve proxy settings directly from system, + * if it is unsuccessful it tries fallback (from environment property http_proxy etc.). + */ + public static void reloadNetworkProxy() { + LOGGER.log(Level.FINE, "System network proxy reloading started."); //NOI18N + NetworkProxySettings networkProxySettings = NETWORK_PROXY_RESOLVER.getNetworkProxySettings(); + + if (!networkProxySettings.isResolved()) { + LOGGER.log(Level.WARNING, "System network proxy reloading failed! Trying fallback resolver."); //NOI18N + NetworkProxySettings fallbackNetworkProxySettings = FALLBACK_NETWORK_PROXY_RESOLVER.getNetworkProxySettings(); + if (fallbackNetworkProxySettings.isResolved()) { + LOGGER.log(Level.INFO, "System network proxy reloading succeeded. Fallback provider was successful."); //NOI18N + networkProxySettings = fallbackNetworkProxySettings; + } else { + LOGGER.log(Level.WARNING, "System network proxy reloading failed! Fallback provider was unsuccessful."); //NOI18N + } + } else { + LOGGER.log(Level.INFO, "System network proxy reloading succeeded."); //NOI18N + } + + switch (networkProxySettings.getProxyMode()) { + case AUTO: + LOGGER.log(Level.INFO, "System network proxy - mode: auto"); //NOI18N + LOGGER.log(Level.INFO, "System network proxy - pac url: {0}", networkProxySettings.getPacFileUrl()); //NOI18N + getPreferences().remove(ProxySettings.SYSTEM_PROXY_HTTP_HOST); + getPreferences().remove(ProxySettings.SYSTEM_PROXY_HTTP_PORT); + getPreferences().remove(ProxySettings.SYSTEM_PROXY_HTTPS_HOST); + getPreferences().remove(ProxySettings.SYSTEM_PROXY_HTTPS_PORT); + getPreferences().remove(ProxySettings.SYSTEM_PROXY_SOCKS_HOST); + getPreferences().remove(ProxySettings.SYSTEM_PROXY_SOCKS_PORT); + getPreferences().remove(ProxySettings.SYSTEM_NON_PROXY_HOSTS); + getPreferences().put(ProxySettings.SYSTEM_PAC, networkProxySettings.getPacFileUrl()); + break; + case MANUAL: + LOGGER.log(Level.INFO, "System network proxy - mode: manual"); //NOI18N + LOGGER.log(Level.INFO, "System network proxy - http host: {0}", networkProxySettings.getHttpProxyHost()); //NOI18N + LOGGER.log(Level.INFO, "System network proxy - http port: {0}", networkProxySettings.getHttpProxyPort()); //NOI18N + LOGGER.log(Level.INFO, "System network proxy - https host: {0}", networkProxySettings.getHttpsProxyHost()); //NOI18N + LOGGER.log(Level.INFO, "System network proxy - https port: {0}", networkProxySettings.getHttpsProxyPort()); //NOI18N + LOGGER.log(Level.INFO, "System network proxy - socks host: {0}", networkProxySettings.getSocksProxyHost()); //NOI18N + LOGGER.log(Level.INFO, "System network proxy - socks port: {0}", networkProxySettings.getSocksProxyPort()); //NOI18N + LOGGER.log(Level.INFO, "System network proxy - no prohy hosts: {0}", getStringFromArray(networkProxySettings.getNoProxyHosts())); //NOI18N + getPreferences().put(ProxySettings.SYSTEM_PROXY_HTTP_HOST, networkProxySettings.getHttpProxyHost()); + getPreferences().put(ProxySettings.SYSTEM_PROXY_HTTP_PORT, networkProxySettings.getHttpProxyPort()); + getPreferences().put(ProxySettings.SYSTEM_PROXY_HTTPS_HOST, networkProxySettings.getHttpsProxyHost()); + getPreferences().put(ProxySettings.SYSTEM_PROXY_HTTPS_PORT, networkProxySettings.getHttpsProxyPort()); + getPreferences().put(ProxySettings.SYSTEM_PROXY_SOCKS_HOST, networkProxySettings.getSocksProxyHost()); + getPreferences().put(ProxySettings.SYSTEM_PROXY_SOCKS_PORT, networkProxySettings.getSocksProxyPort()); + getPreferences().put(ProxySettings.SYSTEM_NON_PROXY_HOSTS, getStringFromArray(networkProxySettings.getNoProxyHosts())); + getPreferences().remove(ProxySettings.SYSTEM_PAC); + break; + case DIRECT: + LOGGER.log(Level.INFO, "System network proxy - mode: direct"); //NOI18N + default: + LOGGER.log(Level.INFO, "System network proxy: falled to default (corect if direct mode went before)"); //NOI18N + getPreferences().remove(ProxySettings.SYSTEM_PROXY_HTTP_HOST); + getPreferences().remove(ProxySettings.SYSTEM_PROXY_HTTP_PORT); + getPreferences().remove(ProxySettings.SYSTEM_PROXY_HTTPS_HOST); + getPreferences().remove(ProxySettings.SYSTEM_PROXY_HTTPS_PORT); + getPreferences().remove(ProxySettings.SYSTEM_PROXY_SOCKS_HOST); + getPreferences().remove(ProxySettings.SYSTEM_PROXY_SOCKS_PORT); + getPreferences().remove(ProxySettings.SYSTEM_NON_PROXY_HOSTS); + getPreferences().remove(ProxySettings.SYSTEM_PAC); + } + LOGGER.log(Level.FINE, "System network proxy reloading fineshed."); //NOI18N + } + + /** + * Returns string from array of strings. Strings are separated by comma. + * + * @param stringArray + * @return String from array of strings. Strings are separated by comma. + */ + private static String getStringFromArray(String[] stringArray) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < stringArray.length; i++) { + sb.append(stringArray[i]); + if (i == stringArray.length - 1) { + sb.append(COMMA); + } + } + + return sb.toString(); + } + + /** + * Returns preferences for proxy settings. + * + * @return Preferences for proxy settings. + */ + private static Preferences getPreferences() { + return NbPreferences.forModule(ProxySettings.class); + } + + /** + * Returns proper network resolver for running environment. + * + * If not suitable proxy resolver found, the fallback is used. + * + * @return Proper network resolver for running environment. + */ + private static NetworkProxyResolver getNetworkProxyResolver() { + if (NETWORK_PROXY_RESOLVER == null) { + if (Utilities.isWindows()) { + LOGGER.log(Level.INFO, "System network proxy resolver: Windows"); //NOI18N + return new WindowsNetworkProxy(); + } + + if (Utilities.isMac()) { + LOGGER.log(Level.INFO, "System network proxy resolver: Mac"); //NOI18N + return new MacNetworkProxy(); + } + + if (Utilities.isUnix()){ + String env = System.getProperty(RUNNING_ENV_SYS_PROPERTY); + if (env != null) { + if (env.toLowerCase().equals(GNOME)) { + LOGGER.log(Level.INFO, "System network proxy resolver: Gnome"); //NOI18N + return new GnomeNetworkProxy(); + } + + if (env.toLowerCase().equals(KDE)) { + LOGGER.log(Level.INFO, "System network proxy resolver: KDE"); //NOI18N + return new KdeNetworkProxy(); + } + } + } + + LOGGER.log(Level.WARNING, "System network proxy resolver: no suitable found, using fallback."); //NOI18N + return new FallbackNetworkProxy(); + } else { + return NETWORK_PROXY_RESOLVER; + } + } + + /** + * Returns fallback proxy resolver. + * + * @return Fallback proxy resolver. + */ + private static NetworkProxyResolver getFallbackProxyResolver() { + if (FALLBACK_NETWORK_PROXY_RESOLVER == null) { + return new FallbackNetworkProxy(); + } else { + return FALLBACK_NETWORK_PROXY_RESOLVER; + } + } + + @Override + public void reload() { + NetworkProxyReloader.reloadNetworkProxy(); + } +} diff -r 3bff97f36acc core.network/src/org/netbeans/core/network/proxy/NetworkProxyResolver.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/src/org/netbeans/core/network/proxy/NetworkProxyResolver.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,61 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2013 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2013 Sun Microsystems, Inc. + */ +package org.netbeans.core.network.proxy; + +/** + * Interface for system (platform) dependent proxy resolvers. + * + * Different resolvers for Windows, Mac OS X, Gnome and KDE. Also there is + * a fallback resolver. + * + * @author lfischme + */ +public interface NetworkProxyResolver { + + /** + * Returns NetworkProxySetting - wrapper for all proxy settings. + * + * @return NetworkProxySettings + */ + public NetworkProxySettings getNetworkProxySettings(); + +} diff -r 3bff97f36acc core.network/src/org/netbeans/core/network/proxy/NetworkProxySettings.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/src/org/netbeans/core/network/proxy/NetworkProxySettings.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,266 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2013 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2013 Sun Microsystems, Inc. + */ +package org.netbeans.core.network.proxy; + +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Immutable class representing all network proxy settings. + * + * Holds all proxy settings values if they were successfully retrieved + * or tells that they were not retrieved well. + * + * @author lfischme + */ +public final class NetworkProxySettings { + + public static enum ProxyMode { + DIRECT, + AUTO, + MANUAL + } + + private final static Logger LOGGER = Logger.getLogger(NetworkProxySettings.class.getName()); + private final static String COLON = ":"; //NOI18N + private final static String SLASH = "/"; //NOI18N + private final static String EMPTY_STRING = ""; //NOI18N + private final boolean resolved; + private final ProxyMode proxyMode; + private final String httpProxyHost; + private final String httpProxyPort; + private final String httpsProxyHost; + private final String httpsProxyPort; + private final String socksProxyHost; + private final String socksProxyPort; + private final String pacFileUrl; + private final String[] noProxyHosts; + + public NetworkProxySettings() { + this.resolved = true; + this.proxyMode = ProxyMode.DIRECT; + this.pacFileUrl = null; + this.httpProxyHost = null; + this.httpProxyPort = null; + this.httpsProxyHost = null; + this.httpsProxyPort = null; + this.socksProxyHost = null; + this.socksProxyPort = null; + this.noProxyHosts = new String[0]; + } + + public NetworkProxySettings(String httpProxy, String[] noProxyHosts) { + String httpProxyHostChecked = getHost(httpProxy); + String httpProxyPortChecked = getPort(httpProxy); + + this.resolved = true; + this.proxyMode = ProxyMode.MANUAL; + this.pacFileUrl = null; + this.httpProxyHost = httpProxyHostChecked; + this.httpProxyPort = httpProxyPortChecked; + this.httpsProxyHost = httpProxyHostChecked; + this.httpsProxyPort = httpProxyPortChecked; + this.socksProxyHost = httpProxyHostChecked; + this.socksProxyPort = httpProxyPortChecked; + this.noProxyHosts = checkArray(noProxyHosts); + } + + public NetworkProxySettings(String httpProxy, String httpsProxy, String socksProxy, String[] noProxyHosts) { + this.resolved = true; + this.proxyMode = ProxyMode.MANUAL; + this.pacFileUrl = null; + this.httpProxyHost = getHost(httpProxy); + this.httpProxyPort = getPort(httpProxy); + this.httpsProxyHost = getHost(httpsProxy); + this.httpsProxyPort = getPort(httpsProxy); + this.socksProxyHost = getHost(socksProxy); + this.socksProxyPort = getPort(socksProxy); + this.noProxyHosts = checkArray(noProxyHosts); + } + + public NetworkProxySettings(String httpProxyHost, String httpProxyPort, String[] noProxyHosts) { + String httpProxyHostChecked = checkNull(httpProxyHost); + String httpProxyPortChecked = checkNumber(httpProxyPort); + + this.resolved = true; + this.proxyMode = ProxyMode.MANUAL; + this.pacFileUrl = null; + this.httpProxyHost = httpProxyHostChecked; + this.httpProxyPort = httpProxyPortChecked; + this.httpsProxyHost = httpProxyHostChecked; + this.httpsProxyPort = httpProxyPortChecked; + this.socksProxyHost = httpProxyHostChecked; + this.socksProxyPort = httpProxyPortChecked; + this.noProxyHosts = checkArray(noProxyHosts); + } + + public NetworkProxySettings(String httpProxyHost, String httpProxyPort, + String httpsProxyHost, String httpsProxyPort, + String socksProxyHost, String socksProxyPort, String[] noProxyHosts) { + this.resolved = true; + this.proxyMode = ProxyMode.MANUAL; + this.pacFileUrl = null; + this.httpProxyHost = checkNull(httpProxyHost); + this.httpProxyPort = checkNumber(httpProxyPort); + this.httpsProxyHost = checkNull(httpsProxyHost); + this.httpsProxyPort = checkNumber(httpsProxyPort); + this.socksProxyHost = checkNull(socksProxyHost); + this.socksProxyPort = checkNumber(socksProxyPort); + this.noProxyHosts = checkArray(noProxyHosts); + } + + public NetworkProxySettings(String pacFileUrl) { + this.resolved = true; + this.proxyMode = ProxyMode.AUTO; + this.pacFileUrl = checkNull(pacFileUrl); + this.httpProxyHost = null; + this.httpProxyPort = null; + this.httpsProxyHost = null; + this.httpsProxyPort = null; + this.socksProxyHost = null; + this.socksProxyPort = null; + this.noProxyHosts = new String[0]; + } + + public NetworkProxySettings(boolean resolved) { + this.resolved = resolved; + this.proxyMode = ProxyMode.DIRECT; + this.pacFileUrl = null; + this.httpProxyHost = null; + this.httpProxyPort = null; + this.httpsProxyHost = null; + this.httpsProxyPort = null; + this.socksProxyHost = null; + this.socksProxyPort = null; + this.noProxyHosts = new String[0]; + } + + + + private String getHost(String string) { + if (string == null) { + return EMPTY_STRING; + } else { + if (string.contains(COLON)) { + return string.substring(0, string.lastIndexOf(COLON)); + } else { + return string; + } + } + } + + private String getPort(String string) { + if (string == null) { + return EMPTY_STRING; + } else { + if (string.endsWith(SLASH)) { + string = string.substring(string.length() - 1, string.length()); + } + if (string.contains(COLON)) { + return string.substring(string.lastIndexOf(COLON) + 1); + } else { + return EMPTY_STRING; + } + } + } + + private String checkNull(String string) { + return string == null ? EMPTY_STRING : string; + } + + private String checkNumber(String string) { + if (string != null) { + try { + Integer.parseInt(string); + return string; + } catch (NumberFormatException nfe) { + LOGGER.log(Level.SEVERE, "Cannot parse number {0}", string); //NOI18N + } + } + + return EMPTY_STRING; + } + + private String[] checkArray(String[] array) { + return array == null ? new String[0] : array; + } + + public boolean isResolved() { + return resolved; + } + + public ProxyMode getProxyMode() { + return proxyMode; + } + + public String getHttpProxyHost() { + return httpProxyHost; + } + + public String getHttpProxyPort() { + return httpProxyPort; + } + + public String getHttpsProxyHost() { + return httpsProxyHost; + } + + public String getHttpsProxyPort() { + return httpsProxyPort; + } + + public String getSocksProxyHost() { + return socksProxyHost; + } + + public String getSocksProxyPort() { + return socksProxyPort; + } + + public String getPacFileUrl() { + return pacFileUrl; + } + + public String[] getNoProxyHosts() { + return noProxyHosts; + } +} diff -r 3bff97f36acc core.network/src/org/netbeans/core/network/proxy/ProxyAutoConfig.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/src/org/netbeans/core/network/proxy/ProxyAutoConfig.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,349 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2011-2013 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2011 Sun Microsystems, Inc. + */ +package org.netbeans.core.network.proxy; + +import org.netbeans.core.ProxySettings; +import java.io.*; +import java.net.*; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.script.Invocable; +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; +import org.openide.filesystems.FileObject; +import org.openide.filesystems.FileUtil; +import org.openide.filesystems.URLMapper; +import org.openide.util.RequestProcessor; +import org.openide.util.RequestProcessor.Task; +import org.openide.util.Utilities; + +/** + * + * @author Jirka Rechtacek + */ +public class ProxyAutoConfig { + + private static final Map file2pac = new HashMap(2); + private static RequestProcessor RP = new RequestProcessor(ProxyAutoConfig.class); + private static final String NS_PROXY_AUTO_CONFIG_URL = "nbinst://org.netbeans.core/modules/ext/nsProxyAutoConfig.js"; // NOI18N + private static final String PROTO_FILE = "file://"; + + /** + * + * @param pacFile The string to be parsed into a URI + * @return ProxyAutoConfig for given pacFile or null if constructor failed + */ + public static synchronized ProxyAutoConfig get(String pacFile) { + if (file2pac.get(pacFile) == null) { + LOGGER.fine("Init ProxyAutoConfig for " + pacFile); + ProxyAutoConfig instance = null; + try { + instance = new ProxyAutoConfig(pacFile); + } catch (URISyntaxException ex) { + Logger.getLogger(ProxyAutoConfig.class.getName()).warning("Parsing " + pacFile + " to URI throws " + ex); + } finally { + file2pac.put(pacFile, instance); + } + } + return file2pac.get(pacFile); + } + private static final Logger LOGGER = Logger.getLogger(ProxyAutoConfig.class.getName()); + private Invocable inv = null; + private final Task initTask; + private final URI pacURI; + + private ProxyAutoConfig(final String pacURL) throws URISyntaxException { + assert file2pac.get(pacURL) == null : "Only once object for " + pacURL + " must exist."; + String normPAC = normalizePAC(pacURL); + pacURI = new URI(normPAC); + initTask = RP.post(new Runnable() { + + @Override + public void run() { + initEngine(); + } + }); + } + + public URI getPacURI() { + return pacURI; + } + + private void initEngine() { + InputStream pacIS; + try { + if (pacURI.isAbsolute()) { + pacIS = downloadPAC(pacURI.toURL()); + } else { + pacIS = null; + } + } catch (IOException ex) { + LOGGER.log(Level.INFO, "InputStream for " + pacURI + " throws " + ex, ex); + return; + } + if (pacIS == null) { + return ; + } + String utils = downloadUtils(); + ScriptEngine eng; + try { + eng = evalPAC(pacIS, utils); + } catch (FileNotFoundException ex) { + LOGGER.log(Level.FINE, "While constructing ProxyAutoConfig thrown " + ex, ex); + return ; + } catch (ScriptException ex) { + LOGGER.log(Level.FINE, "While constructing ProxyAutoConfig thrown " + ex, ex); + return ; + } finally { + if (pacIS != null) { + try { + pacIS.close(); + } catch (IOException ex) { + LOGGER.log(Level.FINE, "While closing PAC input stream thrown " + ex, ex); + } + } + } + assert eng != null : "JavaScri5pt engine cannot be null"; + if (eng == null) { + LOGGER.log(Level.WARNING, "JavaScript engine cannot be null"); + return ; + } + inv = (Invocable) eng; + } + + @SuppressWarnings("unchecked") + public List findProxyForURL(URI u) { + assert initTask != null : "initTask has be to posted."; + if (!initTask.isFinished()) { + while (!initTask.isFinished()) { + try { + RP.post(new Runnable() { + + @Override + public void run() { + } + }).waitFinished(100); + } catch (InterruptedException ex) { + LOGGER.log(Level.FINEST, ex.getMessage(), ex); + } + } + } + if (inv == null) { + return Collections.singletonList(Proxy.NO_PROXY); + } + Object proxies = null; + try { + proxies = inv.invokeFunction("FindProxyForURL", u.toString(), u.getHost()); // NOI18N + } catch (ScriptException ex) { + LOGGER.log(Level.FINE, "While invoking FindProxyForURL(" + u + ", " + u.getHost() + " thrown " + ex, ex); + } catch (NoSuchMethodException ex) { + LOGGER.log(Level.FINE, "While invoking FindProxyForURL(" + u + ", " + u.getHost() + " thrown " + ex, ex); + } + List res = analyzeResult(u, proxies); + if (res == null) { + LOGGER.info("findProxyForURL(" + u + ") returns null."); + res = Collections.emptyList(); + } + LOGGER.fine("findProxyForURL(" + u + ") returns " + Arrays.asList(res)); + return res; + } + + private static InputStream downloadPAC (URL pacURL) throws IOException { + InputStream is; + URLConnection conn = pacURL.openConnection(Proxy.NO_PROXY); + is = conn.getInputStream(); + return is; + } + + private static ScriptEngine evalPAC(InputStream is, String utils) throws FileNotFoundException, ScriptException { + ScriptEngineManager factory = new ScriptEngineManager(); + ScriptEngine engine = factory.getEngineByName("JavaScript"); + Reader pacReader = new InputStreamReader(is); + engine.eval(pacReader); + engine.eval(utils); + return engine; + } + + private List analyzeResult(URI uri, Object proxiesString) { + if (proxiesString == null) { + LOGGER.fine("Null result for " + uri); + return null; + } + Proxy.Type proxyType; + String protocol = uri.getScheme(); + assert protocol != null : "Invalid scheme of uri " + uri + ". Scheme cannot be null!"; + if (protocol == null) { + return null; + } else { + if (("http".equals(protocol)) || ("https".equals(protocol))) { // NOI18N + proxyType = Proxy.Type.HTTP; + } else { + proxyType = Proxy.Type.SOCKS; + } + } + StringTokenizer st = new StringTokenizer(proxiesString.toString(), ";"); //NOI18N + List proxies = new LinkedList(); + while (st.hasMoreTokens()) { + String proxy = st.nextToken(); + if (ProxySettings.DIRECT.equals(proxy.trim())) { + proxies.add(Proxy.NO_PROXY); + } else { + String host = getHost(proxy); + Integer port = getPort(proxy); + if (host != null && port != null) { + proxies.add(new Proxy(proxyType, new InetSocketAddress(host, port))); + } + } + } + return proxies; + } + + private static String getHost(String proxy) { + if (proxy.startsWith("PROXY ")) { + proxy = proxy.substring(6); + } + int i = proxy.lastIndexOf(":"); // NOI18N + if (i <= 0 || i >= proxy.length() - 1) { + LOGGER.info("No port in " + proxy); + return null; + } + + String host = proxy.substring(0, i); + + return ProxySettings.normalizeProxyHost(host); + } + + private static Integer getPort(String proxy) { + if (proxy.startsWith("PROXY ")) { + proxy = proxy.substring(6); + } + int i = proxy.lastIndexOf(":"); // NOI18N + if (i <= 0 || i >= proxy.length() - 1) { + LOGGER.info("No port in " + proxy); + return null; + } + + String port = proxy.substring(i + 1); + if (port.indexOf('/') >= 0) { + port = port.substring(0, port.indexOf('/')); + } + + try { + return Integer.parseInt(port); + } catch (NumberFormatException ex) { + LOGGER.log(Level.INFO, ex.getLocalizedMessage(), ex); + return null; + } + } + + private static String downloadUtils() { + StringBuilder builder = new StringBuilder(); + BufferedReader reader = null; + // XXX why is the below not more simply: + // reader = new BufferedReader(new URL(NS_PROXY_AUTO_CONFIG_URL).openStream()); + FileObject fo = null; + try { + try { + fo = URLMapper.findFileObject(new URL(NS_PROXY_AUTO_CONFIG_URL)); + } catch (MalformedURLException ex) { + LOGGER.log(Level.INFO, ex.getMessage(), ex); + } + reader = new BufferedReader(new java.io.FileReader(FileUtil.toFile(fo))); + } catch (FileNotFoundException ex) { + LOGGER.log(Level.INFO, ex.getMessage(), ex); + } + try { + String line; + boolean doAppend = false; + while ((line = reader.readLine()) != null) { + line = line.trim(); + if( line.startsWith("var pacUtils =") ) { //NOI18N + doAppend = true; + } + if( !doAppend ) + continue; + if (line.endsWith("+")) { // NOI18N + line = line.substring(0, line.length() - 1); + } + builder.append(line.replaceAll("\"", "").replaceAll("\\\\n", "").replaceAll("\\\\\\\\", "\\\\")); // NOI18N + builder.append(System.getProperty("line.separator")); // NOI18N + } + } catch (IOException ex) { + LOGGER.log(Level.INFO, "While downloading nsProxyAutoConfig.js thrown " + ex.getMessage(), ex); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException ex) { + LOGGER.log(Level.FINE, ex.getMessage(), ex); + } + } + } + return builder.toString(); + } + + private String normalizePAC(String pacURL) { + int index; + if ((index = pacURL.indexOf("\n")) != -1) { // NOI18N + pacURL = pacURL.substring(0, index); + } + if ((index = pacURL.indexOf("\r")) != -1) { // NOI18N + pacURL = pacURL.substring(0, index); + } + String fileLocation = pacURL; + if (fileLocation.startsWith(PROTO_FILE)) { + fileLocation = fileLocation.substring(PROTO_FILE.length()); + } + File f = new File(fileLocation); + if (f.canRead()) { + pacURL = Utilities.toURI(f).toString(); + } else { + pacURL = pacURL.replaceAll("\\\\", "/"); //NOI18N + } + if ((index = pacURL.indexOf(" ")) != -1) { // NOI18N + pacURL = pacURL.substring(0, index); + } + return pacURL.trim(); + } +} diff -r 3bff97f36acc core.network/src/org/netbeans/core/network/proxy/fallback/FallbackNetworkProxy.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/src/org/netbeans/core/network/proxy/fallback/FallbackNetworkProxy.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,121 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2013 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2013 Sun Microsystems, Inc. + */ +package org.netbeans.core.network.proxy.fallback; + +import java.util.logging.Level; +import java.util.logging.Logger; +import org.netbeans.core.network.proxy.NetworkProxyResolver; +import org.netbeans.core.network.proxy.NetworkProxySettings; + +/** + * Fallback resolver tries to retrieve proxy setting from environment variables. + * + * It is looking for: http_proxy, https_proxy, socks_proxy and no_proxy + * variables. It cannot resolve if PAC is set up. Also environment variables may + * be set but in system there are not used. Fallback cannot resolve it. + * + * @author lfischme + */ +public class FallbackNetworkProxy implements NetworkProxyResolver { + + private final static Logger LOGGER = Logger.getLogger(FallbackNetworkProxy.class.getName()); + + private final static String AT = "@"; //NOI18N + private final static String COMMA = ","; //NOI18N + private final static String SLASH = "/"; //NOI18N + private final static String PROTOCOL_PREXIF_SEPARATOR = "://"; //NOI18N + private final static String EMPTY_STRING = ""; //NOI18N + + private final static String HTTP_PROXY_SYS_PROPERTY = "http_proxy"; //NOI18N + private final static String HTTPS_PROXY_SYS_PROPERTY = "https_proxy"; //NOI18N + private final static String SOCKS_PROXY_SYS_PROPERTY = "socks_proxy"; //NOI18N + private final static String NO_PROXY_SYS_PROPERTY = "no_proxy"; //NOI18N + + @Override + public NetworkProxySettings getNetworkProxySettings() { + LOGGER.log(Level.FINE, "Fallback system proxy resolver started."); //NOI18N + String httpProxyRaw = System.getenv(HTTP_PROXY_SYS_PROPERTY); + if (httpProxyRaw != null && !httpProxyRaw.isEmpty()) { + String httpsProxyRaw = System.getenv(HTTPS_PROXY_SYS_PROPERTY); + String socksProxyRaw = System.getenv(SOCKS_PROXY_SYS_PROPERTY); + String noProxyRaw = System.getenv(NO_PROXY_SYS_PROPERTY); + + LOGGER.log(Level.INFO, "Fallback system proxy resolver: http_proxy={0}", httpProxyRaw); //NOI18N + LOGGER.log(Level.INFO, "Fallback system proxy resolver: https_proxy={0}", httpsProxyRaw); //NOI18N + LOGGER.log(Level.INFO, "Fallback system proxy resolver: socks_proxy={0}", socksProxyRaw); //NOI18N + LOGGER.log(Level.INFO, "Fallback system proxy resolver: no_proxy={0}", noProxyRaw); //NOI18N + + String httpProxy = prepareVariable(httpProxyRaw); + String httpsProxy = prepareVariable(httpsProxyRaw); + String socksProxy = prepareVariable(socksProxyRaw); + String[] noProxyHosts = noProxyRaw == null ? new String[0] : noProxyRaw.split(COMMA); + + return new NetworkProxySettings(httpProxy, httpsProxy, socksProxy, noProxyHosts); + } + + LOGGER.log(Level.INFO, "Fallback system proxy resolver: no http_proxy variable found"); //NOI18N + return new NetworkProxySettings(); + } + + private String prepareVariable(String variable) { + if (variable == null) { + return EMPTY_STRING; + } + + // remove slash at the end if present + if (variable.endsWith(SLASH)) { + variable = variable.substring(0, variable.length() - 1); + } + + // remove username and password if present + if (variable.contains(AT)) { + variable = variable.substring(variable.lastIndexOf(AT) + 1); + } + + // remove protocol prefix if presented + if (variable.contains(PROTOCOL_PREXIF_SEPARATOR)) { + variable = variable.substring(variable.indexOf(PROTOCOL_PREXIF_SEPARATOR) + 3); + } + + return variable; + } +} diff -r 3bff97f36acc core.network/src/org/netbeans/core/network/proxy/gnome/GconfNetworkProxy.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/src/org/netbeans/core/network/proxy/gnome/GconfNetworkProxy.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,232 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2013 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2013 Sun Microsystems, Inc. + */ +package org.netbeans.core.network.proxy.gnome; + +import java.io.BufferedReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.netbeans.core.network.proxy.NetworkProxySettings; +import static org.netbeans.core.network.proxy.gnome.GnomeNetworkProxy.executeCommand; + +/** + * + * @author lfischme + */ +public class GconfNetworkProxy { + + private final static Logger LOGGER = Logger.getLogger(GconfNetworkProxy.class.getName()); + + private final static String EQUALS = "="; //NOI18N + private final static String COLON = ","; //NOI18N + private final static String SQ_BRACKET_LEFT = "["; //NOI18N + private final static String SQ_BRACKET_RIGHT = "]"; //NOI18N + + protected final static String GCONF_PATH = "/usr/bin/gconftool-2"; //NOI18N + private final static String GCONF_ARGUMENT_LIST_RECURSIVELY = " -R "; //NOI18N + private final static String GCONF_NODE_PROXY = "/system/proxy"; //NOI18N + private final static String GCONF_NODE_HTTP_PROXY = "/system/http_proxy"; //NOI18N + private final static String GCONF_KEY_MODE = "mode"; //NOI18N + private final static String GCONF_KEY_PAC_URL = "autoconfig_url"; //NOI18N + private final static String GCONF_KEY_HTTP_ALL = "use_http_proxy"; //NOI18N + private final static String GCONF_KEY_HTTP_HOST = "host"; //NOI18N + private final static String GCONF_KEY_HTTP_PORT = "port"; //NOI18N + private final static String GCONF_KEY_HTTPS_HOST = "secure_host"; //NOI18N + private final static String GCONF_KEY_HTTPS_PORT = "secure_port"; //NOI18N + private final static String GCONF_KEY_SOCKS_HOST = "socks_host"; //NOI18N + private final static String GCONF_KEY_SOCKS_PORT = "socks_port"; //NOI18N + private final static String GCONF_KEY_IGNORE_HOSTS = "ignore_hosts"; //NOI18N + private final static String GCONF_VALUE_NONE = "none"; //NOI18N + private final static String GCONF_VALUE_AUTO = "auto"; //NOI18N + private final static String GCONF_VALUE_MANUAL = "manual"; //NOI18N + + /** + * Returns network proxy settings - retrieved via gconftool. + * + * @return network proxy settings via GSettings. + */ + protected static NetworkProxySettings getNetworkProxySettings() { + LOGGER.log(Level.FINE, "GConf system proxy resolver started."); //NOI18N + Map proxyProperties = getGconfMap(GCONF_NODE_PROXY); + + String proxyMode = proxyProperties.get(GCONF_KEY_MODE); + if (proxyMode == null) { + LOGGER.log(Level.SEVERE, "GConf proxy mode is null."); + return new NetworkProxySettings(false); + } + + if (proxyMode.equals(GCONF_VALUE_NONE)) { + LOGGER.log(Level.INFO, "GConf system proxy resolver: direct connection"); //NOI18N + return new NetworkProxySettings(); + } + + if (proxyMode.equals(GCONF_VALUE_AUTO)) { + String pacUrl = proxyProperties.get(GCONF_KEY_PAC_URL); + + LOGGER.log(Level.INFO, "GConf system proxy resolver: auto - PAC ({0})", pacUrl); //NOI18N + + if (pacUrl != null) { + return new NetworkProxySettings(pacUrl); + } else { + return new NetworkProxySettings(""); + } + } + + if (proxyMode.equals(GCONF_VALUE_MANUAL)) { + proxyProperties.putAll(getGconfMap(GCONF_NODE_HTTP_PROXY)); + + String httpProxyAll = proxyProperties.get(GCONF_KEY_HTTP_ALL); + String httpProxyHost = proxyProperties.get(GCONF_KEY_HTTP_HOST); + String httpProxyPort = proxyProperties.get(GCONF_KEY_HTTP_PORT); + String noProxyHosts = proxyProperties.get(GCONF_KEY_IGNORE_HOSTS); + + LOGGER.log(Level.INFO, "GConf system proxy resolver: manual - http for all ({0})", httpProxyAll); //NOI18N + LOGGER.log(Level.INFO, "GConf system proxy resolver: manual - http host ({0})", httpProxyHost); //NOI18N + LOGGER.log(Level.INFO, "GConf system proxy resolver: manual - http port ({0})", httpProxyPort); //NOI18N + LOGGER.log(Level.INFO, "GConf system proxy resolver: manual - ho proxy hosts ({0})", noProxyHosts); //NOI18N + + if (httpProxyAll != null && Boolean.parseBoolean(httpProxyAll)) { + return new NetworkProxySettings(httpProxyHost, httpProxyPort, getNoProxyHosts(noProxyHosts)); + } else { + String httpsProxyHost = proxyProperties.get(GCONF_KEY_HTTPS_HOST); + String httpsProxyPort = proxyProperties.get(GCONF_KEY_HTTPS_PORT); + String socksProxyHost = proxyProperties.get(GCONF_KEY_SOCKS_HOST); + String socksProxyPort = proxyProperties.get(GCONF_KEY_SOCKS_PORT); + + LOGGER.log(Level.INFO, "GConf system proxy resolver: manual - https host ({0})", httpsProxyHost); //NOI18N + LOGGER.log(Level.INFO, "GConf system proxy resolver: manual - https port ({0})", httpsProxyPort); //NOI18N + LOGGER.log(Level.INFO, "GConf system proxy resolver: manual - socks host ({0})", socksProxyHost); //NOI18N + LOGGER.log(Level.INFO, "GConf system proxy resolver: manual - socks port ({0})", socksProxyPort); //NOI18N + + return new NetworkProxySettings(httpProxyHost, httpProxyPort, + httpsProxyHost, httpsProxyPort, + socksProxyHost, socksProxyPort, getNoProxyHosts(noProxyHosts)); + } + } + + return new NetworkProxySettings(false); + } + + /** + * Returns map of properties retrieved from gconftool-2. + * + * Executes the command "/usr/bin/gconftool-2 -R [node]". + * + * @param gconfNode Node for which the properties should be returned. + * @return Map of properties retrieved from gconftool-2. + */ + private static Map getGconfMap(String gconfNode) { + Map map = new HashMap(); + + String command = GCONF_PATH + GCONF_ARGUMENT_LIST_RECURSIVELY + gconfNode; + + try { + BufferedReader reader = executeCommand(command); + if (reader != null) { + String line = reader.readLine(); + while (line != null) { + String key = getKey(line).toLowerCase(); + if (key != null && !key.isEmpty()) { + String value = getValue(line); + map.put(key, value); + } + line = reader.readLine(); + } + } else { + return map; + } + } catch (IOException ioe) { + LOGGER.log(Level.SEVERE, "Cannot read line: " + command, ioe); //NOI18N + } + + return map; + } + + /** + * Returns the key for one line response from gconftool-2. + * + * @param line Line from gconftool-2 response. + * @return The key for one line response from gconftool-2. + */ + private static String getKey(String line) { + return line.substring(0, line.indexOf(EQUALS)).trim(); + } + + /** + * Returns the value for one line response from gconftool-2. + * + * @param line Line from gconftool-2 response. + * @return The value for one line response from gconftool-2. + */ + private static String getValue(String line) { + return line.substring(line.indexOf(EQUALS) + 1).trim(); + } + + /** + * Returns array of Strings of no proxy hosts. + * + * The value responding to "ignore_hosts" key. + * + * Parses the value returned from gconftool-2. + * Usually [host1,host2,host3] + * + * @param noProxyHostsString The value returned from gconftool-2. + * @return Array of Strings of no proxy hosts. + */ + private static String[] getNoProxyHosts(String noProxyHostsString) { + if (noProxyHostsString != null && !noProxyHostsString.isEmpty()) { + if (noProxyHostsString.startsWith(SQ_BRACKET_LEFT)) { + noProxyHostsString = noProxyHostsString.substring(1); + } + + if (noProxyHostsString.endsWith(SQ_BRACKET_RIGHT)) { + noProxyHostsString = noProxyHostsString.substring(0, noProxyHostsString.length() - 1); + } + + return noProxyHostsString.split(COLON); + } + + return new String[0]; + } +} diff -r 3bff97f36acc core.network/src/org/netbeans/core/network/proxy/gnome/GnomeNetworkProxy.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/src/org/netbeans/core/network/proxy/gnome/GnomeNetworkProxy.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,93 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2013 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2013 Sun Microsystems, Inc. + */ +package org.netbeans.core.network.proxy.gnome; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.netbeans.core.network.proxy.NetworkProxyResolver; +import org.netbeans.core.network.proxy.NetworkProxySettings; + +/** + * + * @author lfischme + */ +public class GnomeNetworkProxy implements NetworkProxyResolver{ + + private final static Logger LOGGER = Logger.getLogger(GnomeNetworkProxy.class.getName()); + + @Override + public NetworkProxySettings getNetworkProxySettings() { + if (new File(GsettingsNetworkProxy.GSETTINGS_PATH).exists()) { + return GsettingsNetworkProxy.getNetworkProxySettings(); + } else if (new File(GconfNetworkProxy.GCONF_PATH).exists()) { + return GconfNetworkProxy.getNetworkProxySettings(); + } else { + return new NetworkProxySettings(false); + } + } + + /** + * + * + * @param command + * @return + */ + protected static BufferedReader executeCommand(String command) { + BufferedReader reader = null; + + try { + Process p = Runtime.getRuntime().exec(command); + p.waitFor(); + reader = new BufferedReader(new InputStreamReader(p.getInputStream())); + } catch (IOException ioe) { + LOGGER.log(Level.SEVERE, "Cannot execute command: " + command, ioe); + } catch (InterruptedException ie) { + LOGGER.log(Level.SEVERE, "Cannot execute command: " + command, ie); + } + + return reader; + } +} diff -r 3bff97f36acc core.network/src/org/netbeans/core/network/proxy/gnome/GsettingsNetworkProxy.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/src/org/netbeans/core/network/proxy/gnome/GsettingsNetworkProxy.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,245 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2013 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2013 Sun Microsystems, Inc. + */ +package org.netbeans.core.network.proxy.gnome; + +import java.io.BufferedReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.netbeans.core.network.proxy.NetworkProxySettings; +import static org.netbeans.core.network.proxy.gnome.GnomeNetworkProxy.executeCommand; + +/** + * + * @author lfischme + */ +public class GsettingsNetworkProxy { + + private final static Logger LOGGER = Logger.getLogger(GsettingsNetworkProxy.class.getName()); + + private final static String EMPTY_STRING = ""; //NOI18N + private final static String SPACE = " "; //NOI18N + private final static String DOT = "."; //NOI18N + private final static String COLON = ","; //NOI18N + private final static String SINGLE_QUOTE = "'"; //NOI18N + private final static String SQ_BRACKET_LEFT = "["; //NOI18N + private final static String SQ_BRACKET_RIGHT = "]"; //NOI18N + + protected final static String GSETTINGS_PATH = "/usr/bin/gsettings"; //NOI18N + private final static String GSETTINGS_ARGUMENT_LIST_RECURSIVELY = " list-recursively "; //NOI18N + private final static String GSETTINGS_PROXY_SCHEMA = "org.gnome.system.proxy"; //NOI18N + + private final static String GSETTINGS_KEY_MODE = "org.gnome.system.proxy.mode"; //NOI18N + private final static String GSETTINGS_KEY_PAC_URL = "org.gnome.system.proxy.autoconfig-url"; //NOI18N + private final static String GSETTINGS_KEY_HTTP_ALL = "org.gnome.system.proxy.http.use-same-proxy"; //NOI18N + private final static String GSETTINGS_KEY_HTTP_HOST = "org.gnome.system.proxy.http.host"; //NOI18N + private final static String GSETTINGS_KEY_HTTP_PORT = "org.gnome.system.proxy.http.port"; //NOI18N + private final static String GSETTINGS_KEY_HTTPS_HOST = "org.gnome.system.proxy.https.host"; //NOI18N + private final static String GSETTINGS_KEY_HTTPS_PORT = "org.gnome.system.proxy.https.port"; //NOI18N + private final static String GSETTINGS_KEY_SOCKS_HOST = "org.gnome.system.proxy.socks.host"; //NOI18N + private final static String GSETTINGS_KEY_SOCKS_PORT = "org.gnome.system.proxy.socks.port"; //NOI18N + private final static String GSETTINGS_KEY_IGNORE_HOSTS = "org.gnome.system.proxy.ignore-hosts"; //NOI18N + private final static String GSETTINGS_VALUE_NONE = "none"; //NOI18N + private final static String GSETTINGS_VALUE_AUTO = "auto"; //NOI18N + private final static String GSETTINGS_VALUE_MANUAL = "manual"; //NOI18N + + /** + * Returns network proxy settings - retrieved via GSettings (preferred). + * + * @return network proxy settings via GSettings. + */ + protected static NetworkProxySettings getNetworkProxySettings() { + LOGGER.log(Level.FINE, "GSettings system proxy resolver started."); //NOI18N + Map proxyProperties = getGsettingsMap(); + + String proxyMode = proxyProperties.get(GSETTINGS_KEY_MODE); + if (proxyMode == null) { + LOGGER.log(Level.SEVERE, "GSettings proxy mode is null."); + return new NetworkProxySettings(false); + } + + if (proxyMode.equals(GSETTINGS_VALUE_NONE)) { + LOGGER.log(Level.INFO, "GSettings system proxy resolver: direct connection"); //NOI18N + return new NetworkProxySettings(); + } + + if (proxyMode.equals(GSETTINGS_VALUE_AUTO)) { + String pacUrl = proxyProperties.get(GSETTINGS_KEY_PAC_URL); + + LOGGER.log(Level.INFO, "GSettings system proxy resolver: auto - PAC ({0})", pacUrl); //NOI18N + + if (pacUrl != null) { + return new NetworkProxySettings(pacUrl); + } else { + return new NetworkProxySettings(""); + } + } + + if (proxyMode.equals(GSETTINGS_VALUE_MANUAL)) { + String httpProxyAll = proxyProperties.get(GSETTINGS_KEY_HTTP_ALL); + String httpProxyHost = proxyProperties.get(GSETTINGS_KEY_HTTP_HOST); + String httpProxyPort = proxyProperties.get(GSETTINGS_KEY_HTTP_PORT); + String noProxyHosts = proxyProperties.get(GSETTINGS_KEY_IGNORE_HOSTS); + + LOGGER.log(Level.INFO, "GSettings system proxy resolver: manual - http for all ({0})", httpProxyAll); //NOI18N + LOGGER.log(Level.INFO, "GSettings system proxy resolver: manual - http host ({0})", httpProxyHost); //NOI18N + LOGGER.log(Level.INFO, "GSettings system proxy resolver: manual - http port ({0})", httpProxyPort); //NOI18N + LOGGER.log(Level.INFO, "GSettings system proxy resolver: manual - ho proxy hosts ({0})", noProxyHosts); //NOI18N + + if (httpProxyAll != null && Boolean.parseBoolean(httpProxyAll)) { + return new NetworkProxySettings(httpProxyHost, httpProxyPort, getNoProxyHosts(noProxyHosts)); + } else { + String httpsProxyHost = proxyProperties.get(GSETTINGS_KEY_HTTPS_HOST); + String httpsProxyPort = proxyProperties.get(GSETTINGS_KEY_HTTPS_PORT); + String socksProxyHost = proxyProperties.get(GSETTINGS_KEY_SOCKS_HOST); + String socksProxyPort = proxyProperties.get(GSETTINGS_KEY_SOCKS_PORT); + + LOGGER.log(Level.INFO, "GSettings system proxy resolver: manual - https host ({0})", httpsProxyHost); //NOI18N + LOGGER.log(Level.INFO, "GSettings system proxy resolver: manual - https port ({0})", httpsProxyPort); //NOI18N + LOGGER.log(Level.INFO, "GSettings system proxy resolver: manual - socks host ({0})", socksProxyHost); //NOI18N + LOGGER.log(Level.INFO, "GSettings system proxy resolver: manual - socks port ({0})", socksProxyPort); //NOI18N + + return new NetworkProxySettings(httpProxyHost, httpProxyPort, + httpsProxyHost, httpsProxyPort, + socksProxyHost, socksProxyPort, getNoProxyHosts(noProxyHosts)); + } + } + + return new NetworkProxySettings(false); + } + + /** + * Returns map of properties retrieved from GSettings. + * + * Executes the command "/usr/bin/gsettings list-recursively org.gnome.system.proxy". + * + * @return Map of properties retrieved from GSettings. + */ + private static Map getGsettingsMap() { + Map map = new HashMap(); + + String command = GSETTINGS_PATH + GSETTINGS_ARGUMENT_LIST_RECURSIVELY + GSETTINGS_PROXY_SCHEMA; + + try { + BufferedReader reader = executeCommand(command); + String line = reader.readLine(); + while (line != null) { + String key = getKey(line).toLowerCase(); + if (key != null && !key.isEmpty()) { + String value = getValue(line); + map.put(key, value); + } + line = reader.readLine(); + } + } catch (IOException ioe) { + LOGGER.log(Level.SEVERE, "Cannot read line: " + command, ioe); //NOI18N + } + + return map; + } + + /** + * Returns the key for one line response from GSettings. + * + * @param line Line from GSettings response. + * @return The key for one line response from GSettings. + */ + private static String getKey(String line) { + String[] splittedLine = line.split(SPACE); + + if (splittedLine.length >= 2) { + return splittedLine[0] + DOT + splittedLine[1]; + } else { + return null; + } + } + + /** + * Returns the value for one line response from GSettings. + * + * @param line Line from GSettings response. + * @return The value for one line response from GSettings. + */ + private static String getValue(String line) { + String[] splittedLine = line.split(SPACE); + + if (splittedLine.length > 2) { + StringBuilder value = new StringBuilder(); + for (int i = 2; i < splittedLine.length; i++) { + value.append(splittedLine[i]); + } + return value.toString().replaceAll(SINGLE_QUOTE, EMPTY_STRING); + } else { + return null; + } + } + + /** + * Returns array of Strings of no proxy hosts. + * + * The value responding to "ignore_hosts" key. + * + * Parses the value returned from GSettings. + * Usually ['host1', 'host2', 'host3'] + * But value is in form [host1,host2,host3] + * + * @param noProxyHostsString The value returned from GSettingsc. + * @return Array of Strings of no proxy hosts. + */ + private static String[] getNoProxyHosts(String noProxyHostsString) { + if (noProxyHostsString != null && !noProxyHostsString.isEmpty()) { + if (noProxyHostsString.startsWith(SQ_BRACKET_LEFT)) { + noProxyHostsString = noProxyHostsString.substring(1); + } + + if (noProxyHostsString.endsWith(SQ_BRACKET_RIGHT)) { + noProxyHostsString = noProxyHostsString.substring(0, noProxyHostsString.length() - 1); + } + + return noProxyHostsString.split(COLON); + } + + return new String[0]; + } +} diff -r 3bff97f36acc core.network/src/org/netbeans/core/network/proxy/kde/KdeNetworkProxy.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/src/org/netbeans/core/network/proxy/kde/KdeNetworkProxy.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,220 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2013 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2013 Sun Microsystems, Inc. + */ +package org.netbeans.core.network.proxy.kde; + +import java.io.BufferedReader; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.netbeans.core.network.proxy.NetworkProxyResolver; +import org.netbeans.core.network.proxy.NetworkProxySettings; + +/** + * + * @author lfischme + */ +public class KdeNetworkProxy implements NetworkProxyResolver { + + private final static Logger LOGGER = Logger.getLogger(KdeNetworkProxy.class.getName()); + + private final static String EMPTY_STRING = ""; //NOI18N + private final static String SPACE = " "; //NOI18N + private final static String EQUALS = "="; //NOI18N + private final static String COLON = ":"; //NOI18N + private final static String COMMA = ","; //NOI18N + private final static String SQ_BRACKET_LEFT = "["; //NOI18N + private final static String HOME = "HOME"; //NOI18N + private final static String KIOSLAVERC_PROXY_SETTINGS_GROUP = "[Proxy Settings]"; //NOI18N + private final static String KIOSLAVERC_PROXY_TYPE = "ProxyType"; //NOI18N + private final static String KIOSLAVERC_PROXY_CONFIG_SCRIPT = "Proxy Config Script"; //NOI18N + private final static String KIOSLAVERC_HTTP_PROXY = "httpProxy"; //NOI18N + private final static String KIOSLAVERC_HTTPS_PROXY = "httpsProxy"; //NOI18N + private final static String KIOSLAVERC_SOCKS_PROXY = "socksProxy"; //NOI18N + private final static String KIOSLAVERC_NO_PROXY_FOR = "NoProxyFor"; //NOI18N + private final static String KIOSLAVERC_PROXY_TYPE_NONE = "0"; //NOI18N + private final static String KIOSLAVERC_PROXY_TYPE_MANUAL = "1"; //NOI18N + private final static String KIOSLAVERC_PROXY_TYPE_PAC = "2"; //NOI18N + private final static String KIOSLAVERC_PROXY_TYPE_AUTO = "3"; //NOI18N + private final static String KIOSLAVERC_PROXY_TYPE_SYSTEM = "4"; //NOI18N + private final static String KIOSLAVERC_PATH_IN_HOME = ".kde/share/config/kioslaverc"; //NOI18N + private final String KIOSLAVERC_PATH; + + public KdeNetworkProxy() { + KIOSLAVERC_PATH = getKioslavercPath(); + } + + @Override + public NetworkProxySettings getNetworkProxySettings() { + LOGGER.log(Level.FINE, "KDE system proxy resolver started."); //NOI18N + Map kioslavercMap = getKioslavercMap(); + + String proxyType = kioslavercMap.get(KIOSLAVERC_PROXY_TYPE); + if (proxyType == null) { + LOGGER.log(Level.WARNING, "KDE system proxy resolver: The kioslaverc key not found ({0})", KIOSLAVERC_PROXY_TYPE); //NOI18N + return new NetworkProxySettings(false); + } + + if (proxyType.equals(KIOSLAVERC_PROXY_TYPE_NONE) || proxyType.equals(KIOSLAVERC_PROXY_TYPE_AUTO)) { + LOGGER.log(Level.INFO, "KDE system proxy resolver: direct (proxy type: {0})", proxyType); //NOI18N + return new NetworkProxySettings(); + } + + if (proxyType.equals(KIOSLAVERC_PROXY_TYPE_PAC)) { + LOGGER.log(Level.INFO, "KDE system proxy resolver: auto - PAC"); //NOI18N + String pacFileUrl = kioslavercMap.get(KIOSLAVERC_PROXY_CONFIG_SCRIPT); + if (pacFileUrl != null) { + LOGGER.log(Level.INFO, "KDE system proxy resolver: PAC URL ({0})", pacFileUrl); //NOI18N + return new NetworkProxySettings(pacFileUrl); + } else { + LOGGER.log(Level.INFO, "KDE system proxy resolver: PAC URL null value"); //NOI18N + return new NetworkProxySettings(false); + } + } + + if (proxyType.equals(KIOSLAVERC_PROXY_TYPE_MANUAL) || proxyType.equals(KIOSLAVERC_PROXY_TYPE_SYSTEM)) { + LOGGER.log(Level.INFO, "KDE system proxy resolver: manual (proxy type: {0})", proxyType); //NOI18N + + String httpProxy = kioslavercMap.get(KIOSLAVERC_HTTP_PROXY); + String httpsProxy = kioslavercMap.get(KIOSLAVERC_HTTPS_PROXY); + String socksProxy = kioslavercMap.get(KIOSLAVERC_SOCKS_PROXY); + String noProxyFor = kioslavercMap.get(KIOSLAVERC_NO_PROXY_FOR); + + LOGGER.log(Level.INFO, "KDE system proxy resolver: http proxy ({0})", httpProxy); //NOI18N + LOGGER.log(Level.INFO, "KDE system proxy resolver: https proxy ({0})", httpsProxy); //NOI18N + LOGGER.log(Level.INFO, "KDE system proxy resolver: socks proxy ({0})", socksProxy); //NOI18N + LOGGER.log(Level.INFO, "KDE system proxy resolver: no proxy ({0})", noProxyFor); //NOI18N + + if (proxyType.equals(KIOSLAVERC_PROXY_TYPE_MANUAL)) { + httpProxy = httpProxy == null ? EMPTY_STRING : httpProxy.trim().replaceAll(SPACE, COLON); + httpsProxy = httpsProxy == null ? EMPTY_STRING : httpsProxy.trim().replaceAll(SPACE, COLON); + socksProxy = socksProxy == null ? EMPTY_STRING : socksProxy.trim().replaceAll(SPACE, COLON); + } + + String[] noProxyHosts = getNoProxyHosts(noProxyFor); + + return new NetworkProxySettings(httpProxy, httpsProxy, socksProxy, noProxyHosts); + } + + return new NetworkProxySettings(false); + } + + /** + * Raturns map of keys and values from kioslaverc group Proxy settings. + * + * Reads "[userhome]/.kde/share/config/kioslaverc" file. + * + * @return Map of keys and values from kioslaverc group Proxy settings. + */ + private Map getKioslavercMap() { + File kioslavercFile = new File(KIOSLAVERC_PATH); + Map map = new HashMap(); + + if (kioslavercFile.exists()) { + try { + FileInputStream fis = new FileInputStream(kioslavercFile); + DataInputStream dis = new DataInputStream(fis); + BufferedReader br = new BufferedReader(new InputStreamReader(dis)); + String line; + boolean inGroup = false; + while ((line = br.readLine()) != null) { + if (inGroup) { + if (line.contains(EQUALS)) { + int indexOfEquals = line.indexOf(EQUALS); + String key = line.substring(0, indexOfEquals); + String value = line.substring(indexOfEquals + 1); + map.put(key, value); + } else if (line.startsWith(SQ_BRACKET_LEFT)) { + break; + } + } else if (line.startsWith(KIOSLAVERC_PROXY_SETTINGS_GROUP)) { + inGroup = true; + } + } + dis.close(); + } catch (FileNotFoundException fnfe) { + LOGGER.log(Level.SEVERE, "Cannot read file: ", fnfe); + } catch (IOException ioe) { + LOGGER.log(Level.SEVERE, "Cannot read file: ", ioe); + } + } else { + LOGGER.log(Level.WARNING, "KDE system proxy resolver: The kioslaverc file not found ({0})", KIOSLAVERC_PATH); + } + + return map; + } + + /** + * Returns path of the kioslaverc config file. + * + * @return Path of the kioslaverc config file. + */ + private String getKioslavercPath() { + String homePath = System.getenv(HOME); + + if (homePath != null) { + return homePath + File.separator + KIOSLAVERC_PATH_IN_HOME; + } else { + return EMPTY_STRING; + } + } + + /** + * Returns array of Strings of no proxy hosts. + * + * @param noProxyHostsString No proxy host in one string separated by comma. + * @return Array of Strings of no proxy hosts. + */ + private static String[] getNoProxyHosts(String noProxyHostsString) { + if (noProxyHostsString != null && !noProxyHostsString.isEmpty()) { + return noProxyHostsString.split(COMMA); + } + + return new String[0]; + } +} diff -r 3bff97f36acc core.network/src/org/netbeans/core/network/proxy/mac/MacCoreFoundationLibrary.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/src/org/netbeans/core/network/proxy/mac/MacCoreFoundationLibrary.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,36 @@ +package org.netbeans.core.network.proxy.mac; + +import com.sun.jna.Library; +import com.sun.jna.Native; +import com.sun.jna.Pointer; +import com.sun.jna.Structure; + +/** + * + * @author lfischme + */ +public interface MacCoreFoundationLibrary extends Library { + MacCoreFoundationLibrary LIBRARY = (MacCoreFoundationLibrary) Native.loadLibrary("CoreFoundation", MacCoreFoundationLibrary.class); + + public boolean CFDictionaryGetValueIfPresent(Pointer dictionary, Pointer key, Pointer[] returnValue); + + public Pointer CFDictionaryGetValue(Pointer dictionary, Pointer key); + + public Pointer CFStringCreateWithCString(Pointer alloc, byte[] string, Pointer encoding); + + public long CFStringGetLength(Pointer cfStringRef); + + public long CFStringGetMaximumSizeForEncoding(long lenght, int encoding); + + public boolean CFStringGetCString(Pointer cfStringRef, Pointer buffer, long maxSize, int encoding); + + public Pointer CFNumberGetType(Pointer cfNumberRef); + + public boolean CFNumberGetValue(Pointer cfNumberRef, Pointer cfNumberType, Pointer value); + + public long CFNumberGetByteSize(Pointer cfNumberRef); + + public long CFArrayGetCount(Pointer cfArrayRef); + + public Pointer CFArrayGetValueAtIndex(Pointer cfArrayRef, Pointer cfIndex); +} diff -r 3bff97f36acc core.network/src/org/netbeans/core/network/proxy/mac/MacNetworkProxy.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/src/org/netbeans/core/network/proxy/mac/MacNetworkProxy.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,258 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2013 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2013 Sun Microsystems, Inc. + */ +package org.netbeans.core.network.proxy.mac; + +import com.sun.jna.Memory; +import com.sun.jna.NativeLibrary; +import com.sun.jna.Pointer; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.netbeans.core.network.proxy.NetworkProxyResolver; +import org.netbeans.core.network.proxy.NetworkProxySettings; + +/** + * + * @author lfischme + */ +public class MacNetworkProxy implements NetworkProxyResolver { + + private final static Logger LOGGER = Logger.getLogger(MacNetworkProxy.class.getName()); + + private final static MacNetworkProxyLibrary cfNetworkLibrary = MacNetworkProxyLibrary.LIBRARY; + private final static MacCoreFoundationLibrary cfLibrary = MacCoreFoundationLibrary.LIBRARY; + + private final static String COMMA = ","; //NOI18N + + private final static NativeLibrary NETWORK_LIBRARY = NativeLibrary.getInstance("CFNetwork"); //NOI18N + private final static String KEY_AUTO_DISCOVERY_ENABLE = "kCFNetworkProxiesProxyAutoDiscoveryEnable"; //NOI18N + private final static String KEY_PAC_ENABLE = "kCFNetworkProxiesProxyAutoConfigEnable"; //NOI18N + private final static String KEY_PAC_URL = "kCFNetworkProxiesProxyAutoConfigURLString"; //NOI18N + private final static String KEY_HTTP_ENABLE = "kCFNetworkProxiesHTTPEnable"; //NOI18N + private final static String KEY_HTTP_HOST = "kCFNetworkProxiesHTTPProxy"; //NOI18N + private final static String KEY_HTTP_PORT = "kCFNetworkProxiesHTTPPort"; //NOI18N + private final static String KEY_HTTPS_ENABLE = "kCFNetworkProxiesHTTPSEnable"; //NOI18N + private final static String KEY_HTTPS_HOST = "kCFNetworkProxiesHTTPSProxy"; //NOI18N + private final static String KEY_HTTPS_PORT = "kCFNetworkProxiesHTTPSPort"; //NOI18N + private final static String KEY_SOCKS_ENABLE = "kCFNetworkProxiesSOCKSEnable"; //NOI18N + private final static String KEY_SOCKS_HOST = "kCFNetworkProxiesSOCKSProxy"; //NOI18N + private final static String KEY_SOCKS_PORT = "kCFNetworkProxiesSOCKSPort"; //NOI18N + private final static String KEY_EXCEPTIONS_LIST = "kCFNetworkProxiesExceptionsList"; //NOI18N + + @Override + public NetworkProxySettings getNetworkProxySettings() { + LOGGER.log(Level.FINE, "Mac system proxy resolver started."); //NOI18N + Pointer settingsDictionary = cfNetworkLibrary.CFNetworkCopySystemProxySettings(); + + Pointer autoDiscoveryEnable = cfLibrary.CFDictionaryGetValue(settingsDictionary, getKeyCFStringRef(KEY_AUTO_DISCOVERY_ENABLE)); + if (getIntFromCFNumberRef(autoDiscoveryEnable) != 0) { + LOGGER.log(Level.INFO, "Mac system proxy resolver: auto detect"); //NOI18N + return new NetworkProxySettings(); + } + + Pointer pacEnable = cfLibrary.CFDictionaryGetValue(settingsDictionary, getKeyCFStringRef(KEY_PAC_ENABLE)); + if (getIntFromCFNumberRef(pacEnable) != 0) { + Pointer[] pacUrlPointer = new Pointer[1]; + if (cfLibrary.CFDictionaryGetValueIfPresent(settingsDictionary, getKeyCFStringRef(KEY_PAC_URL), pacUrlPointer)) { + String pacUrl = getStringFromCFStringRef(pacUrlPointer[0]); + + LOGGER.log(Level.INFO, "Mac system proxy resolver: auto - PAC ({0})", pacUrl); //NOI18N + return new NetworkProxySettings(pacUrl); + } + } + + Pointer httpEnable = cfLibrary.CFDictionaryGetValue(settingsDictionary, getKeyCFStringRef(KEY_HTTP_ENABLE)); + Pointer httpsEnable = cfLibrary.CFDictionaryGetValue(settingsDictionary, getKeyCFStringRef(KEY_HTTPS_ENABLE)); + Pointer socksEnable = cfLibrary.CFDictionaryGetValue(settingsDictionary, getKeyCFStringRef(KEY_SOCKS_ENABLE)); + if (getIntFromCFNumberRef(httpEnable) != 0 || getIntFromCFNumberRef(httpsEnable) != 0 || getIntFromCFNumberRef(socksEnable) != 0) { + String httpHost = getStringFromCFStringRef(getValueIfExists(settingsDictionary, KEY_HTTP_HOST)); + String httpPort = getStringFromCFNumberRef(getValueIfExists(settingsDictionary, KEY_HTTP_PORT)); + String httpsHost = getStringFromCFStringRef(getValueIfExists(settingsDictionary, KEY_HTTPS_HOST)); + String httpsPort = getStringFromCFNumberRef(getValueIfExists(settingsDictionary, KEY_HTTPS_PORT)); + String socksHost = getStringFromCFStringRef(getValueIfExists(settingsDictionary, KEY_SOCKS_HOST)); + String socksPort = getStringFromCFNumberRef(getValueIfExists(settingsDictionary, KEY_SOCKS_PORT)); + String[] noProxyHosts = getNoProxyHosts(getValueIfExists(settingsDictionary, KEY_EXCEPTIONS_LIST)); + + LOGGER.log(Level.INFO, "Mac system proxy resolver: manual - http host ({0})", httpHost); //NOI18N + LOGGER.log(Level.INFO, "Mac system proxy resolver: manual - http port ({0})", httpPort); //NOI18N + LOGGER.log(Level.INFO, "Mac system proxy resolver: manual - https host ({0})", httpsHost); //NOI18N + LOGGER.log(Level.INFO, "Mac system proxy resolver: manual - https port ({0})", httpsPort); //NOI18N + LOGGER.log(Level.INFO, "Mac system proxy resolver: manual - socks host ({0})", socksHost); //NOI18N + LOGGER.log(Level.INFO, "Mac system proxy resolver: manual - socks port ({0})", socksPort); //NOI18N + LOGGER.log(Level.INFO, "Mac system proxy resolver: manual - no proxy hosts ({0})", getStringFromArray(noProxyHosts)); //NOI18N + + return new NetworkProxySettings(httpHost, httpPort, httpsHost, httpsPort, socksHost, socksPort, noProxyHosts); + } + + return new NetworkProxySettings(false); + } + + /** + * Converts String key object to CFString key object. + * + * @param key String key + * @return CFString key object pointer + */ + private Pointer getKeyCFStringRef(String key) { + return NETWORK_LIBRARY.getGlobalVariableAddress(key).getPointer(0L); + } + + /** + * Converts CFString object to String. + * + * @param cfStringPointer Pointer to CFString object + * @return String from CFString + */ + private String getStringFromCFStringRef(Pointer cfStringPointer) { + if (cfStringPointer != null) { + long lenght = cfLibrary.CFStringGetLength(cfStringPointer); + long maxSize = cfLibrary.CFStringGetMaximumSizeForEncoding(lenght, 0x08000100); // 0x08000100 = UTF-8 + + Pointer buffer = new Memory(maxSize); + + if (cfLibrary.CFStringGetCString(cfStringPointer, buffer, maxSize, 0x08000100)) { // 0x08000100 = UTF-8 + return buffer.getString(0L); + } + } + + return null; + } + + /** + * Converts CFNumber to int. + * + * @param cfNumberPointer pointer to CFNumber object + * @return int from CFNumber + */ + private int getIntFromCFNumberRef(Pointer cfNumberPointer) { + if (cfNumberPointer != null) { + Pointer cfNumberType = cfLibrary.CFNumberGetType(cfNumberPointer); + + long numberSize = cfLibrary.CFNumberGetByteSize(cfNumberPointer); + Pointer numberValue = new Memory(numberSize); + if (cfLibrary.CFNumberGetValue(cfNumberPointer, cfNumberType, numberValue)) { + return numberValue.getInt(0L); + } + } + + return 0; + } + + /** + * Converts CFNumber to String. + * + * @param cfNumberPointer pointer to CFNumber object + * @return String from CFNumber + */ + private String getStringFromCFNumberRef(Pointer cfNumberPointer) { + if (cfNumberPointer != null) { + Pointer cfNumberType = cfLibrary.CFNumberGetType(cfNumberPointer); + + long numberSize = cfLibrary.CFNumberGetByteSize(cfNumberPointer); + Pointer numberValue = new Memory(numberSize); + if (cfLibrary.CFNumberGetValue(cfNumberPointer, cfNumberType, numberValue)) { + return String.valueOf(numberValue.getInt(0L)); + } + } + + return null; + } + + /** + * Returns array of Strings with no proxy hosts retrieved from pointer to CFArray. + * + * @param noProxyHostsPointer Pointer to CFArray of CFStrings with no proxy hosts + * @return Array of Strings with no proxy hosts retrieved from pointer to CFArray. + */ + private String[] getNoProxyHosts(Pointer noProxyHostsPointer) { + if (noProxyHostsPointer != null) { + long arrayLenght = cfLibrary.CFArrayGetCount(noProxyHostsPointer); + String[] noProxyHosts = new String[(int) arrayLenght]; + for (long i = 0; i < arrayLenght; i++) { + Pointer value = cfLibrary.CFArrayGetValueAtIndex(noProxyHostsPointer, new Pointer(i)); + String noProxyHost = getStringFromCFStringRef(value); + noProxyHosts[(int) i] = noProxyHost; + } + // Much more better would be to use CFArrayGetValues method. + // But I was unsuccessful to retrieve value correctly. + // the const void **value is problem in this case + // also CFRange wasn't easy to create (via Structure) + + return noProxyHosts; + } + + return new String[0]; + } + + /** + * Returns value from CFDictionary if exists. + * + * @param settingsDictionary pointer to CFDictionary + * @param key Key for which value should be returned + * @return Value from CFDictionary if exists. + */ + private Pointer getValueIfExists(Pointer settingsDictionary, String key) { + Pointer[] returnValue = new Pointer[1]; + if (cfLibrary.CFDictionaryGetValueIfPresent(settingsDictionary, getKeyCFStringRef(key), returnValue)) { + return returnValue[0]; + } else { + return null; + } + } + + /** + * Returns string from array of strings. Strings are sepparated by comma. + * + * @param stringArray + * @return String from array of strings. Strings are sepparated by comma. + */ + private static String getStringFromArray(String[] stringArray) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < stringArray.length; i++) { + sb.append(stringArray[i]); + if (i == stringArray.length - 1) { + sb.append(COMMA); + } + } + + return sb.toString(); + } +} diff -r 3bff97f36acc core.network/src/org/netbeans/core/network/proxy/mac/MacNetworkProxyLibrary.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/src/org/netbeans/core/network/proxy/mac/MacNetworkProxyLibrary.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,15 @@ +package org.netbeans.core.network.proxy.mac; + +import com.sun.jna.Library; +import com.sun.jna.Native; +import com.sun.jna.Pointer; + +/** + * + * @author lfischme + */ +public interface MacNetworkProxyLibrary extends Library { + MacNetworkProxyLibrary LIBRARY = (MacNetworkProxyLibrary) Native.loadLibrary("CFNetwork", MacNetworkProxyLibrary.class); + + public Pointer CFNetworkCopySystemProxySettings(); +} diff -r 3bff97f36acc core.network/src/org/netbeans/core/network/proxy/windows/WindowsNetworkProxy.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/src/org/netbeans/core/network/proxy/windows/WindowsNetworkProxy.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,154 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2013 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2013 Sun Microsystems, Inc. + */ +package org.netbeans.core.network.proxy.windows; + +import com.sun.jna.Pointer; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.netbeans.core.network.proxy.NetworkProxyResolver; +import org.netbeans.core.network.proxy.NetworkProxySettings; + +/** + * + * @author lfischme + */ +public class WindowsNetworkProxy implements NetworkProxyResolver { + + private final static Logger LOGGER = Logger.getLogger(WindowsNetworkProxy.class.getName()); + + private final static String HTTP_PROPERTY_NAME = "http="; //NOI18N + private final static String HTTPS_PROPERTY_NAME = "https="; //NOI18N + private final static String SOCKS_PROPERTY_NAME = "socks="; //NOI18N + + private final static String SPACE = " "; //NOI18N + private final static String COLON = ":"; //NOI18N + private final static String SEMI_COLON = ";"; //NOI18N + + + @Override + public NetworkProxySettings getNetworkProxySettings() { + LOGGER.log(Level.FINE, "Windows system proxy resolver started."); //NOI18N + WindowsNetworkProxyLibrary.ProxyConfig.ByReference prxCnf = new WindowsNetworkProxyLibrary.ProxyConfig.ByReference(); + + boolean result = WindowsNetworkProxyLibrary.LIBRARY.WinHttpGetIEProxyConfigForCurrentUser(prxCnf); + + if (result) { + LOGGER.log(Level.FINE, "Windows system proxy resolver successfully retrieved proxy settings."); //NOI18N + + if (prxCnf.autoDetect) { + LOGGER.log(Level.INFO, "Windows system proxy resolver: auto detect"); //NOI18N + return new NetworkProxySettings(); + } + + Pointer pacFilePointer = prxCnf.pacFile; + if (pacFilePointer != null) { + String pacFileUrl = pacFilePointer.getString(0L, true); + + LOGGER.log(Level.INFO, "Windows system proxy resolver: auto - PAC ({0})", pacFileUrl); //NOI18N + return new NetworkProxySettings(pacFileUrl); + } + + Pointer proxyPointer = prxCnf.proxy; + Pointer proxyBypassPointer = prxCnf.proxyBypass; + if (proxyPointer != null) { + String proxyString = proxyPointer.getString(0L, true); + + LOGGER.log(Level.INFO, "Windows system proxy resolver: manual ({0})", proxyString); //NOI18N + + String httpProxy = null; + String httpsProxy = null; + String socksProxy = null; + String[] noProxyHosts; + + if (proxyString != null) { + proxyString = proxyString.toLowerCase(); + } + + if (proxyString.contains(SEMI_COLON)) { + String[] proxies = proxyString.split(SEMI_COLON); + for (String singleProxy : proxies) { + if (singleProxy.startsWith(HTTP_PROPERTY_NAME)) { + httpProxy = singleProxy.substring(HTTP_PROPERTY_NAME.length()); + } else if (singleProxy.startsWith(HTTPS_PROPERTY_NAME)) { + httpsProxy = singleProxy.substring(HTTPS_PROPERTY_NAME.length()); + } else if (singleProxy.startsWith(SOCKS_PROPERTY_NAME)) { + socksProxy = singleProxy.substring(SOCKS_PROPERTY_NAME.length()); + } + } + } else { + if (proxyString.startsWith(HTTP_PROPERTY_NAME)) { + proxyString = proxyString.substring(HTTP_PROPERTY_NAME.length()); + httpProxy = proxyString.replace(SPACE, COLON); + } else if (proxyString.startsWith(HTTPS_PROPERTY_NAME)) { + proxyString = proxyString.substring(HTTPS_PROPERTY_NAME.length()); + httpsProxy = proxyString.replace(SPACE, COLON); + } else if (proxyString.startsWith(SOCKS_PROPERTY_NAME)) { + proxyString = proxyString.substring(SOCKS_PROPERTY_NAME.length()); + socksProxy = proxyString.replace(SPACE, COLON); + } else { + httpProxy = proxyString; + httpsProxy = proxyString; + } + } + + if (proxyBypassPointer != null) { + String proxyBypass = proxyBypassPointer.getString(0L, true); + + LOGGER.log(Level.INFO, "Windows system proxy resolver: manual - no proxy hosts ({0})", proxyBypass); //NOI18N + + noProxyHosts = proxyBypass.split(SEMI_COLON); + } else { + noProxyHosts = new String[0]; + } + + return new NetworkProxySettings(httpProxy, httpsProxy, socksProxy, noProxyHosts); + } + + LOGGER.log(Level.FINE, "Windows system proxy resolver: no proxy"); //NOI18N + return new NetworkProxySettings(); + } else { + LOGGER.log(Level.SEVERE, "Windows system proxy resolver cannot retrieve proxy settings from Windows API!"); //NOI18N + } + + return new NetworkProxySettings(false); + } +} diff -r 3bff97f36acc core.network/src/org/netbeans/core/network/proxy/windows/WindowsNetworkProxyLibrary.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/src/org/netbeans/core/network/proxy/windows/WindowsNetworkProxyLibrary.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,68 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2013 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2013 Sun Microsystems, Inc. + */ +package org.netbeans.core.network.proxy.windows; + +import com.sun.jna.Library; +import com.sun.jna.Native; +import com.sun.jna.Pointer; +import com.sun.jna.Structure; + +/** + * + * @author lfischme + */ +public interface WindowsNetworkProxyLibrary extends Library { + WindowsNetworkProxyLibrary LIBRARY = (WindowsNetworkProxyLibrary) Native.loadLibrary("winhttp.dll", WindowsNetworkProxyLibrary.class); + + public class ProxyConfig extends Structure { + public static class ByReference extends ProxyConfig implements Structure.ByReference { } + + public boolean autoDetect; + public Pointer pacFile; + public Pointer proxy; + public Pointer proxyBypass; + } + + public boolean WinHttpGetIEProxyConfigForCurrentUser( + ProxyConfig proxyConfig + ); +} diff -r 3bff97f36acc core.network/test/unit/data/pacFiles/wpad space.dat --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/test/unit/data/pacFiles/wpad space.dat Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,8 @@ +function FindProxyForURL(url, host) +{ + // Make everything lower case. + url = url.toLowerCase(); + host = host.toLowerCase(); + if (isPlainHostName(host)) return "DIRECT"; + return "PROXY www-proxy.us.oracle.com:80"; +}; diff -r 3bff97f36acc core.network/test/unit/data/pacFiles/wpad.dat --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/test/unit/data/pacFiles/wpad.dat Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,8 @@ +function FindProxyForURL(url, host) +{ + // Make everything lower case. + url = url.toLowerCase(); + host = host.toLowerCase(); + if (isPlainHostName(host)) return "DIRECT"; + return "PROXY www-proxy.us.oracle.com:80"; +}; diff -r 3bff97f36acc core.network/test/unit/src/org/netbeans/core/network/proxy/CanProxyToLocalhostTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/test/unit/src/org/netbeans/core/network/proxy/CanProxyToLocalhostTest.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,113 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2012 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun + * Microsystems, Inc. All Rights Reserved. + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + */ +package org.netbeans.core.network.proxy; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import org.netbeans.junit.NbTestCase; + +/** + * Check whether we can proxy to localhost. + */ +public class CanProxyToLocalhostTest extends NbTestCase { + + private static String USER_PROXY_HOST = "my.webcache"; + private static int USER_PROXY_PORT = 8080; + private ProxySelector selector; + private static URI TO_LOCALHOST; + private static URI TO_NB; + private MyPS myPS; + + public CanProxyToLocalhostTest(String name) { + super(name); + } + + @Override + protected void setUp() throws Exception { + myPS = new MyPS(); + ProxySelector.setDefault(myPS); + selector = new NbProxySelector(); + TO_LOCALHOST = new URI("http://localhost"); + TO_NB = new URI("http://netbeans.org"); + } + + public void testNoProxyForLocalhost() { + Locale.setDefault(Locale.US); + assertEquals("Connect TO_LOCALHOST DIRECT.", "DIRECT", selector.select(TO_LOCALHOST).get(0).toString()); + } + + public void testProxyForLocalhost() { + Locale.setDefault(new Locale("te", "ST")); + assertEquals("Connect TO_LOCALHOST provided by MyPS", "HTTP @ my.webcache:8080", selector.select(TO_LOCALHOST).get(0).toString()); + assertEquals("One call to my ps", 1, myPS.called); + } + + public void testAlwaysProxyForNonLocalhost() { + Locale.setDefault(Locale.US); + assertEquals("Connect TO_NB provided by MyPS", "HTTP @ my.webcache:8080", selector.select(TO_NB).get(0).toString()); + assertEquals("One call to my ps", 1, myPS.called); + } + + private static class MyPS extends ProxySelector { + + int called; + + @Override + public List select(URI uri) { + called++; + return Collections.singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(USER_PROXY_HOST, USER_PROXY_PORT))); + } + + @Override + public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { + } + } +} diff -r 3bff97f36acc core.network/test/unit/src/org/netbeans/core/network/proxy/DontUseProxyTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/test/unit/src/org/netbeans/core/network/proxy/DontUseProxyTest.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,97 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun + * Microsystems, Inc. All Rights Reserved. + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + */ + +package org.netbeans.core.network.proxy; + +import org.netbeans.junit.*; + +/** Tests HTTP Proxy settings. + * + * @author Jiri Rechtacek + * @see http://www.netbeans.org/issues/show_bug.cgi?id=125588 + */ +public class DontUseProxyTest extends NbTestCase { + public DontUseProxyTest (String name) { + super (name); + } + + public void testFullIpAdress () { + String nonProxyHosts = "192.168.1.0|200.100.200.100"; + assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.0")); + assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.1")); + assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.2.0")); + assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.169.1.0")); + assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "193.168.1.0")); + assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168")); + assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.0/1")); + + assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "200.100.200.100")); + assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "200.100.200.200")); + } + + public void testWildcardIpAdress () { + String nonProxyHosts = "192.*|200.100.200.*"; + assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.0")); + assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.1")); + assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.2.0")); + assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.169.1.0")); + assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "193.168.1.0")); + assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168")); + assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.0/1")); + + assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "200.100.200.100")); + assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "200.100.200.200")); + } + + public void testWildcardHostName () { + String nonProxyHosts = "*.netbeans.org|*.other.org|*netbeans.com|netbeans.org|*.our.intranet|private.*"; + assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "www.netbeans.org")); + assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "www.netbeans.com")); + assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "www.dummynetbeans.org")); + assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "subversion.our.intranet")); + assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "private")); + assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "private.all")); + } + +} diff -r 3bff97f36acc core.network/test/unit/src/org/netbeans/core/network/proxy/HttpSettingsTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/test/unit/src/org/netbeans/core/network/proxy/HttpSettingsTest.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,418 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2012 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun + * Microsystems, Inc. All Rights Reserved. + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + */ + +package org.netbeans.core.network.proxy; + +import java.lang.reflect.Field; +import java.util.prefs.AbstractPreferences; +import java.util.prefs.PreferenceChangeEvent; +import java.util.prefs.PreferenceChangeListener; +import java.util.prefs.Preferences; +import junit.framework.TestResult; +import org.netbeans.core.ProxySettings; +import org.netbeans.junit.NbTestCase; +import org.netbeans.junit.RandomlyFails; +import org.openide.util.NbPreferences; + +/** Tests HTTP Proxy settings. + * + * @author Jiri Rechtacek + * @see http://www.netbeans.org/issues/show_bug.cgi?id=51641 + */ +@RandomlyFails +public class HttpSettingsTest extends NbTestCase { + private final Object sync = getEventQueueSync (); + private static String SYSTEM_PROXY_HOST = "system.cache.org"; + private static String SYSTEM_PROXY_PORT = "777"; + private static String USER_PROXY_HOST = "my.webcache"; + private static String USER_PROXY_PORT = "8080"; + private static String USER_HTTPS_PROXY_HOST = "secure.webcache"; + private static String USER_HTTPS_PROXY_PORT = "8080"; + + private Preferences proxyPreferences; + private static String SILLY_USER_PROXY_HOST = "http://my.webcache"; + private static String SILLY_SYSTEM_PROXY_HOST = "http://system.cache.org"; + private static String SILLY_SYSTEM_PROXY_PORT = "777//"; + private static String MY_NON_PROXY_HOSTS = "myhost.mydomain.net"; + + private static String NETBEANS_ORG = "*.netbeans.org"; + private static String OTHER_ORG = "*.other.org"; + + public HttpSettingsTest (String name) { + super (name); + } + + @Override + public void run (final TestResult result) { + //just initialize Preferences before code NbTestCase + Preferences.userRoot (); + super.run (result); + } + + @Override + protected int timeOut () { + return 20 * 1000; + } + + @Override + protected void setUp () throws Exception { + super.setUp (); + System.setProperty ("http.nonProxyHosts", NETBEANS_ORG + ',' + NETBEANS_ORG); + new NbProxySelector(); + proxyPreferences = NbPreferences.root ().node ("/org/netbeans/core"); + proxyPreferences.addPreferenceChangeListener (new PreferenceChangeListener() { + @Override + public void preferenceChange(PreferenceChangeEvent arg0) { + synchronized (sync) { + sync.notifyAll (); + } + } + }); + System.setProperty ("netbeans.system_http_proxy", SYSTEM_PROXY_HOST + ":" + SYSTEM_PROXY_PORT); + System.setProperty ("netbeans.system_http_non_proxy_hosts", OTHER_ORG); + synchronized (sync) { + if (! USER_PROXY_HOST.equals (proxyPreferences.get ("proxyHttpHost", ""))) { + proxyPreferences.put ("proxyHttpHost", USER_PROXY_HOST); + sync.wait (10000); + } + } + synchronized (sync) { + if (! USER_PROXY_PORT.equals (proxyPreferences.get ("proxyHttpPort", ""))) { + proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT); + sync.wait (10000); + } + } + synchronized (sync) { + if (! USER_HTTPS_PROXY_HOST.equals (proxyPreferences.get ("proxyHttpsHost", ""))) { + proxyPreferences.put ("proxyHttpsHost", USER_HTTPS_PROXY_HOST); + sync.wait (10000); + } + } + synchronized (sync) { + if (! USER_HTTPS_PROXY_PORT.equals (proxyPreferences.get ("proxyHttpsPort", ""))) { + proxyPreferences.put ("proxyHttpsPort", USER_HTTPS_PROXY_PORT); + sync.wait (10000); + } + } + } + + private void sillySetUp () throws Exception { + synchronized (sync) { + if (ProxySettings.DIRECT_CONNECTION != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION); + sync.wait (); + } + } + + System.setProperty ("netbeans.system_http_proxy", SILLY_SYSTEM_PROXY_HOST + ":" + SILLY_SYSTEM_PROXY_PORT); + synchronized (sync) { + if (! SILLY_USER_PROXY_HOST.equals (proxyPreferences.get ("proxyHttpHost", ""))) { + proxyPreferences.put ("proxyHttpHost", SILLY_USER_PROXY_HOST); + sync.wait (10000); + } + } + proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT); + synchronized (sync) { + if (! USER_PROXY_PORT.equals (proxyPreferences.get ("proxyHttpPort", ""))) { + proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT); + sync.wait (10000); + } + } + } + + private void setUpAutoDirect () throws Exception { + synchronized (sync) { + if (ProxySettings.DIRECT_CONNECTION != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION); + sync.wait (); + } + } + System.setProperty ("netbeans.system_http_proxy", "DIRECT"); + synchronized (sync) { + if (! "".equals (proxyPreferences.get ("proxyHttpHost", ""))) { + proxyPreferences.put ("proxyHttpHost", ""); + sync.wait (10000); + } + } + synchronized (sync) { + if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY); + sync.wait (); + } + } + } + + public void testDirectConnection () throws InterruptedException { + System.setProperty ("http.proxyHost", ""); + System.setProperty ("http.proxyPort", ""); + synchronized (sync) { + if (ProxySettings.DIRECT_CONNECTION != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION); + sync.wait (); + } + } + assertEquals ("Proxy type DIRECT_CONNECTION.", ProxySettings.DIRECT_CONNECTION, ProxySettings.getProxyType ()); + assertEquals ("No Proxy Host set.", null, System.getProperty ("http.proxyHost")); + assertEquals ("No Proxy Port set.", null, System.getProperty ("http.proxyPort")); + } + + public void testAutoDetectProxy () throws InterruptedException { + System.setProperty ("http.proxyHost", ""); + System.setProperty ("http.proxyPort", ""); + synchronized (sync) { + if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY); + sync.wait (); + } + } + assertEquals("Proxy type AUTO_DETECT_PROXY.", + ProxySettings.AUTO_DETECT_PROXY, + ProxySettings.getProxyType()); + assertEquals("System Proxy Host: ", SYSTEM_PROXY_HOST, + System.getProperty("http.proxyHost")); + assertEquals("System Proxy Port: ", SYSTEM_PROXY_PORT, + System.getProperty("http.proxyPort")); + } + + public void testManualSetProxy () throws InterruptedException { + synchronized (sync) { + if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY); + sync.wait (); + } + } + assertEquals ("Proxy type MANUAL_SET_PROXY.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ()); + assertEquals ("Manual Set Proxy Host from ProxySettings: ", USER_PROXY_HOST, ProxySettings.getHttpHost ()); + assertEquals ("Manual Set Proxy Port from ProxySettings: ", USER_PROXY_PORT, ProxySettings.getHttpPort ()); + assertEquals ("Manual Set Proxy Host from System.getProperty(): ", USER_PROXY_HOST, System.getProperty ("http.proxyHost")); + assertEquals ("Manual Set Proxy Port from System.getProperty(): ", USER_PROXY_PORT, System.getProperty ("http.proxyPort")); + } + + public void testHttpsManualSetProxy () throws InterruptedException { + synchronized (sync) { + if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY); + sync.wait (); + } + } + assertEquals ("Proxy type MANUAL_SET_PROXY.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ()); + + // HTTP + assertEquals ("Manual Set Proxy Host from ProxySettings: ", USER_PROXY_HOST, ProxySettings.getHttpHost ()); + assertEquals ("Manual Set Proxy Port from ProxySettings: ", USER_PROXY_PORT, ProxySettings.getHttpPort ()); + assertEquals ("Manual Set Proxy Host from System.getProperty(): ", USER_PROXY_HOST, System.getProperty ("http.proxyHost")); + assertEquals ("Manual Set Proxy Port from System.getProperty(): ", USER_PROXY_PORT, System.getProperty ("http.proxyPort")); + + // HTTPS + assertEquals ("Manual Set HTTPS Proxy Host from ProxySettings: ", USER_HTTPS_PROXY_HOST, ProxySettings.getHttpsHost ()); + assertEquals ("Manual Set HTTPS Proxy Port from ProxySettings: ", USER_HTTPS_PROXY_PORT, ProxySettings.getHttpsPort ()); + assertEquals ("Manual Set HTTPS Proxy Host from System.getProperty(): ", USER_HTTPS_PROXY_HOST, System.getProperty ("https.proxyHost")); + assertEquals ("Manual Set HTTPS Proxy Port from System.getProperty(): ", USER_HTTPS_PROXY_PORT, System.getProperty ("https.proxyPort")); + } + + public void testIfTakeUpNonProxyFromProperty () { + assertTrue (NETBEANS_ORG + " in one of Non-Proxy hosts.", ProxySettings.getNonProxyHosts ().indexOf (NETBEANS_ORG) != -1); + } + + public void testNonProxy () throws InterruptedException { + assertEquals ("The ProxySettings takes as same value as System properties in initial.", System.getProperty ("http.nonProxyHosts"), ProxySettings.getNonProxyHosts ()); + + // change value in ProxySettings + synchronized (sync) { + if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY); + sync.wait (); + } + } + synchronized (sync) { + if (! MY_NON_PROXY_HOSTS.equals (proxyPreferences.get ("proxyNonProxyHosts", ""))) { + proxyPreferences.put ("proxyNonProxyHosts", MY_NON_PROXY_HOSTS); + sync.wait (); + } + } + assertEquals ("ProxySettings returns new value.", "myhost.mydomain.net", ProxySettings.getNonProxyHosts ()); + assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.getNonProxyHosts (), System.getProperty ("http.nonProxyHosts")); + + // switch proxy type to DIRECT_CONNECTION + //System.setProperty ("http.nonProxyHosts", ""); + synchronized (sync) { + if (ProxySettings.DIRECT_CONNECTION != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION); + sync.wait (); + } + } + Thread.sleep (1000); // XXX: tunning test on Windows platform, other platforms are passing + assertEquals ("System.getProperty() doesn't return new value if DIRECT_CONNECTION set.", null, System.getProperty ("http.nonProxyHosts")); + + // switch proxy type back to MANUAL_SET_PROXY + synchronized (sync) { + if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY); + sync.wait (); + } + } + assertEquals ("ProxySettings again returns new value.", "myhost.mydomain.net", ProxySettings.getNonProxyHosts ()); + assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.getNonProxyHosts (), System.getProperty ("http.nonProxyHosts")); + + // switch proxy type to AUTO_DETECT_PROXY + synchronized (sync) { + if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY); + sync.wait (); + } + } + log ("AUTO_DETECT_PROXY: ProxySettings.SystemProxySettings.getNonProxyHosts (): " + ProxySettings.getSystemNonProxyHosts()); + log ("AUTO_DETECT_PROXY: System.getProperty (\"http.nonProxyHosts\"): " + System.getProperty ("http.nonProxyHosts")); + assertTrue ("ProxySettings contains OTHER_ORG if AUTO_DETECT_PROXY set.", System.getProperty ("http.nonProxyHosts").indexOf (OTHER_ORG) > 0); + + // switch proxy type back to MANUAL_SET_PROXY + synchronized (sync) { + if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY); + sync.wait (); + } + } + assertEquals ("ProxySettings again returns new value.", "myhost.mydomain.net", ProxySettings.getNonProxyHosts ()); + assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.getNonProxyHosts (), System.getProperty ("http.nonProxyHosts")); + } + + public void testAvoidDuplicateNonProxySetting () throws InterruptedException { + synchronized (sync) { + if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY); + sync.wait (); + } + } + assertTrue (NETBEANS_ORG + " is among Non-proxy hosts detect from OS.", ProxySettings.getSystemNonProxyHosts().indexOf (NETBEANS_ORG) != -1); + assertFalse (NETBEANS_ORG + " is in Non-Proxy hosts only once.", ProxySettings.getSystemNonProxyHosts().indexOf (NETBEANS_ORG) < ProxySettings.getNonProxyHosts ().lastIndexOf (NETBEANS_ORG)); + assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.getSystemNonProxyHosts(), System.getProperty ("http.nonProxyHosts")); + } + + public void testReadNonProxySettingFromSystem () throws InterruptedException { + synchronized (sync) { + if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY); + sync.wait (); + } + } + assertTrue (OTHER_ORG + " is among Non-proxy hosts detect from OS.", ProxySettings.getSystemNonProxyHosts().indexOf (OTHER_ORG) != -1); + assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.getSystemNonProxyHosts(), System.getProperty ("http.nonProxyHosts")); + } + + public void testSillySetManualProxy () throws Exception { + sillySetUp (); + synchronized (sync) { + if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY); + sync.wait (); + } + } + assertEquals ("Proxy type MANUAL_SET_PROXY.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ()); + assertEquals ("Manual Set Proxy Host from ProxySettings doesn't return SILLY_USER_PROXY_HOST anymore.", USER_PROXY_HOST, ProxySettings.getHttpHost ()); + assertEquals ("Manual Set Proxy Port from ProxySettings doesn't return SILLY_USER_PROXY_PORT anymore.", USER_PROXY_PORT, ProxySettings.getHttpPort ()); + assertEquals ("Manual Set Proxy Host from System.getProperty(): ", USER_PROXY_HOST, System.getProperty ("http.proxyHost")); + assertEquals ("Manual Set Proxy Port from System.getProperty(): ", USER_PROXY_PORT, System.getProperty ("http.proxyPort")); + } + + public void testAutoDetectSillySetProxy () throws Exception { + sillySetUp (); + synchronized (sync) { + if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY); + sync.wait (); + } + } + assertEquals ("Proxy type AUTO_DETECT_PROXY.", ProxySettings.AUTO_DETECT_PROXY, ProxySettings.getProxyType ()); + assertEquals ("Auto Detected Proxy Host from ProxySettings doesn't return SILLY_SYSTEM_PROXY_HOST anymore.", SYSTEM_PROXY_HOST, ProxySettings.getSystemHttpHost()); + assertEquals ("Auto Detected Proxy Port from ProxySettings doesn't return SILLY_SYSTEM_PROXY_PORT anymore.", SYSTEM_PROXY_PORT, ProxySettings.getSystemHttpPort()); + assertEquals ("System Proxy Host: ", SYSTEM_PROXY_HOST, System.getProperty ("http.proxyHost")); + assertEquals ("System Proxy Port: ", SYSTEM_PROXY_PORT, System.getProperty ("http.proxyPort")); + } + + public void testSwitchAutoAndManualMode () throws Exception { + setUpAutoDirect (); + + // ensure auto detect mode + assertEquals("Proxy type AUTO_DETECT_PROXY.", + ProxySettings.AUTO_DETECT_PROXY, + ProxySettings.getProxyType()); + assertEquals ("Auto Proxy Host from System.getProperty(): ", null, System.getProperty ("http.proxyHost")); + assertEquals ("Auto Proxy Port from System.getProperty(): ", null, System.getProperty ("http.proxyPort")); + + // switch to manual + proxyPreferences.put ("proxyHttpHost", "foo"); + synchronized (sync) { + if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY); + sync.wait (); + } + } + assertEquals ("Proxy type MANUAL_SET_PROXY.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ()); + assertEquals ("Auto Proxy Host from System.getProperty(): ", "foo", System.getProperty ("http.proxyHost")); + + // switch back to auto detect + synchronized (sync) { + if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { + proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY); + sync.wait (); + } + } + assertEquals("Proxy type AUTO_DETECT_PROXY.", + ProxySettings.AUTO_DETECT_PROXY, + ProxySettings.getProxyType()); + assertEquals ("Auto Proxy Host from System.getProperty(): ", null, System.getProperty ("http.proxyHost")); + assertEquals ("Auto Proxy Port from System.getProperty(): ", null, System.getProperty ("http.proxyPort")); + + } + + private Object getEventQueueSync() { + try { + Field f = AbstractPreferences.class.getDeclaredField("eventQueue"); + f.setAccessible(true); + return f.get(null); + } catch (Exception ex) { + throw new ExceptionInInitializerError(ex); + } + } +} diff -r 3bff97f36acc core.network/test/unit/src/org/netbeans/core/network/proxy/NonProxyHostsTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/test/unit/src/org/netbeans/core/network/proxy/NonProxyHostsTest.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,173 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 1997-2012 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * Contributor(s): + * + * The Original Software is NetBeans. The Initial Developer of the Original + * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun + * Microsystems, Inc. All Rights Reserved. + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + */ + +package org.netbeans.core.network.proxy; + +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.URI; +import java.util.prefs.PreferenceChangeEvent; +import java.util.prefs.PreferenceChangeListener; +import java.util.prefs.Preferences; +import org.netbeans.core.ProxySettings; +import org.netbeans.junit.NbTestCase; +import org.netbeans.junit.RandomlyFails; +import org.openide.util.NbPreferences; + +/** Tests Detect OS nonProxyHosts settings. + * + * @author Jiri Rechtacek + * @see http://www.netbeans.org/issues/show_bug.cgi?id=77053 + */ +@RandomlyFails // NB-Core-Build #1247, 1248 +public class NonProxyHostsTest extends NbTestCase { + private static String SYSTEM_PROXY_HOST = "system.cache.org"; + private static String SYSTEM_PROXY_PORT = "777"; + private static String USER_PROXY_HOST = "my.webcache"; + private static String USER_PROXY_PORT = "8080"; + + private Preferences proxyPreferences; + private ProxySelector selector; + private static URI TO_LOCALHOST; + private static URI TO_LOCAL_DOMAIN_1; + private static URI TO_LOCAL_DOMAIN_2; + private static URI TO_EXTERNAL; + private static URI SOCKS_TO_LOCALHOST; + private static URI SOCKS_TO_LOCAL_DOMAIN_1; + private static URI SOCKS_TO_LOCAL_DOMAIN_2; + private static URI SOCKS_TO_EXTERNAL; + + private boolean isWaiting = false; + + public NonProxyHostsTest (String name) { + super (name); + } + + @Override + protected void setUp () throws Exception { + super.setUp (); + System.setProperty ("netbeans.system_http_proxy", SYSTEM_PROXY_HOST + ":" + SYSTEM_PROXY_PORT); + System.setProperty ("netbeans.system_socks_proxy", SYSTEM_PROXY_HOST + ":" + SYSTEM_PROXY_PORT); + System.setProperty ("netbeans.system_http_non_proxy_hosts", "*.other.org"); + System.setProperty ("http.nonProxyHosts", "*.netbeans.org"); + new NbProxySelector(); + selector = ProxySelector.getDefault (); + proxyPreferences = NbPreferences.root ().node ("/org/netbeans/core"); + proxyPreferences.addPreferenceChangeListener (new PreferenceChangeListener () { + public void preferenceChange (PreferenceChangeEvent arg0) { + isWaiting = false; + } + }); + proxyPreferences.put ("proxyHttpHost", USER_PROXY_HOST); + proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT); + proxyPreferences.put ("proxySocksHost", USER_PROXY_HOST); + proxyPreferences.put ("proxySocksPort", USER_PROXY_PORT); + while (isWaiting); + isWaiting = true; + TO_LOCALHOST = new URI ("http://localhost"); + TO_LOCAL_DOMAIN_1 = new URI ("http://core.netbeans.org"); + TO_LOCAL_DOMAIN_2 = new URI ("http://core.other.org"); + TO_EXTERNAL = new URI ("http://worldwide.net"); + + SOCKS_TO_LOCALHOST = new URI ("socket://localhost:8041"); + SOCKS_TO_LOCAL_DOMAIN_1 = new URI ("socket://core.netbeans.org"); + SOCKS_TO_LOCAL_DOMAIN_2 = new URI ("socket://core.other.org"); + SOCKS_TO_EXTERNAL = new URI ("socket://worldwide.net"); + } + + public void testDirectProxySetting () { + proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION); + while (isWaiting); + assertEquals ("Proxy type DIRECT_CONNECTION.", ProxySettings.DIRECT_CONNECTION, ProxySettings.getProxyType ()); + assertEquals ("Connect " + TO_LOCALHOST + " DIRECT.", "[DIRECT]", selector.select (TO_LOCALHOST).toString ()); + assertEquals ("Connect " + SOCKS_TO_LOCALHOST + " DIRECT.", Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCALHOST).get(0)); + assertEquals ("Connect " + TO_LOCAL_DOMAIN_1 + " DIRECT.", "[DIRECT]", selector.select (TO_LOCAL_DOMAIN_1).toString ()); + assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_1 + " DIRECT.", "[DIRECT]", selector.select (SOCKS_TO_LOCAL_DOMAIN_1).toString ()); + assertEquals ("Connect " + TO_LOCAL_DOMAIN_2 + " DIRECT.", "[DIRECT]", selector.select (TO_LOCAL_DOMAIN_2).toString ()); + assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_2 + " DIRECT.", "[DIRECT]", selector.select (SOCKS_TO_LOCAL_DOMAIN_2).toString ()); + assertEquals ("Connect " + TO_EXTERNAL + " DIRECT.", "[DIRECT]", selector.select (TO_EXTERNAL).toString ()); + assertEquals ("Connect " + SOCKS_TO_EXTERNAL + " DIRECT.", "[DIRECT]", selector.select (SOCKS_TO_EXTERNAL).toString ()); + } + + @RandomlyFails + public void testManualProxySettins () { + proxyPreferences.put (ProxySettings.NOT_PROXY_HOSTS, "localhost|" + "*.netbeans.org"); + proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY); + while (isWaiting); + assertEquals ("Proxy type DIRECT_CONNECTION.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ()); + assertEquals ("Connect TO_LOCALHOST DIRECT.", Proxy.NO_PROXY, selector.select (TO_LOCALHOST).get(0)); + assertEquals ("Connect " + SOCKS_TO_LOCALHOST + " DIRECT.", Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCALHOST).get(0)); + assertEquals ("Connect " + TO_LOCAL_DOMAIN_1 + " DIRECT.", Proxy.NO_PROXY, selector.select (TO_LOCAL_DOMAIN_1).get (0)); + assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_1 + " DIRECT.", + Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCAL_DOMAIN_1).get (0)); + assertEquals ("Connect " + TO_LOCAL_DOMAIN_2 + " via my.webcache:8080 proxy.", + "HTTP @ my.webcache:8080", selector.select (TO_LOCAL_DOMAIN_2).get (0).toString ()); + assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_2 + " via my.webcache:8080 proxy.", + "SOCKS @ my.webcache:8080", selector.select (SOCKS_TO_LOCAL_DOMAIN_2).get (0).toString ()); + assertEquals ("Connect TO_EXTERNAL via my.webcache:8080 proxy.", "HTTP @ my.webcache:8080", selector.select (TO_EXTERNAL).get (0).toString ()); + assertEquals ("Connect SOCKS_TO_EXTERNAL via my.webcache:8080 proxy.", + "SOCKS @ my.webcache:8080", selector.select (SOCKS_TO_EXTERNAL).get (0).toString ()); + } + + @RandomlyFails + public void testSystemProxySettings () { + proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY); + while (isWaiting); + log ("Value of System.getProperty (\"http.nonProxyHosts\"): " + System.getProperty ("http.nonProxyHosts")); + assertTrue ("*.other.org is one of non-proxy hosts", System.getProperty ("http.nonProxyHosts").indexOf ("*.other.org") != -1); + assertEquals ("Proxy type DIRECT_CONNECTION.", ProxySettings.AUTO_DETECT_PROXY, ProxySettings.getProxyType ()); + assertEquals ("Connect TO_LOCALHOST DIRECT.", Proxy.NO_PROXY, selector.select (TO_LOCALHOST).get(0)); + assertEquals ("Connect " + SOCKS_TO_LOCALHOST + " DIRECT.", Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCALHOST).get(0)); + assertEquals ("Connect " + TO_LOCAL_DOMAIN_1 + " DIRECT.", Proxy.NO_PROXY, selector.select (TO_LOCAL_DOMAIN_1).get (0)); + assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_1 + " DIRECT.", + Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCAL_DOMAIN_1).get (0)); + assertEquals ("Connect " + TO_LOCAL_DOMAIN_2 + " DIRECT ignoring settings " + System.getProperty ("http.nonProxyHosts"), Proxy.NO_PROXY, selector.select (TO_LOCAL_DOMAIN_2).get (0)); + assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_2 + " DIRECT ignoring settings " + System.getProperty ("http.nonProxyHosts"), + Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCAL_DOMAIN_2).get (0)); + assertEquals ("Connect TO_EXTERNAL via system.cache.org:777 proxy.", "HTTP @ system.cache.org:777", selector.select (TO_EXTERNAL).get (0).toString ()); + assertEquals ("Connect SOCKS_TO_EXTERNAL via system.cache.org:777 proxy.", "SOCKS @ system.cache.org:777", + selector.select (SOCKS_TO_EXTERNAL).get (0).toString ()); + } + +} diff -r 3bff97f36acc core.network/test/unit/src/org/netbeans/core/network/proxy/ProxyAutoConfigTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/core.network/test/unit/src/org/netbeans/core/network/proxy/ProxyAutoConfigTest.java Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,159 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright 2011 Oracle and/or its affiliates. All rights reserved. + * + * Oracle and Java are registered trademarks of Oracle and/or its affiliates. + * Other names may be trademarks of their respective owners. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common + * Development and Distribution License("CDDL") (collectively, the + * "License"). You may not use this file except in compliance with the + * License. You can obtain a copy of the License at + * http://www.netbeans.org/cddl-gplv2.html + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the + * specific language governing permissions and limitations under the + * License. When distributing the software, include this License Header + * Notice in each file and include the License file at + * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the GPL Version 2 section of the License file that + * accompanied this code. If applicable, add the following below the + * License Header, with the fields enclosed by brackets [] replaced by + * your own identifying information: + * "Portions Copyrighted [year] [name of copyright owner]" + * + * If you wish your version of this file to be governed by only the CDDL + * or only the GPL Version 2, indicate your decision by adding + * "[Contributor] elects to include this software in this distribution + * under the [CDDL or GPL Version 2] license." If you do not indicate a + * single choice of license, a recipient has the option to distribute + * your version of this file under either the CDDL, the GPL Version 2 or + * to extend the choice of license to its licensees as provided above. + * However, if you add GPL Version 2 code and therefore, elected the GPL + * Version 2 license, then the option applies only if the new code is + * made subject to such option by the copyright holder. + * + * Contributor(s): + * + * Portions Copyrighted 2011 Sun Microsystems, Inc. + */ +package org.netbeans.core.network.proxy; + +import java.io.File; +import java.net.Proxy; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.LinkedList; +import java.util.List; +import junit.framework.Test; +import org.netbeans.junit.NbModuleSuite; +import org.netbeans.junit.NbTestCase; + +/** + * + * @author Jirka Rechtacek + */ +public class ProxyAutoConfigTest extends NbTestCase { + + public static Test suite() { + return NbModuleSuite + .emptyConfiguration() + .gui(false) + .addTest(ProxyAutoConfigTest.class) + .suite(); + } + + public ProxyAutoConfigTest(String name) { + super(name); + } + + public void testGetProxyAutoConfig() { + assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt")); + } + + // #issue 201995 + public void testGetProxyAutoConfigWithMultipleURL() { + assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt http://pac/pac.txt http://pac/pac.txt")); + } + + public void testGetProxyAutoConfigWithNewLineURL() { + assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt\nhttp://pac/pac.txt")); + } + + public void testGetProxyAutoConfigWithLineTerminatorURL() { + assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt\rhttp://pac/pac.txt")); + } + + public void testGetProxyAutoConfigWithBothTerminatorsURL() { + assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt\r\nhttp://pac/pac.txt")); + } + + public void testGetProxyAutoConfigWithInvalidURL() { + assertNotNull(ProxyAutoConfig.get("http:\\\\pac\\pac.txt")); + } + + public void testGetProxyAutoConfigWithRelativePath() { + assertNotNull(ProxyAutoConfig.get("http://pac/../pac/pac.txt")); + } + + public void testGetProxyAutoConfigWithLocalPAC() throws URISyntaxException { + List pacFileLocations = new LinkedList(); + for (File pacFile : new File(getDataDir(), "pacFiles").listFiles()) { + pacFileLocations.add(pacFile.getAbsolutePath()); + pacFileLocations.add("file://" + pacFile.getAbsolutePath()); + pacFileLocations.add(pacFile.toURI().toString()); + } + for (String pacFileLoc : pacFileLocations) { + ProxyAutoConfig pac = ProxyAutoConfig.get(pacFileLoc); + assertNotNull(pac); + URI uri = pac.getPacURI(); + assertNotNull(uri); + assertNull(uri.getHost()); + List proxies = pac.findProxyForURL(new URI("http://netbeans.org")); + assertEquals(1, proxies.size()); + assertTrue(pacFileLoc + ": " + proxies.get(0).toString(), proxies.get(0).toString().startsWith("HTTP @ www-proxy.us.oracle.com/")); + System.setProperty("netbeans.system_http_proxy", "PAC " + pacFileLoc); + proxies = NbProxySelector.getDefault().select(new URI("http://netbeans.org")); + assertTrue(pacFileLoc + ": " + proxies.get(0).toString(), proxies.get(0).toString().startsWith("HTTP @ www-proxy.us.oracle.com/")); + + proxies = pac.findProxyForURL(new URI("https://netbeans.org")); + assertEquals(1, proxies.size()); + assertTrue(pacFileLoc + ": " + proxies.get(0).toString(), proxies.get(0).toString().startsWith("HTTP @ www-proxy.us.oracle.com/")); + System.setProperty("netbeans.system_http_proxy", "PAC " + pacFileLoc); + proxies = NbProxySelector.getDefault().select(new URI("https://netbeans.org")); + assertTrue(pacFileLoc + ": " + proxies.get(0).toString(), proxies.get(0).toString().startsWith("HTTP @ www-proxy.us.oracle.com/")); + + proxies = pac.findProxyForURL(new URI("http://localhost")); + assertEquals(1, proxies.size()); + assertEquals(pacFileLoc + ": " + proxies.get(0).toString(), "DIRECT", proxies.get(0).toString()); + proxies = NbProxySelector.getDefault().select(new URI("http://localhost")); + assertEquals(pacFileLoc + ": " + proxies.get(0).toString(), "DIRECT", proxies.get(0).toString()); + } + } + + public void testGetProxyAutoConfigWithLocalInvalidPAC() throws URISyntaxException { + List pacFileLocations = new LinkedList(); + for (File pacFile : new File[] { + new File(getDataDir(), "pacFiles"), + new File(getDataDir(), "doesNotExist") + }) { + pacFileLocations.add(pacFile.getAbsolutePath()); + pacFileLocations.add("file://" + pacFile.getAbsolutePath()); + pacFileLocations.add(pacFile.toURI().toString()); + } + for (String pacFileLoc : pacFileLocations) { + ProxyAutoConfig pac = ProxyAutoConfig.get(pacFileLoc); + assertNotNull(pac); + URI uri = pac.getPacURI(); + assertNotNull(uri); + List proxies = pac.findProxyForURL(new URI("http://netbeans.org")); + assertEquals(1, proxies.size()); + assertEquals("DIRECT", proxies.get(0).toString()); + System.setProperty("netbeans.system_http_proxy", "PAC " + pacFileLoc); + proxies = NbProxySelector.getDefault().select(new URI("http://netbeans.org")); + assertEquals(pacFileLoc + ": " + proxies.get(0).toString(), "DIRECT", proxies.get(0).toString()); + } + } +} diff -r 3bff97f36acc core.ui/src/org/netbeans/core/ui/options/general/Bundle.properties --- a/core.ui/src/org/netbeans/core/ui/options/general/Bundle.properties Tue Mar 26 12:16:28 2013 +0100 +++ b/core.ui/src/org/netbeans/core/ui/options/general/Bundle.properties Tue Mar 26 12:52:42 2013 +0100 @@ -267,3 +267,6 @@ General.Options.Export.Category.displayName=General General.Options.Export.displayName=General Other.Options.Export.displayName=All Other Unspecified +GeneralOptionsPanel.bReloadProxy.text=Reload +GeneralOptionsPanel.bTestConnection.text=Test connection +GeneralOptionsPanel.lblTestResult.text= diff -r 3bff97f36acc core.ui/src/org/netbeans/core/ui/options/general/GeneralOptionsModel.java --- a/core.ui/src/org/netbeans/core/ui/options/general/GeneralOptionsModel.java Tue Mar 26 12:16:28 2013 +0100 +++ b/core.ui/src/org/netbeans/core/ui/options/general/GeneralOptionsModel.java Tue Mar 26 12:52:42 2013 +0100 @@ -207,9 +207,8 @@ } static boolean usePAC() { - String s = System.getProperty ("netbeans.system_http_proxy"); // NOI18N - boolean usePAC = s != null && s.startsWith("PAC"); // NOI18N - return usePAC; + String pacUrl = getProxyPreferences().get(ProxySettings.SYSTEM_PAC, ""); // NOI18N + return pacUrl != null && pacUrl.length() > 0; } // private helper methods .................................................. diff -r 3bff97f36acc core.ui/src/org/netbeans/core/ui/options/general/GeneralOptionsPanel.form --- a/core.ui/src/org/netbeans/core/ui/options/general/GeneralOptionsPanel.form Tue Mar 26 12:16:28 2013 +0100 +++ b/core.ui/src/org/netbeans/core/ui/options/general/GeneralOptionsPanel.form Tue Mar 26 12:52:42 2013 +0100 @@ -30,27 +30,48 @@ - - - - + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - + + + + + @@ -79,25 +100,30 @@ - + + + + - + + + + + + + + - + + + - - - - + + - - - - - - + @@ -144,6 +170,9 @@ + + + @@ -298,5 +327,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff -r 3bff97f36acc core.ui/src/org/netbeans/core/ui/options/general/GeneralOptionsPanel.java --- a/core.ui/src/org/netbeans/core/ui/options/general/GeneralOptionsPanel.java Tue Mar 26 12:16:28 2013 +0100 +++ b/core.ui/src/org/netbeans/core/ui/options/general/GeneralOptionsPanel.java Tue Mar 26 12:52:42 2013 +0100 @@ -1,7 +1,7 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * - * Copyright 1997-2011 Oracle and/or its affiliates. All rights reserved. + * Copyright 1997-2013 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. @@ -52,6 +52,7 @@ import java.awt.event.ActionListener; import java.net.MalformedURLException; import java.net.URL; +import java.util.prefs.Preferences; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; @@ -71,6 +72,7 @@ import org.openide.util.ImageUtilities; import org.openide.util.Lookup; import org.openide.util.NbBundle; +import org.openide.util.NbPreferences; /** * Implementation of one panel in Options Dialog. @@ -174,13 +176,6 @@ lblUsageInfo.setVisible(false); lblLearnMore.setVisible(false); } - - // if system proxy setting is not detectable, disable this radio - // button - // do not disable this radio button at all - // it could use JDK detection sometime - //if (System.getProperty("netbeans.system_http_proxy") == null) // NOI18N - //rbUseSystemProxy.setEnabled(false); } /** This method is called from within the constructor to @@ -212,6 +207,9 @@ lblUsageInfo = new javax.swing.JLabel(); jUsageCheck = new javax.swing.JCheckBox(); lUsage = new javax.swing.JLabel(); + bReloadProxy = new javax.swing.JButton(); + bTestConnection = new javax.swing.JButton(); + lblTestResult = new javax.swing.JLabel(); lWebBrowser.setLabelFor(cbWebBrowser); org.openide.awt.Mnemonics.setLocalizedText(lWebBrowser, org.openide.util.NbBundle.getMessage(GeneralOptionsPanel.class, "GeneralOptionsPanel.lWebBrowser.text")); // NOI18N @@ -314,6 +312,22 @@ gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3); jPanel1.add(lUsage, gridBagConstraints); + org.openide.awt.Mnemonics.setLocalizedText(bReloadProxy, org.openide.util.NbBundle.getMessage(GeneralOptionsPanel.class, "GeneralOptionsPanel.bReloadProxy.text")); // NOI18N + bReloadProxy.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + bReloadProxyActionPerformed(evt); + } + }); + + org.openide.awt.Mnemonics.setLocalizedText(bTestConnection, org.openide.util.NbBundle.getMessage(GeneralOptionsPanel.class, "GeneralOptionsPanel.bTestConnection.text")); // NOI18N + bTestConnection.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + bTestConnectionActionPerformed(evt); + } + }); + + org.openide.awt.Mnemonics.setLocalizedText(lblTestResult, org.openide.util.NbBundle.getMessage(GeneralOptionsPanel.class, "GeneralOptionsPanel.lblTestResult.text")); // NOI18N + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( @@ -332,24 +346,39 @@ .addComponent(lWebProxy) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(rbNoProxy) - .addComponent(rbUseSystemProxy) - .addComponent(rbHTTPProxy) .addGroup(layout.createSequentialGroup() - .addGap(17, 17, 17) + .addGap(90, 90, 90) + .addComponent(errorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 1313, Short.MAX_VALUE)) + .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() - .addComponent(bMoreProxy) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(rbHTTPProxy) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(lProxyHost) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(tfProxyHost, javax.swing.GroupLayout.DEFAULT_SIZE, 1055, Short.MAX_VALUE)) + .addGroup(layout.createSequentialGroup() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(rbNoProxy) + .addGroup(layout.createSequentialGroup() + .addComponent(rbUseSystemProxy) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(bReloadProxy))) + .addGap(0, 0, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(errorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 1279, Short.MAX_VALUE)) + .addComponent(lProxyPort) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(tfProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(bMoreProxy)) .addGroup(layout.createSequentialGroup() - .addComponent(lProxyHost) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) - .addComponent(tfProxyHost, javax.swing.GroupLayout.DEFAULT_SIZE, 1137, Short.MAX_VALUE) - .addGap(12, 12, 12) - .addComponent(lProxyPort) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) - .addComponent(tfProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))) + .addComponent(bTestConnection) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(lblTestResult) + .addGap(0, 0, Short.MAX_VALUE))) + .addContainerGap()))) .addComponent(jSeparator3, javax.swing.GroupLayout.DEFAULT_SIZE, 1495, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) @@ -370,21 +399,25 @@ .addGroup(layout.createSequentialGroup() .addComponent(rbNoProxy) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(rbUseSystemProxy) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(rbUseSystemProxy) + .addComponent(bReloadProxy)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(rbHTTPProxy)) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(rbHTTPProxy) + .addComponent(lProxyHost) + .addComponent(tfProxyHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(lProxyPort) + .addComponent(tfProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(bMoreProxy))) .addComponent(lWebProxy)) + .addGap(30, 30, 30) + .addComponent(errorLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) - .addComponent(lProxyHost) - .addComponent(tfProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) - .addComponent(tfProxyHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) - .addComponent(lProxyPort)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) - .addComponent(bMoreProxy) - .addComponent(errorLabel)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(bTestConnection) + .addComponent(lblTestResult)) + .addGap(11, 11, 11) .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) @@ -475,10 +508,21 @@ } }//GEN-LAST:event_lblLearnMoreMousePressed + + private void bReloadProxyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bReloadProxyActionPerformed + ProxySettings.reload(); + rbUseSystemProxy.setToolTipText(getUseSystemProxyToolTip()); + }//GEN-LAST:event_bReloadProxyActionPerformed + + private void bTestConnectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bTestConnectionActionPerformed + + }//GEN-LAST:event_bTestConnectionActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bMoreProxy; + private javax.swing.JButton bReloadProxy; + private javax.swing.JButton bTestConnection; private javax.swing.JComboBox cbWebBrowser; private javax.swing.JButton editBrowserButton; private javax.swing.JLabel errorLabel; @@ -492,6 +536,7 @@ private javax.swing.JLabel lWebBrowser; private javax.swing.JLabel lWebProxy; private javax.swing.JLabel lblLearnMore; + private javax.swing.JLabel lblTestResult; private javax.swing.JLabel lblUsageInfo; private javax.swing.JRadioButton rbHTTPProxy; private javax.swing.JRadioButton rbNoProxy; @@ -542,18 +587,17 @@ return NbBundle.getMessage (GeneralOptionsPanel.class, key, params); } - private String getUseSystemProxyToolTip () { - if (rbUseSystemProxy.isSelected ()) { + private String getUseSystemProxyToolTip() { + if (rbUseSystemProxy.isSelected()) { String toolTip; - String sHost = System.getProperty ("http.proxyHost"); // NOI18N - if (sHost == null || sHost.trim ().length () == 0) { - toolTip = loc ("GeneralOptionsPanel_rbUseSystemProxy_Direct"); // NOI18N - } else { - String sPort = System.getProperty ("http.proxyPort"); // NOI18N - toolTip = loc ("GeneralOptionsPanel_rbUseSystemProxy_Format", sHost, sPort); - } + String sHost = getProxyPreferences().get(ProxySettings.SYSTEM_PROXY_HTTP_HOST, ""); // NOI18N if (GeneralOptionsModel.usePAC()) { toolTip = getPacFile(); + } else if (sHost == null || sHost.trim().length() == 0) { + toolTip = loc("GeneralOptionsPanel_rbUseSystemProxy_Direct"); // NOI18N + } else { + String sPort = getProxyPreferences().get(ProxySettings.SYSTEM_PROXY_HTTP_PORT, ""); // NOI18N + toolTip = loc("GeneralOptionsPanel_rbUseSystemProxy_Format", sHost, sPort); } return toolTip; } else { @@ -710,8 +754,10 @@ } private static String getPacFile() { - String init = System.getProperty("netbeans.system_http_proxy"); // NOI18N - return init.substring(4).trim(); + return getProxyPreferences().get(ProxySettings.SYSTEM_PAC, ""); } + private static Preferences getProxyPreferences() { + return NbPreferences.forModule(ProxySettings.class); + } } diff -r 3bff97f36acc libs.jna/nbproject/project.xml --- a/libs.jna/nbproject/project.xml Tue Mar 26 12:16:28 2013 +0100 +++ b/libs.jna/nbproject/project.xml Tue Mar 26 12:52:42 2013 +0100 @@ -71,21 +71,22 @@ org.jruby org.netbeans.core.browser.xulrunner org.netbeans.core.nativeaccess + org.netbeans.core.network + org.netbeans.libs.djnsswt.gtklinuxx64 + org.netbeans.libs.djnsswt.gtklinuxx86 + org.netbeans.libs.djnsswt.win32x64 + org.netbeans.libs.djnsswt.win32x86 + org.netbeans.libs.svnClientAdapter.svnkit org.netbeans.modules.dlight.nativeexecution org.netbeans.modules.extbrowser org.netbeans.modules.extexecution.impl org.netbeans.modules.keyring.impl + org.netbeans.modules.libs.djnsswt + org.netbeans.modules.masterfs.linux + org.netbeans.modules.masterfs.macosx + org.netbeans.modules.masterfs.solaris org.netbeans.modules.masterfs.windows - org.netbeans.modules.masterfs.linux - org.netbeans.modules.masterfs.solaris - org.netbeans.modules.masterfs.macosx org.netbeans.modules.python.qshell - org.netbeans.libs.svnClientAdapter.svnkit - org.netbeans.modules.libs.djnsswt - org.netbeans.libs.djnsswt.gtklinuxx86 - org.netbeans.libs.djnsswt.gtklinuxx64 - org.netbeans.libs.djnsswt.win32x86 - org.netbeans.libs.djnsswt.win32x64 com.sun.jna com.sun.jna.ptr com.sun.jna.win32 diff -r 3bff97f36acc nbbuild/cluster.properties --- a/nbbuild/cluster.properties Tue Mar 26 12:16:28 2013 +0100 +++ b/nbbuild/cluster.properties Tue Mar 26 12:52:42 2013 +0100 @@ -167,6 +167,7 @@ core.multiview,\ core.nativeaccess,\ core.netigso,\ + core.network,\ core.osgi,\ core.output2,\ core.startup,\ diff -r 3bff97f36acc o.n.bootstrap/apichanges.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/o.n.bootstrap/apichanges.xml Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,102 @@ + + + + + + + + + Startup Proxy System Property Devel API + + + + + + Launcher does not provide proxy setting properties. + + + + + +

+ Launcher does not provide netbeans.system_http_proxy and + netbeans.system_http_non_proxy_hosts properties anymore. + Proxy settings are now detected in Core Network module. +

+
+ +
+
+ + + + + + Change History for the Friend Core APIs + + + + + + +

Introduction

+ +

+This document lists changes made to the API between core/startup and core +modules. It is a friend API so it does not need to be developed compatibly, +and indeed it is not. +

+ + + +
+ +

@FOOTER@

+ + +
+ +
diff -r 3bff97f36acc o.n.bootstrap/arch.xml --- a/o.n.bootstrap/arch.xml Tue Mar 26 12:16:28 2013 +0100 +++ b/o.n.bootstrap/arch.xml Tue Mar 26 12:52:42 2013 +0100 @@ -505,23 +505,6 @@
  • - - System proxy setting in the format of hostname:port. The - launcher does its best to detect the OS/desktop HTTP proxy - setting. There is no guarantee that it succeeds. The property - may not be set at all or its value may be totally wrong. - -
  • -
  • - - List of addresses that are not accessed through proxy. The - launcher attempts to detect the OS/desktop HTTP proxy - setting. There is no guarantee that it succeeds. The property - may not be set at all or its value may be totally wrong and - its format is not defined. - -
  • -
  • Classpath to prepend to core loader (normally just lib/*.jar). Possibly useful for testing diff -r 3bff97f36acc o.n.bootstrap/launcher/unix/nbexec --- a/o.n.bootstrap/launcher/unix/nbexec Tue Mar 26 12:16:28 2013 +0100 +++ b/o.n.bootstrap/launcher/unix/nbexec Tue Mar 26 12:52:42 2013 +0100 @@ -352,185 +352,12 @@ fi } -# detect system http proxy setting - -detect_system_proxy () { - if [ ! -z "$http_proxy" ]; then - http_proxy_tmp=$http_proxy +if [ "$KDE_FULL_SESSION" = "true" ] ; then + jargs="-Dnetbeans.running.environment=kde $jargs" +else + if [ ! -z "$GNOME_DESKTOP_SESSION_ID" ] ; then + jargs="-Dnetbeans.running.environment=gnome $jargs" fi - return 0 -} - -detect_gnome_proxy () { - gsettings=/usr/bin/gsettings - if [ -x $gsettings ] ; then - translate=/usr/bin/tr - - proxy_mode=`$gsettings get org.gnome.system.proxy mode 2>/dev/null` - if [ "$proxy_mode" = "'manual'" ] ; then - http_proxy_host=`$gsettings get org.gnome.system.proxy.http host 2>/dev/null | $translate -d "'"` - http_proxy_port=`$gsettings get org.gnome.system.proxy.http port 2>/dev/null` - http_proxy_tmp=$http_proxy_host:$http_proxy_port - http_non_proxy_hosts=`$gsettings get org.gnome.system.proxy ignore-hosts 2>/dev/null` - if [ $? ] ; then - http_non_proxy_hosts=`echo $http_non_proxy_hosts | $translate -d "[]' "` - fi - socks_proxy_host=`$gsettings get org.gnome.system.proxy.socks host 2>/dev/null | $translate -d "'"` - socks_proxy_port=`$gsettings get org.gnome.system.proxy.socks port 2>/dev/null` - socks_proxy_tmp=$socks_proxy_host:$socks_proxy_port - - return 0 - else - if [ "$proxy_mode" = "'none'" ] ; then - detect_system_proxy - if [ -z "$http_proxy_tmp" ]; then - http_proxy_tmp="DIRECT" - fi - return 0 - else - if [ "$proxy_mode" = "'auto'" ] ; then - detect_system_proxy - pac_file=`$gsettings get org.gnome.system.proxy autoconfig-url 2>/dev/null | $translate -d "'"` - if [ ! -z "$pac_file" ]; then - http_proxy_tmp="PAC "$pac_file - fi - return 0 - fi - fi - fi - fi - - gconftool=/usr/bin/gconftool-2 - if [ -x $gconftool ] ; then - proxy_mode=`$gconftool --get /system/proxy/mode 2>/dev/null` - if [ "$proxy_mode" = "manual" ] ; then - http_proxy_host=`$gconftool --get /system/http_proxy/host 2>/dev/null` - http_proxy_port=`$gconftool --get /system/http_proxy/port 2>/dev/null` - http_proxy_tmp=$http_proxy_host:$http_proxy_port - http_non_proxy_hosts=`$gconftool --get /system/http_proxy/ignore_hosts 2>/dev/null` - if [ $? ] ; then - http_non_proxy_hosts=`echo $http_non_proxy_hosts | /bin/sed 's/\]//'` - fi - socks_proxy_host=`$gconftool --get /system/proxy/socks_host 2>/dev/null` - socks_proxy_port=`$gconftool --get /system/proxy/socks_port 2>/dev/null` - socks_proxy_tmp=$socks_proxy_host:$socks_proxy_port - - return 0 - else - if [ "$proxy_mode" = "none" ] ; then - detect_system_proxy - if [ -z "$http_proxy_tmp" ]; then - http_proxy_tmp="DIRECT" - fi - return 0 - else - if [ "$proxy_mode" = "auto" ] ; then - detect_system_proxy - pac_file=`$gconftool --get /system/proxy/autoconfig_url 2>/dev/null` - if [ ! -z "$pac_file" ]; then - http_proxy_tmp="PAC "$pac_file - fi - return 0 - fi - fi - fi - fi - return 1 -} - -detect_kde_proxy () { - kioslaverc="${HOME}/.kde/share/config/kioslaverc" - if [ -f $kioslaverc ] ; then - if /bin/grep 'ProxyType=1' "$kioslaverc" >/dev/null 2>&1; then - http_proxy_tmp=`/bin/grep 'httpProxy=http://' "$kioslaverc"` - if [ $? ] ; then - http_proxy_tmp=`echo $http_proxy_tmp | /bin/sed 's/httpProxy=http:\/\///'` - return 0 - fi - http_non_proxy_hosts=`/bin/grep 'NoProxyFor=' "$kioslaverc"` - if [ $? ] ; then - http_non_proxy_hosts=`echo $http_non_proxy_hosts | /bin/sed 's/NoProxyFor=//'` - fi - else - if /bin/grep 'ProxyType=0' "$kioslaverc" >/dev/null 2>&1; then - detect_system_proxy - if [ -z "$http_proxy_tmp" ]; then - http_proxy_tmp="DIRECT" - fi - return 0 - else - if /bin/grep 'ProxyType=2' "$kioslaverc" >/dev/null 2>&1; then - pac_file=`grep "Proxy Config Script=" $kioslaverc | cut -f 2 -d =` - http_proxy_tmp="PAC "$pac_file - return 0 - fi - fi - fi - fi - return 1 -} - -detect_macosx_proxy () { - if [ ! -x /usr/sbin/scutil ] ; then - return 1 - fi - - scutil_out=/tmp/nb-proxy-detection.$$ - cat < ${scutil_out} -open -show State:/Network/Global/Proxies -close -EOF - - if /usr/bin/grep "ProxyAuto.*: *1" ${scutil_out} >/dev/null 2>&1; then - if /usr/bin/grep "ProxyAutoConfigEnable.*: *1" ${scutil_out} >/dev/null 2>&1; then - http_proxy_tmp="PAC `/usr/bin/grep ProxyAutoConfigURLString ${scutil_out} | /usr/bin/awk 'END{print $3}'`" - rm ${scutil_out} - return 0 - fi - - rm ${scutil_out} - return 1 - fi - - if /usr/bin/grep "HTTPEnable *: *1" ${scutil_out} >/dev/null 2>&1; then - http_proxy_host=`/usr/bin/grep HTTPProxy ${scutil_out} | /usr/bin/awk 'END{print $3}'` - http_proxy_port=`/usr/bin/grep HTTPPort ${scutil_out} | /usr/bin/awk 'END{print $3} '` - http_proxy_tmp=$http_proxy_host:$http_proxy_port - rm ${scutil_out} - return 0 - fi - - http_proxy_tmp="DIRECT" - rm ${scutil_out} - return 0 -} - -unset http_proxy_tmp - -if [ `uname` = Darwin ] ; then - detect_macosx_proxy -else - if [ "$KDE_FULL_SESSION" = "true" ] ; then - detect_kde_proxy - else - if [ ! -z "$GNOME_DESKTOP_SESSION_ID" ] ; then - detect_gnome_proxy - fi - fi -fi - -# fall back to the environment-defined http_proxy if nothing found so far -if [ -z "$http_proxy_tmp" ]; then - http_proxy_tmp=$http_proxy -fi - -if [ ! -z "$http_proxy_tmp" ] ; then - jargs="-Dnetbeans.system_http_proxy=\"$http_proxy_tmp\" -Dnetbeans.system_http_non_proxy_hosts=\"$http_non_proxy_hosts\" $jargs" -fi - -if [ ! -z "$socks_proxy_tmp" ] ; then - jargs="-Dnetbeans.system_socks_proxy=\"$socks_proxy_tmp\" $jargs" fi if [ ! -z "${DEFAULT_USERDIR_ROOT}" ] ; then diff -r 3bff97f36acc o.n.bootstrap/launcher/windows/nbexec.dll Binary file o.n.bootstrap/launcher/windows/nbexec.dll has changed diff -r 3bff97f36acc o.n.bootstrap/launcher/windows/nbexec.exe Binary file o.n.bootstrap/launcher/windows/nbexec.exe has changed diff -r 3bff97f36acc o.n.bootstrap/launcher/windows/nbexec64.dll Binary file o.n.bootstrap/launcher/windows/nbexec64.dll has changed diff -r 3bff97f36acc o.n.bootstrap/launcher/windows/nbexec64.exe Binary file o.n.bootstrap/launcher/windows/nbexec64.exe has changed diff -r 3bff97f36acc o.n.bootstrap/launcher/windows/nbexec_exe64.res Binary file o.n.bootstrap/launcher/windows/nbexec_exe64.res has changed diff -r 3bff97f36acc o.n.bootstrap/launcher/windows/platformlauncher.cpp --- a/o.n.bootstrap/launcher/windows/platformlauncher.cpp Tue Mar 26 12:16:28 2013 +0100 +++ b/o.n.bootstrap/launcher/windows/platformlauncher.cpp Tue Mar 26 12:52:42 2013 +0100 @@ -72,9 +72,6 @@ const char *PlatformLauncher::OPT_NB_CLUSTERS = "-Dnetbeans.dirs="; const char *PlatformLauncher::OPT_NB_USERDIR = "-Dnetbeans.user="; const char *PlatformLauncher::OPT_DEFAULT_USERDIR_ROOT = "-Dnetbeans.default_userdir_root="; -const char *PlatformLauncher::OPT_HTTP_PROXY = "-Dnetbeans.system_http_proxy="; -const char *PlatformLauncher::OPT_HTTP_NONPROXY = "-Dnetbeans.system_http_non_proxy_hosts="; -const char *PlatformLauncher::OPT_SOCKS_PROXY = "-Dnetbeans.system_socks_proxy="; const char *PlatformLauncher::OPT_HEAP_DUMP = "-XX:+HeapDumpOnOutOfMemoryError"; const char *PlatformLauncher::OPT_HEAP_DUMP_PATH = "-XX:HeapDumpPath="; const char *PlatformLauncher::OPT_KEEP_WORKING_SET_ON_MINIMIZE = "-Dsun.awt.keepWorkingSetOnMinimize=true"; @@ -82,12 +79,6 @@ const char *PlatformLauncher::OPT_SPLASH = "-splash:"; const char *PlatformLauncher::OPT_SPLASH_PATH = "\\var\\cache\\splash.png"; -const char *PlatformLauncher::REG_PROXY_KEY = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet settings"; -const char *PlatformLauncher::REG_PROXY_ENABLED_NAME = "ProxyEnable"; -const char *PlatformLauncher::REG_PROXY_SERVER_NAME = "ProxyServer"; -const char *PlatformLauncher::REG_PROXY_OVERRIDE_NAME = "ProxyOverride"; -const char *PlatformLauncher::REG_PAC_FILE = "AutoConfigURL"; -const char *PlatformLauncher::PROXY_DIRECT = "DIRECT"; const char *PlatformLauncher::HEAP_DUMP_PATH = "\\var\\log\\heapdump.hprof"; const char *PlatformLauncher::RESTART_FILE_PATH = "\\var\\restart"; @@ -596,96 +587,11 @@ MoveFile (heapdumpfile.c_str(), heapdumpfileold.c_str()); } } - - string proxy, nonProxy, socksProxy; - if (!findHttpProxyFromEnv(proxy)) { - findProxiesFromRegistry(proxy, nonProxy, socksProxy); - } - if (!proxy.empty()) { - option = OPT_HTTP_PROXY; - option += proxy; - javaOptions.push_back(option); - } - if (!nonProxy.empty()) { - option = OPT_HTTP_NONPROXY; - option += nonProxy; - javaOptions.push_back(option); - } - if (!socksProxy.empty()) { - option = OPT_SOCKS_PROXY; - option += socksProxy; - javaOptions.push_back(option); - } - + option = OPT_KEEP_WORKING_SET_ON_MINIMIZE; javaOptions.push_back(option); } -// Reads value of http_proxy environment variable to use it as proxy setting -bool PlatformLauncher::findHttpProxyFromEnv(string &proxy) { - logMsg("findHttpProxyFromEnv()"); - char *envVar = getenv("http_proxy"); - if (envVar) { - // is it URL? - int prefixLen = strlen("http://"); - if (strncmp(envVar, "http://", prefixLen) == 0 && envVar[strlen(envVar) - 1] == '/' - && strlen(envVar) > strlen("http://")) { - // trim URL part to keep only 'host[:port]' - proxy = envVar + prefixLen; - proxy.erase(proxy.size() - 1); - logMsg("Found proxy in environment variable: %s", proxy.c_str()); - return true; - } - } - return false; -} - -bool PlatformLauncher::findProxiesFromRegistry(string &proxy, string &nonProxy, string &socksProxy) { - logMsg("findProxiesFromRegistry()"); - socksProxy = nonProxy = proxy = ""; - DWORD proxyEnable = 0; - if (!getDwordFromRegistry(HKEY_CURRENT_USER, REG_PROXY_KEY, REG_PROXY_ENABLED_NAME, proxyEnable)) { - return false; - } - - if (!proxyEnable) { - logMsg("Manual Proxy disabled"); - string pacFile; - if (getStringFromRegistry(HKEY_CURRENT_USER, REG_PROXY_KEY, REG_PAC_FILE, pacFile)) { - logMsg("AutoConfigURL found."); - proxy = "PAC " + pacFile; - } else { - proxy = PROXY_DIRECT; - } - return true; - } - - string proxyServer; - if (!getStringFromRegistry(HKEY_CURRENT_USER, REG_PROXY_KEY, REG_PROXY_SERVER_NAME, proxyServer)) { - return false; - } - - if (proxyServer.find('=') == string::npos) { - proxy = proxyServer; - } else { - string::size_type pos = proxyServer.find("socks="); - if (pos != string::npos) { - if (proxyServer.size() > pos + 1 && proxyServer.at(pos) != ';') { - string::size_type endPos = proxyServer.find(';', pos); - socksProxy = proxyServer.substr(pos, endPos == string::npos ? string::npos : endPos - pos); - } - } - pos = proxyServer.find("http="); - if (pos != string::npos) { - string::size_type endPos = proxyServer.find(';', pos); - proxy = proxyServer.substr(pos, endPos == string::npos ? string::npos : endPos - pos); - } - } - logMsg("Proxy servers:\n\tproxy: %s\n\tsocks proxy: %s\n\tnonProxy: %s", proxy.c_str(), socksProxy.c_str(), nonProxy.c_str()); - getStringFromRegistry(HKEY_CURRENT_USER, REG_PROXY_KEY, REG_PROXY_OVERRIDE_NAME, nonProxy); - return true; -} - string & PlatformLauncher::constructClassPath(bool runUpdater) { logMsg("constructClassPath()"); addedToCP.clear(); diff -r 3bff97f36acc o.n.bootstrap/launcher/windows/platformlauncher.h --- a/o.n.bootstrap/launcher/windows/platformlauncher.h Tue Mar 26 12:16:28 2013 +0100 +++ b/o.n.bootstrap/launcher/windows/platformlauncher.h Tue Mar 26 12:52:42 2013 +0100 @@ -55,13 +55,7 @@ class PlatformLauncher { static const char *REQ_JAVA_VERSION; static const char *HELP_MSG; - static const char *REG_PROXY_KEY; - static const char *REG_PROXY_ENABLED_NAME; - static const char *REG_PROXY_SERVER_NAME; - static const char *REG_PROXY_OVERRIDE_NAME; - static const char *REG_PAC_FILE; - static const char *PROXY_DIRECT; static const char *HEAP_DUMP_PATH; static const char *RESTART_FILE_PATH; @@ -70,9 +64,6 @@ static const char *OPT_NB_CLUSTERS; static const char *OPT_NB_USERDIR; static const char *OPT_DEFAULT_USERDIR_ROOT; - static const char *OPT_HTTP_PROXY; - static const char *OPT_HTTP_NONPROXY; - static const char *OPT_SOCKS_PROXY; static const char *OPT_HEAP_DUMP; static const char *OPT_HEAP_DUMP_PATH; static const char *OPT_KEEP_WORKING_SET_ON_MINIMIZE; @@ -106,8 +97,6 @@ bool shouldAutoUpdate(bool firstStart, const char *basePath); bool shouldAutoUpdateClusters(bool firstStart); void prepareOptions(); - bool findHttpProxyFromEnv(std::string &proxy); - bool findProxiesFromRegistry(std::string &proxy, std::string &nonProxy, std::string &socksProxy); std::string & constructClassPath(bool runUpdater); void addFilesToClassPath(const char *dir, const char *subdir, const char *pattern); void addToClassPath(const char *path, bool onlyIfExists = false); diff -r 3bff97f36acc o.n.bootstrap/manifest.mf --- a/o.n.bootstrap/manifest.mf Tue Mar 26 12:16:28 2013 +0100 +++ b/o.n.bootstrap/manifest.mf Tue Mar 26 12:52:42 2013 +0100 @@ -1,6 +1,6 @@ Manifest-Version: 1.0 OpenIDE-Module: org.netbeans.bootstrap/1 -OpenIDE-Module-Specification-Version: 2.59 +OpenIDE-Module-Specification-Version: 2.60 OpenIDE-Module-Localizing-Bundle: org/netbeans/Bundle.properties OpenIDE-Module-Recommends: org.netbeans.NetigsoFramework diff -r 3bff97f36acc o.n.bootstrap/nbproject/project.properties --- a/o.n.bootstrap/nbproject/project.properties Tue Mar 26 12:16:28 2013 +0100 +++ b/o.n.bootstrap/nbproject/project.properties Tue Mar 26 12:52:42 2013 +0100 @@ -1,6 +1,6 @@ # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. # -# Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. +# Copyright 1997-2013 Oracle and/or its affiliates. All rights reserved. # # Oracle and Java are registered trademarks of Oracle and/or its affiliates. # Other names may be trademarks of their respective owners. @@ -52,6 +52,7 @@ nbm.executable.files=lib/nbexec javadoc.arch=${basedir}/arch.xml +javadoc.apichanges=${basedir}/apichanges.xml # When changing this list, change 'verifyexcludes' param. of 'makejnlp' task in apisupport.harness/release/jnlp.xml as well jnlp.verify.excludes=lib/nbexec,lib/nbexec.exe,lib/nbexec64.exe,lib/nbexec.dll,lib/nbexec64.dll diff -r 3bff97f36acc o.n.core/apichanges.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/o.n.core/apichanges.xml Tue Mar 26 12:52:42 2013 +0100 @@ -0,0 +1,142 @@ + + + + + + + + + Bridge Core with Core Network Friend API + + + + + + Core Network provides ProxySelector + + + + + +

    + The o.n.core module finds a instance of java.net.ProxySelector + in the default org.openide.util.Lookup. If some found + then will be registred as default ProxySelector.setDedault(). +

    +
    + + +
    + + + + ProxySettings.Reload allows reload the Network Proxy Settings + + + + + +

    + An implementation of this class brings a facility to reload Network + Proxy Settings from underlying OS. + The module core.network provides a implementation + which may be accessible via Lookup.getDefault(). It's not guaranteed + any implementation is found on all distribution. +

    +
    + + +
    + + + + NbProxySelector and ProxyAutoConfig moved to new Core Network module. + + + + + +

    + Classes NbProxySelector and ProxyAutoConfig have been + moved to Core Network module. Now the NbProxySelector can be accessed + via lookup - in CoreBridgeImpl. +

    +
    + + + +
    +
    + + + + + + Change History for the Friend Core APIs + + + + + + +

    Introduction

    + +

    +This document lists changes made to the API between core/startup and core +modules. It is a friend API so it does not need to be developed compatibly, +and indeed it is not. +

    + + + +
    + +

    @FOOTER@

    + + +
    + +
    diff -r 3bff97f36acc o.n.core/manifest.mf --- a/o.n.core/manifest.mf Tue Mar 26 12:16:28 2013 +0100 +++ b/o.n.core/manifest.mf Tue Mar 26 12:52:42 2013 +0100 @@ -4,4 +4,6 @@ OpenIDE-Module-Layer: org/netbeans/core/resources/mf-layer.xml AutoUpdate-Show-In-Client: false AutoUpdate-Essential-Module: true -OpenIDE-Module-Specification-Version: 3.39 +OpenIDE-Module-Recommends: org.netbeans.core.ProxySettings.Reloader +OpenIDE-Module-Specification-Version: 3.40 + diff -r 3bff97f36acc o.n.core/nbproject/project.properties --- a/o.n.core/nbproject/project.properties Tue Mar 26 12:16:28 2013 +0100 +++ b/o.n.core/nbproject/project.properties Tue Mar 26 12:52:42 2013 +0100 @@ -1,6 +1,6 @@ # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. # -# Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. +# Copyright 1997-2013 Oracle and/or its affiliates. All rights reserved. # # Oracle and Java are registered trademarks of Oracle and/or its affiliates. # Other names may be trademarks of their respective owners. @@ -44,6 +44,7 @@ javac.source=1.6 javadoc.arch=${basedir}/arch.xml +javadoc.apichanges=${basedir}/apichanges.xml release.external/nsProxyAutoConfig.js=modules/ext/nsProxyAutoConfig.js jnlp.indirect.files=modules/ext/nsProxyAutoConfig.js diff -r 3bff97f36acc o.n.core/nbproject/project.xml --- a/o.n.core/nbproject/project.xml Tue Mar 26 12:16:28 2013 +0100 +++ b/o.n.core/nbproject/project.xml Tue Mar 26 12:52:42 2013 +0100 @@ -278,6 +278,7 @@ org.netbeans.core.browser.webview org.netbeans.core.browser.xulrunner org.netbeans.core.execution + org.netbeans.core.network org.netbeans.core.ui org.netbeans.core.windows org.netbeans.modules.jellytools.platform diff -r 3bff97f36acc o.n.core/src/org/netbeans/core/CoreBridgeImpl.java --- a/o.n.core/src/org/netbeans/core/CoreBridgeImpl.java Tue Mar 26 12:16:28 2013 +0100 +++ b/o.n.core/src/org/netbeans/core/CoreBridgeImpl.java Tue Mar 26 12:52:42 2013 +0100 @@ -1,7 +1,7 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. + * Copyright 1997-2013 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. @@ -48,6 +48,7 @@ import java.io.File; import java.io.InputStream; import java.io.OutputStream; +import java.net.ProxySelector; import java.util.logging.Level; import java.util.logging.Logger; import java.util.prefs.Preferences; @@ -58,6 +59,7 @@ import org.netbeans.swing.plaf.Startup; import org.openide.nodes.NodeOp; import org.openide.util.Exceptions; +import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.openide.util.NbPreferences; import org.openide.util.RequestProcessor; @@ -204,9 +206,11 @@ NodeOp.registerPropertyEditors(); } }); - - // install java.net.ProxySelector - NbProxySelector.register(); + ProxySelector selector = Lookup.getDefault().lookup(ProxySelector.class); + if (selector != null) { + // install java.net.ProxySelector + ProxySelector.setDefault(selector); + } editorsRegistered = true; } diff -r 3bff97f36acc o.n.core/src/org/netbeans/core/NbProxySelector.java --- a/o.n.core/src/org/netbeans/core/NbProxySelector.java Tue Mar 26 12:16:28 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,446 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * Oracle and Java are registered trademarks of Oracle and/or its affiliates. - * Other names may be trademarks of their respective owners. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * Contributor(s): - * - * The Original Software is NetBeans. The Initial Developer of the Original - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2011 Sun - * Microsystems, Inc. All Rights Reserved. - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - */ - -package org.netbeans.core; - -import java.io.IOException; -import java.lang.reflect.Method; -import java.net.*; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.prefs.PreferenceChangeEvent; -import java.util.prefs.PreferenceChangeListener; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -/** - * - * @author Jiri Rechtacek - */ -public final class NbProxySelector extends ProxySelector { - - private final ProxySelector original; - private static final Logger LOG = Logger.getLogger (NbProxySelector.class.getName ()); - private static Object useSystemProxies; - - /** Creates a new instance of NbProxySelector */ - private NbProxySelector (ProxySelector delegate) { - original = delegate; - LOG.fine ("java.net.useSystemProxies has been set to " + useSystemProxies ()); - LOG.fine ("In launcher was detected netbeans.system_http_proxy: " + System.getProperty ("netbeans.system_http_proxy", "N/A")); - LOG.fine ("In launcher was detected netbeans.system_socks_proxy: " + System.getProperty ("netbeans.system_socks_proxy", "N/A")); - ProxySettings.addPreferenceChangeListener (new ProxySettingsListener ()); - copySettingsToSystem (); - } - - static ProxySelector create(ProxySelector delegate) { - return new NbProxySelector(delegate); - } - - static void register() { - ProxySelector prev = ProxySelector.getDefault(); - if (prev == null) { - LOG.warning("No default system ProxySelector was found thus NetBeans ProxySelector won't delegate on it"); - } else { - LOG.log(Level.FINE, "Override the original ProxySelector: {0}", prev); - } - ProxySelector.setDefault(create(prev)); - } - - @Override - public List select(URI uri) { - List res = new ArrayList (); - int proxyType = ProxySettings.getProxyType (); - switch (proxyType) { - case ProxySettings.DIRECT_CONNECTION: - res = Collections.singletonList (Proxy.NO_PROXY); - break; - case ProxySettings.AUTO_DETECT_PROXY: - if (useSystemProxies ()) { - if (original != null) { - res = original.select (uri); - } - } else { - String protocol = uri.getScheme (); - assert protocol != null : "Invalid scheme of uri " + uri + ". Scheme cannot be null!"; - if (dontUseProxy (ProxySettings.SystemProxySettings.getNonProxyHosts (), uri.getHost ())) { - res.add (Proxy.NO_PROXY); - break; - } - if (protocol.toLowerCase (Locale.US).startsWith("http")) { - String ports = ProxySettings.SystemProxySettings.getHttpPort (); - if (ports != null && ports.length () > 0 && ProxySettings.SystemProxySettings.getHttpHost ().length () > 0) { - int porti = Integer.parseInt(ports); - Proxy p = new Proxy (Proxy.Type.HTTP, new InetSocketAddress (ProxySettings.SystemProxySettings.getHttpHost (), porti)); - res.add (p); - } - } else { // supposed SOCKS - String ports = ProxySettings.SystemProxySettings.getSocksPort (); - String hosts = ProxySettings.SystemProxySettings.getSocksHost (); - if (ports != null && ports.length () > 0 && hosts.length () > 0) { - int porti = Integer.parseInt(ports); - Proxy p = new Proxy (Proxy.Type.SOCKS, new InetSocketAddress (hosts, porti)); - res.add (p); - } - } - if (original != null) { - res.addAll (original.select (uri)); - } - } - break; - case ProxySettings.MANUAL_SET_PROXY: - String protocol = uri.getScheme (); - assert protocol != null : "Invalid scheme of uri " + uri + ". Scheme cannot be null!"; - - // handling nonProxyHosts first - if (dontUseProxy (ProxySettings.getNonProxyHosts (), uri.getHost ())) { - res.add (Proxy.NO_PROXY); - break; - } - if (protocol.toLowerCase (Locale.US).startsWith("http")) { - String hosts = ProxySettings.getHttpHost (); - String ports = ProxySettings.getHttpPort (); - if (ports != null && ports.length () > 0 && hosts.length () > 0) { - int porti = Integer.parseInt(ports); - Proxy p = new Proxy (Proxy.Type.HTTP, new InetSocketAddress (hosts, porti)); - res.add (p); - } else { - LOG.fine ("Incomplete HTTP Proxy [" + hosts + "/" + ports + "] found in ProxySelector[Type: " + ProxySettings.getProxyType () + "] for uri " + uri + ". "); - if (original != null) { - LOG.finest ("Fallback to the default ProxySelector which returns " + original.select (uri)); - res.addAll (original.select (uri)); - } - } - } else { // supposed SOCKS - String ports = ProxySettings.getSocksPort (); - String hosts = ProxySettings.getSocksHost (); - if (ports != null && ports.length () > 0 && hosts.length () > 0) { - int porti = Integer.parseInt(ports); - Proxy p = new Proxy (Proxy.Type.SOCKS, new InetSocketAddress (hosts, porti)); - res.add (p); - } else { - LOG.fine ("Incomplete SOCKS Server [" + hosts + "/" + ports + "] found in ProxySelector[Type: " + ProxySettings.getProxyType () + "] for uri " + uri + ". "); - if (original != null) { - LOG.finest ("Fallback to the default ProxySelector which returns " + original.select (uri)); - res.addAll (original.select (uri)); - } - } - } - res.add (Proxy.NO_PROXY); - break; - case ProxySettings.AUTO_DETECT_PAC: - if (useSystemProxies ()) { - if (original != null) { - res = original.select (uri); - } - } else { - // handling nonProxyHosts first - if (dontUseProxy (ProxySettings.getNonProxyHosts (), uri.getHost ())) { - res.add (Proxy.NO_PROXY); - break; - } - ProxyAutoConfig pac = ProxyAutoConfig.get(getPacFile()); - assert pac != null : "Instance of ProxyAutoConfig found for " + getPacFile(); - if (pac == null) { - LOG.finest ("No instance of ProxyAutoConfig(" + getPacFile() + ") for URI " + uri); - res.add(Proxy.NO_PROXY); - } - if (pac.getPacURI().getHost() == null) { - LOG.log(Level.FINEST, "Identifying proxy for URI {0}---{1}, PAC LOCAL URI: {2}", //NOI18N - new Object[] { uri.toString(), uri.getHost(), pac.getPacURI().toString() }); - res.addAll(pac.findProxyForURL(uri)); - } else if (pac.getPacURI().getHost().equals(uri.getHost())) { - // don't proxy PAC files - res.add(Proxy.NO_PROXY); - } else { - LOG.log(Level.FINEST, "Identifying proxy for URI {0}---{1}, PAC URI: {2}---{3}", //NOI18N - new Object[] { uri.toString(), uri.getHost(), pac.getPacURI().toString(), pac.getPacURI().getHost() }); - res.addAll(pac.findProxyForURL(uri)); // NOI18N - } - } - res.add (Proxy.NO_PROXY); - break; - case ProxySettings.MANUAL_SET_PAC: - // handling nonProxyHosts first - if (dontUseProxy (ProxySettings.getNonProxyHosts (), uri.getHost ())) { - res.add (Proxy.NO_PROXY); - break; - } - ProxyAutoConfig pac = ProxyAutoConfig.get(getPacFile()); - assert pac != null : "Instance of ProxyAutoConfig found for " + getPacFile(); - if (pac == null) { - LOG.finest ("No instance of ProxyAutoConfig(" + getPacFile() + ") for URI " + uri); - res.add(Proxy.NO_PROXY); - } - if (pac.getPacURI().getHost() == null) { - LOG.log(Level.FINEST, "Identifying proxy for URI {0}---{1}, PAC LOCAL URI: {2}", //NOI18N - new Object[] { uri.toString(), uri.getHost(), pac.getPacURI().toString() }); - res.addAll(pac.findProxyForURL(uri)); - } else if (pac.getPacURI().getHost().equals(uri.getHost())) { - // don't proxy PAC files - res.add(Proxy.NO_PROXY); - } else { - LOG.log(Level.FINEST, "Identifying proxy for URI {0}---{1}, PAC URI: {2}---{3}", //NOI18N - new Object[] { uri.toString(), uri.getHost(), pac.getPacURI().toString(), pac.getPacURI().getHost() }); - res.addAll(pac.findProxyForURL(uri)); // NOI18N - } - res.add (Proxy.NO_PROXY); - break; - default: - assert false : "Invalid proxy type: " + proxyType; - } - LOG.finest ("NbProxySelector[Type: " + ProxySettings.getProxyType () + - ", Use HTTP for all protocols: " + ProxySettings.useProxyAllProtocols ()+ - "] returns " + res + " for URI " + uri); - return res; - } - - @Override - public void connectFailed (URI arg0, SocketAddress arg1, IOException arg2) { - LOG.log (Level.INFO, "connectionFailed(" + arg0 + ", " + arg1 +")", arg2); - } - - // several modules listenes on these properties and propagates it futher - private class ProxySettingsListener implements PreferenceChangeListener { - @Override - public void preferenceChange(PreferenceChangeEvent evt) { - if (evt.getKey ().startsWith ("proxy") || evt.getKey ().startsWith ("useProxy")) { - copySettingsToSystem (); - } - } - } - - private void copySettingsToSystem () { - String host = null, port = null, nonProxyHosts = null; - String sHost = null, sPort = null; - String httpsHost = null, httpsPort = null; - int proxyType = ProxySettings.getProxyType (); - switch (proxyType) { - case ProxySettings.DIRECT_CONNECTION: - host = null; - port = null; - httpsHost = null; - httpsPort = null; - nonProxyHosts = null; - sHost = null; - sPort = null; - break; - case ProxySettings.AUTO_DETECT_PROXY: - host = ProxySettings.SystemProxySettings.getHttpHost (); - port = ProxySettings.SystemProxySettings.getHttpPort (); - httpsHost = ProxySettings.SystemProxySettings.getHttpsHost (); - httpsPort = ProxySettings.SystemProxySettings.getHttpsPort (); - sHost = ProxySettings.SystemProxySettings.getSocksHost (); - sPort = ProxySettings.SystemProxySettings.getSocksPort (); - ProxySettings.SystemProxySettings.getNonProxyHosts (); - break; - case ProxySettings.MANUAL_SET_PROXY: - host = ProxySettings.getHttpHost (); - port = ProxySettings.getHttpPort (); - httpsHost = ProxySettings.getHttpsHost (); - httpsPort = ProxySettings.getHttpsPort (); - nonProxyHosts = ProxySettings.getNonProxyHosts (); - sHost = ProxySettings.getSocksHost (); - sPort = ProxySettings.getSocksPort (); - break; - case ProxySettings.AUTO_DETECT_PAC: - host = null; - port = null; - httpsHost = null; - httpsPort = null; - ProxySettings.SystemProxySettings.getNonProxyHosts (); - sHost = null; - sPort = null; - break; - case ProxySettings.MANUAL_SET_PAC: - host = null; - port = null; - httpsHost = null; - httpsPort = null; - ProxySettings.getNonProxyHosts (); - sHost = null; - sPort = null; - break; - default: - assert false : "Invalid proxy type: " + proxyType; - } - setOrClearProperty ("http.proxyHost", host, false); - setOrClearProperty ("http.proxyPort", port, true); - setOrClearProperty ("http.nonProxyHosts", nonProxyHosts, false); - setOrClearProperty ("https.proxyHost", httpsHost, false); - setOrClearProperty ("https.proxyPort", httpsPort, true); - setOrClearProperty ("https.nonProxyHosts", nonProxyHosts, false); - setOrClearProperty ("socksProxyHost", sHost, false); - setOrClearProperty ("socksProxyPort", sPort, true); - LOG.fine ("Set System's http.proxyHost/Port/NonProxyHost to " + host + "/" + port + "/" + nonProxyHosts); - LOG.fine ("Set System's https.proxyHost/Port to " + httpsHost + "/" + httpsPort); - LOG.fine ("Set System's socksProxyHost/Port to " + sHost + "/" + sPort); - } - - private void setOrClearProperty (String key, String value, boolean isInteger) { - assert key != null; - if (value == null || value.length () == 0) { - System.clearProperty (key); - } else { - if (isInteger) { - try { - Integer.parseInt (value); - } catch (NumberFormatException nfe) { - LOG.log (Level.INFO, nfe.getMessage(), nfe); - } - } - System.setProperty (key, value); - } - } - - // package-private for unit-testing - static boolean dontUseProxy (String nonProxyHosts, String host) { - if (host == null) return false; - - // try IP adress first - if (dontUseIp (nonProxyHosts, host)) { - return true; - } else { - return dontUseHostName (nonProxyHosts, host); - } - - } - - private static boolean dontUseHostName (String nonProxyHosts, String host) { - if (host == null) return false; - - boolean dontUseProxy = false; - StringTokenizer st = new StringTokenizer (nonProxyHosts, "|", false); - while (st.hasMoreTokens () && !dontUseProxy) { - String token = st.nextToken ().trim(); - int star = token.indexOf ("*"); - if (star == -1) { - dontUseProxy = token.equals (host); - if (dontUseProxy) { - LOG.finest ("NbProxySelector[Type: " + ProxySettings.getProxyType () + "]. Host " + host + " found in nonProxyHosts: " + nonProxyHosts); - } - } else { - String start = token.substring (0, star - 1 < 0 ? 0 : star - 1); - String end = token.substring (star + 1 > token.length () ? token.length () : star + 1); - - //Compare left of * if and only if * is not first character in token - boolean compareStart = star > 0; // not first character - //Compare right of * if and only if * is not the last character in token - boolean compareEnd = star < (token.length() - 1); // not last character - dontUseProxy = (compareStart && host.startsWith(start)) || (compareEnd && host.endsWith(end)); - - if (dontUseProxy) { - LOG.finest ("NbProxySelector[Type: " + ProxySettings.getProxyType () + "]. Host " + host + " found in nonProxyHosts: " + nonProxyHosts); - } - } - } - return dontUseProxy; - } - - private static boolean dontUseIp (String nonProxyHosts, String host) { - if (host == null) return false; - - String ip = null; - try { - ip = InetAddress.getByName (host).getHostAddress (); - } catch (UnknownHostException ex) { - LOG.log (Level.FINE, ex.getLocalizedMessage (), ex); - } - - if (ip == null) { - return false; - } - - boolean dontUseProxy = false; - StringTokenizer st = new StringTokenizer (nonProxyHosts, "|", false); - while (st.hasMoreTokens () && !dontUseProxy) { - String nonProxyHost = st.nextToken ().trim(); - int star = nonProxyHost.indexOf ("*"); - if (star == -1) { - dontUseProxy = nonProxyHost.equals (ip); - if (dontUseProxy) { - LOG.finest ("NbProxySelector[Type: " + ProxySettings.getProxyType () + "]. Host's IP " + ip + " found in nonProxyHosts: " + nonProxyHosts); - } - } else { - // match with given dotted-quad IP - try { - dontUseProxy = Pattern.matches (nonProxyHost, ip); - if (dontUseProxy) { - LOG.finest ("NbProxySelector[Type: " + ProxySettings.getProxyType () + "]. Host's IP" + ip + " found in nonProxyHosts: " + nonProxyHosts); - } - } catch (PatternSyntaxException pse) { - // may ignore it here - } - } - } - return dontUseProxy; - } - - // NetProperties is JDK vendor specific, access only by reflection - static boolean useSystemProxies () { - if (useSystemProxies == null) { - try { - Class clazz = Class.forName ("sun.net.NetProperties"); - Method getBoolean = clazz.getMethod ("getBoolean", String.class); - useSystemProxies = getBoolean.invoke (null, "java.net.useSystemProxies"); - } catch (Exception x) { - LOG.log (Level.FINEST, "Cannot get value of java.net.useSystemProxies bacause " + x.getMessage(), x); - } - } - return useSystemProxies != null && "true".equalsIgnoreCase (useSystemProxies.toString ()); - } - - static boolean usePAC() { - String s = System.getProperty ("netbeans.system_http_proxy"); // NOI18N - boolean usePAC = s != null && s.startsWith(ProxySettings.PAC); - return usePAC; - } - - private static String getPacFile() { - String init = System.getProperty("netbeans.system_http_proxy"); // NOI18N - return init.substring(4).trim(); - } - -} diff -r 3bff97f36acc o.n.core/src/org/netbeans/core/ProxyAutoConfig.java --- a/o.n.core/src/org/netbeans/core/ProxyAutoConfig.java Tue Mar 26 12:16:28 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,348 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 2011-2012 Oracle and/or its affiliates. All rights reserved. - * - * Oracle and Java are registered trademarks of Oracle and/or its affiliates. - * Other names may be trademarks of their respective owners. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - * - * Contributor(s): - * - * Portions Copyrighted 2011 Sun Microsystems, Inc. - */ -package org.netbeans.core; - -import java.io.*; -import java.net.*; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.script.Invocable; -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.ScriptException; -import org.openide.filesystems.FileObject; -import org.openide.filesystems.FileUtil; -import org.openide.filesystems.URLMapper; -import org.openide.util.RequestProcessor; -import org.openide.util.RequestProcessor.Task; -import org.openide.util.Utilities; - -/** - * - * @author Jirka Rechtacek - */ -public class ProxyAutoConfig { - - private static final Map file2pac = new HashMap(2); - private static RequestProcessor RP = new RequestProcessor(ProxyAutoConfig.class); - private static final String NS_PROXY_AUTO_CONFIG_URL = "nbinst://org.netbeans.core/modules/ext/nsProxyAutoConfig.js"; // NOI18N - private static final String PROTO_FILE = "file://"; - - /** - * - * @param pacFile The string to be parsed into a URI - * @return ProxyAutoConfig for given pacFile or null if constructor failed - */ - public static synchronized ProxyAutoConfig get(String pacFile) { - if (file2pac.get(pacFile) == null) { - LOGGER.fine("Init ProxyAutoConfig for " + pacFile); - ProxyAutoConfig instance = null; - try { - instance = new ProxyAutoConfig(pacFile); - } catch (URISyntaxException ex) { - Logger.getLogger(ProxyAutoConfig.class.getName()).warning("Parsing " + pacFile + " to URI throws " + ex); - } finally { - file2pac.put(pacFile, instance); - } - } - return file2pac.get(pacFile); - } - private static final Logger LOGGER = Logger.getLogger(ProxyAutoConfig.class.getName()); - private Invocable inv = null; - private final Task initTask; - private final URI pacURI; - - private ProxyAutoConfig(final String pacURL) throws URISyntaxException { - assert file2pac.get(pacURL) == null : "Only once object for " + pacURL + " must exist."; - String normPAC = normalizePAC(pacURL); - pacURI = new URI(normPAC); - initTask = RP.post(new Runnable() { - - @Override - public void run() { - initEngine(); - } - }); - } - - public URI getPacURI() { - return pacURI; - } - - private void initEngine() { - InputStream pacIS; - try { - if (pacURI.isAbsolute()) { - pacIS = downloadPAC(pacURI.toURL()); - } else { - pacIS = null; - } - } catch (IOException ex) { - LOGGER.log(Level.INFO, "InputStream for " + pacURI + " throws " + ex, ex); - return; - } - if (pacIS == null) { - return ; - } - String utils = downloadUtils(); - ScriptEngine eng; - try { - eng = evalPAC(pacIS, utils); - } catch (FileNotFoundException ex) { - LOGGER.log(Level.FINE, "While constructing ProxyAutoConfig thrown " + ex, ex); - return ; - } catch (ScriptException ex) { - LOGGER.log(Level.FINE, "While constructing ProxyAutoConfig thrown " + ex, ex); - return ; - } finally { - if (pacIS != null) { - try { - pacIS.close(); - } catch (IOException ex) { - LOGGER.log(Level.FINE, "While closing PAC input stream thrown " + ex, ex); - } - } - } - assert eng != null : "JavaScri5pt engine cannot be null"; - if (eng == null) { - LOGGER.log(Level.WARNING, "JavaScript engine cannot be null"); - return ; - } - inv = (Invocable) eng; - } - - @SuppressWarnings("unchecked") - public List findProxyForURL(URI u) { - assert initTask != null : "initTask has be to posted."; - if (!initTask.isFinished()) { - while (!initTask.isFinished()) { - try { - RP.post(new Runnable() { - - @Override - public void run() { - } - }).waitFinished(100); - } catch (InterruptedException ex) { - LOGGER.log(Level.FINEST, ex.getMessage(), ex); - } - } - } - if (inv == null) { - return Collections.singletonList(Proxy.NO_PROXY); - } - Object proxies = null; - try { - proxies = inv.invokeFunction("FindProxyForURL", u.toString(), u.getHost()); // NOI18N - } catch (ScriptException ex) { - LOGGER.log(Level.FINE, "While invoking FindProxyForURL(" + u + ", " + u.getHost() + " thrown " + ex, ex); - } catch (NoSuchMethodException ex) { - LOGGER.log(Level.FINE, "While invoking FindProxyForURL(" + u + ", " + u.getHost() + " thrown " + ex, ex); - } - List res = analyzeResult(u, proxies); - if (res == null) { - LOGGER.info("findProxyForURL(" + u + ") returns null."); - res = Collections.emptyList(); - } - LOGGER.fine("findProxyForURL(" + u + ") returns " + Arrays.asList(res)); - return res; - } - - private static InputStream downloadPAC (URL pacURL) throws IOException { - InputStream is; - URLConnection conn = pacURL.openConnection(Proxy.NO_PROXY); - is = conn.getInputStream(); - return is; - } - - private static ScriptEngine evalPAC(InputStream is, String utils) throws FileNotFoundException, ScriptException { - ScriptEngineManager factory = new ScriptEngineManager(); - ScriptEngine engine = factory.getEngineByName("JavaScript"); - Reader pacReader = new InputStreamReader(is); - engine.eval(pacReader); - engine.eval(utils); - return engine; - } - - private List analyzeResult(URI uri, Object proxiesString) { - if (proxiesString == null) { - LOGGER.fine("Null result for " + uri); - return null; - } - Proxy.Type proxyType; - String protocol = uri.getScheme(); - assert protocol != null : "Invalid scheme of uri " + uri + ". Scheme cannot be null!"; - if (protocol == null) { - return null; - } else { - if (("http".equals(protocol)) || ("https".equals(protocol))) { // NOI18N - proxyType = Proxy.Type.HTTP; - } else { - proxyType = Proxy.Type.SOCKS; - } - } - StringTokenizer st = new StringTokenizer(proxiesString.toString(), ";"); //NOI18N - List proxies = new LinkedList(); - while (st.hasMoreTokens()) { - String proxy = st.nextToken(); - if (ProxySettings.DIRECT.equals(proxy.trim())) { - proxies.add(Proxy.NO_PROXY); - } else { - String host = getHost(proxy); - Integer port = getPort(proxy); - if (host != null && port != null) { - proxies.add(new Proxy(proxyType, new InetSocketAddress(host, port))); - } - } - } - return proxies; - } - - private static String getHost(String proxy) { - if (proxy.startsWith("PROXY ")) { - proxy = proxy.substring(6); - } - int i = proxy.lastIndexOf(":"); // NOI18N - if (i <= 0 || i >= proxy.length() - 1) { - LOGGER.info("No port in " + proxy); - return null; - } - - String host = proxy.substring(0, i); - - return ProxySettings.normalizeProxyHost(host); - } - - private static Integer getPort(String proxy) { - if (proxy.startsWith("PROXY ")) { - proxy = proxy.substring(6); - } - int i = proxy.lastIndexOf(":"); // NOI18N - if (i <= 0 || i >= proxy.length() - 1) { - LOGGER.info("No port in " + proxy); - return null; - } - - String port = proxy.substring(i + 1); - if (port.indexOf('/') >= 0) { - port = port.substring(0, port.indexOf('/')); - } - - try { - return Integer.parseInt(port); - } catch (NumberFormatException ex) { - LOGGER.log(Level.INFO, ex.getLocalizedMessage(), ex); - return null; - } - } - - private static String downloadUtils() { - StringBuilder builder = new StringBuilder(); - BufferedReader reader = null; - // XXX why is the below not more simply: - // reader = new BufferedReader(new URL(NS_PROXY_AUTO_CONFIG_URL).openStream()); - FileObject fo = null; - try { - try { - fo = URLMapper.findFileObject(new URL(NS_PROXY_AUTO_CONFIG_URL)); - } catch (MalformedURLException ex) { - LOGGER.log(Level.INFO, ex.getMessage(), ex); - } - reader = new BufferedReader(new java.io.FileReader(FileUtil.toFile(fo))); - } catch (FileNotFoundException ex) { - LOGGER.log(Level.INFO, ex.getMessage(), ex); - } - try { - String line; - boolean doAppend = false; - while ((line = reader.readLine()) != null) { - line = line.trim(); - if( line.startsWith("var pacUtils =") ) { //NOI18N - doAppend = true; - } - if( !doAppend ) - continue; - if (line.endsWith("+")) { // NOI18N - line = line.substring(0, line.length() - 1); - } - builder.append(line.replaceAll("\"", "").replaceAll("\\\\n", "").replaceAll("\\\\\\\\", "\\\\")); // NOI18N - builder.append(System.getProperty("line.separator")); // NOI18N - } - } catch (IOException ex) { - LOGGER.log(Level.INFO, "While downloading nsProxyAutoConfig.js thrown " + ex.getMessage(), ex); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException ex) { - LOGGER.log(Level.FINE, ex.getMessage(), ex); - } - } - } - return builder.toString(); - } - - private String normalizePAC(String pacURL) { - int index; - if ((index = pacURL.indexOf("\n")) != -1) { // NOI18N - pacURL = pacURL.substring(0, index); - } - if ((index = pacURL.indexOf("\r")) != -1) { // NOI18N - pacURL = pacURL.substring(0, index); - } - String fileLocation = pacURL; - if (fileLocation.startsWith(PROTO_FILE)) { - fileLocation = fileLocation.substring(PROTO_FILE.length()); - } - File f = new File(fileLocation); - if (f.canRead()) { - pacURL = Utilities.toURI(f).toString(); - } else { - pacURL = pacURL.replaceAll("\\\\", "/"); //NOI18N - } - if ((index = pacURL.indexOf(" ")) != -1) { // NOI18N - pacURL = pacURL.substring(0, index); - } - return pacURL.trim(); - } -} diff -r 3bff97f36acc o.n.core/src/org/netbeans/core/ProxySettings.java --- a/o.n.core/src/org/netbeans/core/ProxySettings.java Tue Mar 26 12:16:28 2013 +0100 +++ b/o.n.core/src/org/netbeans/core/ProxySettings.java Tue Mar 26 12:52:42 2013 +0100 @@ -1,7 +1,7 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * - * Copyright 1997-2012 Oracle and/or its affiliates. All rights reserved. + * Copyright 1997-2013 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. @@ -75,6 +75,51 @@ public static final String DIRECT = "DIRECT"; public static final String PAC = "PAC"; + public static final String SYSTEM_PROXY_HTTP_HOST = "systemProxyHttpHost"; + public static final String SYSTEM_PROXY_HTTP_PORT = "systemProxyHttpPort"; + public static final String SYSTEM_PROXY_HTTPS_HOST = "systemProxyHttpsHost"; + public static final String SYSTEM_PROXY_HTTPS_PORT = "systemProxyHttpsPort"; + public static final String SYSTEM_PROXY_SOCKS_HOST = "systemProxySocksHost"; + public static final String SYSTEM_PROXY_SOCKS_PORT = "systemProxySocksPort"; + public static final String SYSTEM_NON_PROXY_HOSTS = "systemProxyNonProxyHosts"; + public static final String SYSTEM_PAC = "systemPAC"; + + + // TODO move to proper place + public static String getSystemHttpHost() { + return getPreferences().get(SYSTEM_PROXY_HTTP_HOST, ""); + } + + public static String getSystemHttpPort() { + return getPreferences().get(SYSTEM_PROXY_HTTP_PORT, ""); + } + + public static String getSystemHttpsHost() { + return getPreferences().get(SYSTEM_PROXY_HTTPS_HOST, ""); + } + + public static String getSystemHttpsPort() { + return getPreferences().get(SYSTEM_PROXY_HTTPS_PORT, ""); + } + + public static String getSystemSocksHost() { + return getPreferences().get(SYSTEM_PROXY_SOCKS_HOST, ""); + } + + public static String getSystemSocksPort() { + return getPreferences().get(SYSTEM_PROXY_SOCKS_PORT, ""); + } + + public static String getSystemNonProxyHosts() { + return getPreferences().get(SYSTEM_NON_PROXY_HOSTS, ""); + } + + public static String getSystemPac() { + return getPreferences().get(SYSTEM_PAC, null); + } + + + private static String presetNonProxyHosts; /** No proxy is used to connect. */ @@ -146,7 +191,7 @@ public static int getProxyType () { int type = getPreferences ().getInt (PROXY_TYPE, AUTO_DETECT_PROXY); if (AUTO_DETECT_PROXY == type) { - type = NbProxySelector.usePAC() ? AUTO_DETECT_PAC : AUTO_DETECT_PROXY; + type = ProxySettings.getSystemPac() != null ? AUTO_DETECT_PAC : AUTO_DETECT_PROXY; } return type; } @@ -179,154 +224,13 @@ NbBundle.getMessage(ProxySettings.class, "ProxySettings.password.description")); } - static void addPreferenceChangeListener (PreferenceChangeListener l) { + public static void addPreferenceChangeListener (PreferenceChangeListener l) { getPreferences ().addPreferenceChangeListener (l); } - static void removePreferenceChangeListener (PreferenceChangeListener l) { + public static void removePreferenceChangeListener (PreferenceChangeListener l) { getPreferences ().removePreferenceChangeListener (l); } - - static class SystemProxySettings extends ProxySettings { - - public static String getHttpHost () { - if (isSystemProxyDetect ()) { - return getSystemProxyHost (); - } else { - return ""; - } - } - - public static String getHttpPort () { - if (isSystemProxyDetect ()) { - return getSystemProxyPort (); - } else { - return ""; - } - } - - public static String getHttpsHost () { - if (isSystemProxyDetect ()) { - return getSystemProxyHost (); - } else { - return ""; - } - } - - public static String getHttpsPort () { - if (isSystemProxyDetect ()) { - return getSystemProxyPort (); - } else { - return ""; - } - } - - public static String getSocksHost () { - if (isSystemSocksServerDetect ()) { - return getSystemSocksServerHost (); - } else { - return ""; - } - } - - public static String getSocksPort () { - if (isSystemSocksServerDetect ()) { - return getSystemSocksServerPort (); - } else { - return ""; - } - } - - public static String getNonProxyHosts () { - return getDefaultUserNonProxyHosts (); - } - - // helper methods - private static boolean isSystemProxyDetect () { - if (NbProxySelector.useSystemProxies ()) { - return true; - } - String s = System.getProperty ("netbeans.system_http_proxy"); // NOI18N - return s != null && ! DIRECT.equals (s); // NOI18N - } - - private static String getSystemProxyHost () { - String systemProxy = System.getProperty ("netbeans.system_http_proxy"); // NOI18N - if (systemProxy == null) { - return ""; // NOI18N - } - - int i = systemProxy.lastIndexOf (":"); // NOI18N - if (i <= 0 || i >= systemProxy.length () - 1) { - return ""; // NOI18N - } - - return normalizeProxyHost (systemProxy.substring (0, i)); - } - - private static String getSystemProxyPort () { - String systemProxy = System.getProperty ("netbeans.system_http_proxy"); // NOI18N - if (systemProxy == null) { - return ""; // NOI18N - } - - int i = systemProxy.lastIndexOf (":"); // NOI18N - if (i <= 0 || i >= systemProxy.length () - 1) { - return ""; // NOI18N - } - - String p = systemProxy.substring (i + 1); - if (p.indexOf ('/') >= 0) { - p = p.substring (0, p.indexOf ('/')); - } - - return p; - } - - private static boolean isSystemSocksServerDetect () { - return isSystemProxyDetect () && System.getProperty ("netbeans.system_socks_proxy") != null; // NOI18N - } - - private static String getSystemSocksServerHost () { - String systemProxy = System.getProperty ("netbeans.system_socks_proxy"); // NOI18N - if (systemProxy == null) { - return ""; // NOI18N - } - - int i = systemProxy.lastIndexOf (":"); // NOI18N - if (i <= 0 || i >= systemProxy.length () - 1) { - return ""; // NOI18N - } - - return normalizeProxyHost (systemProxy.substring (0, i)); - } - - private static String getSystemSocksServerPort () { - String systemProxy = System.getProperty ("netbeans.system_socks_proxy"); // NOI18N - if (systemProxy == null) { - return ""; // NOI18N - } - - int i = systemProxy.lastIndexOf (":"); // NOI18N - if (i <= 0 || i >= systemProxy.length () - 1) { - return ""; // NOI18N - } - - String p = systemProxy.substring (i + 1); - if (p.indexOf ('/') >= 0) { - p = p.substring (0, p.indexOf ('/')); - } - - return p; - } - - } - - private static String getSystemNonProxyHosts () { - String systemProxy = System.getProperty ("netbeans.system_http_non_proxy_hosts"); // NOI18N - - return systemProxy == null ? "" : systemProxy; - } private static String getPresetNonProxyHosts () { if (presetNonProxyHosts == null) { @@ -478,6 +382,11 @@ } } } + + public static void reload() { + Reloader reloader = Lookup.getDefault().lookup(Reloader.class); + reloader.reload(); + } @ServiceProvider(service = NetworkSettings.ProxyCredentialsProvider.class, position = 1000) public static class NbProxyCredentialsProvider extends NetworkSettings.ProxyCredentialsProvider { @@ -525,4 +434,20 @@ } } + + /** A bridge between o.n.core and core.network. + * An implementation of this class brings a facility to reload Network Proxy Settings + * from underlying OS. + * The module core.network provides a implementation which may be accessible + * via Lookup.getDefault(). It's not guaranteed any implementation is found on all distribution. + * + * @since 3.40 + */ + public abstract static class Reloader { + + /** Reloads Network Proxy Settings from underlying system. + * + */ + public abstract void reload(); + } } diff -r 3bff97f36acc o.n.core/test/unit/data/pacFiles/wpad space.dat --- a/o.n.core/test/unit/data/pacFiles/wpad space.dat Tue Mar 26 12:16:28 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,8 +0,0 @@ -function FindProxyForURL(url, host) -{ - // Make everything lower case. - url = url.toLowerCase(); - host = host.toLowerCase(); - if (isPlainHostName(host)) return "DIRECT"; - return "PROXY www-proxy.us.oracle.com:80"; -}; diff -r 3bff97f36acc o.n.core/test/unit/data/pacFiles/wpad.dat --- a/o.n.core/test/unit/data/pacFiles/wpad.dat Tue Mar 26 12:16:28 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,8 +0,0 @@ -function FindProxyForURL(url, host) -{ - // Make everything lower case. - url = url.toLowerCase(); - host = host.toLowerCase(); - if (isPlainHostName(host)) return "DIRECT"; - return "PROXY www-proxy.us.oracle.com:80"; -}; diff -r 3bff97f36acc o.n.core/test/unit/src/org/netbeans/core/CanProxyToLocalhostTest.java --- a/o.n.core/test/unit/src/org/netbeans/core/CanProxyToLocalhostTest.java Tue Mar 26 12:16:28 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,113 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 2012 Oracle and/or its affiliates. All rights reserved. - * - * Oracle and Java are registered trademarks of Oracle and/or its affiliates. - * Other names may be trademarks of their respective owners. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * Contributor(s): - * - * The Original Software is NetBeans. The Initial Developer of the Original - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun - * Microsystems, Inc. All Rights Reserved. - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - */ - -package org.netbeans.core; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Proxy; -import java.net.ProxySelector; -import java.net.SocketAddress; -import java.net.URI; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.Locale; -import org.netbeans.junit.NbTestCase; -import org.openide.util.NetworkSettings; -import org.openide.util.lookup.ServiceProvider; - -/** Check whether we can proxy to localhost. - */ -public class CanProxyToLocalhostTest extends NbTestCase { - private static String USER_PROXY_HOST = "my.webcache"; - private static int USER_PROXY_PORT = 8080; - - private ProxySelector selector; - private static URI TO_LOCALHOST; - private static URI TO_NB; - private MyPS myPS; - - public CanProxyToLocalhostTest (String name) { - super (name); - } - - @Override - protected void setUp () throws Exception { - myPS = new MyPS(); - selector = NbProxySelector.create(myPS); - TO_LOCALHOST = new URI ("http://localhost"); - TO_NB = new URI ("http://netbeans.org"); - } - - public void testNoProxyForLocalhost() { - Locale.setDefault(Locale.US); - assertEquals ("Connect TO_LOCALHOST DIRECT.", "DIRECT", selector.select (TO_LOCALHOST).get(0).toString()); - } - public void testProxyForLocalhost() { - Locale.setDefault(new Locale("te", "ST")); - assertEquals ("Connect TO_LOCALHOST provided by MyPS", "HTTP @ my.webcache:8080", selector.select (TO_LOCALHOST).get(0).toString()); - assertEquals("One call to my ps", 1, myPS.called); - } - public void testAlwaysProxyForNonLocalhost() { - Locale.setDefault(Locale.US); - assertEquals ("Connect TO_LOCALHOST DIRECT.", "HTTP @ my.webcache:8080", selector.select (TO_NB).get(0).toString()); - assertEquals("One call to my ps", 1, myPS.called); - } - - private static class MyPS extends ProxySelector { - int called; - - @Override - public List select(URI uri) { - called++; - return Collections.singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(USER_PROXY_HOST, USER_PROXY_PORT))); - } - - @Override - public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { - } - } -} diff -r 3bff97f36acc o.n.core/test/unit/src/org/netbeans/core/DontUseProxyTest.java --- a/o.n.core/test/unit/src/org/netbeans/core/DontUseProxyTest.java Tue Mar 26 12:16:28 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,97 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. - * - * Oracle and Java are registered trademarks of Oracle and/or its affiliates. - * Other names may be trademarks of their respective owners. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * Contributor(s): - * - * The Original Software is NetBeans. The Initial Developer of the Original - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun - * Microsystems, Inc. All Rights Reserved. - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - */ - -package org.netbeans.core; - -import org.netbeans.junit.*; - -/** Tests HTTP Proxy settings. - * - * @author Jiri Rechtacek - * @see http://www.netbeans.org/issues/show_bug.cgi?id=125588 - */ -public class DontUseProxyTest extends NbTestCase { - public DontUseProxyTest (String name) { - super (name); - } - - public void testFullIpAdress () { - String nonProxyHosts = "192.168.1.0|200.100.200.100"; - assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.0")); - assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.1")); - assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.2.0")); - assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.169.1.0")); - assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "193.168.1.0")); - assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168")); - assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.0/1")); - - assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "200.100.200.100")); - assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "200.100.200.200")); - } - - public void testWildcardIpAdress () { - String nonProxyHosts = "192.*|200.100.200.*"; - assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.0")); - assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.1")); - assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.2.0")); - assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.169.1.0")); - assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "193.168.1.0")); - assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168")); - assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.0/1")); - - assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "200.100.200.100")); - assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "200.100.200.200")); - } - - public void testWildcardHostName () { - String nonProxyHosts = "*.netbeans.org|*.other.org|*netbeans.com|netbeans.org|*.our.intranet|private.*"; - assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "www.netbeans.org")); - assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "www.netbeans.com")); - assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "www.dummynetbeans.org")); - assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "subversion.our.intranet")); - assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "private")); - assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "private.all")); - } - -} diff -r 3bff97f36acc o.n.core/test/unit/src/org/netbeans/core/HttpSettingsTest.java --- a/o.n.core/test/unit/src/org/netbeans/core/HttpSettingsTest.java Tue Mar 26 12:16:28 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,417 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * Oracle and Java are registered trademarks of Oracle and/or its affiliates. - * Other names may be trademarks of their respective owners. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * Contributor(s): - * - * The Original Software is NetBeans. The Initial Developer of the Original - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun - * Microsystems, Inc. All Rights Reserved. - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - */ - -package org.netbeans.core; - -import java.lang.reflect.Field; -import java.util.prefs.AbstractPreferences; -import java.util.prefs.PreferenceChangeEvent; -import java.util.prefs.PreferenceChangeListener; -import java.util.prefs.Preferences; -import junit.framework.TestResult; -import org.netbeans.junit.NbTestCase; -import org.netbeans.junit.RandomlyFails; -import org.openide.util.NbPreferences; - -/** Tests HTTP Proxy settings. - * - * @author Jiri Rechtacek - * @see http://www.netbeans.org/issues/show_bug.cgi?id=51641 - */ -@RandomlyFails -public class HttpSettingsTest extends NbTestCase { - private final Object sync = getEventQueueSync (); - private static String SYSTEM_PROXY_HOST = "system.cache.org"; - private static String SYSTEM_PROXY_PORT = "777"; - private static String USER_PROXY_HOST = "my.webcache"; - private static String USER_PROXY_PORT = "8080"; - private static String USER_HTTPS_PROXY_HOST = "secure.webcache"; - private static String USER_HTTPS_PROXY_PORT = "8080"; - - private Preferences proxyPreferences; - private static String SILLY_USER_PROXY_HOST = "http://my.webcache"; - private static String SILLY_SYSTEM_PROXY_HOST = "http://system.cache.org"; - private static String SILLY_SYSTEM_PROXY_PORT = "777//"; - private static String MY_NON_PROXY_HOSTS = "myhost.mydomain.net"; - - private static String NETBEANS_ORG = "*.netbeans.org"; - private static String OTHER_ORG = "*.other.org"; - - public HttpSettingsTest (String name) { - super (name); - } - - @Override - public void run (final TestResult result) { - //just initialize Preferences before code NbTestCase - Preferences.userRoot (); - super.run (result); - } - - @Override - protected int timeOut () { - return 20 * 1000; - } - - @Override - protected void setUp () throws Exception { - super.setUp (); - System.setProperty ("http.nonProxyHosts", NETBEANS_ORG + ',' + NETBEANS_ORG); - NbProxySelector.register(); - proxyPreferences = NbPreferences.root ().node ("/org/netbeans/core"); - proxyPreferences.addPreferenceChangeListener (new PreferenceChangeListener() { - @Override - public void preferenceChange(PreferenceChangeEvent arg0) { - synchronized (sync) { - sync.notifyAll (); - } - } - }); - System.setProperty ("netbeans.system_http_proxy", SYSTEM_PROXY_HOST + ":" + SYSTEM_PROXY_PORT); - System.setProperty ("netbeans.system_http_non_proxy_hosts", OTHER_ORG); - synchronized (sync) { - if (! USER_PROXY_HOST.equals (proxyPreferences.get ("proxyHttpHost", ""))) { - proxyPreferences.put ("proxyHttpHost", USER_PROXY_HOST); - sync.wait (10000); - } - } - synchronized (sync) { - if (! USER_PROXY_PORT.equals (proxyPreferences.get ("proxyHttpPort", ""))) { - proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT); - sync.wait (10000); - } - } - synchronized (sync) { - if (! USER_HTTPS_PROXY_HOST.equals (proxyPreferences.get ("proxyHttpsHost", ""))) { - proxyPreferences.put ("proxyHttpsHost", USER_HTTPS_PROXY_HOST); - sync.wait (10000); - } - } - synchronized (sync) { - if (! USER_HTTPS_PROXY_PORT.equals (proxyPreferences.get ("proxyHttpsPort", ""))) { - proxyPreferences.put ("proxyHttpsPort", USER_HTTPS_PROXY_PORT); - sync.wait (10000); - } - } - } - - private void sillySetUp () throws Exception { - synchronized (sync) { - if (ProxySettings.DIRECT_CONNECTION != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION); - sync.wait (); - } - } - - System.setProperty ("netbeans.system_http_proxy", SILLY_SYSTEM_PROXY_HOST + ":" + SILLY_SYSTEM_PROXY_PORT); - synchronized (sync) { - if (! SILLY_USER_PROXY_HOST.equals (proxyPreferences.get ("proxyHttpHost", ""))) { - proxyPreferences.put ("proxyHttpHost", SILLY_USER_PROXY_HOST); - sync.wait (10000); - } - } - proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT); - synchronized (sync) { - if (! USER_PROXY_PORT.equals (proxyPreferences.get ("proxyHttpPort", ""))) { - proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT); - sync.wait (10000); - } - } - } - - private void setUpAutoDirect () throws Exception { - synchronized (sync) { - if (ProxySettings.DIRECT_CONNECTION != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION); - sync.wait (); - } - } - System.setProperty ("netbeans.system_http_proxy", "DIRECT"); - synchronized (sync) { - if (! "".equals (proxyPreferences.get ("proxyHttpHost", ""))) { - proxyPreferences.put ("proxyHttpHost", ""); - sync.wait (10000); - } - } - synchronized (sync) { - if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY); - sync.wait (); - } - } - } - - public void testDirectConnection () throws InterruptedException { - System.setProperty ("http.proxyHost", ""); - System.setProperty ("http.proxyPort", ""); - synchronized (sync) { - if (ProxySettings.DIRECT_CONNECTION != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION); - sync.wait (); - } - } - assertEquals ("Proxy type DIRECT_CONNECTION.", ProxySettings.DIRECT_CONNECTION, ProxySettings.getProxyType ()); - assertEquals ("No Proxy Host set.", null, System.getProperty ("http.proxyHost")); - assertEquals ("No Proxy Port set.", null, System.getProperty ("http.proxyPort")); - } - - public void testAutoDetectProxy () throws InterruptedException { - System.setProperty ("http.proxyHost", ""); - System.setProperty ("http.proxyPort", ""); - synchronized (sync) { - if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY); - sync.wait (); - } - } - assertEquals("Proxy type AUTO_DETECT_PROXY.", - ProxySettings.AUTO_DETECT_PROXY, - ProxySettings.getProxyType()); - assertEquals("System Proxy Host: ", SYSTEM_PROXY_HOST, - System.getProperty("http.proxyHost")); - assertEquals("System Proxy Port: ", SYSTEM_PROXY_PORT, - System.getProperty("http.proxyPort")); - } - - public void testManualSetProxy () throws InterruptedException { - synchronized (sync) { - if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY); - sync.wait (); - } - } - assertEquals ("Proxy type MANUAL_SET_PROXY.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ()); - assertEquals ("Manual Set Proxy Host from ProxySettings: ", USER_PROXY_HOST, ProxySettings.getHttpHost ()); - assertEquals ("Manual Set Proxy Port from ProxySettings: ", USER_PROXY_PORT, ProxySettings.getHttpPort ()); - assertEquals ("Manual Set Proxy Host from System.getProperty(): ", USER_PROXY_HOST, System.getProperty ("http.proxyHost")); - assertEquals ("Manual Set Proxy Port from System.getProperty(): ", USER_PROXY_PORT, System.getProperty ("http.proxyPort")); - } - - public void testHttpsManualSetProxy () throws InterruptedException { - synchronized (sync) { - if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY); - sync.wait (); - } - } - assertEquals ("Proxy type MANUAL_SET_PROXY.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ()); - - // HTTP - assertEquals ("Manual Set Proxy Host from ProxySettings: ", USER_PROXY_HOST, ProxySettings.getHttpHost ()); - assertEquals ("Manual Set Proxy Port from ProxySettings: ", USER_PROXY_PORT, ProxySettings.getHttpPort ()); - assertEquals ("Manual Set Proxy Host from System.getProperty(): ", USER_PROXY_HOST, System.getProperty ("http.proxyHost")); - assertEquals ("Manual Set Proxy Port from System.getProperty(): ", USER_PROXY_PORT, System.getProperty ("http.proxyPort")); - - // HTTPS - assertEquals ("Manual Set HTTPS Proxy Host from ProxySettings: ", USER_HTTPS_PROXY_HOST, ProxySettings.getHttpsHost ()); - assertEquals ("Manual Set HTTPS Proxy Port from ProxySettings: ", USER_HTTPS_PROXY_PORT, ProxySettings.getHttpsPort ()); - assertEquals ("Manual Set HTTPS Proxy Host from System.getProperty(): ", USER_HTTPS_PROXY_HOST, System.getProperty ("https.proxyHost")); - assertEquals ("Manual Set HTTPS Proxy Port from System.getProperty(): ", USER_HTTPS_PROXY_PORT, System.getProperty ("https.proxyPort")); - } - - public void testIfTakeUpNonProxyFromProperty () { - assertTrue (NETBEANS_ORG + " in one of Non-Proxy hosts.", ProxySettings.getNonProxyHosts ().indexOf (NETBEANS_ORG) != -1); - } - - public void testNonProxy () throws InterruptedException { - assertEquals ("The ProxySettings takes as same value as System properties in initial.", System.getProperty ("http.nonProxyHosts"), ProxySettings.getNonProxyHosts ()); - - // change value in ProxySettings - synchronized (sync) { - if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY); - sync.wait (); - } - } - synchronized (sync) { - if (! MY_NON_PROXY_HOSTS.equals (proxyPreferences.get ("proxyNonProxyHosts", ""))) { - proxyPreferences.put ("proxyNonProxyHosts", MY_NON_PROXY_HOSTS); - sync.wait (); - } - } - assertEquals ("ProxySettings returns new value.", "myhost.mydomain.net", ProxySettings.getNonProxyHosts ()); - assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.getNonProxyHosts (), System.getProperty ("http.nonProxyHosts")); - - // switch proxy type to DIRECT_CONNECTION - //System.setProperty ("http.nonProxyHosts", ""); - synchronized (sync) { - if (ProxySettings.DIRECT_CONNECTION != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION); - sync.wait (); - } - } - Thread.sleep (1000); // XXX: tunning test on Windows platform, other platforms are passing - assertEquals ("System.getProperty() doesn't return new value if DIRECT_CONNECTION set.", null, System.getProperty ("http.nonProxyHosts")); - - // switch proxy type back to MANUAL_SET_PROXY - synchronized (sync) { - if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY); - sync.wait (); - } - } - assertEquals ("ProxySettings again returns new value.", "myhost.mydomain.net", ProxySettings.getNonProxyHosts ()); - assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.getNonProxyHosts (), System.getProperty ("http.nonProxyHosts")); - - // switch proxy type to AUTO_DETECT_PROXY - synchronized (sync) { - if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY); - sync.wait (); - } - } - log ("AUTO_DETECT_PROXY: ProxySettings.SystemProxySettings.getNonProxyHosts (): " + ProxySettings.SystemProxySettings.getNonProxyHosts ()); - log ("AUTO_DETECT_PROXY: System.getProperty (\"http.nonProxyHosts\"): " + System.getProperty ("http.nonProxyHosts")); - assertTrue ("ProxySettings contains OTHER_ORG if AUTO_DETECT_PROXY set.", System.getProperty ("http.nonProxyHosts").indexOf (OTHER_ORG) > 0); - - // switch proxy type back to MANUAL_SET_PROXY - synchronized (sync) { - if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY); - sync.wait (); - } - } - assertEquals ("ProxySettings again returns new value.", "myhost.mydomain.net", ProxySettings.getNonProxyHosts ()); - assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.getNonProxyHosts (), System.getProperty ("http.nonProxyHosts")); - } - - public void testAvoidDuplicateNonProxySetting () throws InterruptedException { - synchronized (sync) { - if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY); - sync.wait (); - } - } - assertTrue (NETBEANS_ORG + " is among Non-proxy hosts detect from OS.", ProxySettings.SystemProxySettings.getNonProxyHosts ().indexOf (NETBEANS_ORG) != -1); - assertFalse (NETBEANS_ORG + " is in Non-Proxy hosts only once.", ProxySettings.SystemProxySettings.getNonProxyHosts ().indexOf (NETBEANS_ORG) < ProxySettings.getNonProxyHosts ().lastIndexOf (NETBEANS_ORG)); - assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.SystemProxySettings.getNonProxyHosts (), System.getProperty ("http.nonProxyHosts")); - } - - public void testReadNonProxySettingFromSystem () throws InterruptedException { - synchronized (sync) { - if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY); - sync.wait (); - } - } - assertTrue (OTHER_ORG + " is among Non-proxy hosts detect from OS.", ProxySettings.SystemProxySettings.getNonProxyHosts ().indexOf (OTHER_ORG) != -1); - assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.SystemProxySettings.getNonProxyHosts (), System.getProperty ("http.nonProxyHosts")); - } - - public void testSillySetManualProxy () throws Exception { - sillySetUp (); - synchronized (sync) { - if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY); - sync.wait (); - } - } - assertEquals ("Proxy type MANUAL_SET_PROXY.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ()); - assertEquals ("Manual Set Proxy Host from ProxySettings doesn't return SILLY_USER_PROXY_HOST anymore.", USER_PROXY_HOST, ProxySettings.getHttpHost ()); - assertEquals ("Manual Set Proxy Port from ProxySettings doesn't return SILLY_USER_PROXY_PORT anymore.", USER_PROXY_PORT, ProxySettings.getHttpPort ()); - assertEquals ("Manual Set Proxy Host from System.getProperty(): ", USER_PROXY_HOST, System.getProperty ("http.proxyHost")); - assertEquals ("Manual Set Proxy Port from System.getProperty(): ", USER_PROXY_PORT, System.getProperty ("http.proxyPort")); - } - - public void testAutoDetectSillySetProxy () throws Exception { - sillySetUp (); - synchronized (sync) { - if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY); - sync.wait (); - } - } - assertEquals ("Proxy type AUTO_DETECT_PROXY.", ProxySettings.AUTO_DETECT_PROXY, ProxySettings.getProxyType ()); - assertEquals ("Auto Detected Proxy Host from ProxySettings doesn't return SILLY_SYSTEM_PROXY_HOST anymore.", SYSTEM_PROXY_HOST, ProxySettings.SystemProxySettings.getHttpHost ()); - assertEquals ("Auto Detected Proxy Port from ProxySettings doesn't return SILLY_SYSTEM_PROXY_PORT anymore.", SYSTEM_PROXY_PORT, ProxySettings.SystemProxySettings.getHttpPort ()); - assertEquals ("System Proxy Host: ", SYSTEM_PROXY_HOST, System.getProperty ("http.proxyHost")); - assertEquals ("System Proxy Port: ", SYSTEM_PROXY_PORT, System.getProperty ("http.proxyPort")); - } - - public void testSwitchAutoAndManualMode () throws Exception { - setUpAutoDirect (); - - // ensure auto detect mode - assertEquals("Proxy type AUTO_DETECT_PROXY.", - ProxySettings.AUTO_DETECT_PROXY, - ProxySettings.getProxyType()); - assertEquals ("Auto Proxy Host from System.getProperty(): ", null, System.getProperty ("http.proxyHost")); - assertEquals ("Auto Proxy Port from System.getProperty(): ", null, System.getProperty ("http.proxyPort")); - - // switch to manual - proxyPreferences.put ("proxyHttpHost", "foo"); - synchronized (sync) { - if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY); - sync.wait (); - } - } - assertEquals ("Proxy type MANUAL_SET_PROXY.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ()); - assertEquals ("Auto Proxy Host from System.getProperty(): ", "foo", System.getProperty ("http.proxyHost")); - - // switch back to auto detect - synchronized (sync) { - if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) { - proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY); - sync.wait (); - } - } - assertEquals("Proxy type AUTO_DETECT_PROXY.", - ProxySettings.AUTO_DETECT_PROXY, - ProxySettings.getProxyType()); - assertEquals ("Auto Proxy Host from System.getProperty(): ", null, System.getProperty ("http.proxyHost")); - assertEquals ("Auto Proxy Port from System.getProperty(): ", null, System.getProperty ("http.proxyPort")); - - } - - private Object getEventQueueSync() { - try { - Field f = AbstractPreferences.class.getDeclaredField("eventQueue"); - f.setAccessible(true); - return f.get(null); - } catch (Exception ex) { - throw new ExceptionInInitializerError(ex); - } - } -} diff -r 3bff97f36acc o.n.core/test/unit/src/org/netbeans/core/NonProxyHostsTest.java --- a/o.n.core/test/unit/src/org/netbeans/core/NonProxyHostsTest.java Tue Mar 26 12:16:28 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,172 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 1997-2012 Oracle and/or its affiliates. All rights reserved. - * - * Oracle and Java are registered trademarks of Oracle and/or its affiliates. - * Other names may be trademarks of their respective owners. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * Contributor(s): - * - * The Original Software is NetBeans. The Initial Developer of the Original - * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun - * Microsystems, Inc. All Rights Reserved. - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - */ - -package org.netbeans.core; - -import java.net.Proxy; -import java.net.ProxySelector; -import java.net.URI; -import java.util.prefs.PreferenceChangeEvent; -import java.util.prefs.PreferenceChangeListener; -import java.util.prefs.Preferences; -import org.netbeans.junit.NbTestCase; -import org.netbeans.junit.RandomlyFails; -import org.openide.util.NbPreferences; - -/** Tests Detect OS nonProxyHosts settings. - * - * @author Jiri Rechtacek - * @see http://www.netbeans.org/issues/show_bug.cgi?id=77053 - */ -@RandomlyFails // NB-Core-Build #1247, 1248 -public class NonProxyHostsTest extends NbTestCase { - private static String SYSTEM_PROXY_HOST = "system.cache.org"; - private static String SYSTEM_PROXY_PORT = "777"; - private static String USER_PROXY_HOST = "my.webcache"; - private static String USER_PROXY_PORT = "8080"; - - private Preferences proxyPreferences; - private ProxySelector selector; - private static URI TO_LOCALHOST; - private static URI TO_LOCAL_DOMAIN_1; - private static URI TO_LOCAL_DOMAIN_2; - private static URI TO_EXTERNAL; - private static URI SOCKS_TO_LOCALHOST; - private static URI SOCKS_TO_LOCAL_DOMAIN_1; - private static URI SOCKS_TO_LOCAL_DOMAIN_2; - private static URI SOCKS_TO_EXTERNAL; - - private boolean isWaiting = false; - - public NonProxyHostsTest (String name) { - super (name); - } - - @Override - protected void setUp () throws Exception { - super.setUp (); - System.setProperty ("netbeans.system_http_proxy", SYSTEM_PROXY_HOST + ":" + SYSTEM_PROXY_PORT); - System.setProperty ("netbeans.system_socks_proxy", SYSTEM_PROXY_HOST + ":" + SYSTEM_PROXY_PORT); - System.setProperty ("netbeans.system_http_non_proxy_hosts", "*.other.org"); - System.setProperty ("http.nonProxyHosts", "*.netbeans.org"); - NbProxySelector.register(); - selector = ProxySelector.getDefault (); - proxyPreferences = NbPreferences.root ().node ("/org/netbeans/core"); - proxyPreferences.addPreferenceChangeListener (new PreferenceChangeListener () { - public void preferenceChange (PreferenceChangeEvent arg0) { - isWaiting = false; - } - }); - proxyPreferences.put ("proxyHttpHost", USER_PROXY_HOST); - proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT); - proxyPreferences.put ("proxySocksHost", USER_PROXY_HOST); - proxyPreferences.put ("proxySocksPort", USER_PROXY_PORT); - while (isWaiting); - isWaiting = true; - TO_LOCALHOST = new URI ("http://localhost"); - TO_LOCAL_DOMAIN_1 = new URI ("http://core.netbeans.org"); - TO_LOCAL_DOMAIN_2 = new URI ("http://core.other.org"); - TO_EXTERNAL = new URI ("http://worldwide.net"); - - SOCKS_TO_LOCALHOST = new URI ("socket://localhost:8041"); - SOCKS_TO_LOCAL_DOMAIN_1 = new URI ("socket://core.netbeans.org"); - SOCKS_TO_LOCAL_DOMAIN_2 = new URI ("socket://core.other.org"); - SOCKS_TO_EXTERNAL = new URI ("socket://worldwide.net"); - } - - public void testDirectProxySetting () { - proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION); - while (isWaiting); - assertEquals ("Proxy type DIRECT_CONNECTION.", ProxySettings.DIRECT_CONNECTION, ProxySettings.getProxyType ()); - assertEquals ("Connect " + TO_LOCALHOST + " DIRECT.", "[DIRECT]", selector.select (TO_LOCALHOST).toString ()); - assertEquals ("Connect " + SOCKS_TO_LOCALHOST + " DIRECT.", Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCALHOST).get(0)); - assertEquals ("Connect " + TO_LOCAL_DOMAIN_1 + " DIRECT.", "[DIRECT]", selector.select (TO_LOCAL_DOMAIN_1).toString ()); - assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_1 + " DIRECT.", "[DIRECT]", selector.select (SOCKS_TO_LOCAL_DOMAIN_1).toString ()); - assertEquals ("Connect " + TO_LOCAL_DOMAIN_2 + " DIRECT.", "[DIRECT]", selector.select (TO_LOCAL_DOMAIN_2).toString ()); - assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_2 + " DIRECT.", "[DIRECT]", selector.select (SOCKS_TO_LOCAL_DOMAIN_2).toString ()); - assertEquals ("Connect " + TO_EXTERNAL + " DIRECT.", "[DIRECT]", selector.select (TO_EXTERNAL).toString ()); - assertEquals ("Connect " + SOCKS_TO_EXTERNAL + " DIRECT.", "[DIRECT]", selector.select (SOCKS_TO_EXTERNAL).toString ()); - } - - @RandomlyFails - public void testManualProxySettins () { - proxyPreferences.put (ProxySettings.NOT_PROXY_HOSTS, "localhost|" + "*.netbeans.org"); - proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY); - while (isWaiting); - assertEquals ("Proxy type DIRECT_CONNECTION.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ()); - assertEquals ("Connect TO_LOCALHOST DIRECT.", Proxy.NO_PROXY, selector.select (TO_LOCALHOST).get(0)); - assertEquals ("Connect " + SOCKS_TO_LOCALHOST + " DIRECT.", Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCALHOST).get(0)); - assertEquals ("Connect " + TO_LOCAL_DOMAIN_1 + " DIRECT.", Proxy.NO_PROXY, selector.select (TO_LOCAL_DOMAIN_1).get (0)); - assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_1 + " DIRECT.", - Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCAL_DOMAIN_1).get (0)); - assertEquals ("Connect " + TO_LOCAL_DOMAIN_2 + " via my.webcache:8080 proxy.", - "HTTP @ my.webcache:8080", selector.select (TO_LOCAL_DOMAIN_2).get (0).toString ()); - assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_2 + " via my.webcache:8080 proxy.", - "SOCKS @ my.webcache:8080", selector.select (SOCKS_TO_LOCAL_DOMAIN_2).get (0).toString ()); - assertEquals ("Connect TO_EXTERNAL via my.webcache:8080 proxy.", "HTTP @ my.webcache:8080", selector.select (TO_EXTERNAL).get (0).toString ()); - assertEquals ("Connect SOCKS_TO_EXTERNAL via my.webcache:8080 proxy.", - "SOCKS @ my.webcache:8080", selector.select (SOCKS_TO_EXTERNAL).get (0).toString ()); - } - - @RandomlyFails - public void testSystemProxySettings () { - proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY); - while (isWaiting); - log ("Value of System.getProperty (\"http.nonProxyHosts\"): " + System.getProperty ("http.nonProxyHosts")); - assertTrue ("*.other.org is one of non-proxy hosts", System.getProperty ("http.nonProxyHosts").indexOf ("*.other.org") != -1); - assertEquals ("Proxy type DIRECT_CONNECTION.", ProxySettings.AUTO_DETECT_PROXY, ProxySettings.getProxyType ()); - assertEquals ("Connect TO_LOCALHOST DIRECT.", Proxy.NO_PROXY, selector.select (TO_LOCALHOST).get(0)); - assertEquals ("Connect " + SOCKS_TO_LOCALHOST + " DIRECT.", Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCALHOST).get(0)); - assertEquals ("Connect " + TO_LOCAL_DOMAIN_1 + " DIRECT.", Proxy.NO_PROXY, selector.select (TO_LOCAL_DOMAIN_1).get (0)); - assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_1 + " DIRECT.", - Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCAL_DOMAIN_1).get (0)); - assertEquals ("Connect " + TO_LOCAL_DOMAIN_2 + " DIRECT ignoring settings " + System.getProperty ("http.nonProxyHosts"), Proxy.NO_PROXY, selector.select (TO_LOCAL_DOMAIN_2).get (0)); - assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_2 + " DIRECT ignoring settings " + System.getProperty ("http.nonProxyHosts"), - Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCAL_DOMAIN_2).get (0)); - assertEquals ("Connect TO_EXTERNAL via system.cache.org:777 proxy.", "HTTP @ system.cache.org:777", selector.select (TO_EXTERNAL).get (0).toString ()); - assertEquals ("Connect SOCKS_TO_EXTERNAL via system.cache.org:777 proxy.", "SOCKS @ system.cache.org:777", - selector.select (SOCKS_TO_EXTERNAL).get (0).toString ()); - } - -} diff -r 3bff97f36acc o.n.core/test/unit/src/org/netbeans/core/ProxyAutoConfigTest.java --- a/o.n.core/test/unit/src/org/netbeans/core/ProxyAutoConfigTest.java Tue Mar 26 12:16:28 2013 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,160 +0,0 @@ -/* - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * - * Copyright 2011 Oracle and/or its affiliates. All rights reserved. - * - * Oracle and Java are registered trademarks of Oracle and/or its affiliates. - * Other names may be trademarks of their respective owners. - * - * The contents of this file are subject to the terms of either the GNU - * General Public License Version 2 only ("GPL") or the Common - * Development and Distribution License("CDDL") (collectively, the - * "License"). You may not use this file except in compliance with the - * License. You can obtain a copy of the License at - * http://www.netbeans.org/cddl-gplv2.html - * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the - * specific language governing permissions and limitations under the - * License. When distributing the software, include this License Header - * Notice in each file and include the License file at - * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the GPL Version 2 section of the License file that - * accompanied this code. If applicable, add the following below the - * License Header, with the fields enclosed by brackets [] replaced by - * your own identifying information: - * "Portions Copyrighted [year] [name of copyright owner]" - * - * If you wish your version of this file to be governed by only the CDDL - * or only the GPL Version 2, indicate your decision by adding - * "[Contributor] elects to include this software in this distribution - * under the [CDDL or GPL Version 2] license." If you do not indicate a - * single choice of license, a recipient has the option to distribute - * your version of this file under either the CDDL, the GPL Version 2 or - * to extend the choice of license to its licensees as provided above. - * However, if you add GPL Version 2 code and therefore, elected the GPL - * Version 2 license, then the option applies only if the new code is - * made subject to such option by the copyright holder. - * - * Contributor(s): - * - * Portions Copyrighted 2011 Sun Microsystems, Inc. - */ -package org.netbeans.core; - -import java.io.File; -import java.net.Proxy; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.LinkedList; -import java.util.List; -import junit.framework.Test; -import org.netbeans.junit.NbModuleSuite; -import org.netbeans.junit.NbTestCase; -import org.openide.util.Utilities; - -/** - * - * @author Jirka Rechtacek - */ -public class ProxyAutoConfigTest extends NbTestCase { - - public static Test suite() { - return NbModuleSuite - .emptyConfiguration() - .gui(false) - .addTest(ProxyAutoConfigTest.class) - .suite(); - } - - public ProxyAutoConfigTest(String name) { - super(name); - } - - public void testGetProxyAutoConfig() { - assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt")); - } - - // #issue 201995 - public void testGetProxyAutoConfigWithMultipleURL() { - assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt http://pac/pac.txt http://pac/pac.txt")); - } - - public void testGetProxyAutoConfigWithNewLineURL() { - assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt\nhttp://pac/pac.txt")); - } - - public void testGetProxyAutoConfigWithLineTerminatorURL() { - assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt\rhttp://pac/pac.txt")); - } - - public void testGetProxyAutoConfigWithBothTerminatorsURL() { - assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt\r\nhttp://pac/pac.txt")); - } - - public void testGetProxyAutoConfigWithInvalidURL() { - assertNotNull(ProxyAutoConfig.get("http:\\\\pac\\pac.txt")); - } - - public void testGetProxyAutoConfigWithRelativePath() { - assertNotNull(ProxyAutoConfig.get("http://pac/../pac/pac.txt")); - } - - public void testGetProxyAutoConfigWithLocalPAC() throws URISyntaxException { - List pacFileLocations = new LinkedList(); - for (File pacFile : new File(getDataDir(), "pacFiles").listFiles()) { - pacFileLocations.add(pacFile.getAbsolutePath()); - pacFileLocations.add("file://" + pacFile.getAbsolutePath()); - pacFileLocations.add(pacFile.toURI().toString()); - } - for (String pacFileLoc : pacFileLocations) { - ProxyAutoConfig pac = ProxyAutoConfig.get(pacFileLoc); - assertNotNull(pac); - URI uri = pac.getPacURI(); - assertNotNull(uri); - assertNull(uri.getHost()); - List proxies = pac.findProxyForURL(new URI("http://netbeans.org")); - assertEquals(1, proxies.size()); - assertTrue(pacFileLoc + ": " + proxies.get(0).toString(), proxies.get(0).toString().startsWith("HTTP @ www-proxy.us.oracle.com/")); - System.setProperty("netbeans.system_http_proxy", "PAC " + pacFileLoc); - proxies = NbProxySelector.getDefault().select(new URI("http://netbeans.org")); - assertTrue(pacFileLoc + ": " + proxies.get(0).toString(), proxies.get(0).toString().startsWith("HTTP @ www-proxy.us.oracle.com/")); - - proxies = pac.findProxyForURL(new URI("https://netbeans.org")); - assertEquals(1, proxies.size()); - assertTrue(pacFileLoc + ": " + proxies.get(0).toString(), proxies.get(0).toString().startsWith("HTTP @ www-proxy.us.oracle.com/")); - System.setProperty("netbeans.system_http_proxy", "PAC " + pacFileLoc); - proxies = NbProxySelector.getDefault().select(new URI("https://netbeans.org")); - assertTrue(pacFileLoc + ": " + proxies.get(0).toString(), proxies.get(0).toString().startsWith("HTTP @ www-proxy.us.oracle.com/")); - - proxies = pac.findProxyForURL(new URI("http://localhost")); - assertEquals(1, proxies.size()); - assertEquals(pacFileLoc + ": " + proxies.get(0).toString(), "DIRECT", proxies.get(0).toString()); - proxies = NbProxySelector.getDefault().select(new URI("http://localhost")); - assertEquals(pacFileLoc + ": " + proxies.get(0).toString(), "DIRECT", proxies.get(0).toString()); - } - } - - public void testGetProxyAutoConfigWithLocalInvalidPAC() throws URISyntaxException { - List pacFileLocations = new LinkedList(); - for (File pacFile : new File[] { - new File(getDataDir(), "pacFiles"), - new File(getDataDir(), "doesNotExist") - }) { - pacFileLocations.add(pacFile.getAbsolutePath()); - pacFileLocations.add("file://" + pacFile.getAbsolutePath()); - pacFileLocations.add(pacFile.toURI().toString()); - } - for (String pacFileLoc : pacFileLocations) { - ProxyAutoConfig pac = ProxyAutoConfig.get(pacFileLoc); - assertNotNull(pac); - URI uri = pac.getPacURI(); - assertNotNull(uri); - List proxies = pac.findProxyForURL(new URI("http://netbeans.org")); - assertEquals(1, proxies.size()); - assertEquals("DIRECT", proxies.get(0).toString()); - System.setProperty("netbeans.system_http_proxy", "PAC " + pacFileLoc); - proxies = NbProxySelector.getDefault().select(new URI("http://netbeans.org")); - assertEquals(pacFileLoc + ": " + proxies.get(0).toString(), "DIRECT", proxies.get(0).toString()); - } - } -}