This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues.

View | Details | Raw Unified | Return to bug 201731
Collapse All | Expand All

(-)a/.hgtags (+5 lines)
Lines 941-943 Link Here
941
c78d6484d78ea8dd1faa3ceb5e90898a78fa3adb javaee7_base
941
c78d6484d78ea8dd1faa3ceb5e90898a78fa3adb javaee7_base
942
f9c322a6c6f20740ac785b2da18d4c8013f6251f release73_base
942
f9c322a6c6f20740ac785b2da18d4c8013f6251f release73_base
943
a1020f3273f1d09077d8003451dc7148ea81403a sspatch_platform_1
943
a1020f3273f1d09077d8003451dc7148ea81403a sspatch_platform_1
944
0f3db632e5712cbcd04d8818f10917d14b854228 system_proxy_reload_in_core
945
0f3db632e5712cbcd04d8818f10917d14b854228 system_proxy_reload_in_core
946
0000000000000000000000000000000000000000 system_proxy_reload_in_core
947
0000000000000000000000000000000000000000 system_proxy_reload_in_core
948
d717d0d73743fd59c0084480e655eb63e3dcce8f system_proxy_reload_in_core
(-)a/cnd.modelimpl/run.sh (-1 lines)
Lines 194-200 Link Here
194
    DEBUG="${DEBUG},suspend=${SUSPEND},address=${DBGPORT}"
194
    DEBUG="${DEBUG},suspend=${SUSPEND},address=${DBGPORT}"
195
fi
195
fi
196
196
197
##DEFS="-J-Dnetbeans.system_http_proxy=webcache:8080"
198
DEFS=""
197
DEFS=""
199
DEFS="${DEFS} ${CONSOLE}"
198
DEFS="${DEFS} ${CONSOLE}"
200
DEFS="${DEFS} ${PARSERRORS}"
199
DEFS="${DEFS} ${PARSERRORS}"
(-)3bff97f36acc (+5 lines)
Added Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project basedir="." default="netbeans" name="core.network">
3
    <description>Builds, tests, and runs the project org.netbeans.core.network</description>
4
    <import file="../nbbuild/templates/projectized.xml"/>
5
</project>
(-)3bff97f36acc (+6 lines)
Added Link Here
1
Manifest-Version: 1.0
2
OpenIDE-Module: org.netbeans.core.network
3
OpenIDE-Module-Localizing-Bundle: org/netbeans/core/network/Bundle.properties
4
OpenIDE-Module-Provides: org.netbeans.core.ProxySettings.Reloader
5
OpenIDE-Module-Specification-Version: 1.0
6
(-)3bff97f36acc (+3 lines)
Added Link Here
1
is.autoload=true
2
javac.source=1.6
3
javac.compilerargs=-Xlint -Xlint:-serial
(-)3bff97f36acc (+95 lines)
Added Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://www.netbeans.org/ns/project/1">
3
    <type>org.netbeans.modules.apisupport.project</type>
4
    <configuration>
5
        <data xmlns="http://www.netbeans.org/ns/nb-module-project/3">
6
            <code-name-base>org.netbeans.core.network</code-name-base>
7
            <module-dependencies>
8
                <dependency>
9
                    <code-name-base>org.netbeans.core</code-name-base>
10
                    <build-prerequisite/>
11
                    <compile-dependency/>
12
                    <run-dependency>
13
                        <release-version>2</release-version>
14
                        <specification-version>3.40</specification-version>
15
                    </run-dependency>
16
                </dependency>
17
                <dependency>
18
                    <code-name-base>org.netbeans.libs.jna</code-name-base>
19
                    <build-prerequisite/>
20
                    <compile-dependency/>
21
                    <run-dependency>
22
                        <release-version>1</release-version>
23
                        <specification-version>1.26</specification-version>
24
                    </run-dependency>
25
                </dependency>
26
                <dependency>
27
                    <code-name-base>org.netbeans.modules.keyring</code-name-base>
28
                    <build-prerequisite/>
29
                    <compile-dependency/>
30
                    <run-dependency>
31
                        <specification-version>1.15</specification-version>
32
                    </run-dependency>
33
                </dependency>
34
                <dependency>
35
                    <code-name-base>org.openide.awt</code-name-base>
36
                    <build-prerequisite/>
37
                    <compile-dependency/>
38
                    <run-dependency>
39
                        <specification-version>7.56</specification-version>
40
                    </run-dependency>
41
                </dependency>
42
                <dependency>
43
                    <code-name-base>org.openide.dialogs</code-name-base>
44
                    <build-prerequisite/>
45
                    <compile-dependency/>
46
                    <run-dependency>
47
                        <specification-version>7.29</specification-version>
48
                    </run-dependency>
49
                </dependency>
50
                <dependency>
51
                    <code-name-base>org.openide.filesystems</code-name-base>
52
                    <build-prerequisite/>
53
                    <compile-dependency/>
54
                    <run-dependency>
55
                        <specification-version>8.6</specification-version>
56
                    </run-dependency>
57
                </dependency>
58
                <dependency>
59
                    <code-name-base>org.openide.util</code-name-base>
60
                    <build-prerequisite/>
61
                    <compile-dependency/>
62
                    <run-dependency>
63
                        <specification-version>8.30</specification-version>
64
                    </run-dependency>
65
                </dependency>
66
                <dependency>
67
                    <code-name-base>org.openide.util.lookup</code-name-base>
68
                    <build-prerequisite/>
69
                    <compile-dependency/>
70
                    <run-dependency>
71
                        <specification-version>8.20</specification-version>
72
                    </run-dependency>
73
                </dependency>
74
            </module-dependencies>
75
            <test-dependencies>
76
                <test-type>
77
                    <name>unit</name>
78
                    <test-dependency>
79
                        <code-name-base>org.netbeans.insane</code-name-base>
80
                        <compile-dependency/>
81
                    </test-dependency>
82
                    <test-dependency>
83
                        <code-name-base>org.netbeans.libs.junit4</code-name-base>
84
                        <compile-dependency/>
85
                    </test-dependency>
86
                    <test-dependency>
87
                        <code-name-base>org.netbeans.modules.nbjunit</code-name-base>
88
                        <compile-dependency/>
89
                    </test-dependency>
90
                </test-type>
91
            </test-dependencies>
92
            <public-packages/>
93
        </data>
94
    </configuration>
95
</project>
(-)3bff97f36acc (+1 lines)
Added Link Here
1
OpenIDE-Module-Name=Core Network Settings
(-)3bff97f36acc (+428 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2013 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2011 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
package org.netbeans.core.network.proxy;
46
47
import java.io.IOException;
48
import java.lang.reflect.Method;
49
import java.net.*;
50
import java.util.*;
51
import java.util.logging.Level;
52
import java.util.logging.Logger;
53
import java.util.prefs.PreferenceChangeEvent;
54
import java.util.prefs.PreferenceChangeListener;
55
import java.util.regex.Pattern;
56
import java.util.regex.PatternSyntaxException;
57
import org.netbeans.core.ProxySettings;
58
import org.openide.util.lookup.ServiceProvider;
59
60
/**
61
 *
62
 * @author Jiri Rechtacek
63
 */
64
@ServiceProvider(service = ProxySelector.class, position = 1000)
65
public final class NbProxySelector extends ProxySelector {
66
    
67
    private final ProxySelector original;
68
    private static final Logger LOG = Logger.getLogger (NbProxySelector.class.getName ());
69
    private static Object useSystemProxies;
70
    private static final String DEFAULT_PROXY_SELECTOR_CLASS_NAME = "sun.net.spi.DefaultProxySelector";
71
        
72
    /** Creates a new instance of NbProxySelector */
73
    public NbProxySelector() {
74
        original = ProxySelector.getDefault();
75
        LOG.log(Level.FINE, "java.net.useSystemProxies has been set to {0}", useSystemProxies());
76
        if (original.getClass().getName().equals(DEFAULT_PROXY_SELECTOR_CLASS_NAME) || original == null) {
77
            NetworkProxyReloader.reloadNetworkProxy();
78
        }
79
        ProxySettings.addPreferenceChangeListener(new ProxySettingsListener());
80
        copySettingsToSystem();
81
    } 
82
    
83
    @Override
84
    public List<Proxy> select(URI uri) {
85
        List<Proxy> res = new ArrayList<Proxy> ();
86
        int proxyType = ProxySettings.getProxyType ();
87
        switch (proxyType) {
88
            case ProxySettings.DIRECT_CONNECTION:
89
                res = Collections.singletonList (Proxy.NO_PROXY);
90
                break;
91
            case ProxySettings.AUTO_DETECT_PROXY:
92
                if (!useSystemProxies ()) {                    
93
                    String protocol = uri.getScheme ();
94
                    assert protocol != null : "Invalid scheme of uri " + uri + ". Scheme cannot be null!";
95
                    if (dontUseProxy (ProxySettings.getSystemNonProxyHosts(), uri.getHost ())) {
96
                        res.add (Proxy.NO_PROXY);
97
                        break;
98
                    }
99
                    if (protocol.toLowerCase (Locale.US).startsWith("http")) {
100
                        String ports = ProxySettings.getSystemHttpPort();
101
                        if (ports != null && ports.length () > 0 && ProxySettings.getSystemHttpHost().length () > 0) {
102
                            int porti = Integer.parseInt(ports);
103
                            Proxy p = new Proxy (Proxy.Type.HTTP,  new InetSocketAddress (ProxySettings.getSystemHttpHost(), porti));
104
                            res.add (p);
105
                        }
106
                    } else { // supposed SOCKS
107
                        String ports = ProxySettings.getSystemSocksPort();
108
                        String hosts = ProxySettings.getSystemSocksHost();
109
                        if (ports != null && ports.length () > 0 && hosts.length () > 0) {
110
                            int porti = Integer.parseInt(ports);
111
                            Proxy p = new Proxy (Proxy.Type.SOCKS,  new InetSocketAddress (hosts, porti));
112
                            res.add (p);
113
                        }
114
                    }
115
                    if (original != null) {
116
                        res.addAll (original.select (uri));
117
                    }
118
                }
119
                break;
120
            case ProxySettings.MANUAL_SET_PROXY:
121
                String protocol = uri.getScheme ();
122
                assert protocol != null : "Invalid scheme of uri " + uri + ". Scheme cannot be null!";
123
124
                // handling nonProxyHosts first
125
                if (dontUseProxy (ProxySettings.getNonProxyHosts (), uri.getHost ())) {
126
                    res.add (Proxy.NO_PROXY);
127
                    break;
128
                }
129
                if (protocol.toLowerCase (Locale.US).startsWith("http")) {
130
                    String hosts = ProxySettings.getHttpHost ();
131
                    String ports = ProxySettings.getHttpPort ();
132
                    if (ports != null && ports.length () > 0 && hosts.length () > 0) {
133
                        int porti = Integer.parseInt(ports);
134
                        Proxy p = new Proxy (Proxy.Type.HTTP,  new InetSocketAddress (hosts, porti));
135
                        res.add (p);
136
                    } else {
137
                        LOG.log(Level.FINE, "Incomplete HTTP Proxy [{0}/{1}] found in ProxySelector[Type: {2}] for uri {3}. ", new Object[]{hosts, ports, ProxySettings.getProxyType (), uri});
138
                        if (original != null) {
139
                            LOG.log(Level.FINEST, "Fallback to the default ProxySelector which returns {0}", original.select (uri));
140
                            res.addAll (original.select (uri));
141
                        }
142
                    }
143
                } else { // supposed SOCKS
144
                    String ports = ProxySettings.getSocksPort ();
145
                    String hosts = ProxySettings.getSocksHost ();
146
                    if (ports != null && ports.length () > 0 && hosts.length () > 0) {
147
                        int porti = Integer.parseInt(ports);
148
                        Proxy p = new Proxy (Proxy.Type.SOCKS,  new InetSocketAddress (hosts, porti));
149
                        res.add (p);
150
                    } else {
151
                        LOG.log(Level.FINE, "Incomplete SOCKS Server [{0}/{1}] found in ProxySelector[Type: {2}] for uri {3}. ", new Object[]{hosts, ports, ProxySettings.getProxyType (), uri});
152
                        if (original != null) {
153
                            LOG.log(Level.FINEST, "Fallback to the default ProxySelector which returns {0}", original.select (uri));
154
                            res.addAll (original.select (uri));
155
                        }
156
                    }
157
                }
158
                res.add (Proxy.NO_PROXY);
159
                break;
160
            case ProxySettings.AUTO_DETECT_PAC:
161
                if (!useSystemProxies ()) {
162
                    ProxyAutoConfig pac = ProxyAutoConfig.get(getPacFile());
163
                    assert pac != null : "Instance of ProxyAutoConfig found for " + getPacFile();
164
                    if (pac == null) {
165
                        LOG.log(Level.FINEST, "No instance of ProxyAutoConfig({0}) for URI {1}", new Object[]{getPacFile(), uri});
166
                        res.add(Proxy.NO_PROXY);
167
                    }
168
                    if (pac.getPacURI().getHost() == null) {
169
                        LOG.log(Level.FINEST, "Identifying proxy for URI {0}---{1}, PAC LOCAL URI: {2}", //NOI18N
170
                                new Object[] { uri.toString(), uri.getHost(), pac.getPacURI().toString() });
171
                        res.addAll(pac.findProxyForURL(uri));
172
                    } else if (pac.getPacURI().getHost().equals(uri.getHost())) {
173
                        // don't proxy PAC files
174
                        res.add(Proxy.NO_PROXY);
175
                    } else {
176
                        LOG.log(Level.FINEST, "Identifying proxy for URI {0}---{1}, PAC URI: {2}---{3}", //NOI18N
177
                                new Object[] { uri.toString(), uri.getHost(), pac.getPacURI().toString(), pac.getPacURI().getHost() });
178
                        res.addAll(pac.findProxyForURL(uri));
179
                    }                    
180
                }
181
                
182
                if (original != null) {
183
                    res.addAll (original.select (uri));
184
                }
185
                
186
                res.add (Proxy.NO_PROXY);
187
                break;
188
            case ProxySettings.MANUAL_SET_PAC:
189
                // unused branch - never can setup PAC file from NetBeans
190
                
191
                ProxyAutoConfig pac = ProxyAutoConfig.get(getPacFile());
192
                assert pac != null : "Instance of ProxyAutoConfig found for " + getPacFile();
193
                if (pac == null) {
194
                    LOG.log(Level.FINEST, "No instance of ProxyAutoConfig({0}) for URI {1}", new Object[]{getPacFile(), uri});
195
                    res.add(Proxy.NO_PROXY);
196
                }
197
                if (pac.getPacURI().getHost() == null) {
198
                        LOG.log(Level.FINEST, "Identifying proxy for URI {0}---{1}, PAC LOCAL URI: {2}", //NOI18N
199
                                new Object[] { uri.toString(), uri.getHost(), pac.getPacURI().toString() });
200
                        res.addAll(pac.findProxyForURL(uri));
201
                } else if (pac.getPacURI().getHost().equals(uri.getHost())) {
202
                    // don't proxy PAC files
203
                    res.add(Proxy.NO_PROXY);
204
                } else {
205
                    LOG.log(Level.FINEST, "Identifying proxy for URI {0}---{1}, PAC URI: {2}---{3}", //NOI18N
206
                            new Object[] { uri.toString(), uri.getHost(), pac.getPacURI().toString(), pac.getPacURI().getHost() });
207
                    res.addAll(pac.findProxyForURL(uri)); // NOI18N
208
                }
209
                res.add (Proxy.NO_PROXY);
210
                break;
211
            default:
212
                assert false : "Invalid proxy type: " + proxyType;
213
        }
214
        LOG.log(Level.FINEST, "NbProxySelector[Type: {0}, Use HTTP for all protocols: {1}] returns {2} for URI {3}", 
215
                new Object[]{ProxySettings.getProxyType (), ProxySettings.useProxyAllProtocols (), res, uri});
216
        return res;
217
    }
218
    
219
    @Override
220
    public void connectFailed (URI arg0, SocketAddress arg1, IOException arg2) {
221
        LOG.log  (Level.INFO, "connectionFailed(" + arg0 + ", " + arg1 +")", arg2);
222
    }
223
224
    // several modules listenes on these properties and propagates it futher
225
    private class ProxySettingsListener implements PreferenceChangeListener {
226
        @Override
227
        public void preferenceChange(PreferenceChangeEvent evt) {
228
            if (evt.getKey ().startsWith ("proxy") || evt.getKey ().startsWith ("useProxy")) {
229
                copySettingsToSystem ();
230
            }
231
        }
232
    }
233
    
234
    private void copySettingsToSystem () {
235
        String host = null, port = null, nonProxyHosts = null;
236
        String socksHost = null, socksPort = null;
237
        String httpsHost = null, httpsPort = null;
238
        int proxyType = ProxySettings.getProxyType ();
239
        switch (proxyType) {
240
            case ProxySettings.DIRECT_CONNECTION:
241
                host = null;
242
                port = null;
243
                httpsHost = null;
244
                httpsPort = null;
245
                nonProxyHosts = null;
246
                socksHost = null;
247
                socksPort = null;
248
                break;
249
            case ProxySettings.AUTO_DETECT_PROXY:
250
                host = ProxySettings.getSystemHttpHost();
251
                port = ProxySettings.getSystemHttpPort();
252
                httpsHost = ProxySettings.getSystemHttpsHost();
253
                httpsPort = ProxySettings.getSystemHttpsPort();
254
                socksHost = ProxySettings.getSystemSocksHost();
255
                socksPort = ProxySettings.getSystemSocksPort();
256
                nonProxyHosts = ProxySettings.getSystemNonProxyHosts();
257
                break;
258
            case ProxySettings.MANUAL_SET_PROXY:
259
                host = ProxySettings.getHttpHost ();
260
                port = ProxySettings.getHttpPort ();
261
                httpsHost = ProxySettings.getHttpsHost ();
262
                httpsPort = ProxySettings.getHttpsPort ();
263
                nonProxyHosts = ProxySettings.getNonProxyHosts ();
264
                socksHost = ProxySettings.getSocksHost ();
265
                socksPort = ProxySettings.getSocksPort ();
266
                break;
267
            case ProxySettings.AUTO_DETECT_PAC:
268
                host = null;
269
                port = null;
270
                httpsHost = null;
271
                httpsPort = null;
272
                nonProxyHosts = null;
273
                socksHost = null;
274
                socksPort = null;
275
                break;
276
            case ProxySettings.MANUAL_SET_PAC:
277
                host = null;
278
                port = null;
279
                httpsHost = null;
280
                httpsPort = null;
281
                nonProxyHosts = ProxySettings.getNonProxyHosts();
282
                socksHost = null;
283
                socksPort = null;
284
                break;
285
            default:
286
                assert false : "Invalid proxy type: " + proxyType;
287
        }
288
        setOrClearProperty ("http.proxyHost", host, false);
289
        setOrClearProperty ("http.proxyPort", port, true);
290
        setOrClearProperty ("http.nonProxyHosts", nonProxyHosts, false);
291
        setOrClearProperty ("https.proxyHost", httpsHost, false);
292
        setOrClearProperty ("https.proxyPort", httpsPort, true);
293
        setOrClearProperty ("https.nonProxyHosts", nonProxyHosts, false);
294
        setOrClearProperty ("socksProxyHost", socksHost, false);
295
        setOrClearProperty ("socksProxyPort", socksPort, true);
296
        LOG.log (Level.FINE, "Set System''s http.proxyHost/Port/NonProxyHost to {0}/{1}/{2}", new Object[]{host, port, nonProxyHosts});
297
        LOG.log (Level.FINE, "Set System''s https.proxyHost/Port to {0}/{1}", new Object[]{httpsHost, httpsPort});
298
        LOG.log (Level.FINE, "Set System''s socksProxyHost/Port to {0}/{1}", new Object[]{socksHost, socksPort});
299
    }
300
    
301
    private void setOrClearProperty (String key, String value, boolean isInteger) {
302
        assert key != null;
303
        if (value == null || value.length () == 0) {
304
            System.clearProperty (key);
305
        } else {
306
            if (isInteger) {
307
                try {
308
                    Integer.parseInt (value);
309
                } catch (NumberFormatException nfe) {
310
                    LOG.log (Level.INFO, nfe.getMessage(), nfe);
311
                }
312
            }
313
            System.setProperty (key, value);
314
        }
315
    }
316
317
    // package-private for unit-testing
318
    static boolean dontUseProxy (String nonProxyHosts, String host) {
319
        if (host == null) {
320
            return false;
321
        }
322
        
323
        // try IP adress first
324
        if (dontUseIp (nonProxyHosts, host)) {
325
            return true;
326
        } else {
327
            return dontUseHostName (nonProxyHosts, host);
328
        }
329
330
    }
331
    
332
    private static boolean dontUseHostName (String nonProxyHosts, String host) {
333
        if (host == null) {
334
            return false;
335
        }
336
        
337
        boolean dontUseProxy = false;
338
        StringTokenizer st = new StringTokenizer (nonProxyHosts, "|", false);
339
        while (st.hasMoreTokens () && !dontUseProxy) {
340
            String token = st.nextToken ().trim();
341
            int star = token.indexOf ("*");
342
            if (star == -1) {
343
                dontUseProxy = token.equals (host);
344
                if (dontUseProxy) {
345
                    LOG.log(Level.FINEST, "NbProxySelector[Type: {0}]. Host {1} found in nonProxyHosts: {2}", new Object[]{ProxySettings.getProxyType (), host, nonProxyHosts});
346
                }
347
            } else {
348
                String start = token.substring (0, star - 1 < 0 ? 0 : star - 1);
349
                String end = token.substring (star + 1 > token.length () ? token.length () : star + 1);
350
351
                //Compare left of * if and only if * is not first character in token
352
                boolean compareStart = star > 0; // not first character
353
                //Compare right of * if and only if * is not the last character in token
354
                boolean compareEnd = star < (token.length() - 1); // not last character
355
                dontUseProxy = (compareStart && host.startsWith(start)) || (compareEnd && host.endsWith(end));
356
357
                if (dontUseProxy) {
358
                    LOG.log(Level.FINEST, "NbProxySelector[Type: {0}]. Host {1} found in nonProxyHosts: {2}", new Object[]{ProxySettings.getProxyType (), host, nonProxyHosts});
359
                }
360
            }
361
        }
362
        return dontUseProxy;
363
    }
364
    
365
    private static boolean dontUseIp (String nonProxyHosts, String host) {
366
        if (host == null) {
367
            return false;
368
        }
369
        
370
        String ip = null;
371
        try {
372
            ip = InetAddress.getByName (host).getHostAddress ();
373
        } catch (UnknownHostException ex) {
374
            LOG.log (Level.FINE, ex.getLocalizedMessage (), ex);
375
        }
376
        
377
        if (ip == null) {
378
            return false;
379
        }
380
381
        boolean dontUseProxy = false;
382
        StringTokenizer st = new StringTokenizer (nonProxyHosts, "|", false);
383
        while (st.hasMoreTokens () && !dontUseProxy) {
384
            String nonProxyHost = st.nextToken ().trim();
385
            int star = nonProxyHost.indexOf ("*");
386
            if (star == -1) {
387
                dontUseProxy = nonProxyHost.equals (ip);
388
                if (dontUseProxy) {
389
                    LOG.log(Level.FINEST, "NbProxySelector[Type: {0}]. Host''s IP {1} found in nonProxyHosts: {2}", new Object[]{ProxySettings.getProxyType (), ip, nonProxyHosts});
390
                }
391
            } else {
392
                // match with given dotted-quad IP
393
                try {
394
                    dontUseProxy = Pattern.matches (nonProxyHost, ip);
395
                    if (dontUseProxy) {
396
                        LOG.log(Level.FINEST, "NbProxySelector[Type: {0}]. Host''s IP{1} found in nonProxyHosts: {2}", new Object[]{ProxySettings.getProxyType (), ip, nonProxyHosts});
397
                    }
398
                } catch (PatternSyntaxException pse) {
399
                    // may ignore it here
400
                }
401
            }
402
        }
403
        return dontUseProxy;
404
    }
405
    
406
    // NetProperties is JDK vendor specific, access only by reflection
407
    static boolean useSystemProxies () {
408
        if (useSystemProxies == null) {
409
            try {
410
                Class<?> clazz = Class.forName ("sun.net.NetProperties");
411
                Method getBoolean = clazz.getMethod ("getBoolean", String.class);
412
                useSystemProxies = getBoolean.invoke (null, "java.net.useSystemProxies");
413
            } catch (Exception x) {
414
                LOG.log (Level.FINEST, "Cannot get value of java.net.useSystemProxies bacause " + x.getMessage(), x);
415
            }
416
        }
417
        return useSystemProxies != null && "true".equalsIgnoreCase (useSystemProxies.toString ());
418
    }
419
    
420
    static boolean usePAC() {
421
        String pacFile = ProxySettings.getSystemPac();
422
        return pacFile != null;
423
    }
424
    
425
    private static String getPacFile() {
426
        return ProxySettings.getSystemPac();
427
    }
428
}
(-)3bff97f36acc (+230 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2013 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2013 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.core.network.proxy;
43
44
import org.netbeans.core.ProxySettings;
45
import java.util.logging.Level;
46
import java.util.logging.Logger;
47
import java.util.prefs.Preferences;
48
import org.netbeans.core.network.proxy.fallback.FallbackNetworkProxy;
49
import org.netbeans.core.network.proxy.gnome.GnomeNetworkProxy;
50
import org.netbeans.core.network.proxy.kde.KdeNetworkProxy;
51
import org.netbeans.core.network.proxy.mac.MacNetworkProxy;
52
import org.netbeans.core.network.proxy.windows.WindowsNetworkProxy;
53
import org.openide.util.NbPreferences;
54
import org.openide.util.Utilities;
55
import org.openide.util.lookup.ServiceProvider;
56
57
/**
58
 * This class allows user to reload system network proxy settings.
59
 * 
60
 * @author lfischme
61
 */
62
@ServiceProvider(service = ProxySettings.Reloader.class, position = 1000)
63
public class NetworkProxyReloader extends ProxySettings.Reloader {
64
    
65
    private final static Logger LOGGER = Logger.getLogger(NetworkProxyReloader.class.getName());
66
    
67
    private final static String COMMA = ","; //NOI18N
68
    
69
    private final static String GNOME = "gnome"; //NOI18N
70
    private final static String KDE = "kde"; //NOI18N
71
    private final static String RUNNING_ENV_SYS_PROPERTY = "netbeans.running.environment"; //NOI18N
72
    
73
    private static final NetworkProxyResolver NETWORK_PROXY_RESOLVER = getNetworkProxyResolver();
74
    private static final NetworkProxyResolver FALLBACK_NETWORK_PROXY_RESOLVER = getFallbackProxyResolver();
75
    /**
76
     * Reloads system proxy network settings.
77
     * 
78
     * The first it tries to retrieve proxy settings directly from system,
79
     * if it is unsuccessful it tries fallback (from environment property http_proxy etc.).
80
     */
81
    public static void reloadNetworkProxy() {        
82
        LOGGER.log(Level.FINE, "System network proxy reloading started."); //NOI18N
83
        NetworkProxySettings networkProxySettings = NETWORK_PROXY_RESOLVER.getNetworkProxySettings();
84
        
85
        if (!networkProxySettings.isResolved()) {
86
            LOGGER.log(Level.WARNING, "System network proxy reloading failed! Trying fallback resolver."); //NOI18N
87
            NetworkProxySettings fallbackNetworkProxySettings = FALLBACK_NETWORK_PROXY_RESOLVER.getNetworkProxySettings();
88
            if (fallbackNetworkProxySettings.isResolved()) {
89
                LOGGER.log(Level.INFO, "System network proxy reloading succeeded. Fallback provider was successful."); //NOI18N
90
                networkProxySettings = fallbackNetworkProxySettings;
91
            } else {
92
                LOGGER.log(Level.WARNING, "System network proxy reloading failed! Fallback provider was unsuccessful."); //NOI18N
93
            }
94
        } else {
95
            LOGGER.log(Level.INFO, "System network proxy reloading succeeded."); //NOI18N
96
        }
97
                       
98
        switch (networkProxySettings.getProxyMode()) {
99
            case AUTO:
100
                LOGGER.log(Level.INFO, "System network proxy - mode: auto"); //NOI18N
101
                LOGGER.log(Level.INFO, "System network proxy - pac url: {0}", networkProxySettings.getPacFileUrl()); //NOI18N
102
                getPreferences().remove(ProxySettings.SYSTEM_PROXY_HTTP_HOST);
103
                getPreferences().remove(ProxySettings.SYSTEM_PROXY_HTTP_PORT);
104
                getPreferences().remove(ProxySettings.SYSTEM_PROXY_HTTPS_HOST);
105
                getPreferences().remove(ProxySettings.SYSTEM_PROXY_HTTPS_PORT);
106
                getPreferences().remove(ProxySettings.SYSTEM_PROXY_SOCKS_HOST);
107
                getPreferences().remove(ProxySettings.SYSTEM_PROXY_SOCKS_PORT);
108
                getPreferences().remove(ProxySettings.SYSTEM_NON_PROXY_HOSTS);
109
                getPreferences().put(ProxySettings.SYSTEM_PAC, networkProxySettings.getPacFileUrl());
110
                break;
111
            case MANUAL:
112
                LOGGER.log(Level.INFO, "System network proxy - mode: manual"); //NOI18N
113
                LOGGER.log(Level.INFO, "System network proxy - http host: {0}", networkProxySettings.getHttpProxyHost()); //NOI18N
114
                LOGGER.log(Level.INFO, "System network proxy - http port: {0}", networkProxySettings.getHttpProxyPort()); //NOI18N
115
                LOGGER.log(Level.INFO, "System network proxy - https host: {0}", networkProxySettings.getHttpsProxyHost()); //NOI18N
116
                LOGGER.log(Level.INFO, "System network proxy - https port: {0}", networkProxySettings.getHttpsProxyPort()); //NOI18N
117
                LOGGER.log(Level.INFO, "System network proxy - socks host: {0}", networkProxySettings.getSocksProxyHost()); //NOI18N
118
                LOGGER.log(Level.INFO, "System network proxy - socks port: {0}", networkProxySettings.getSocksProxyPort()); //NOI18N
119
                LOGGER.log(Level.INFO, "System network proxy - no prohy hosts: {0}", getStringFromArray(networkProxySettings.getNoProxyHosts())); //NOI18N
120
                getPreferences().put(ProxySettings.SYSTEM_PROXY_HTTP_HOST, networkProxySettings.getHttpProxyHost());
121
                getPreferences().put(ProxySettings.SYSTEM_PROXY_HTTP_PORT, networkProxySettings.getHttpProxyPort());
122
                getPreferences().put(ProxySettings.SYSTEM_PROXY_HTTPS_HOST, networkProxySettings.getHttpsProxyHost());
123
                getPreferences().put(ProxySettings.SYSTEM_PROXY_HTTPS_PORT, networkProxySettings.getHttpsProxyPort());
124
                getPreferences().put(ProxySettings.SYSTEM_PROXY_SOCKS_HOST, networkProxySettings.getSocksProxyHost());
125
                getPreferences().put(ProxySettings.SYSTEM_PROXY_SOCKS_PORT, networkProxySettings.getSocksProxyPort());
126
                getPreferences().put(ProxySettings.SYSTEM_NON_PROXY_HOSTS, getStringFromArray(networkProxySettings.getNoProxyHosts()));
127
                getPreferences().remove(ProxySettings.SYSTEM_PAC);
128
                break;
129
            case DIRECT:
130
                LOGGER.log(Level.INFO, "System network proxy - mode: direct"); //NOI18N
131
            default:
132
                LOGGER.log(Level.INFO, "System network proxy: falled to default (corect if direct mode went before)"); //NOI18N
133
                getPreferences().remove(ProxySettings.SYSTEM_PROXY_HTTP_HOST);
134
                getPreferences().remove(ProxySettings.SYSTEM_PROXY_HTTP_PORT);
135
                getPreferences().remove(ProxySettings.SYSTEM_PROXY_HTTPS_HOST);
136
                getPreferences().remove(ProxySettings.SYSTEM_PROXY_HTTPS_PORT);
137
                getPreferences().remove(ProxySettings.SYSTEM_PROXY_SOCKS_HOST);
138
                getPreferences().remove(ProxySettings.SYSTEM_PROXY_SOCKS_PORT);
139
                getPreferences().remove(ProxySettings.SYSTEM_NON_PROXY_HOSTS);
140
                getPreferences().remove(ProxySettings.SYSTEM_PAC);
141
        }        
142
        LOGGER.log(Level.FINE, "System network proxy reloading fineshed."); //NOI18N
143
    }
144
    
145
    /**
146
     * Returns string from array of strings. Strings are separated by comma.
147
     * 
148
     * @param stringArray
149
     * @return String from array of strings. Strings are separated by comma.
150
     */
151
    private static String getStringFromArray(String[] stringArray) {
152
        StringBuilder sb = new StringBuilder();
153
        for (int i = 0; i < stringArray.length; i++) {
154
            sb.append(stringArray[i]);
155
            if (i == stringArray.length - 1) {
156
                sb.append(COMMA);
157
            }
158
        }
159
        
160
        return sb.toString();
161
    }
162
    
163
    /**
164
     * Returns preferences for proxy settings.
165
     * 
166
     * @return Preferences for proxy settings.
167
     */
168
    private static Preferences getPreferences() {
169
        return NbPreferences.forModule(ProxySettings.class);
170
    }
171
    
172
    /**
173
     * Returns proper network resolver for running environment.
174
     * 
175
     * If not suitable proxy resolver found, the fallback is used.
176
     * 
177
     * @return Proper network resolver for running environment.
178
     */
179
    private static NetworkProxyResolver getNetworkProxyResolver() {
180
        if (NETWORK_PROXY_RESOLVER == null) {        
181
            if (Utilities.isWindows()) {
182
                LOGGER.log(Level.INFO, "System network proxy resolver: Windows"); //NOI18N
183
                return new WindowsNetworkProxy();
184
            } 
185
            
186
            if (Utilities.isMac()) {
187
                LOGGER.log(Level.INFO, "System network proxy resolver: Mac"); //NOI18N
188
                return new MacNetworkProxy();
189
            }
190
            
191
            if (Utilities.isUnix()){
192
                String env = System.getProperty(RUNNING_ENV_SYS_PROPERTY);
193
                if (env != null) {
194
                    if (env.toLowerCase().equals(GNOME)) {
195
                        LOGGER.log(Level.INFO, "System network proxy resolver: Gnome"); //NOI18N
196
                        return new GnomeNetworkProxy();
197
                    }
198
                    
199
                    if (env.toLowerCase().equals(KDE)) {
200
                        LOGGER.log(Level.INFO, "System network proxy resolver: KDE"); //NOI18N
201
                        return new KdeNetworkProxy();
202
                    }
203
                }
204
            }
205
            
206
            LOGGER.log(Level.WARNING, "System network proxy resolver: no suitable found, using fallback."); //NOI18N
207
            return new FallbackNetworkProxy();
208
        } else {
209
            return NETWORK_PROXY_RESOLVER;
210
        }   
211
    }
212
    
213
    /**
214
     * Returns fallback proxy resolver.
215
     * 
216
     * @return Fallback proxy resolver.
217
     */
218
    private static NetworkProxyResolver getFallbackProxyResolver() {
219
        if (FALLBACK_NETWORK_PROXY_RESOLVER == null) {
220
            return new FallbackNetworkProxy();
221
        } else {
222
            return FALLBACK_NETWORK_PROXY_RESOLVER;
223
        }
224
    }
225
226
    @Override
227
    public void reload() {
228
        NetworkProxyReloader.reloadNetworkProxy();
229
    }
230
}
(-)3bff97f36acc (+61 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2013 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2013 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.core.network.proxy;
43
44
/**
45
 * Interface for system (platform) dependent proxy resolvers.
46
 * 
47
 * Different resolvers for Windows, Mac OS X, Gnome and KDE. Also there is
48
 * a fallback resolver.
49
 * 
50
 * @author lfischme
51
 */
52
public interface NetworkProxyResolver {
53
    
54
    /**
55
     * Returns NetworkProxySetting - wrapper for all proxy settings.
56
     * 
57
     * @return NetworkProxySettings
58
     */
59
    public NetworkProxySettings getNetworkProxySettings();
60
61
}
(-)3bff97f36acc (+266 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2013 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2013 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.core.network.proxy;
43
44
import java.util.logging.Level;
45
import java.util.logging.Logger;
46
47
/**
48
 * Immutable class representing all network proxy settings.
49
 * 
50
 * Holds all proxy settings values if they were successfully retrieved
51
 * or tells that they were not retrieved well.
52
 * 
53
 * @author lfischme
54
 */
55
public final class NetworkProxySettings {
56
57
    public static enum ProxyMode {
58
        DIRECT,
59
        AUTO,
60
        MANUAL
61
    }        
62
    
63
    private final static Logger LOGGER = Logger.getLogger(NetworkProxySettings.class.getName());
64
    private final static String COLON = ":"; //NOI18N
65
    private final static String SLASH = "/"; //NOI18N
66
    private final static String EMPTY_STRING = ""; //NOI18N
67
    private final boolean resolved;
68
    private final ProxyMode proxyMode;
69
    private final String httpProxyHost;
70
    private final String httpProxyPort;
71
    private final String httpsProxyHost;
72
    private final String httpsProxyPort;
73
    private final String socksProxyHost;
74
    private final String socksProxyPort;
75
    private final String pacFileUrl;
76
    private final String[] noProxyHosts;
77
78
    public NetworkProxySettings() {
79
        this.resolved = true;
80
        this.proxyMode = ProxyMode.DIRECT;
81
        this.pacFileUrl = null;
82
        this.httpProxyHost = null;
83
        this.httpProxyPort = null;
84
        this.httpsProxyHost = null;
85
        this.httpsProxyPort = null;
86
        this.socksProxyHost = null;
87
        this.socksProxyPort = null;
88
        this.noProxyHosts = new String[0];
89
    }
90
    
91
    public NetworkProxySettings(String httpProxy, String[] noProxyHosts) {
92
        String httpProxyHostChecked = getHost(httpProxy);
93
        String httpProxyPortChecked = getPort(httpProxy);
94
        
95
        this.resolved = true;
96
        this.proxyMode = ProxyMode.MANUAL;
97
        this.pacFileUrl = null;       
98
        this.httpProxyHost = httpProxyHostChecked;
99
        this.httpProxyPort = httpProxyPortChecked;
100
        this.httpsProxyHost = httpProxyHostChecked;
101
        this.httpsProxyPort = httpProxyPortChecked;
102
        this.socksProxyHost = httpProxyHostChecked;
103
        this.socksProxyPort = httpProxyPortChecked;
104
        this.noProxyHosts = checkArray(noProxyHosts);
105
    }
106
107
    public NetworkProxySettings(String httpProxy, String httpsProxy, String socksProxy, String[] noProxyHosts) {
108
        this.resolved = true;
109
        this.proxyMode = ProxyMode.MANUAL;
110
        this.pacFileUrl = null;
111
        this.httpProxyHost = getHost(httpProxy);
112
        this.httpProxyPort = getPort(httpProxy);
113
        this.httpsProxyHost = getHost(httpsProxy);
114
        this.httpsProxyPort = getPort(httpsProxy);
115
        this.socksProxyHost = getHost(socksProxy);
116
        this.socksProxyPort = getPort(socksProxy);
117
        this.noProxyHosts = checkArray(noProxyHosts);
118
    }
119
120
    public NetworkProxySettings(String httpProxyHost, String httpProxyPort, String[] noProxyHosts) {
121
        String httpProxyHostChecked = checkNull(httpProxyHost);
122
        String httpProxyPortChecked = checkNumber(httpProxyPort);
123
        
124
        this.resolved = true;
125
        this.proxyMode = ProxyMode.MANUAL;
126
        this.pacFileUrl = null;
127
        this.httpProxyHost = httpProxyHostChecked;
128
        this.httpProxyPort = httpProxyPortChecked;
129
        this.httpsProxyHost = httpProxyHostChecked;
130
        this.httpsProxyPort = httpProxyPortChecked;
131
        this.socksProxyHost = httpProxyHostChecked;
132
        this.socksProxyPort = httpProxyPortChecked;
133
        this.noProxyHosts = checkArray(noProxyHosts);
134
    }
135
136
    public NetworkProxySettings(String httpProxyHost, String httpProxyPort,
137
            String httpsProxyHost, String httpsProxyPort,
138
            String socksProxyHost, String socksProxyPort, String[] noProxyHosts) {
139
        this.resolved = true;
140
        this.proxyMode = ProxyMode.MANUAL;
141
        this.pacFileUrl = null;
142
        this.httpProxyHost = checkNull(httpProxyHost);
143
        this.httpProxyPort = checkNumber(httpProxyPort);
144
        this.httpsProxyHost = checkNull(httpsProxyHost);
145
        this.httpsProxyPort = checkNumber(httpsProxyPort);
146
        this.socksProxyHost = checkNull(socksProxyHost);
147
        this.socksProxyPort = checkNumber(socksProxyPort);
148
        this.noProxyHosts = checkArray(noProxyHosts);
149
    }
150
151
    public NetworkProxySettings(String pacFileUrl) {
152
        this.resolved = true;
153
        this.proxyMode = ProxyMode.AUTO;
154
        this.pacFileUrl = checkNull(pacFileUrl);
155
        this.httpProxyHost = null;
156
        this.httpProxyPort = null;
157
        this.httpsProxyHost = null;
158
        this.httpsProxyPort = null;
159
        this.socksProxyHost = null;
160
        this.socksProxyPort = null;
161
        this.noProxyHosts = new String[0];
162
    }
163
164
    public NetworkProxySettings(boolean resolved) {
165
        this.resolved = resolved;
166
        this.proxyMode = ProxyMode.DIRECT;
167
        this.pacFileUrl = null;
168
        this.httpProxyHost = null;
169
        this.httpProxyPort = null;
170
        this.httpsProxyHost = null;
171
        this.httpsProxyPort = null;
172
        this.socksProxyHost = null;
173
        this.socksProxyPort = null;
174
        this.noProxyHosts = new String[0];
175
    }
176
    
177
    
178
179
    private String getHost(String string) {
180
        if (string == null) {
181
            return EMPTY_STRING;
182
        } else {
183
            if (string.contains(COLON)) {
184
                return string.substring(0, string.lastIndexOf(COLON));
185
            } else {
186
                return string;
187
            }
188
        }
189
    }
190
191
    private String getPort(String string) {
192
        if (string == null) {
193
            return EMPTY_STRING;
194
        } else {
195
            if (string.endsWith(SLASH)) {
196
                string = string.substring(string.length() - 1, string.length());
197
            }
198
            if (string.contains(COLON)) {
199
                return string.substring(string.lastIndexOf(COLON) + 1);
200
            } else {
201
                return EMPTY_STRING;
202
            }
203
        }
204
    }
205
206
    private String checkNull(String string) {
207
        return string == null ? EMPTY_STRING : string;
208
    }
209
210
    private String checkNumber(String string) {
211
        if (string != null) {
212
            try {
213
                Integer.parseInt(string);
214
                return string;
215
            } catch (NumberFormatException nfe) {
216
                LOGGER.log(Level.SEVERE, "Cannot parse number {0}", string); //NOI18N
217
            }
218
        }
219
220
        return EMPTY_STRING;
221
    }
222
223
    private String[] checkArray(String[] array) {
224
        return array == null ? new String[0] : array;
225
    }
226
227
    public boolean isResolved() {
228
        return resolved;
229
    }
230
231
    public ProxyMode getProxyMode() {
232
        return proxyMode;
233
    }
234
235
    public String getHttpProxyHost() {
236
        return httpProxyHost;
237
    }
238
239
    public String getHttpProxyPort() {
240
        return httpProxyPort;
241
    }
242
243
    public String getHttpsProxyHost() {
244
        return httpsProxyHost;
245
    }
246
247
    public String getHttpsProxyPort() {
248
        return httpsProxyPort;
249
    }
250
251
    public String getSocksProxyHost() {
252
        return socksProxyHost;
253
    }
254
255
    public String getSocksProxyPort() {
256
        return socksProxyPort;
257
    }
258
259
    public String getPacFileUrl() {
260
        return pacFileUrl;
261
    }
262
263
    public String[] getNoProxyHosts() {
264
        return noProxyHosts;
265
    }
266
}
(-)3bff97f36acc (+349 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011-2013 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2011 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.core.network.proxy;
43
44
import org.netbeans.core.ProxySettings;
45
import java.io.*;
46
import java.net.*;
47
import java.util.*;
48
import java.util.logging.Level;
49
import java.util.logging.Logger;
50
import javax.script.Invocable;
51
import javax.script.ScriptEngine;
52
import javax.script.ScriptEngineManager;
53
import javax.script.ScriptException;
54
import org.openide.filesystems.FileObject;
55
import org.openide.filesystems.FileUtil;
56
import org.openide.filesystems.URLMapper;
57
import org.openide.util.RequestProcessor;
58
import org.openide.util.RequestProcessor.Task;
59
import org.openide.util.Utilities;
60
61
/**
62
 *
63
 * @author Jirka Rechtacek
64
 */
65
public class ProxyAutoConfig {
66
67
    private static final Map<String, ProxyAutoConfig> file2pac = new HashMap<String, ProxyAutoConfig>(2);
68
    private static RequestProcessor RP = new RequestProcessor(ProxyAutoConfig.class);
69
    private static final String NS_PROXY_AUTO_CONFIG_URL = "nbinst://org.netbeans.core/modules/ext/nsProxyAutoConfig.js"; // NOI18N
70
    private static final String PROTO_FILE = "file://";
71
72
    /**
73
     * 
74
     * @param pacFile The string to be parsed into a URI
75
     * @return ProxyAutoConfig for given pacFile or <code>null</code> if constructor failed
76
     */
77
    public static synchronized ProxyAutoConfig get(String pacFile) {
78
        if (file2pac.get(pacFile) == null) {
79
            LOGGER.fine("Init ProxyAutoConfig for " + pacFile);
80
            ProxyAutoConfig instance = null;
81
            try {
82
                instance = new ProxyAutoConfig(pacFile);
83
            } catch (URISyntaxException ex) {
84
                Logger.getLogger(ProxyAutoConfig.class.getName()).warning("Parsing " + pacFile + " to URI throws " + ex);
85
            } finally {
86
                file2pac.put(pacFile, instance);
87
            }
88
        }
89
        return file2pac.get(pacFile);
90
    }
91
    private static final Logger LOGGER = Logger.getLogger(ProxyAutoConfig.class.getName());
92
    private Invocable inv = null;
93
    private final Task initTask;
94
    private final URI pacURI;
95
96
    private ProxyAutoConfig(final String pacURL) throws URISyntaxException {
97
        assert file2pac.get(pacURL) == null : "Only once object for " + pacURL + " must exist.";
98
        String normPAC = normalizePAC(pacURL);
99
        pacURI = new URI(normPAC);
100
        initTask = RP.post(new Runnable() {
101
102
            @Override
103
            public void run() {
104
                initEngine();
105
            }
106
        });
107
    }
108
109
    public URI getPacURI() {
110
        return pacURI;
111
    }
112
113
    private void initEngine() {
114
        InputStream pacIS;
115
        try {
116
            if (pacURI.isAbsolute()) {
117
                pacIS = downloadPAC(pacURI.toURL());
118
            } else {
119
                pacIS = null;
120
            }
121
        } catch (IOException ex) {
122
            LOGGER.log(Level.INFO, "InputStream for " + pacURI + " throws " + ex, ex);
123
            return;
124
        }
125
        if (pacIS == null) {
126
            return ;
127
        }
128
        String utils = downloadUtils();
129
        ScriptEngine eng;
130
        try {
131
            eng = evalPAC(pacIS, utils);
132
        } catch (FileNotFoundException ex) {
133
            LOGGER.log(Level.FINE, "While constructing ProxyAutoConfig thrown " + ex, ex);
134
            return ;
135
        } catch (ScriptException ex) {
136
            LOGGER.log(Level.FINE, "While constructing ProxyAutoConfig thrown " + ex, ex);
137
            return ;
138
        } finally {
139
            if (pacIS != null) {
140
                try {
141
                    pacIS.close();
142
                } catch (IOException ex) {
143
                    LOGGER.log(Level.FINE, "While closing PAC input stream thrown " + ex, ex);
144
                }
145
            }
146
        }
147
        assert eng != null : "JavaScri5pt engine cannot be null";
148
        if (eng == null) {
149
            LOGGER.log(Level.WARNING, "JavaScript engine cannot be null");
150
            return ;
151
        }
152
        inv = (Invocable) eng;
153
    }
154
155
    @SuppressWarnings("unchecked")
156
    public List<Proxy> findProxyForURL(URI u) {
157
        assert initTask != null : "initTask has be to posted.";
158
        if (!initTask.isFinished()) {
159
            while (!initTask.isFinished()) {
160
                try {
161
                    RP.post(new Runnable() {
162
163
                        @Override
164
                        public void run() {
165
                        }
166
                    }).waitFinished(100);
167
                } catch (InterruptedException ex) {
168
                    LOGGER.log(Level.FINEST, ex.getMessage(), ex);
169
                }
170
            }
171
        }
172
        if (inv == null) {
173
            return Collections.singletonList(Proxy.NO_PROXY);
174
        }
175
        Object proxies = null;
176
        try {
177
            proxies = inv.invokeFunction("FindProxyForURL", u.toString(), u.getHost()); // NOI18N
178
        } catch (ScriptException ex) {
179
            LOGGER.log(Level.FINE, "While invoking FindProxyForURL(" + u + ", " + u.getHost() + " thrown " + ex, ex);
180
        } catch (NoSuchMethodException ex) {
181
            LOGGER.log(Level.FINE, "While invoking FindProxyForURL(" + u + ", " + u.getHost() + " thrown " + ex, ex);
182
        }
183
        List<Proxy> res = analyzeResult(u, proxies);
184
        if (res == null) {
185
            LOGGER.info("findProxyForURL(" + u + ") returns null.");
186
            res = Collections.emptyList();
187
        }
188
        LOGGER.fine("findProxyForURL(" + u + ") returns " + Arrays.asList(res));
189
        return res;
190
    }
191
192
    private static InputStream downloadPAC (URL pacURL) throws IOException {
193
        InputStream is;
194
        URLConnection conn = pacURL.openConnection(Proxy.NO_PROXY);
195
        is = conn.getInputStream();
196
        return is;
197
    }
198
199
    private static ScriptEngine evalPAC(InputStream is, String utils) throws FileNotFoundException, ScriptException {
200
        ScriptEngineManager factory = new ScriptEngineManager();
201
        ScriptEngine engine = factory.getEngineByName("JavaScript");
202
        Reader pacReader = new InputStreamReader(is);
203
        engine.eval(pacReader);
204
        engine.eval(utils);
205
        return engine;
206
    }
207
208
    private List<Proxy> analyzeResult(URI uri, Object proxiesString) {
209
        if (proxiesString == null) {
210
            LOGGER.fine("Null result for " + uri);
211
            return null;
212
        }
213
        Proxy.Type proxyType;
214
        String protocol = uri.getScheme();
215
        assert protocol != null : "Invalid scheme of uri " + uri + ". Scheme cannot be null!";
216
        if (protocol == null) {
217
            return null;
218
        } else {
219
            if (("http".equals(protocol)) || ("https".equals(protocol))) { // NOI18N
220
                proxyType = Proxy.Type.HTTP;
221
            } else {
222
                proxyType = Proxy.Type.SOCKS;
223
            }
224
        }
225
        StringTokenizer st = new StringTokenizer(proxiesString.toString(), ";"); //NOI18N
226
        List<Proxy> proxies = new LinkedList<Proxy>();
227
        while (st.hasMoreTokens()) {
228
            String proxy = st.nextToken();
229
            if (ProxySettings.DIRECT.equals(proxy.trim())) {
230
                proxies.add(Proxy.NO_PROXY);
231
            } else {
232
                String host = getHost(proxy);
233
                Integer port = getPort(proxy);
234
                if (host != null && port != null) {
235
                    proxies.add(new Proxy(proxyType, new InetSocketAddress(host, port)));
236
                }
237
            }
238
        }
239
        return proxies;
240
    }
241
242
    private static String getHost(String proxy) {
243
        if (proxy.startsWith("PROXY ")) {
244
            proxy = proxy.substring(6);
245
        }
246
        int i = proxy.lastIndexOf(":"); // NOI18N
247
        if (i <= 0 || i >= proxy.length() - 1) {
248
            LOGGER.info("No port in " + proxy);
249
            return null;
250
        }
251
252
        String host = proxy.substring(0, i);
253
254
        return ProxySettings.normalizeProxyHost(host);
255
    }
256
257
    private static Integer getPort(String proxy) {
258
        if (proxy.startsWith("PROXY ")) {
259
            proxy = proxy.substring(6);
260
        }
261
        int i = proxy.lastIndexOf(":"); // NOI18N
262
        if (i <= 0 || i >= proxy.length() - 1) {
263
            LOGGER.info("No port in " + proxy);
264
            return null;
265
        }
266
267
        String port = proxy.substring(i + 1);
268
        if (port.indexOf('/') >= 0) {
269
            port = port.substring(0, port.indexOf('/'));
270
        }
271
272
        try {
273
            return Integer.parseInt(port);
274
        } catch (NumberFormatException ex) {
275
            LOGGER.log(Level.INFO, ex.getLocalizedMessage(), ex);
276
            return null;
277
        }
278
    }
279
280
    private static String downloadUtils() {
281
        StringBuilder builder = new StringBuilder();
282
        BufferedReader reader = null;
283
        // XXX why is the below not more simply:
284
        // reader = new BufferedReader(new URL(NS_PROXY_AUTO_CONFIG_URL).openStream());
285
        FileObject fo = null;
286
        try {
287
            try {
288
                fo = URLMapper.findFileObject(new URL(NS_PROXY_AUTO_CONFIG_URL));
289
            } catch (MalformedURLException ex) {
290
                LOGGER.log(Level.INFO, ex.getMessage(), ex);
291
            }
292
            reader = new BufferedReader(new java.io.FileReader(FileUtil.toFile(fo)));
293
        } catch (FileNotFoundException ex) {
294
            LOGGER.log(Level.INFO, ex.getMessage(), ex);
295
        }
296
        try {
297
            String line;
298
            boolean doAppend = false;
299
            while ((line = reader.readLine()) != null) {
300
                line = line.trim();
301
                if( line.startsWith("var pacUtils =") ) { //NOI18N
302
                    doAppend = true;
303
                }
304
                if( !doAppend )
305
                    continue;
306
                if (line.endsWith("+")) { // NOI18N
307
                    line = line.substring(0, line.length() - 1);
308
                }
309
                builder.append(line.replaceAll("\"", "").replaceAll("\\\\n", "").replaceAll("\\\\\\\\", "\\\\")); // NOI18N
310
                builder.append(System.getProperty("line.separator")); // NOI18N
311
            }
312
        } catch (IOException ex) {
313
            LOGGER.log(Level.INFO, "While downloading nsProxyAutoConfig.js thrown " + ex.getMessage(), ex);
314
        } finally {
315
            if (reader != null) {
316
                try {
317
                    reader.close();
318
                } catch (IOException ex) {
319
                    LOGGER.log(Level.FINE, ex.getMessage(), ex);
320
                }
321
            }
322
        }
323
        return builder.toString();
324
    }
325
326
    private String normalizePAC(String pacURL) {
327
        int index;
328
        if ((index = pacURL.indexOf("\n")) != -1) { // NOI18N
329
            pacURL = pacURL.substring(0, index);
330
        }
331
        if ((index = pacURL.indexOf("\r")) != -1) { // NOI18N
332
            pacURL = pacURL.substring(0, index);
333
        }
334
        String fileLocation = pacURL;
335
        if (fileLocation.startsWith(PROTO_FILE)) {
336
            fileLocation = fileLocation.substring(PROTO_FILE.length());
337
        }
338
        File f = new File(fileLocation);
339
        if (f.canRead()) {
340
            pacURL = Utilities.toURI(f).toString();
341
        } else {
342
            pacURL = pacURL.replaceAll("\\\\", "/"); //NOI18N
343
        }
344
        if ((index = pacURL.indexOf(" ")) != -1) { // NOI18N
345
            pacURL = pacURL.substring(0, index);
346
        }
347
        return pacURL.trim();
348
    }
349
}
(-)3bff97f36acc (+121 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2013 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2013 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.core.network.proxy.fallback;
43
44
import java.util.logging.Level;
45
import java.util.logging.Logger;
46
import org.netbeans.core.network.proxy.NetworkProxyResolver;
47
import org.netbeans.core.network.proxy.NetworkProxySettings;
48
49
/**
50
 * Fallback resolver tries to retrieve proxy setting from environment variables.
51
 *
52
 * It is looking for: http_proxy, https_proxy, socks_proxy and no_proxy
53
 * variables. It cannot resolve if PAC is set up. Also environment variables may
54
 * be set but in system there are not used. Fallback cannot resolve it.
55
 *
56
 * @author lfischme
57
 */
58
public class FallbackNetworkProxy implements NetworkProxyResolver {
59
    
60
    private final static Logger LOGGER = Logger.getLogger(FallbackNetworkProxy.class.getName());
61
62
    private final static String AT = "@"; //NOI18N
63
    private final static String COMMA = ","; //NOI18N
64
    private final static String SLASH = "/"; //NOI18N
65
    private final static String PROTOCOL_PREXIF_SEPARATOR = "://"; //NOI18N
66
    private final static String EMPTY_STRING = ""; //NOI18N
67
    
68
    private final static String HTTP_PROXY_SYS_PROPERTY = "http_proxy"; //NOI18N
69
    private final static String HTTPS_PROXY_SYS_PROPERTY = "https_proxy"; //NOI18N
70
    private final static String SOCKS_PROXY_SYS_PROPERTY = "socks_proxy"; //NOI18N
71
    private final static String NO_PROXY_SYS_PROPERTY = "no_proxy"; //NOI18N
72
73
    @Override
74
    public NetworkProxySettings getNetworkProxySettings() {
75
        LOGGER.log(Level.FINE, "Fallback system proxy resolver started."); //NOI18N
76
        String httpProxyRaw = System.getenv(HTTP_PROXY_SYS_PROPERTY);
77
        if (httpProxyRaw != null && !httpProxyRaw.isEmpty()) {
78
            String httpsProxyRaw = System.getenv(HTTPS_PROXY_SYS_PROPERTY);
79
            String socksProxyRaw = System.getenv(SOCKS_PROXY_SYS_PROPERTY);
80
            String noProxyRaw = System.getenv(NO_PROXY_SYS_PROPERTY);
81
            
82
            LOGGER.log(Level.INFO, "Fallback system proxy resolver: http_proxy={0}", httpProxyRaw); //NOI18N
83
            LOGGER.log(Level.INFO, "Fallback system proxy resolver: https_proxy={0}", httpsProxyRaw); //NOI18N
84
            LOGGER.log(Level.INFO, "Fallback system proxy resolver: socks_proxy={0}", socksProxyRaw); //NOI18N
85
            LOGGER.log(Level.INFO, "Fallback system proxy resolver: no_proxy={0}", noProxyRaw); //NOI18N
86
            
87
            String httpProxy = prepareVariable(httpProxyRaw);
88
            String httpsProxy = prepareVariable(httpsProxyRaw);
89
            String socksProxy = prepareVariable(socksProxyRaw);
90
            String[] noProxyHosts = noProxyRaw == null ? new String[0] : noProxyRaw.split(COMMA);                   
91
            
92
            return new NetworkProxySettings(httpProxy, httpsProxy, socksProxy, noProxyHosts);
93
        }
94
        
95
        LOGGER.log(Level.INFO, "Fallback system proxy resolver: no http_proxy variable found"); //NOI18N
96
        return new NetworkProxySettings();
97
    }
98
99
    private String prepareVariable(String variable) {
100
        if (variable == null) {
101
            return EMPTY_STRING;
102
        }
103
104
        // remove slash at the end if present
105
        if (variable.endsWith(SLASH)) {
106
            variable = variable.substring(0, variable.length() - 1);
107
        }
108
109
        // remove username and password if present
110
        if (variable.contains(AT)) {
111
            variable = variable.substring(variable.lastIndexOf(AT) + 1);
112
        }
113
        
114
        // remove protocol prefix if presented
115
        if (variable.contains(PROTOCOL_PREXIF_SEPARATOR)) {
116
            variable = variable.substring(variable.indexOf(PROTOCOL_PREXIF_SEPARATOR) + 3);
117
        }
118
119
        return variable;
120
    }       
121
}
(-)3bff97f36acc (+232 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2013 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2013 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.core.network.proxy.gnome;
43
44
import java.io.BufferedReader;
45
import java.io.IOException;
46
import java.util.HashMap;
47
import java.util.Map;
48
import java.util.logging.Level;
49
import java.util.logging.Logger;
50
import org.netbeans.core.network.proxy.NetworkProxySettings;
51
import static org.netbeans.core.network.proxy.gnome.GnomeNetworkProxy.executeCommand;
52
53
/**
54
 *
55
 * @author lfischme
56
 */
57
public class GconfNetworkProxy {
58
    
59
    private final static Logger LOGGER = Logger.getLogger(GconfNetworkProxy.class.getName());
60
    
61
    private final static String EQUALS = "="; //NOI18N
62
    private final static String COLON = ","; //NOI18N
63
    private final static String SQ_BRACKET_LEFT = "["; //NOI18N
64
    private final static String SQ_BRACKET_RIGHT = "]"; //NOI18N
65
    
66
    protected final static String GCONF_PATH = "/usr/bin/gconftool-2"; //NOI18N
67
    private final static String GCONF_ARGUMENT_LIST_RECURSIVELY = " -R "; //NOI18N
68
    private final static String GCONF_NODE_PROXY = "/system/proxy"; //NOI18N
69
    private final static String GCONF_NODE_HTTP_PROXY = "/system/http_proxy"; //NOI18N
70
    private final static String GCONF_KEY_MODE = "mode"; //NOI18N
71
    private final static String GCONF_KEY_PAC_URL = "autoconfig_url"; //NOI18N
72
    private final static String GCONF_KEY_HTTP_ALL = "use_http_proxy"; //NOI18N
73
    private final static String GCONF_KEY_HTTP_HOST = "host"; //NOI18N
74
    private final static String GCONF_KEY_HTTP_PORT = "port"; //NOI18N
75
    private final static String GCONF_KEY_HTTPS_HOST = "secure_host"; //NOI18N
76
    private final static String GCONF_KEY_HTTPS_PORT = "secure_port"; //NOI18N
77
    private final static String GCONF_KEY_SOCKS_HOST = "socks_host"; //NOI18N
78
    private final static String GCONF_KEY_SOCKS_PORT = "socks_port"; //NOI18N
79
    private final static String GCONF_KEY_IGNORE_HOSTS = "ignore_hosts"; //NOI18N
80
    private final static String GCONF_VALUE_NONE = "none"; //NOI18N
81
    private final static String GCONF_VALUE_AUTO = "auto"; //NOI18N
82
    private final static String GCONF_VALUE_MANUAL = "manual"; //NOI18N
83
84
    /**
85
     * Returns network proxy settings - retrieved via gconftool.
86
     * 
87
     * @return network proxy settings via GSettings.
88
     */
89
    protected static NetworkProxySettings getNetworkProxySettings() {
90
        LOGGER.log(Level.FINE, "GConf system proxy resolver started."); //NOI18N
91
        Map<String, String> proxyProperties = getGconfMap(GCONF_NODE_PROXY);
92
                        
93
        String proxyMode = proxyProperties.get(GCONF_KEY_MODE);
94
        if (proxyMode == null) {
95
            LOGGER.log(Level.SEVERE, "GConf proxy mode is null.");
96
            return new NetworkProxySettings(false);
97
        }        
98
        
99
        if (proxyMode.equals(GCONF_VALUE_NONE)) {
100
            LOGGER.log(Level.INFO, "GConf system proxy resolver: direct connection"); //NOI18N
101
            return new NetworkProxySettings();
102
        }
103
        
104
        if (proxyMode.equals(GCONF_VALUE_AUTO)) {
105
            String pacUrl = proxyProperties.get(GCONF_KEY_PAC_URL);
106
            
107
            LOGGER.log(Level.INFO, "GConf system proxy resolver: auto - PAC ({0})", pacUrl); //NOI18N
108
            
109
            if (pacUrl != null) {
110
                return new NetworkProxySettings(pacUrl);             
111
            } else {
112
                return new NetworkProxySettings("");
113
            }
114
        }
115
        
116
        if (proxyMode.equals(GCONF_VALUE_MANUAL)) {
117
            proxyProperties.putAll(getGconfMap(GCONF_NODE_HTTP_PROXY));
118
            
119
            String httpProxyAll = proxyProperties.get(GCONF_KEY_HTTP_ALL);
120
            String httpProxyHost = proxyProperties.get(GCONF_KEY_HTTP_HOST);
121
            String httpProxyPort = proxyProperties.get(GCONF_KEY_HTTP_PORT);
122
            String noProxyHosts = proxyProperties.get(GCONF_KEY_IGNORE_HOSTS);
123
            
124
            LOGGER.log(Level.INFO, "GConf system proxy resolver: manual - http for all ({0})", httpProxyAll); //NOI18N
125
            LOGGER.log(Level.INFO, "GConf system proxy resolver: manual - http host ({0})", httpProxyHost); //NOI18N
126
            LOGGER.log(Level.INFO, "GConf system proxy resolver: manual - http port ({0})", httpProxyPort); //NOI18N
127
            LOGGER.log(Level.INFO, "GConf system proxy resolver: manual - ho proxy hosts ({0})", noProxyHosts); //NOI18N
128
            
129
            if (httpProxyAll != null && Boolean.parseBoolean(httpProxyAll)) {
130
                return new NetworkProxySettings(httpProxyHost, httpProxyPort, getNoProxyHosts(noProxyHosts));
131
            } else {
132
                String httpsProxyHost = proxyProperties.get(GCONF_KEY_HTTPS_HOST);
133
                String httpsProxyPort = proxyProperties.get(GCONF_KEY_HTTPS_PORT);
134
                String socksProxyHost = proxyProperties.get(GCONF_KEY_SOCKS_HOST);
135
                String socksProxyPort = proxyProperties.get(GCONF_KEY_SOCKS_PORT);
136
                
137
                LOGGER.log(Level.INFO, "GConf system proxy resolver: manual - https host ({0})", httpsProxyHost); //NOI18N
138
                LOGGER.log(Level.INFO, "GConf system proxy resolver: manual - https port ({0})", httpsProxyPort); //NOI18N
139
                LOGGER.log(Level.INFO, "GConf system proxy resolver: manual - socks host ({0})", socksProxyHost); //NOI18N
140
                LOGGER.log(Level.INFO, "GConf system proxy resolver: manual - socks port ({0})", socksProxyPort); //NOI18N
141
                
142
                return new NetworkProxySettings(httpProxyHost, httpProxyPort, 
143
                        httpsProxyHost, httpsProxyPort, 
144
                        socksProxyHost, socksProxyPort, getNoProxyHosts(noProxyHosts));
145
            }
146
        }
147
        
148
        return new NetworkProxySettings(false);
149
    }    
150
    
151
    /**
152
     * Returns map of properties retrieved from gconftool-2.
153
     * 
154
     * Executes the command "/usr/bin/gconftool-2 -R [node]".
155
     * 
156
     * @param gconfNode Node for which the properties should be returned.
157
     * @return Map of properties retrieved from gconftool-2.
158
     */
159
    private static Map<String, String> getGconfMap(String gconfNode) {
160
        Map<String, String> map = new HashMap<String, String>();
161
        
162
        String command = GCONF_PATH + GCONF_ARGUMENT_LIST_RECURSIVELY + gconfNode;
163
        
164
        try {
165
            BufferedReader reader = executeCommand(command);
166
            if (reader != null) {
167
                String line = reader.readLine();
168
                while (line != null) {
169
                    String key = getKey(line).toLowerCase();                                   
170
                    if (key != null && !key.isEmpty()) {
171
                        String value = getValue(line); 
172
                        map.put(key, value);
173
                    }
174
                    line = reader.readLine();
175
                }
176
            } else {
177
                return map;
178
            }
179
        } catch (IOException ioe) {
180
            LOGGER.log(Level.SEVERE, "Cannot read line: " + command, ioe); //NOI18N
181
        }
182
183
        return map;
184
    }
185
    
186
    /**
187
     * Returns the key for one line response from gconftool-2.
188
     * 
189
     * @param line Line from gconftool-2 response.
190
     * @return The key for one line response from gconftool-2.
191
     */
192
    private static String getKey(String line) {        
193
        return line.substring(0, line.indexOf(EQUALS)).trim();
194
    }
195
196
    /**
197
     * Returns the value for one line response from gconftool-2.
198
     * 
199
     * @param line Line from gconftool-2 response.
200
     * @return The value for one line response from gconftool-2.
201
     */
202
    private static String getValue(String line) {
203
        return line.substring(line.indexOf(EQUALS) + 1).trim();
204
    }
205
    
206
    /**
207
     * Returns array of Strings of no proxy hosts.
208
     * 
209
     * The value responding to "ignore_hosts" key.
210
     * 
211
     * Parses the value returned from gconftool-2.
212
     * Usually [host1,host2,host3]
213
     * 
214
     * @param noProxyHostsString The value returned from gconftool-2.
215
     * @return Array of Strings of no proxy hosts.
216
     */
217
    private static String[] getNoProxyHosts(String noProxyHostsString) {
218
        if (noProxyHostsString != null && !noProxyHostsString.isEmpty()) {
219
            if (noProxyHostsString.startsWith(SQ_BRACKET_LEFT)) {
220
                noProxyHostsString = noProxyHostsString.substring(1);
221
            }
222
            
223
            if (noProxyHostsString.endsWith(SQ_BRACKET_RIGHT)) {
224
                noProxyHostsString = noProxyHostsString.substring(0, noProxyHostsString.length() - 1);
225
            }
226
            
227
            return noProxyHostsString.split(COLON);
228
        }
229
            
230
        return new String[0];
231
    }
232
}
(-)3bff97f36acc (+93 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2013 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2013 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.core.network.proxy.gnome;
43
44
import java.io.BufferedReader;
45
import java.io.File;
46
import java.io.IOException;
47
import java.io.InputStreamReader;
48
import java.util.logging.Level;
49
import java.util.logging.Logger;
50
import org.netbeans.core.network.proxy.NetworkProxyResolver;
51
import org.netbeans.core.network.proxy.NetworkProxySettings;
52
53
/**
54
 *
55
 * @author lfischme
56
 */
57
public class GnomeNetworkProxy implements NetworkProxyResolver{
58
    
59
    private final static Logger LOGGER = Logger.getLogger(GnomeNetworkProxy.class.getName());
60
        
61
    @Override
62
    public NetworkProxySettings getNetworkProxySettings() {
63
        if (new File(GsettingsNetworkProxy.GSETTINGS_PATH).exists()) {
64
            return GsettingsNetworkProxy.getNetworkProxySettings();
65
        } else if (new File(GconfNetworkProxy.GCONF_PATH).exists()) {
66
            return GconfNetworkProxy.getNetworkProxySettings();
67
        } else {
68
            return new NetworkProxySettings(false);
69
        }
70
    }
71
    
72
    /**
73
     * 
74
     * 
75
     * @param command
76
     * @return 
77
     */
78
    protected static BufferedReader executeCommand(String command) {
79
        BufferedReader reader = null;
80
        
81
        try {
82
            Process p = Runtime.getRuntime().exec(command);
83
            p.waitFor();
84
            reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
85
        } catch (IOException ioe) {
86
            LOGGER.log(Level.SEVERE, "Cannot execute command: " + command, ioe);
87
        } catch (InterruptedException ie) {
88
            LOGGER.log(Level.SEVERE, "Cannot execute command: " + command, ie);
89
        }
90
        
91
        return reader;
92
    }        
93
}
(-)3bff97f36acc (+245 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2013 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2013 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.core.network.proxy.gnome;
43
44
import java.io.BufferedReader;
45
import java.io.IOException;
46
import java.util.HashMap;
47
import java.util.Map;
48
import java.util.logging.Level;
49
import java.util.logging.Logger;
50
import org.netbeans.core.network.proxy.NetworkProxySettings;
51
import static org.netbeans.core.network.proxy.gnome.GnomeNetworkProxy.executeCommand;
52
53
/**
54
 *
55
 * @author lfischme
56
 */
57
public class GsettingsNetworkProxy {
58
    
59
    private final static Logger LOGGER = Logger.getLogger(GsettingsNetworkProxy.class.getName());
60
    
61
    private final static String EMPTY_STRING = ""; //NOI18N
62
    private final static String SPACE = " "; //NOI18N
63
    private final static String DOT = "."; //NOI18N
64
    private final static String COLON = ","; //NOI18N
65
    private final static String SINGLE_QUOTE = "'"; //NOI18N
66
    private final static String SQ_BRACKET_LEFT = "["; //NOI18N
67
    private final static String SQ_BRACKET_RIGHT = "]"; //NOI18N
68
    
69
    protected final static String GSETTINGS_PATH = "/usr/bin/gsettings"; //NOI18N
70
    private final static String GSETTINGS_ARGUMENT_LIST_RECURSIVELY = " list-recursively "; //NOI18N
71
    private final static String GSETTINGS_PROXY_SCHEMA = "org.gnome.system.proxy"; //NOI18N
72
    
73
    private final static String GSETTINGS_KEY_MODE = "org.gnome.system.proxy.mode"; //NOI18N
74
    private final static String GSETTINGS_KEY_PAC_URL = "org.gnome.system.proxy.autoconfig-url"; //NOI18N
75
    private final static String GSETTINGS_KEY_HTTP_ALL = "org.gnome.system.proxy.http.use-same-proxy"; //NOI18N
76
    private final static String GSETTINGS_KEY_HTTP_HOST = "org.gnome.system.proxy.http.host"; //NOI18N
77
    private final static String GSETTINGS_KEY_HTTP_PORT = "org.gnome.system.proxy.http.port"; //NOI18N
78
    private final static String GSETTINGS_KEY_HTTPS_HOST = "org.gnome.system.proxy.https.host"; //NOI18N
79
    private final static String GSETTINGS_KEY_HTTPS_PORT = "org.gnome.system.proxy.https.port"; //NOI18N
80
    private final static String GSETTINGS_KEY_SOCKS_HOST = "org.gnome.system.proxy.socks.host"; //NOI18N
81
    private final static String GSETTINGS_KEY_SOCKS_PORT = "org.gnome.system.proxy.socks.port"; //NOI18N
82
    private final static String GSETTINGS_KEY_IGNORE_HOSTS = "org.gnome.system.proxy.ignore-hosts"; //NOI18N       
83
    private final static String GSETTINGS_VALUE_NONE = "none"; //NOI18N
84
    private final static String GSETTINGS_VALUE_AUTO = "auto"; //NOI18N
85
    private final static String GSETTINGS_VALUE_MANUAL = "manual"; //NOI18N
86
87
    /**
88
     * Returns network proxy settings - retrieved via GSettings (preferred).
89
     * 
90
     * @return network proxy settings via GSettings.
91
     */
92
    protected static NetworkProxySettings getNetworkProxySettings() {
93
        LOGGER.log(Level.FINE, "GSettings system proxy resolver started."); //NOI18N
94
        Map<String, String> proxyProperties = getGsettingsMap();
95
                        
96
        String proxyMode = proxyProperties.get(GSETTINGS_KEY_MODE);
97
        if (proxyMode == null) {
98
            LOGGER.log(Level.SEVERE, "GSettings proxy mode is null.");
99
            return new NetworkProxySettings(false);
100
        }        
101
        
102
        if (proxyMode.equals(GSETTINGS_VALUE_NONE)) {
103
            LOGGER.log(Level.INFO, "GSettings system proxy resolver: direct connection"); //NOI18N
104
            return new NetworkProxySettings();
105
        }
106
        
107
        if (proxyMode.equals(GSETTINGS_VALUE_AUTO)) {
108
            String pacUrl = proxyProperties.get(GSETTINGS_KEY_PAC_URL);
109
            
110
            LOGGER.log(Level.INFO, "GSettings system proxy resolver: auto - PAC ({0})", pacUrl); //NOI18N
111
            
112
            if (pacUrl != null) {
113
                return new NetworkProxySettings(pacUrl);             
114
            } else {
115
                return new NetworkProxySettings("");
116
            }
117
        }
118
        
119
        if (proxyMode.equals(GSETTINGS_VALUE_MANUAL)) {            
120
            String httpProxyAll = proxyProperties.get(GSETTINGS_KEY_HTTP_ALL);
121
            String httpProxyHost = proxyProperties.get(GSETTINGS_KEY_HTTP_HOST);
122
            String httpProxyPort = proxyProperties.get(GSETTINGS_KEY_HTTP_PORT);
123
            String noProxyHosts = proxyProperties.get(GSETTINGS_KEY_IGNORE_HOSTS);
124
            
125
            LOGGER.log(Level.INFO, "GSettings system proxy resolver: manual - http for all ({0})", httpProxyAll); //NOI18N
126
            LOGGER.log(Level.INFO, "GSettings system proxy resolver: manual - http host ({0})", httpProxyHost); //NOI18N
127
            LOGGER.log(Level.INFO, "GSettings system proxy resolver: manual - http port ({0})", httpProxyPort); //NOI18N
128
            LOGGER.log(Level.INFO, "GSettings system proxy resolver: manual - ho proxy hosts ({0})", noProxyHosts); //NOI18N
129
            
130
            if (httpProxyAll != null && Boolean.parseBoolean(httpProxyAll)) {
131
                return new NetworkProxySettings(httpProxyHost, httpProxyPort, getNoProxyHosts(noProxyHosts));
132
            } else {
133
                String httpsProxyHost = proxyProperties.get(GSETTINGS_KEY_HTTPS_HOST);
134
                String httpsProxyPort = proxyProperties.get(GSETTINGS_KEY_HTTPS_PORT);
135
                String socksProxyHost = proxyProperties.get(GSETTINGS_KEY_SOCKS_HOST);
136
                String socksProxyPort = proxyProperties.get(GSETTINGS_KEY_SOCKS_PORT);
137
                
138
                LOGGER.log(Level.INFO, "GSettings system proxy resolver: manual - https host ({0})", httpsProxyHost); //NOI18N
139
                LOGGER.log(Level.INFO, "GSettings system proxy resolver: manual - https port ({0})", httpsProxyPort); //NOI18N
140
                LOGGER.log(Level.INFO, "GSettings system proxy resolver: manual - socks host ({0})", socksProxyHost); //NOI18N
141
                LOGGER.log(Level.INFO, "GSettings system proxy resolver: manual - socks port ({0})", socksProxyPort); //NOI18N
142
                
143
                return new NetworkProxySettings(httpProxyHost, httpProxyPort, 
144
                        httpsProxyHost, httpsProxyPort, 
145
                        socksProxyHost, socksProxyPort, getNoProxyHosts(noProxyHosts));
146
            }
147
        }
148
        
149
        return new NetworkProxySettings(false);
150
    }    
151
    
152
    /**
153
     * Returns map of properties retrieved from GSettings.
154
     * 
155
     * Executes the command "/usr/bin/gsettings list-recursively org.gnome.system.proxy".
156
     * 
157
     * @return Map of properties retrieved from GSettings.
158
     */
159
    private static Map<String, String> getGsettingsMap() {
160
        Map<String, String> map = new HashMap<String, String>();
161
        
162
        String command = GSETTINGS_PATH + GSETTINGS_ARGUMENT_LIST_RECURSIVELY + GSETTINGS_PROXY_SCHEMA;
163
        
164
        try {
165
            BufferedReader reader = executeCommand(command);
166
            String line = reader.readLine();
167
            while (line != null) {
168
                String key = getKey(line).toLowerCase();                                                    
169
                if (key != null && !key.isEmpty()) {
170
                    String value = getValue(line);
171
                    map.put(key, value);
172
                }                   
173
                line = reader.readLine();
174
            }
175
        } catch (IOException ioe) {
176
            LOGGER.log(Level.SEVERE, "Cannot read line: " + command, ioe); //NOI18N
177
        }
178
179
        return map;
180
    }
181
    
182
    /**
183
     * Returns the key for one line response from GSettings.
184
     * 
185
     * @param line Line from GSettings response.
186
     * @return The key for one line response from GSettings.
187
     */
188
    private static String getKey(String line) {
189
        String[] splittedLine = line.split(SPACE);
190
        
191
        if (splittedLine.length >= 2) {
192
            return splittedLine[0] + DOT + splittedLine[1];
193
        } else {
194
            return null; 
195
        }
196
    }
197
198
    /**
199
     * Returns the value for one line response from GSettings.
200
     * 
201
     * @param line Line from GSettings response.
202
     * @return The value for one line response from GSettings.
203
     */
204
    private static String getValue(String line) {
205
        String[] splittedLine = line.split(SPACE);
206
        
207
        if (splittedLine.length > 2) {
208
            StringBuilder value = new StringBuilder();
209
            for (int i = 2; i < splittedLine.length; i++) {
210
                value.append(splittedLine[i]);
211
            }
212
            return value.toString().replaceAll(SINGLE_QUOTE, EMPTY_STRING);
213
        } else {
214
            return null;
215
        }
216
    }
217
    
218
    /**
219
     * Returns array of Strings of no proxy hosts.
220
     * 
221
     * The value responding to "ignore_hosts" key.
222
     * 
223
     * Parses the value returned from GSettings.
224
     * Usually ['host1', 'host2', 'host3']
225
     * But value is in form [host1,host2,host3]
226
     * 
227
     * @param noProxyHostsString The value returned from GSettingsc.
228
     * @return Array of Strings of no proxy hosts.
229
     */
230
    private static String[] getNoProxyHosts(String noProxyHostsString) {
231
        if (noProxyHostsString != null && !noProxyHostsString.isEmpty()) {
232
            if (noProxyHostsString.startsWith(SQ_BRACKET_LEFT)) {
233
                noProxyHostsString = noProxyHostsString.substring(1);
234
            }
235
            
236
            if (noProxyHostsString.endsWith(SQ_BRACKET_RIGHT)) {
237
                noProxyHostsString = noProxyHostsString.substring(0, noProxyHostsString.length() - 1);
238
            }
239
            
240
            return noProxyHostsString.split(COLON);
241
        }
242
            
243
        return new String[0];
244
    }    
245
}
(-)3bff97f36acc (+220 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2013 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2013 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.core.network.proxy.kde;
43
44
import java.io.BufferedReader;
45
import java.io.DataInputStream;
46
import java.io.File;
47
import java.io.FileInputStream;
48
import java.io.FileNotFoundException;
49
import java.io.IOException;
50
import java.io.InputStreamReader;
51
import java.util.HashMap;
52
import java.util.Map;
53
import java.util.logging.Level;
54
import java.util.logging.Logger;
55
import org.netbeans.core.network.proxy.NetworkProxyResolver;
56
import org.netbeans.core.network.proxy.NetworkProxySettings;
57
58
/**
59
 *
60
 * @author lfischme
61
 */
62
public class KdeNetworkProxy implements NetworkProxyResolver {
63
    
64
    private final static Logger LOGGER = Logger.getLogger(KdeNetworkProxy.class.getName());
65
66
    private final static String EMPTY_STRING = ""; //NOI18N
67
    private final static String SPACE = " "; //NOI18N
68
    private final static String EQUALS = "="; //NOI18N
69
    private final static String COLON = ":"; //NOI18N
70
    private final static String COMMA = ","; //NOI18N
71
    private final static String SQ_BRACKET_LEFT = "["; //NOI18N
72
    private final static String HOME = "HOME"; //NOI18N
73
    private final static String KIOSLAVERC_PROXY_SETTINGS_GROUP = "[Proxy Settings]"; //NOI18N
74
    private final static String KIOSLAVERC_PROXY_TYPE = "ProxyType"; //NOI18N
75
    private final static String KIOSLAVERC_PROXY_CONFIG_SCRIPT = "Proxy Config Script"; //NOI18N
76
    private final static String KIOSLAVERC_HTTP_PROXY = "httpProxy"; //NOI18N
77
    private final static String KIOSLAVERC_HTTPS_PROXY = "httpsProxy"; //NOI18N
78
    private final static String KIOSLAVERC_SOCKS_PROXY = "socksProxy"; //NOI18N
79
    private final static String KIOSLAVERC_NO_PROXY_FOR = "NoProxyFor"; //NOI18N
80
    private final static String KIOSLAVERC_PROXY_TYPE_NONE = "0"; //NOI18N
81
    private final static String KIOSLAVERC_PROXY_TYPE_MANUAL = "1"; //NOI18N
82
    private final static String KIOSLAVERC_PROXY_TYPE_PAC = "2"; //NOI18N
83
    private final static String KIOSLAVERC_PROXY_TYPE_AUTO = "3"; //NOI18N
84
    private final static String KIOSLAVERC_PROXY_TYPE_SYSTEM = "4"; //NOI18N    
85
    private final static String KIOSLAVERC_PATH_IN_HOME = ".kde/share/config/kioslaverc"; //NOI18N 
86
    private final String KIOSLAVERC_PATH;
87
88
    public KdeNetworkProxy() {
89
        KIOSLAVERC_PATH = getKioslavercPath();
90
    }
91
92
    @Override
93
    public NetworkProxySettings getNetworkProxySettings() {
94
        LOGGER.log(Level.FINE, "KDE system proxy resolver started."); //NOI18N
95
        Map<String, String> kioslavercMap = getKioslavercMap();
96
97
        String proxyType = kioslavercMap.get(KIOSLAVERC_PROXY_TYPE);
98
        if (proxyType == null) {
99
            LOGGER.log(Level.WARNING, "KDE system proxy resolver: The kioslaverc key not found ({0})", KIOSLAVERC_PROXY_TYPE); //NOI18N
100
            return new NetworkProxySettings(false);
101
        }
102
103
        if (proxyType.equals(KIOSLAVERC_PROXY_TYPE_NONE) || proxyType.equals(KIOSLAVERC_PROXY_TYPE_AUTO)) {
104
            LOGGER.log(Level.INFO, "KDE system proxy resolver: direct (proxy type: {0})", proxyType); //NOI18N
105
            return new NetworkProxySettings();
106
        }
107
108
        if (proxyType.equals(KIOSLAVERC_PROXY_TYPE_PAC)) {
109
            LOGGER.log(Level.INFO, "KDE system proxy resolver: auto - PAC"); //NOI18N
110
            String pacFileUrl = kioslavercMap.get(KIOSLAVERC_PROXY_CONFIG_SCRIPT);
111
            if (pacFileUrl != null) {
112
                LOGGER.log(Level.INFO, "KDE system proxy resolver: PAC URL ({0})", pacFileUrl); //NOI18N
113
                return new NetworkProxySettings(pacFileUrl);
114
            } else {
115
                LOGGER.log(Level.INFO, "KDE system proxy resolver: PAC URL null value"); //NOI18N
116
                return new NetworkProxySettings(false);
117
            }
118
        }
119
120
        if (proxyType.equals(KIOSLAVERC_PROXY_TYPE_MANUAL) || proxyType.equals(KIOSLAVERC_PROXY_TYPE_SYSTEM)) {
121
            LOGGER.log(Level.INFO, "KDE system proxy resolver: manual (proxy type: {0})", proxyType); //NOI18N
122
            
123
            String httpProxy = kioslavercMap.get(KIOSLAVERC_HTTP_PROXY);
124
            String httpsProxy = kioslavercMap.get(KIOSLAVERC_HTTPS_PROXY);
125
            String socksProxy = kioslavercMap.get(KIOSLAVERC_SOCKS_PROXY);
126
            String noProxyFor = kioslavercMap.get(KIOSLAVERC_NO_PROXY_FOR);
127
            
128
            LOGGER.log(Level.INFO, "KDE system proxy resolver: http proxy ({0})", httpProxy); //NOI18N
129
            LOGGER.log(Level.INFO, "KDE system proxy resolver: https proxy ({0})", httpsProxy); //NOI18N
130
            LOGGER.log(Level.INFO, "KDE system proxy resolver: socks proxy ({0})", socksProxy); //NOI18N
131
            LOGGER.log(Level.INFO, "KDE system proxy resolver: no proxy ({0})", noProxyFor); //NOI18N
132
            
133
            if (proxyType.equals(KIOSLAVERC_PROXY_TYPE_MANUAL)) {
134
                httpProxy = httpProxy == null ? EMPTY_STRING : httpProxy.trim().replaceAll(SPACE, COLON);
135
                httpsProxy = httpsProxy == null ? EMPTY_STRING : httpsProxy.trim().replaceAll(SPACE, COLON);
136
                socksProxy = socksProxy == null ? EMPTY_STRING : socksProxy.trim().replaceAll(SPACE, COLON);
137
            }
138
            
139
            String[] noProxyHosts = getNoProxyHosts(noProxyFor);
140
            
141
            return new NetworkProxySettings(httpProxy, httpsProxy, socksProxy, noProxyHosts);
142
        }
143
144
        return new NetworkProxySettings(false);
145
    }
146
147
    /**
148
     * Raturns map of keys and values from kioslaverc group Proxy settings.
149
     * 
150
     * Reads "[userhome]/.kde/share/config/kioslaverc" file. 
151
     * 
152
     * @return Map of keys and values from kioslaverc group Proxy settings.
153
     */
154
    private Map<String, String> getKioslavercMap() {
155
        File kioslavercFile = new File(KIOSLAVERC_PATH);
156
        Map<String, String> map = new HashMap<String, String>();
157
158
        if (kioslavercFile.exists()) {
159
            try {
160
                FileInputStream fis = new FileInputStream(kioslavercFile);
161
                DataInputStream dis = new DataInputStream(fis);
162
                BufferedReader br = new BufferedReader(new InputStreamReader(dis));
163
                String line;
164
                boolean inGroup = false;
165
                while ((line = br.readLine()) != null) {
166
                    if (inGroup) {
167
                        if (line.contains(EQUALS)) {
168
                            int indexOfEquals = line.indexOf(EQUALS);
169
                            String key = line.substring(0, indexOfEquals);
170
                            String value = line.substring(indexOfEquals + 1);
171
                            map.put(key, value);
172
                        } else if (line.startsWith(SQ_BRACKET_LEFT)) {
173
                            break;
174
                        }
175
                    } else if (line.startsWith(KIOSLAVERC_PROXY_SETTINGS_GROUP)) {
176
                        inGroup = true;
177
                    }
178
                }
179
                dis.close();
180
            } catch (FileNotFoundException fnfe) {
181
                LOGGER.log(Level.SEVERE, "Cannot read file: ", fnfe);
182
            } catch (IOException ioe) {
183
                LOGGER.log(Level.SEVERE, "Cannot read file: ", ioe);
184
            }
185
        } else {
186
            LOGGER.log(Level.WARNING, "KDE system proxy resolver: The kioslaverc file not found ({0})", KIOSLAVERC_PATH);
187
        }                
188
189
        return map;
190
    }
191
192
    /**
193
     * Returns path of the kioslaverc config file.
194
     * 
195
     * @return Path of the kioslaverc config file.
196
     */
197
    private String getKioslavercPath() {
198
        String homePath = System.getenv(HOME);
199
200
        if (homePath != null) {
201
            return homePath + File.separator + KIOSLAVERC_PATH_IN_HOME;
202
        } else {
203
            return EMPTY_STRING;
204
        }
205
    }
206
    
207
    /**
208
     * Returns array of Strings of no proxy hosts.
209
     * 
210
     * @param noProxyHostsString No proxy host in one string separated by comma.
211
     * @return Array of Strings of no proxy hosts.
212
     */
213
    private static String[] getNoProxyHosts(String noProxyHostsString) {
214
        if (noProxyHostsString != null && !noProxyHostsString.isEmpty()) {
215
            return noProxyHostsString.split(COMMA);
216
        }
217
            
218
        return new String[0];
219
    }
220
}
(-)3bff97f36acc (+36 lines)
Added Link Here
1
package org.netbeans.core.network.proxy.mac;
2
3
import com.sun.jna.Library;
4
import com.sun.jna.Native;
5
import com.sun.jna.Pointer;
6
import com.sun.jna.Structure;
7
8
/**
9
 *
10
 * @author lfischme
11
 */
12
public interface MacCoreFoundationLibrary extends Library {
13
    MacCoreFoundationLibrary LIBRARY = (MacCoreFoundationLibrary) Native.loadLibrary("CoreFoundation", MacCoreFoundationLibrary.class);
14
    
15
    public boolean CFDictionaryGetValueIfPresent(Pointer dictionary, Pointer key, Pointer[] returnValue);
16
    
17
    public Pointer CFDictionaryGetValue(Pointer dictionary, Pointer key);
18
    
19
    public Pointer CFStringCreateWithCString(Pointer alloc, byte[] string, Pointer encoding);
20
    
21
    public long CFStringGetLength(Pointer cfStringRef);
22
    
23
    public long CFStringGetMaximumSizeForEncoding(long lenght, int encoding);
24
    
25
    public boolean CFStringGetCString(Pointer cfStringRef, Pointer buffer, long maxSize, int encoding);
26
    
27
    public Pointer CFNumberGetType(Pointer cfNumberRef);
28
    
29
    public boolean CFNumberGetValue(Pointer cfNumberRef, Pointer cfNumberType, Pointer value);
30
31
    public long CFNumberGetByteSize(Pointer cfNumberRef);
32
    
33
    public long CFArrayGetCount(Pointer cfArrayRef);
34
    
35
    public Pointer CFArrayGetValueAtIndex(Pointer cfArrayRef, Pointer cfIndex);
36
}
(-)3bff97f36acc (+258 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2013 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2013 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.core.network.proxy.mac;
43
44
import com.sun.jna.Memory;
45
import com.sun.jna.NativeLibrary;
46
import com.sun.jna.Pointer;
47
import java.util.logging.Level;
48
import java.util.logging.Logger;
49
import org.netbeans.core.network.proxy.NetworkProxyResolver;
50
import org.netbeans.core.network.proxy.NetworkProxySettings;
51
52
/**
53
 *
54
 * @author lfischme
55
 */
56
public class MacNetworkProxy implements NetworkProxyResolver {
57
    
58
    private final static Logger LOGGER = Logger.getLogger(MacNetworkProxy.class.getName());
59
    
60
    private final static MacNetworkProxyLibrary cfNetworkLibrary = MacNetworkProxyLibrary.LIBRARY;
61
    private final static MacCoreFoundationLibrary cfLibrary = MacCoreFoundationLibrary.LIBRARY;
62
    
63
    private final static String COMMA = ","; //NOI18N
64
    
65
    private final static NativeLibrary NETWORK_LIBRARY = NativeLibrary.getInstance("CFNetwork"); //NOI18N
66
    private final static String KEY_AUTO_DISCOVERY_ENABLE = "kCFNetworkProxiesProxyAutoDiscoveryEnable"; //NOI18N
67
    private final static String KEY_PAC_ENABLE = "kCFNetworkProxiesProxyAutoConfigEnable"; //NOI18N
68
    private final static String KEY_PAC_URL = "kCFNetworkProxiesProxyAutoConfigURLString"; //NOI18N
69
    private final static String KEY_HTTP_ENABLE = "kCFNetworkProxiesHTTPEnable"; //NOI18N
70
    private final static String KEY_HTTP_HOST = "kCFNetworkProxiesHTTPProxy"; //NOI18N
71
    private final static String KEY_HTTP_PORT = "kCFNetworkProxiesHTTPPort"; //NOI18N
72
    private final static String KEY_HTTPS_ENABLE = "kCFNetworkProxiesHTTPSEnable"; //NOI18N
73
    private final static String KEY_HTTPS_HOST = "kCFNetworkProxiesHTTPSProxy"; //NOI18N
74
    private final static String KEY_HTTPS_PORT = "kCFNetworkProxiesHTTPSPort"; //NOI18N
75
    private final static String KEY_SOCKS_ENABLE = "kCFNetworkProxiesSOCKSEnable"; //NOI18N
76
    private final static String KEY_SOCKS_HOST = "kCFNetworkProxiesSOCKSProxy"; //NOI18N
77
    private final static String KEY_SOCKS_PORT = "kCFNetworkProxiesSOCKSPort"; //NOI18N
78
    private final static String KEY_EXCEPTIONS_LIST = "kCFNetworkProxiesExceptionsList"; //NOI18N
79
    
80
    @Override
81
    public NetworkProxySettings getNetworkProxySettings() {
82
        LOGGER.log(Level.FINE, "Mac system proxy resolver started."); //NOI18N
83
        Pointer settingsDictionary = cfNetworkLibrary.CFNetworkCopySystemProxySettings(); 
84
85
        Pointer autoDiscoveryEnable = cfLibrary.CFDictionaryGetValue(settingsDictionary, getKeyCFStringRef(KEY_AUTO_DISCOVERY_ENABLE));
86
        if (getIntFromCFNumberRef(autoDiscoveryEnable) != 0) {
87
            LOGGER.log(Level.INFO, "Mac system proxy resolver: auto detect"); //NOI18N
88
            return new NetworkProxySettings();
89
        }
90
        
91
        Pointer pacEnable = cfLibrary.CFDictionaryGetValue(settingsDictionary, getKeyCFStringRef(KEY_PAC_ENABLE));
92
        if (getIntFromCFNumberRef(pacEnable) != 0) {
93
            Pointer[] pacUrlPointer = new Pointer[1];
94
            if (cfLibrary.CFDictionaryGetValueIfPresent(settingsDictionary, getKeyCFStringRef(KEY_PAC_URL), pacUrlPointer)) {
95
                String pacUrl = getStringFromCFStringRef(pacUrlPointer[0]);
96
                
97
                LOGGER.log(Level.INFO, "Mac system proxy resolver: auto - PAC ({0})", pacUrl); //NOI18N
98
                return new NetworkProxySettings(pacUrl);
99
            }
100
        }
101
        
102
        Pointer httpEnable = cfLibrary.CFDictionaryGetValue(settingsDictionary, getKeyCFStringRef(KEY_HTTP_ENABLE));
103
        Pointer httpsEnable = cfLibrary.CFDictionaryGetValue(settingsDictionary, getKeyCFStringRef(KEY_HTTPS_ENABLE));
104
        Pointer socksEnable = cfLibrary.CFDictionaryGetValue(settingsDictionary, getKeyCFStringRef(KEY_SOCKS_ENABLE));
105
        if (getIntFromCFNumberRef(httpEnable) != 0 || getIntFromCFNumberRef(httpsEnable) != 0 || getIntFromCFNumberRef(socksEnable) != 0) {
106
            String httpHost = getStringFromCFStringRef(getValueIfExists(settingsDictionary, KEY_HTTP_HOST));
107
            String httpPort = getStringFromCFNumberRef(getValueIfExists(settingsDictionary, KEY_HTTP_PORT));
108
            String httpsHost = getStringFromCFStringRef(getValueIfExists(settingsDictionary, KEY_HTTPS_HOST));
109
            String httpsPort = getStringFromCFNumberRef(getValueIfExists(settingsDictionary, KEY_HTTPS_PORT));
110
            String socksHost = getStringFromCFStringRef(getValueIfExists(settingsDictionary, KEY_SOCKS_HOST));
111
            String socksPort = getStringFromCFNumberRef(getValueIfExists(settingsDictionary, KEY_SOCKS_PORT));            
112
            String[] noProxyHosts = getNoProxyHosts(getValueIfExists(settingsDictionary, KEY_EXCEPTIONS_LIST));
113
            
114
            LOGGER.log(Level.INFO, "Mac system proxy resolver: manual - http host ({0})", httpHost); //NOI18N
115
            LOGGER.log(Level.INFO, "Mac system proxy resolver: manual - http port ({0})", httpPort); //NOI18N
116
            LOGGER.log(Level.INFO, "Mac system proxy resolver: manual - https host ({0})", httpsHost); //NOI18N
117
            LOGGER.log(Level.INFO, "Mac system proxy resolver: manual - https port ({0})", httpsPort); //NOI18N
118
            LOGGER.log(Level.INFO, "Mac system proxy resolver: manual - socks host ({0})", socksHost); //NOI18N
119
            LOGGER.log(Level.INFO, "Mac system proxy resolver: manual - socks port ({0})", socksPort); //NOI18N
120
            LOGGER.log(Level.INFO, "Mac system proxy resolver: manual - no proxy hosts ({0})", getStringFromArray(noProxyHosts)); //NOI18N
121
            
122
            return new NetworkProxySettings(httpHost, httpPort, httpsHost, httpsPort, socksHost, socksPort, noProxyHosts);
123
        }
124
        
125
        return new NetworkProxySettings(false);
126
    }
127
    
128
    /**
129
     * Converts String key object to CFString key object.
130
     * 
131
     * @param key String key
132
     * @return CFString key object pointer
133
     */
134
    private Pointer getKeyCFStringRef(String key) {
135
        return NETWORK_LIBRARY.getGlobalVariableAddress(key).getPointer(0L);
136
    }
137
    
138
    /**
139
     * Converts CFString object to String.
140
     * 
141
     * @param cfStringPointer Pointer to CFString object
142
     * @return String from CFString
143
     */
144
    private String getStringFromCFStringRef(Pointer cfStringPointer) {
145
        if (cfStringPointer != null) {
146
            long lenght = cfLibrary.CFStringGetLength(cfStringPointer);
147
            long maxSize = cfLibrary.CFStringGetMaximumSizeForEncoding(lenght, 0x08000100); // 0x08000100 = UTF-8
148
149
            Pointer buffer = new Memory(maxSize);
150
151
            if (cfLibrary.CFStringGetCString(cfStringPointer, buffer, maxSize, 0x08000100)) { // 0x08000100 = UTF-8
152
                return buffer.getString(0L);
153
            }
154
        }
155
        
156
        return null;
157
    }
158
    
159
    /**
160
     * Converts CFNumber to int.
161
     * 
162
     * @param cfNumberPointer pointer to CFNumber object
163
     * @return int from CFNumber
164
     */
165
    private int getIntFromCFNumberRef(Pointer cfNumberPointer) {
166
        if (cfNumberPointer != null) {
167
            Pointer cfNumberType = cfLibrary.CFNumberGetType(cfNumberPointer);
168
            
169
            long numberSize = cfLibrary.CFNumberGetByteSize(cfNumberPointer);
170
            Pointer numberValue = new Memory(numberSize);
171
            if (cfLibrary.CFNumberGetValue(cfNumberPointer, cfNumberType, numberValue)) {
172
                return numberValue.getInt(0L);
173
            }
174
        }
175
        
176
        return 0;
177
    }
178
    
179
    /**
180
     * Converts CFNumber to String.
181
     * 
182
     * @param cfNumberPointer pointer to CFNumber object
183
     * @return String from CFNumber
184
     */
185
    private String getStringFromCFNumberRef(Pointer cfNumberPointer) {
186
        if (cfNumberPointer != null) {
187
            Pointer cfNumberType = cfLibrary.CFNumberGetType(cfNumberPointer);
188
            
189
            long numberSize = cfLibrary.CFNumberGetByteSize(cfNumberPointer);
190
            Pointer numberValue = new Memory(numberSize);
191
            if (cfLibrary.CFNumberGetValue(cfNumberPointer, cfNumberType, numberValue)) {
192
                return String.valueOf(numberValue.getInt(0L));
193
            }
194
        }
195
        
196
        return null;
197
    }
198
    
199
    /**
200
     * Returns array of Strings with no proxy hosts retrieved from pointer to CFArray.
201
     * 
202
     * @param noProxyHostsPointer Pointer to CFArray of CFStrings with no proxy hosts
203
     * @return Array of Strings with no proxy hosts retrieved from pointer to CFArray.
204
     */
205
    private String[] getNoProxyHosts(Pointer noProxyHostsPointer) {
206
        if (noProxyHostsPointer != null) {
207
            long arrayLenght = cfLibrary.CFArrayGetCount(noProxyHostsPointer);
208
            String[] noProxyHosts = new String[(int) arrayLenght];
209
            for (long i = 0; i < arrayLenght; i++) {
210
                Pointer value = cfLibrary.CFArrayGetValueAtIndex(noProxyHostsPointer, new Pointer(i));
211
                String noProxyHost = getStringFromCFStringRef(value);
212
                noProxyHosts[(int) i] = noProxyHost;
213
            }
214
            // Much more better would be to use CFArrayGetValues method.
215
            // But I was unsuccessful to retrieve value correctly.
216
            // the const void **value is problem in this case
217
            // also CFRange wasn't easy to create (via Structure)
218
            
219
            return noProxyHosts;
220
        }
221
        
222
        return new String[0];
223
    }
224
    
225
    /**
226
     * Returns value from CFDictionary if exists.
227
     * 
228
     * @param settingsDictionary pointer to CFDictionary
229
     * @param key Key for which value should be returned
230
     * @return Value from CFDictionary if exists.
231
     */
232
    private Pointer getValueIfExists(Pointer settingsDictionary, String key) {
233
        Pointer[] returnValue = new Pointer[1];
234
        if (cfLibrary.CFDictionaryGetValueIfPresent(settingsDictionary, getKeyCFStringRef(key), returnValue)) {
235
            return returnValue[0];
236
        } else {
237
            return null;
238
        }
239
    }
240
    
241
    /**
242
     * Returns string from array of strings. Strings are sepparated by comma.
243
     * 
244
     * @param stringArray
245
     * @return String from array of strings. Strings are sepparated by comma.
246
     */
247
    private static String getStringFromArray(String[] stringArray) {
248
        StringBuilder sb = new StringBuilder();
249
        for (int i = 0; i < stringArray.length; i++) {
250
            sb.append(stringArray[i]);
251
            if (i == stringArray.length - 1) {
252
                sb.append(COMMA);
253
            }
254
        }
255
        
256
        return sb.toString();
257
    }
258
}
(-)3bff97f36acc (+15 lines)
Added Link Here
1
package org.netbeans.core.network.proxy.mac;
2
3
import com.sun.jna.Library;
4
import com.sun.jna.Native;
5
import com.sun.jna.Pointer;
6
7
/**
8
 *
9
 * @author lfischme
10
 */
11
public interface MacNetworkProxyLibrary extends Library {
12
    MacNetworkProxyLibrary LIBRARY = (MacNetworkProxyLibrary) Native.loadLibrary("CFNetwork", MacNetworkProxyLibrary.class);
13
    
14
    public Pointer CFNetworkCopySystemProxySettings();
15
}
(-)3bff97f36acc (+154 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2013 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2013 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.core.network.proxy.windows;
43
44
import com.sun.jna.Pointer;
45
import java.util.logging.Level;
46
import java.util.logging.Logger;
47
import org.netbeans.core.network.proxy.NetworkProxyResolver;
48
import org.netbeans.core.network.proxy.NetworkProxySettings;
49
50
/**
51
 *
52
 * @author lfischme
53
 */
54
public class WindowsNetworkProxy implements NetworkProxyResolver {
55
    
56
    private final static Logger LOGGER = Logger.getLogger(WindowsNetworkProxy.class.getName());
57
    
58
    private final static String HTTP_PROPERTY_NAME = "http="; //NOI18N
59
    private final static String HTTPS_PROPERTY_NAME = "https="; //NOI18N
60
    private final static String SOCKS_PROPERTY_NAME = "socks="; //NOI18N
61
    
62
    private final static String SPACE = " "; //NOI18N
63
    private final static String COLON = ":"; //NOI18N
64
    private final static String SEMI_COLON = ";"; //NOI18N
65
    
66
67
    @Override
68
    public NetworkProxySettings getNetworkProxySettings() {
69
        LOGGER.log(Level.FINE, "Windows system proxy resolver started."); //NOI18N
70
        WindowsNetworkProxyLibrary.ProxyConfig.ByReference prxCnf = new WindowsNetworkProxyLibrary.ProxyConfig.ByReference();
71
72
        boolean result = WindowsNetworkProxyLibrary.LIBRARY.WinHttpGetIEProxyConfigForCurrentUser(prxCnf);
73
74
        if (result) {
75
            LOGGER.log(Level.FINE, "Windows system proxy resolver successfully retrieved proxy settings."); //NOI18N
76
            
77
            if (prxCnf.autoDetect) {
78
                LOGGER.log(Level.INFO, "Windows system proxy resolver: auto detect"); //NOI18N
79
                return new NetworkProxySettings();
80
            }
81
82
            Pointer pacFilePointer = prxCnf.pacFile;
83
            if (pacFilePointer != null) {
84
                String pacFileUrl = pacFilePointer.getString(0L, true);
85
                
86
                LOGGER.log(Level.INFO, "Windows system proxy resolver: auto - PAC ({0})", pacFileUrl); //NOI18N                
87
                return new NetworkProxySettings(pacFileUrl);
88
            }
89
90
            Pointer proxyPointer = prxCnf.proxy;
91
            Pointer proxyBypassPointer = prxCnf.proxyBypass;
92
            if (proxyPointer != null) {
93
                String proxyString = proxyPointer.getString(0L, true);
94
                
95
                LOGGER.log(Level.INFO, "Windows system proxy resolver: manual ({0})", proxyString); //NOI18N
96
                
97
                String httpProxy = null;
98
                String httpsProxy = null;
99
                String socksProxy = null;
100
                String[] noProxyHosts;
101
                
102
                if (proxyString != null) {
103
                    proxyString = proxyString.toLowerCase();
104
                }
105
                
106
                if (proxyString.contains(SEMI_COLON)) {
107
                    String[] proxies = proxyString.split(SEMI_COLON);
108
                    for (String singleProxy : proxies) {
109
                        if (singleProxy.startsWith(HTTP_PROPERTY_NAME)) {
110
                            httpProxy = singleProxy.substring(HTTP_PROPERTY_NAME.length());
111
                        } else if (singleProxy.startsWith(HTTPS_PROPERTY_NAME)) {
112
                            httpsProxy = singleProxy.substring(HTTPS_PROPERTY_NAME.length()); 
113
                        } else if (singleProxy.startsWith(SOCKS_PROPERTY_NAME)) {
114
                            socksProxy = singleProxy.substring(SOCKS_PROPERTY_NAME.length());
115
                        }
116
                    }
117
                } else {
118
                    if (proxyString.startsWith(HTTP_PROPERTY_NAME)) {
119
                        proxyString = proxyString.substring(HTTP_PROPERTY_NAME.length());
120
                        httpProxy = proxyString.replace(SPACE, COLON);
121
                    } else if (proxyString.startsWith(HTTPS_PROPERTY_NAME)) {
122
                        proxyString = proxyString.substring(HTTPS_PROPERTY_NAME.length());
123
                        httpsProxy = proxyString.replace(SPACE, COLON);
124
                    } else if (proxyString.startsWith(SOCKS_PROPERTY_NAME)) {
125
                        proxyString = proxyString.substring(SOCKS_PROPERTY_NAME.length());
126
                        socksProxy = proxyString.replace(SPACE, COLON);
127
                    } else {
128
                        httpProxy = proxyString;
129
                        httpsProxy = proxyString;                        
130
                    }
131
                }
132
133
                if (proxyBypassPointer != null) {
134
                    String proxyBypass = proxyBypassPointer.getString(0L, true);
135
                    
136
                    LOGGER.log(Level.INFO, "Windows system proxy resolver: manual - no proxy hosts ({0})", proxyBypass); //NOI18N
137
                    
138
                    noProxyHosts = proxyBypass.split(SEMI_COLON);
139
                } else {
140
                    noProxyHosts = new String[0];
141
                }
142
143
                return new NetworkProxySettings(httpProxy, httpsProxy, socksProxy, noProxyHosts);
144
            }
145
            
146
            LOGGER.log(Level.FINE, "Windows system proxy resolver: no proxy"); //NOI18N
147
            return new NetworkProxySettings();
148
        } else {
149
            LOGGER.log(Level.SEVERE, "Windows system proxy resolver cannot retrieve proxy settings from Windows API!"); //NOI18N
150
        }
151
152
        return new NetworkProxySettings(false);
153
    }
154
}
(-)3bff97f36acc (+68 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2013 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2013 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.core.network.proxy.windows;
43
44
import com.sun.jna.Library;
45
import com.sun.jna.Native;
46
import com.sun.jna.Pointer;
47
import com.sun.jna.Structure;
48
49
/**
50
 *
51
 * @author lfischme
52
 */
53
public interface WindowsNetworkProxyLibrary extends Library {
54
    WindowsNetworkProxyLibrary LIBRARY = (WindowsNetworkProxyLibrary) Native.loadLibrary("winhttp.dll", WindowsNetworkProxyLibrary.class);
55
    
56
    public class ProxyConfig extends Structure {
57
        public static class ByReference extends ProxyConfig implements Structure.ByReference { }
58
        
59
        public boolean autoDetect;
60
        public Pointer pacFile;
61
        public Pointer proxy;
62
        public Pointer proxyBypass;        
63
    } 
64
    
65
    public boolean WinHttpGetIEProxyConfigForCurrentUser(
66
            ProxyConfig proxyConfig
67
            );
68
}
(-)3bff97f36acc (+8 lines)
Added Link Here
1
function FindProxyForURL(url, host)
2
{
3
    // Make everything lower case.
4
    url = url.toLowerCase();
5
    host = host.toLowerCase();
6
    if (isPlainHostName(host)) return "DIRECT";
7
    return "PROXY www-proxy.us.oracle.com:80";
8
};
(-)3bff97f36acc (+8 lines)
Added Link Here
1
function FindProxyForURL(url, host)
2
{
3
    // Make everything lower case.
4
    url = url.toLowerCase();
5
    host = host.toLowerCase();
6
    if (isPlainHostName(host)) return "DIRECT";
7
    return "PROXY www-proxy.us.oracle.com:80";
8
};
(-)3bff97f36acc (+113 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
package org.netbeans.core.network.proxy;
45
46
import java.io.IOException;
47
import java.net.InetSocketAddress;
48
import java.net.Proxy;
49
import java.net.ProxySelector;
50
import java.net.SocketAddress;
51
import java.net.URI;
52
import java.util.Collections;
53
import java.util.List;
54
import java.util.Locale;
55
import org.netbeans.junit.NbTestCase;
56
57
/**
58
 * Check whether we can proxy to localhost.
59
 */
60
public class CanProxyToLocalhostTest extends NbTestCase {
61
62
    private static String USER_PROXY_HOST = "my.webcache";
63
    private static int USER_PROXY_PORT = 8080;
64
    private ProxySelector selector;
65
    private static URI TO_LOCALHOST;
66
    private static URI TO_NB;
67
    private MyPS myPS;
68
69
    public CanProxyToLocalhostTest(String name) {
70
        super(name);
71
    }
72
73
    @Override
74
    protected void setUp() throws Exception {
75
        myPS = new MyPS();
76
        ProxySelector.setDefault(myPS);
77
        selector = new NbProxySelector();
78
        TO_LOCALHOST = new URI("http://localhost");
79
        TO_NB = new URI("http://netbeans.org");
80
    }
81
82
    public void testNoProxyForLocalhost() {
83
        Locale.setDefault(Locale.US);
84
        assertEquals("Connect TO_LOCALHOST DIRECT.", "DIRECT", selector.select(TO_LOCALHOST).get(0).toString());
85
    }
86
87
    public void testProxyForLocalhost() {
88
        Locale.setDefault(new Locale("te", "ST"));
89
        assertEquals("Connect TO_LOCALHOST provided by MyPS", "HTTP @ my.webcache:8080", selector.select(TO_LOCALHOST).get(0).toString());
90
        assertEquals("One call to my ps", 1, myPS.called);
91
    }
92
93
    public void testAlwaysProxyForNonLocalhost() {
94
        Locale.setDefault(Locale.US);
95
        assertEquals("Connect TO_NB provided by MyPS", "HTTP @ my.webcache:8080", selector.select(TO_NB).get(0).toString());
96
        assertEquals("One call to my ps", 1, myPS.called);
97
    }
98
99
    private static class MyPS extends ProxySelector {
100
101
        int called;
102
103
        @Override
104
        public List<Proxy> select(URI uri) {
105
            called++;
106
            return Collections.singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(USER_PROXY_HOST, USER_PROXY_PORT)));
107
        }
108
109
        @Override
110
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
111
        }
112
    }
113
}
(-)3bff97f36acc (+97 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
package org.netbeans.core.network.proxy;
46
47
import org.netbeans.junit.*;
48
49
/** Tests HTTP Proxy settings.
50
 *
51
 * @author Jiri Rechtacek
52
 * @see http://www.netbeans.org/issues/show_bug.cgi?id=125588
53
 */
54
public class DontUseProxyTest extends NbTestCase {
55
    public DontUseProxyTest (String name) {
56
        super (name);
57
    }
58
    
59
    public void testFullIpAdress () {
60
        String nonProxyHosts = "192.168.1.0|200.100.200.100";
61
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.0"));
62
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.1"));
63
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.2.0"));
64
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.169.1.0"));
65
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "193.168.1.0"));
66
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168"));
67
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.0/1"));
68
        
69
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "200.100.200.100"));
70
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "200.100.200.200"));
71
    }
72
    
73
    public void testWildcardIpAdress () {
74
        String nonProxyHosts = "192.*|200.100.200.*";
75
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.0"));
76
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.1"));
77
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.2.0"));
78
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.169.1.0"));
79
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "193.168.1.0"));
80
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168"));
81
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.0/1"));
82
        
83
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "200.100.200.100"));
84
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "200.100.200.200"));
85
    }
86
    
87
    public void testWildcardHostName () {
88
        String nonProxyHosts = "*.netbeans.org|*.other.org|*netbeans.com|netbeans.org|*.our.intranet|private.*";
89
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "www.netbeans.org"));
90
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "www.netbeans.com"));
91
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "www.dummynetbeans.org"));
92
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "subversion.our.intranet"));
93
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "private"));
94
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "private.all"));
95
    }
96
97
}
(-)3bff97f36acc (+418 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
package org.netbeans.core.network.proxy;
46
47
import java.lang.reflect.Field;
48
import java.util.prefs.AbstractPreferences;
49
import java.util.prefs.PreferenceChangeEvent;
50
import java.util.prefs.PreferenceChangeListener;
51
import java.util.prefs.Preferences;
52
import junit.framework.TestResult;
53
import org.netbeans.core.ProxySettings;
54
import org.netbeans.junit.NbTestCase;
55
import org.netbeans.junit.RandomlyFails;
56
import org.openide.util.NbPreferences;
57
58
/** Tests HTTP Proxy settings.
59
 *
60
 * @author Jiri Rechtacek
61
 * @see http://www.netbeans.org/issues/show_bug.cgi?id=51641
62
 */
63
@RandomlyFails
64
public class HttpSettingsTest extends NbTestCase {
65
    private final Object sync = getEventQueueSync ();
66
    private static String SYSTEM_PROXY_HOST = "system.cache.org";
67
    private static String SYSTEM_PROXY_PORT = "777";
68
    private static String USER_PROXY_HOST = "my.webcache";
69
    private static String USER_PROXY_PORT = "8080";
70
    private static String USER_HTTPS_PROXY_HOST = "secure.webcache";
71
    private static String USER_HTTPS_PROXY_PORT = "8080";
72
73
    private Preferences proxyPreferences;
74
    private static String SILLY_USER_PROXY_HOST = "http://my.webcache";
75
    private static String SILLY_SYSTEM_PROXY_HOST = "http://system.cache.org";
76
    private static String SILLY_SYSTEM_PROXY_PORT = "777//";
77
    private static String MY_NON_PROXY_HOSTS = "myhost.mydomain.net";
78
    
79
    private static String NETBEANS_ORG = "*.netbeans.org";
80
    private static String OTHER_ORG = "*.other.org";
81
    
82
    public HttpSettingsTest (String name) {
83
        super (name);
84
    }
85
    
86
    @Override
87
    public void run (final TestResult result) {
88
        //just initialize Preferences before code NbTestCase
89
        Preferences.userRoot ();                        
90
        super.run (result);
91
    }
92
    
93
    @Override
94
    protected int timeOut () {
95
        return 20 * 1000;
96
    }
97
    
98
    @Override
99
    protected void setUp () throws Exception {
100
        super.setUp ();
101
        System.setProperty ("http.nonProxyHosts", NETBEANS_ORG + ',' + NETBEANS_ORG);
102
        new NbProxySelector();
103
        proxyPreferences  = NbPreferences.root ().node ("/org/netbeans/core");
104
        proxyPreferences.addPreferenceChangeListener (new PreferenceChangeListener() {
105
            @Override
106
            public void preferenceChange(PreferenceChangeEvent arg0) {
107
                synchronized (sync) {
108
                    sync.notifyAll ();
109
                }
110
            }
111
        });
112
        System.setProperty ("netbeans.system_http_proxy", SYSTEM_PROXY_HOST + ":" + SYSTEM_PROXY_PORT);
113
        System.setProperty ("netbeans.system_http_non_proxy_hosts", OTHER_ORG);
114
        synchronized (sync) {
115
            if (! USER_PROXY_HOST.equals (proxyPreferences.get ("proxyHttpHost", ""))) {
116
                proxyPreferences.put ("proxyHttpHost", USER_PROXY_HOST);
117
                sync.wait (10000);
118
            }
119
        }
120
        synchronized (sync) {
121
            if (! USER_PROXY_PORT.equals (proxyPreferences.get ("proxyHttpPort", ""))) {
122
                proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT);
123
                sync.wait (10000);
124
            }
125
        }
126
        synchronized (sync) {
127
            if (! USER_HTTPS_PROXY_HOST.equals (proxyPreferences.get ("proxyHttpsHost", ""))) {
128
                proxyPreferences.put ("proxyHttpsHost", USER_HTTPS_PROXY_HOST);
129
                sync.wait (10000);
130
            }
131
        }
132
        synchronized (sync) {
133
            if (! USER_HTTPS_PROXY_PORT.equals (proxyPreferences.get ("proxyHttpsPort", ""))) {
134
                proxyPreferences.put ("proxyHttpsPort", USER_HTTPS_PROXY_PORT);
135
                sync.wait (10000);
136
            }
137
        }
138
    }
139
    
140
    private void sillySetUp () throws Exception {
141
        synchronized (sync) {
142
            if (ProxySettings.DIRECT_CONNECTION != (proxyPreferences.getInt ("proxyType", -1))) {
143
                proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION);
144
                sync.wait ();
145
            }
146
        }
147
        
148
        System.setProperty ("netbeans.system_http_proxy", SILLY_SYSTEM_PROXY_HOST + ":" + SILLY_SYSTEM_PROXY_PORT);
149
        synchronized (sync) {
150
            if (! SILLY_USER_PROXY_HOST.equals (proxyPreferences.get ("proxyHttpHost", ""))) {
151
                proxyPreferences.put ("proxyHttpHost", SILLY_USER_PROXY_HOST);
152
                sync.wait (10000);
153
            }
154
        }
155
        proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT);
156
        synchronized (sync) {
157
            if (! USER_PROXY_PORT.equals (proxyPreferences.get ("proxyHttpPort", ""))) {
158
                proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT);
159
                sync.wait (10000);
160
            }
161
        }
162
    }
163
    
164
    private void setUpAutoDirect () throws Exception {
165
        synchronized (sync) {
166
            if (ProxySettings.DIRECT_CONNECTION != (proxyPreferences.getInt ("proxyType", -1))) {
167
                proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION);
168
                sync.wait ();
169
            }
170
        }
171
        System.setProperty ("netbeans.system_http_proxy", "DIRECT");
172
        synchronized (sync) {
173
            if (! "".equals (proxyPreferences.get ("proxyHttpHost", ""))) {
174
                proxyPreferences.put ("proxyHttpHost", "");
175
                sync.wait (10000);
176
            }
177
        }
178
        synchronized (sync) {
179
            if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
180
                proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY);
181
                sync.wait ();
182
            }
183
        }
184
    }
185
    
186
    public void testDirectConnection () throws InterruptedException {
187
        System.setProperty ("http.proxyHost", "");
188
        System.setProperty ("http.proxyPort", "");
189
        synchronized (sync) {
190
            if (ProxySettings.DIRECT_CONNECTION != (proxyPreferences.getInt ("proxyType", -1))) {
191
                proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION);
192
                sync.wait ();
193
            }
194
        }
195
        assertEquals ("Proxy type DIRECT_CONNECTION.", ProxySettings.DIRECT_CONNECTION, ProxySettings.getProxyType ());
196
        assertEquals ("No Proxy Host set.", null, System.getProperty ("http.proxyHost"));
197
        assertEquals ("No Proxy Port set.", null, System.getProperty ("http.proxyPort"));
198
    }
199
    
200
    public void testAutoDetectProxy () throws InterruptedException {
201
        System.setProperty ("http.proxyHost", "");
202
        System.setProperty ("http.proxyPort", "");
203
        synchronized (sync) {
204
            if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
205
                proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY);
206
                sync.wait ();
207
            }
208
        }
209
        assertEquals("Proxy type AUTO_DETECT_PROXY.",
210
                     ProxySettings.AUTO_DETECT_PROXY,
211
                     ProxySettings.getProxyType());
212
        assertEquals("System Proxy Host: ", SYSTEM_PROXY_HOST,
213
                     System.getProperty("http.proxyHost"));
214
        assertEquals("System Proxy Port: ", SYSTEM_PROXY_PORT,
215
                     System.getProperty("http.proxyPort"));
216
    }
217
    
218
    public void testManualSetProxy () throws InterruptedException {
219
        synchronized (sync) {
220
            if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
221
                proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY);
222
                sync.wait ();
223
            }
224
        }
225
        assertEquals ("Proxy type MANUAL_SET_PROXY.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ());
226
        assertEquals ("Manual Set Proxy Host from ProxySettings: ", USER_PROXY_HOST, ProxySettings.getHttpHost ());
227
        assertEquals ("Manual Set Proxy Port from ProxySettings: ", USER_PROXY_PORT, ProxySettings.getHttpPort ());
228
        assertEquals ("Manual Set Proxy Host from System.getProperty(): ", USER_PROXY_HOST, System.getProperty ("http.proxyHost"));
229
        assertEquals ("Manual Set Proxy Port from System.getProperty(): ", USER_PROXY_PORT, System.getProperty ("http.proxyPort"));
230
    }
231
    
232
    public void testHttpsManualSetProxy () throws InterruptedException {
233
        synchronized (sync) {
234
            if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
235
                proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY);
236
                sync.wait ();
237
            }
238
        }
239
        assertEquals ("Proxy type MANUAL_SET_PROXY.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ());
240
        
241
        // HTTP
242
        assertEquals ("Manual Set Proxy Host from ProxySettings: ", USER_PROXY_HOST, ProxySettings.getHttpHost ());
243
        assertEquals ("Manual Set Proxy Port from ProxySettings: ", USER_PROXY_PORT, ProxySettings.getHttpPort ());
244
        assertEquals ("Manual Set Proxy Host from System.getProperty(): ", USER_PROXY_HOST, System.getProperty ("http.proxyHost"));
245
        assertEquals ("Manual Set Proxy Port from System.getProperty(): ", USER_PROXY_PORT, System.getProperty ("http.proxyPort"));
246
        
247
        // HTTPS
248
        assertEquals ("Manual Set HTTPS Proxy Host from ProxySettings: ", USER_HTTPS_PROXY_HOST, ProxySettings.getHttpsHost ());
249
        assertEquals ("Manual Set HTTPS Proxy Port from ProxySettings: ", USER_HTTPS_PROXY_PORT, ProxySettings.getHttpsPort ());
250
        assertEquals ("Manual Set HTTPS Proxy Host from System.getProperty(): ", USER_HTTPS_PROXY_HOST, System.getProperty ("https.proxyHost"));
251
        assertEquals ("Manual Set HTTPS Proxy Port from System.getProperty(): ", USER_HTTPS_PROXY_PORT, System.getProperty ("https.proxyPort"));
252
    }
253
    
254
    public void testIfTakeUpNonProxyFromProperty () {
255
        assertTrue (NETBEANS_ORG + " in one of Non-Proxy hosts.", ProxySettings.getNonProxyHosts ().indexOf (NETBEANS_ORG) != -1);
256
    }
257
    
258
    public void testNonProxy () throws InterruptedException {
259
        assertEquals ("The ProxySettings takes as same value as System properties in initial.", System.getProperty ("http.nonProxyHosts"), ProxySettings.getNonProxyHosts ());
260
        
261
        // change value in ProxySettings
262
        synchronized (sync) {
263
            if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
264
                proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY);
265
                sync.wait ();
266
            }
267
        }
268
        synchronized (sync) {
269
            if (! MY_NON_PROXY_HOSTS.equals (proxyPreferences.get ("proxyNonProxyHosts", ""))) {
270
                proxyPreferences.put ("proxyNonProxyHosts", MY_NON_PROXY_HOSTS);
271
                sync.wait ();
272
            }
273
        }
274
        assertEquals ("ProxySettings returns new value.", "myhost.mydomain.net", ProxySettings.getNonProxyHosts ());
275
        assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.getNonProxyHosts (), System.getProperty ("http.nonProxyHosts"));
276
        
277
        // switch proxy type to DIRECT_CONNECTION
278
        //System.setProperty ("http.nonProxyHosts", "");
279
        synchronized (sync) {
280
            if (ProxySettings.DIRECT_CONNECTION != (proxyPreferences.getInt ("proxyType", -1))) {
281
                proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION);
282
                sync.wait ();
283
            }
284
        }
285
        Thread.sleep (1000); // XXX: tunning test on Windows platform, other platforms are passing
286
        assertEquals ("System.getProperty() doesn't return new value if DIRECT_CONNECTION set.", null, System.getProperty ("http.nonProxyHosts"));
287
        
288
        // switch proxy type back to MANUAL_SET_PROXY
289
        synchronized (sync) {
290
            if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
291
                proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY);
292
                sync.wait ();
293
            }
294
        }
295
        assertEquals ("ProxySettings again returns new value.", "myhost.mydomain.net", ProxySettings.getNonProxyHosts ());
296
        assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.getNonProxyHosts (), System.getProperty ("http.nonProxyHosts"));
297
        
298
        // switch proxy type to AUTO_DETECT_PROXY
299
        synchronized (sync) {
300
            if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
301
                proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY);
302
                sync.wait ();
303
            }
304
        }
305
        log ("AUTO_DETECT_PROXY: ProxySettings.SystemProxySettings.getNonProxyHosts (): " + ProxySettings.getSystemNonProxyHosts());
306
        log ("AUTO_DETECT_PROXY: System.getProperty (\"http.nonProxyHosts\"): " + System.getProperty ("http.nonProxyHosts"));
307
        assertTrue ("ProxySettings contains OTHER_ORG if AUTO_DETECT_PROXY set.", System.getProperty ("http.nonProxyHosts").indexOf (OTHER_ORG) > 0);
308
                
309
        // switch proxy type back to MANUAL_SET_PROXY
310
        synchronized (sync) {
311
            if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
312
                proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY);
313
                sync.wait ();
314
            }
315
        }
316
        assertEquals ("ProxySettings again returns new value.", "myhost.mydomain.net", ProxySettings.getNonProxyHosts ());
317
        assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.getNonProxyHosts (), System.getProperty ("http.nonProxyHosts"));
318
    }
319
    
320
    public void testAvoidDuplicateNonProxySetting () throws InterruptedException {
321
        synchronized (sync) {
322
            if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
323
                proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY);
324
                sync.wait ();
325
            }
326
        }
327
        assertTrue (NETBEANS_ORG + " is among Non-proxy hosts detect from OS.", ProxySettings.getSystemNonProxyHosts().indexOf (NETBEANS_ORG) != -1);
328
        assertFalse (NETBEANS_ORG + " is in Non-Proxy hosts only once.", ProxySettings.getSystemNonProxyHosts().indexOf (NETBEANS_ORG) < ProxySettings.getNonProxyHosts ().lastIndexOf (NETBEANS_ORG));
329
        assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.getSystemNonProxyHosts(), System.getProperty ("http.nonProxyHosts"));
330
    }
331
    
332
    public void testReadNonProxySettingFromSystem () throws InterruptedException {
333
        synchronized (sync) {
334
            if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
335
                proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY);
336
                sync.wait ();
337
            }
338
        }
339
        assertTrue (OTHER_ORG + " is among Non-proxy hosts detect from OS.", ProxySettings.getSystemNonProxyHosts().indexOf (OTHER_ORG) != -1);
340
        assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.getSystemNonProxyHosts(), System.getProperty ("http.nonProxyHosts"));
341
    }
342
    
343
    public void testSillySetManualProxy () throws Exception {
344
        sillySetUp ();
345
        synchronized (sync) {
346
            if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
347
                proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY);
348
                sync.wait ();
349
            }
350
        }
351
        assertEquals ("Proxy type MANUAL_SET_PROXY.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ());
352
        assertEquals ("Manual Set Proxy Host from ProxySettings doesn't return SILLY_USER_PROXY_HOST anymore.", USER_PROXY_HOST, ProxySettings.getHttpHost ());
353
        assertEquals ("Manual Set Proxy Port from ProxySettings doesn't return SILLY_USER_PROXY_PORT anymore.", USER_PROXY_PORT, ProxySettings.getHttpPort ());
354
        assertEquals ("Manual Set Proxy Host from System.getProperty(): ", USER_PROXY_HOST, System.getProperty ("http.proxyHost"));
355
        assertEquals ("Manual Set Proxy Port from System.getProperty(): ", USER_PROXY_PORT, System.getProperty ("http.proxyPort"));
356
    }
357
    
358
    public void testAutoDetectSillySetProxy () throws Exception {
359
        sillySetUp ();
360
        synchronized (sync) {
361
            if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
362
                proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY);
363
                sync.wait ();
364
            }
365
        }
366
        assertEquals ("Proxy type AUTO_DETECT_PROXY.", ProxySettings.AUTO_DETECT_PROXY, ProxySettings.getProxyType ());
367
        assertEquals ("Auto Detected Proxy Host from ProxySettings doesn't return SILLY_SYSTEM_PROXY_HOST anymore.", SYSTEM_PROXY_HOST, ProxySettings.getSystemHttpHost());
368
        assertEquals ("Auto Detected Proxy Port from ProxySettings doesn't return SILLY_SYSTEM_PROXY_PORT anymore.", SYSTEM_PROXY_PORT, ProxySettings.getSystemHttpPort());
369
        assertEquals ("System Proxy Host: ", SYSTEM_PROXY_HOST, System.getProperty ("http.proxyHost"));
370
        assertEquals ("System Proxy Port: ", SYSTEM_PROXY_PORT, System.getProperty ("http.proxyPort"));
371
    }    
372
    
373
    public void testSwitchAutoAndManualMode () throws Exception {
374
        setUpAutoDirect ();
375
        
376
        // ensure auto detect mode
377
        assertEquals("Proxy type AUTO_DETECT_PROXY.",
378
                     ProxySettings.AUTO_DETECT_PROXY,
379
                     ProxySettings.getProxyType());
380
        assertEquals ("Auto Proxy Host from System.getProperty(): ", null, System.getProperty ("http.proxyHost"));
381
        assertEquals ("Auto Proxy Port from System.getProperty(): ", null, System.getProperty ("http.proxyPort"));
382
        
383
        // switch to manual
384
        proxyPreferences.put ("proxyHttpHost", "foo");
385
        synchronized (sync) {
386
            if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
387
                proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY);
388
                sync.wait ();
389
            }
390
        }
391
        assertEquals ("Proxy type MANUAL_SET_PROXY.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ());
392
        assertEquals ("Auto Proxy Host from System.getProperty(): ", "foo", System.getProperty ("http.proxyHost"));
393
        
394
        // switch back to auto detect
395
        synchronized (sync) {
396
            if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
397
                proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY);
398
                sync.wait ();
399
            }
400
        }
401
        assertEquals("Proxy type AUTO_DETECT_PROXY.",
402
                     ProxySettings.AUTO_DETECT_PROXY,
403
                     ProxySettings.getProxyType());
404
        assertEquals ("Auto Proxy Host from System.getProperty(): ", null, System.getProperty ("http.proxyHost"));
405
        assertEquals ("Auto Proxy Port from System.getProperty(): ", null, System.getProperty ("http.proxyPort"));
406
        
407
    }
408
    
409
    private Object getEventQueueSync() {
410
        try {
411
            Field f = AbstractPreferences.class.getDeclaredField("eventQueue");
412
            f.setAccessible(true);
413
            return f.get(null);
414
        } catch (Exception ex) {
415
            throw new ExceptionInInitializerError(ex);
416
        }
417
    }
418
}
(-)3bff97f36acc (+173 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
package org.netbeans.core.network.proxy;
46
47
import java.net.Proxy;
48
import java.net.ProxySelector;
49
import java.net.URI;
50
import java.util.prefs.PreferenceChangeEvent;
51
import java.util.prefs.PreferenceChangeListener;
52
import java.util.prefs.Preferences;
53
import org.netbeans.core.ProxySettings;
54
import org.netbeans.junit.NbTestCase;
55
import org.netbeans.junit.RandomlyFails;
56
import org.openide.util.NbPreferences;
57
58
/** Tests Detect OS nonProxyHosts settings.
59
 *
60
 * @author Jiri Rechtacek
61
 * @see http://www.netbeans.org/issues/show_bug.cgi?id=77053
62
 */
63
@RandomlyFails // NB-Core-Build #1247, 1248
64
public class NonProxyHostsTest extends NbTestCase {
65
    private static String SYSTEM_PROXY_HOST = "system.cache.org";
66
    private static String SYSTEM_PROXY_PORT = "777";
67
    private static String USER_PROXY_HOST = "my.webcache";
68
    private static String USER_PROXY_PORT = "8080";
69
70
    private Preferences proxyPreferences;
71
    private ProxySelector selector;
72
    private static URI TO_LOCALHOST;
73
    private static URI TO_LOCAL_DOMAIN_1;
74
    private static URI TO_LOCAL_DOMAIN_2;
75
    private static URI TO_EXTERNAL;
76
    private static URI SOCKS_TO_LOCALHOST;
77
    private static URI SOCKS_TO_LOCAL_DOMAIN_1;
78
    private static URI SOCKS_TO_LOCAL_DOMAIN_2;
79
    private static URI SOCKS_TO_EXTERNAL;
80
81
    private boolean isWaiting = false;
82
    
83
    public NonProxyHostsTest (String name) {
84
        super (name);
85
    }
86
    
87
    @Override
88
    protected void setUp () throws Exception {
89
        super.setUp ();
90
        System.setProperty ("netbeans.system_http_proxy", SYSTEM_PROXY_HOST + ":" + SYSTEM_PROXY_PORT);
91
        System.setProperty ("netbeans.system_socks_proxy", SYSTEM_PROXY_HOST + ":" + SYSTEM_PROXY_PORT);
92
        System.setProperty ("netbeans.system_http_non_proxy_hosts", "*.other.org");
93
        System.setProperty ("http.nonProxyHosts", "*.netbeans.org");
94
        new NbProxySelector();
95
        selector = ProxySelector.getDefault ();
96
        proxyPreferences  = NbPreferences.root ().node ("/org/netbeans/core");
97
        proxyPreferences.addPreferenceChangeListener (new PreferenceChangeListener () {
98
            public void preferenceChange (PreferenceChangeEvent arg0) {
99
                isWaiting = false;
100
            }
101
        });
102
        proxyPreferences.put ("proxyHttpHost", USER_PROXY_HOST);
103
        proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT);
104
        proxyPreferences.put ("proxySocksHost", USER_PROXY_HOST);
105
        proxyPreferences.put ("proxySocksPort", USER_PROXY_PORT);
106
        while (isWaiting);
107
        isWaiting = true;
108
        TO_LOCALHOST = new URI ("http://localhost");
109
        TO_LOCAL_DOMAIN_1 = new URI ("http://core.netbeans.org");
110
        TO_LOCAL_DOMAIN_2 = new URI ("http://core.other.org");
111
        TO_EXTERNAL = new URI ("http://worldwide.net");
112
        
113
        SOCKS_TO_LOCALHOST = new URI ("socket://localhost:8041");
114
        SOCKS_TO_LOCAL_DOMAIN_1 = new URI ("socket://core.netbeans.org");
115
        SOCKS_TO_LOCAL_DOMAIN_2 = new URI ("socket://core.other.org");
116
        SOCKS_TO_EXTERNAL = new URI ("socket://worldwide.net");
117
    }
118
    
119
    public void testDirectProxySetting () {
120
        proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION);
121
        while (isWaiting);
122
        assertEquals ("Proxy type DIRECT_CONNECTION.", ProxySettings.DIRECT_CONNECTION, ProxySettings.getProxyType ());
123
        assertEquals ("Connect " + TO_LOCALHOST + " DIRECT.", "[DIRECT]", selector.select (TO_LOCALHOST).toString ());
124
        assertEquals ("Connect " + SOCKS_TO_LOCALHOST + " DIRECT.", Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCALHOST).get(0));
125
        assertEquals ("Connect " + TO_LOCAL_DOMAIN_1 + " DIRECT.", "[DIRECT]", selector.select (TO_LOCAL_DOMAIN_1).toString ());
126
        assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_1 + " DIRECT.", "[DIRECT]", selector.select (SOCKS_TO_LOCAL_DOMAIN_1).toString ());
127
        assertEquals ("Connect " + TO_LOCAL_DOMAIN_2 + " DIRECT.", "[DIRECT]", selector.select (TO_LOCAL_DOMAIN_2).toString ());
128
        assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_2 + " DIRECT.", "[DIRECT]", selector.select (SOCKS_TO_LOCAL_DOMAIN_2).toString ());
129
        assertEquals ("Connect " + TO_EXTERNAL + " DIRECT.", "[DIRECT]", selector.select (TO_EXTERNAL).toString ());
130
        assertEquals ("Connect " + SOCKS_TO_EXTERNAL + " DIRECT.", "[DIRECT]", selector.select (SOCKS_TO_EXTERNAL).toString ());
131
    }
132
    
133
    @RandomlyFails
134
    public void testManualProxySettins () {
135
        proxyPreferences.put (ProxySettings.NOT_PROXY_HOSTS, "localhost|" + "*.netbeans.org");
136
        proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY);
137
        while (isWaiting);
138
        assertEquals ("Proxy type DIRECT_CONNECTION.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ());
139
        assertEquals ("Connect TO_LOCALHOST DIRECT.", Proxy.NO_PROXY, selector.select (TO_LOCALHOST).get(0));
140
        assertEquals ("Connect " + SOCKS_TO_LOCALHOST + " DIRECT.", Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCALHOST).get(0));
141
        assertEquals ("Connect " + TO_LOCAL_DOMAIN_1 + " DIRECT.", Proxy.NO_PROXY, selector.select (TO_LOCAL_DOMAIN_1).get (0));
142
        assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_1 + " DIRECT.",
143
                Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCAL_DOMAIN_1).get (0));
144
        assertEquals ("Connect " + TO_LOCAL_DOMAIN_2 + " via my.webcache:8080 proxy.",
145
                "HTTP @ my.webcache:8080", selector.select (TO_LOCAL_DOMAIN_2).get (0).toString ());
146
        assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_2 + " via my.webcache:8080 proxy.",
147
                "SOCKS @ my.webcache:8080", selector.select (SOCKS_TO_LOCAL_DOMAIN_2).get (0).toString ());
148
        assertEquals ("Connect TO_EXTERNAL via my.webcache:8080 proxy.", "HTTP @ my.webcache:8080", selector.select (TO_EXTERNAL).get (0).toString ());
149
        assertEquals ("Connect SOCKS_TO_EXTERNAL via my.webcache:8080 proxy.",
150
                "SOCKS @ my.webcache:8080", selector.select (SOCKS_TO_EXTERNAL).get (0).toString ());
151
    }
152
    
153
    @RandomlyFails
154
    public void testSystemProxySettings () {
155
        proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY);
156
        while (isWaiting);
157
        log ("Value of System.getProperty (\"http.nonProxyHosts\"): " + System.getProperty ("http.nonProxyHosts"));
158
        assertTrue ("*.other.org is one of non-proxy hosts", System.getProperty ("http.nonProxyHosts").indexOf ("*.other.org") != -1);
159
        assertEquals ("Proxy type DIRECT_CONNECTION.", ProxySettings.AUTO_DETECT_PROXY, ProxySettings.getProxyType ());
160
        assertEquals ("Connect TO_LOCALHOST DIRECT.", Proxy.NO_PROXY, selector.select (TO_LOCALHOST).get(0));
161
        assertEquals ("Connect " + SOCKS_TO_LOCALHOST + " DIRECT.", Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCALHOST).get(0));
162
        assertEquals ("Connect " + TO_LOCAL_DOMAIN_1 + " DIRECT.", Proxy.NO_PROXY, selector.select (TO_LOCAL_DOMAIN_1).get (0));
163
        assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_1 + " DIRECT.",
164
                Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCAL_DOMAIN_1).get (0));
165
        assertEquals ("Connect " + TO_LOCAL_DOMAIN_2 + " DIRECT ignoring settings " + System.getProperty ("http.nonProxyHosts"), Proxy.NO_PROXY, selector.select (TO_LOCAL_DOMAIN_2).get (0));
166
        assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_2 + " DIRECT ignoring settings " + System.getProperty ("http.nonProxyHosts"),
167
                Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCAL_DOMAIN_2).get (0));
168
        assertEquals ("Connect TO_EXTERNAL via system.cache.org:777 proxy.", "HTTP @ system.cache.org:777", selector.select (TO_EXTERNAL).get (0).toString ());
169
        assertEquals ("Connect SOCKS_TO_EXTERNAL via system.cache.org:777 proxy.", "SOCKS @ system.cache.org:777",
170
                selector.select (SOCKS_TO_EXTERNAL).get (0).toString ());
171
    }
172
173
}
(-)3bff97f36acc (+159 lines)
Added Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2011 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.core.network.proxy;
43
44
import java.io.File;
45
import java.net.Proxy;
46
import java.net.URI;
47
import java.net.URISyntaxException;
48
import java.util.LinkedList;
49
import java.util.List;
50
import junit.framework.Test;
51
import org.netbeans.junit.NbModuleSuite;
52
import org.netbeans.junit.NbTestCase;
53
54
/**
55
 *
56
 * @author Jirka Rechtacek
57
 */
58
public class ProxyAutoConfigTest extends NbTestCase {
59
    
60
    public static Test suite() {
61
        return NbModuleSuite
62
                .emptyConfiguration()
63
                .gui(false)
64
                .addTest(ProxyAutoConfigTest.class)
65
                .suite();
66
    }
67
    
68
    public ProxyAutoConfigTest(String name) {
69
        super(name);
70
    }
71
    
72
    public void testGetProxyAutoConfig() {
73
        assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt"));
74
    }
75
    
76
    // #issue 201995
77
    public void testGetProxyAutoConfigWithMultipleURL() {
78
        assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt http://pac/pac.txt http://pac/pac.txt"));
79
    }
80
    
81
    public void testGetProxyAutoConfigWithNewLineURL() {
82
        assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt\nhttp://pac/pac.txt"));
83
    }
84
    
85
    public void testGetProxyAutoConfigWithLineTerminatorURL() {
86
        assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt\rhttp://pac/pac.txt"));
87
    }
88
    
89
    public void testGetProxyAutoConfigWithBothTerminatorsURL() {
90
        assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt\r\nhttp://pac/pac.txt"));
91
    }
92
    
93
    public void testGetProxyAutoConfigWithInvalidURL() {
94
        assertNotNull(ProxyAutoConfig.get("http:\\\\pac\\pac.txt"));
95
    }
96
    
97
    public void testGetProxyAutoConfigWithRelativePath() {
98
        assertNotNull(ProxyAutoConfig.get("http://pac/../pac/pac.txt"));
99
    }
100
    
101
    public void testGetProxyAutoConfigWithLocalPAC() throws URISyntaxException {
102
        List<String> pacFileLocations = new LinkedList<String>();
103
        for (File pacFile : new File(getDataDir(), "pacFiles").listFiles()) {
104
            pacFileLocations.add(pacFile.getAbsolutePath());
105
            pacFileLocations.add("file://" + pacFile.getAbsolutePath());
106
            pacFileLocations.add(pacFile.toURI().toString());
107
        }
108
        for (String pacFileLoc : pacFileLocations) {
109
            ProxyAutoConfig pac = ProxyAutoConfig.get(pacFileLoc);
110
            assertNotNull(pac);
111
            URI uri = pac.getPacURI();
112
            assertNotNull(uri);
113
            assertNull(uri.getHost());
114
            List<Proxy> proxies = pac.findProxyForURL(new URI("http://netbeans.org"));
115
            assertEquals(1, proxies.size());
116
            assertTrue(pacFileLoc + ": " + proxies.get(0).toString(), proxies.get(0).toString().startsWith("HTTP @ www-proxy.us.oracle.com/"));
117
            System.setProperty("netbeans.system_http_proxy", "PAC " + pacFileLoc);
118
            proxies = NbProxySelector.getDefault().select(new URI("http://netbeans.org"));
119
            assertTrue(pacFileLoc + ": " + proxies.get(0).toString(), proxies.get(0).toString().startsWith("HTTP @ www-proxy.us.oracle.com/"));
120
            
121
            proxies = pac.findProxyForURL(new URI("https://netbeans.org"));
122
            assertEquals(1, proxies.size());
123
            assertTrue(pacFileLoc + ": " + proxies.get(0).toString(), proxies.get(0).toString().startsWith("HTTP @ www-proxy.us.oracle.com/"));
124
            System.setProperty("netbeans.system_http_proxy", "PAC " + pacFileLoc);
125
            proxies = NbProxySelector.getDefault().select(new URI("https://netbeans.org"));
126
            assertTrue(pacFileLoc + ": " + proxies.get(0).toString(), proxies.get(0).toString().startsWith("HTTP @ www-proxy.us.oracle.com/"));
127
            
128
            proxies = pac.findProxyForURL(new URI("http://localhost"));
129
            assertEquals(1, proxies.size());
130
            assertEquals(pacFileLoc + ": " + proxies.get(0).toString(), "DIRECT", proxies.get(0).toString());
131
            proxies = NbProxySelector.getDefault().select(new URI("http://localhost"));
132
            assertEquals(pacFileLoc + ": " + proxies.get(0).toString(), "DIRECT", proxies.get(0).toString());
133
        }
134
    }
135
    
136
    public void testGetProxyAutoConfigWithLocalInvalidPAC() throws URISyntaxException {
137
        List<String> pacFileLocations = new LinkedList<String>();
138
        for (File pacFile : new File[] {
139
            new File(getDataDir(), "pacFiles"),
140
            new File(getDataDir(), "doesNotExist")
141
        }) {
142
            pacFileLocations.add(pacFile.getAbsolutePath());
143
            pacFileLocations.add("file://" + pacFile.getAbsolutePath());
144
            pacFileLocations.add(pacFile.toURI().toString());
145
        }
146
        for (String pacFileLoc : pacFileLocations) {
147
            ProxyAutoConfig pac = ProxyAutoConfig.get(pacFileLoc);
148
            assertNotNull(pac);
149
            URI uri = pac.getPacURI();
150
            assertNotNull(uri);
151
            List<Proxy> proxies = pac.findProxyForURL(new URI("http://netbeans.org"));
152
            assertEquals(1, proxies.size());
153
            assertEquals("DIRECT", proxies.get(0).toString());
154
            System.setProperty("netbeans.system_http_proxy", "PAC " + pacFileLoc);
155
            proxies = NbProxySelector.getDefault().select(new URI("http://netbeans.org"));
156
            assertEquals(pacFileLoc + ": " + proxies.get(0).toString(), "DIRECT", proxies.get(0).toString());
157
        }
158
    }
159
}
(-)a/core.ui/src/org/netbeans/core/ui/options/general/Bundle.properties (+3 lines)
Lines 267-269 Link Here
267
General.Options.Export.Category.displayName=General
267
General.Options.Export.Category.displayName=General
268
General.Options.Export.displayName=General
268
General.Options.Export.displayName=General
269
Other.Options.Export.displayName=All Other Unspecified
269
Other.Options.Export.displayName=All Other Unspecified
270
GeneralOptionsPanel.bReloadProxy.text=Reload
271
GeneralOptionsPanel.bTestConnection.text=Test connection
272
GeneralOptionsPanel.lblTestResult.text=<test result>
(-)a/core.ui/src/org/netbeans/core/ui/options/general/GeneralOptionsModel.java (-3 / +2 lines)
Lines 207-215 Link Here
207
    }
207
    }
208
    
208
    
209
    static boolean usePAC() {
209
    static boolean usePAC() {
210
        String s = System.getProperty ("netbeans.system_http_proxy"); // NOI18N
210
        String pacUrl = getProxyPreferences().get(ProxySettings.SYSTEM_PAC, ""); // NOI18N
211
        boolean usePAC = s != null && s.startsWith("PAC"); // NOI18N
211
        return pacUrl != null && pacUrl.length() > 0;
212
        return usePAC;
213
    }
212
    }
214
    
213
    
215
    // private helper methods ..................................................
214
    // private helper methods ..................................................
(-)a/core.ui/src/org/netbeans/core/ui/options/general/GeneralOptionsPanel.form (-27 / +83 lines)
Lines 30-56 Link Here
30
                      <Component id="lWebProxy" min="-2" max="-2" attributes="0"/>
30
                      <Component id="lWebProxy" min="-2" max="-2" attributes="0"/>
31
                      <EmptySpace min="-2" pref="18" max="-2" attributes="0"/>
31
                      <EmptySpace min="-2" pref="18" max="-2" attributes="0"/>
32
                      <Group type="103" groupAlignment="0" attributes="0">
32
                      <Group type="103" groupAlignment="0" attributes="0">
33
                          <Component id="rbNoProxy" alignment="0" min="-2" max="-2" attributes="0"/>
34
                          <Component id="rbUseSystemProxy" alignment="0" min="-2" max="-2" attributes="0"/>
35
                          <Component id="rbHTTPProxy" alignment="0" min="-2" max="-2" attributes="0"/>
36
                          <Group type="102" alignment="0" attributes="0">
33
                          <Group type="102" alignment="0" attributes="0">
37
                              <EmptySpace min="17" pref="17" max="17" attributes="0"/>
34
                              <EmptySpace min="-2" pref="90" max="-2" attributes="0"/>
35
                              <Component id="errorLabel" pref="1313" max="32767" attributes="0"/>
36
                          </Group>
37
                          <Group type="102" attributes="0">
38
                              <Group type="103" groupAlignment="0" attributes="0">
38
                              <Group type="103" groupAlignment="0" attributes="0">
39
                                  <Group type="102" alignment="0" attributes="0">
39
                                  <Group type="102" attributes="0">
40
                                      <Group type="103" groupAlignment="0" attributes="0">
41
                                          <Group type="102" alignment="0" attributes="0">
42
                                              <Component id="rbHTTPProxy" min="-2" max="-2" attributes="0"/>
43
                                              <EmptySpace max="-2" attributes="0"/>
44
                                              <Component id="lProxyHost" min="-2" max="-2" attributes="0"/>
45
                                              <EmptySpace max="-2" attributes="0"/>
46
                                              <Component id="tfProxyHost" pref="1055" max="32767" attributes="2"/>
47
                                          </Group>
48
                                          <Group type="102" attributes="0">
49
                                              <Group type="103" groupAlignment="0" attributes="0">
50
                                                  <Component id="rbNoProxy" alignment="0" min="-2" max="-2" attributes="0"/>
51
                                                  <Group type="102" alignment="0" attributes="0">
52
                                                      <Component id="rbUseSystemProxy" min="-2" max="-2" attributes="0"/>
53
                                                      <EmptySpace max="-2" attributes="0"/>
54
                                                      <Component id="bReloadProxy" min="-2" max="-2" attributes="0"/>
55
                                                  </Group>
56
                                              </Group>
57
                                              <EmptySpace min="0" pref="0" max="32767" attributes="0"/>
58
                                          </Group>
59
                                      </Group>
60
                                      <EmptySpace max="-2" attributes="0"/>
61
                                      <Component id="lProxyPort" min="-2" max="-2" attributes="0"/>
62
                                      <EmptySpace max="-2" attributes="0"/>
63
                                      <Component id="tfProxyPort" min="-2" max="-2" attributes="1"/>
64
                                      <EmptySpace max="-2" attributes="0"/>
40
                                      <Component id="bMoreProxy" min="-2" max="-2" attributes="0"/>
65
                                      <Component id="bMoreProxy" min="-2" max="-2" attributes="0"/>
41
                                      <EmptySpace max="-2" attributes="0"/>
42
                                      <Component id="errorLabel" pref="1279" max="32767" attributes="0"/>
43
                                  </Group>
66
                                  </Group>
44
                                  <Group type="102" alignment="0" attributes="0">
67
                                  <Group type="102" alignment="0" attributes="0">
45
                                      <Component id="lProxyHost" min="-2" max="-2" attributes="0"/>
68
                                      <Component id="bTestConnection" min="-2" max="-2" attributes="0"/>
46
                                      <EmptySpace type="unrelated" max="-2" attributes="0"/>
69
                                      <EmptySpace max="-2" attributes="0"/>
47
                                      <Component id="tfProxyHost" pref="1137" max="32767" attributes="2"/>
70
                                      <Component id="lblTestResult" min="-2" max="-2" attributes="0"/>
48
                                      <EmptySpace min="-2" pref="12" max="-2" attributes="0"/>
71
                                      <EmptySpace min="0" pref="0" max="32767" attributes="0"/>
49
                                      <Component id="lProxyPort" min="-2" max="-2" attributes="0"/>
50
                                      <EmptySpace type="unrelated" max="-2" attributes="0"/>
51
                                      <Component id="tfProxyPort" min="-2" max="-2" attributes="1"/>
52
                                  </Group>
72
                                  </Group>
53
                              </Group>
73
                              </Group>
74
                              <EmptySpace max="-2" attributes="0"/>
54
                          </Group>
75
                          </Group>
55
                      </Group>
76
                      </Group>
56
                  </Group>
77
                  </Group>
Lines 79-103 Link Here
79
                  <Group type="102" alignment="0" attributes="0">
100
                  <Group type="102" alignment="0" attributes="0">
80
                      <Component id="rbNoProxy" min="-2" max="-2" attributes="0"/>
101
                      <Component id="rbNoProxy" min="-2" max="-2" attributes="0"/>
81
                      <EmptySpace max="-2" attributes="0"/>
102
                      <EmptySpace max="-2" attributes="0"/>
82
                      <Component id="rbUseSystemProxy" min="-2" max="-2" attributes="0"/>
103
                      <Group type="103" groupAlignment="3" attributes="0">
104
                          <Component id="rbUseSystemProxy" alignment="3" min="-2" max="-2" attributes="0"/>
105
                          <Component id="bReloadProxy" alignment="3" min="-2" max="-2" attributes="0"/>
106
                      </Group>
83
                      <EmptySpace max="-2" attributes="0"/>
107
                      <EmptySpace max="-2" attributes="0"/>
84
                      <Component id="rbHTTPProxy" min="-2" max="-2" attributes="0"/>
108
                      <Group type="103" groupAlignment="3" attributes="0">
109
                          <Component id="rbHTTPProxy" alignment="3" min="-2" max="-2" attributes="0"/>
110
                          <Component id="lProxyHost" alignment="3" min="-2" max="-2" attributes="0"/>
111
                          <Component id="tfProxyHost" alignment="3" min="-2" max="-2" attributes="0"/>
112
                          <Component id="lProxyPort" alignment="3" min="-2" max="-2" attributes="0"/>
113
                          <Component id="tfProxyPort" alignment="3" min="-2" max="-2" attributes="0"/>
114
                          <Component id="bMoreProxy" alignment="3" min="-2" max="-2" attributes="0"/>
115
                      </Group>
85
                  </Group>
116
                  </Group>
86
                  <Component id="lWebProxy" alignment="0" min="-2" max="-2" attributes="0"/>
117
                  <Component id="lWebProxy" alignment="0" min="-2" max="-2" attributes="0"/>
87
              </Group>
118
              </Group>
88
              <EmptySpace min="-2" max="-2" attributes="0"/>
119
              <EmptySpace min="-2" pref="30" max="-2" attributes="0"/>
120
              <Component id="errorLabel" min="-2" max="-2" attributes="0"/>
121
              <EmptySpace max="-2" attributes="0"/>
89
              <Group type="103" groupAlignment="3" attributes="0">
122
              <Group type="103" groupAlignment="3" attributes="0">
90
                  <Component id="lProxyHost" alignment="3" min="-2" max="-2" attributes="0"/>
123
                  <Component id="bTestConnection" alignment="3" min="-2" max="-2" attributes="0"/>
91
                  <Component id="tfProxyPort" alignment="3" min="-2" max="-2" attributes="0"/>
124
                  <Component id="lblTestResult" alignment="3" min="-2" max="-2" attributes="0"/>
92
                  <Component id="tfProxyHost" alignment="3" min="-2" max="-2" attributes="0"/>
93
                  <Component id="lProxyPort" alignment="3" min="-2" max="-2" attributes="0"/>
94
              </Group>
125
              </Group>
95
              <EmptySpace min="-2" max="-2" attributes="0"/>
126
              <EmptySpace min="-2" pref="11" max="-2" attributes="0"/>
96
              <Group type="103" groupAlignment="3" attributes="0">
97
                  <Component id="bMoreProxy" alignment="3" min="-2" max="-2" attributes="0"/>
98
                  <Component id="errorLabel" alignment="3" min="-2" max="-2" attributes="0"/>
99
              </Group>
100
              <EmptySpace type="unrelated" min="-2" max="-2" attributes="0"/>
101
              <Component id="jSeparator3" min="-2" pref="10" max="-2" attributes="0"/>
127
              <Component id="jSeparator3" min="-2" pref="10" max="-2" attributes="0"/>
102
              <EmptySpace type="unrelated" max="-2" attributes="0"/>
128
              <EmptySpace type="unrelated" max="-2" attributes="0"/>
103
              <Component id="jPanel1" min="-2" max="-2" attributes="0"/>
129
              <Component id="jPanel1" min="-2" max="-2" attributes="0"/>
Lines 144-149 Link Here
144
          </Border>
170
          </Border>
145
        </Property>
171
        </Property>
146
      </Properties>
172
      </Properties>
173
      <Events>
174
        <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="rbNoProxyActionPerformed"/>
175
      </Events>
147
    </Component>
176
    </Component>
148
    <Component class="javax.swing.JRadioButton" name="rbUseSystemProxy">
177
    <Component class="javax.swing.JRadioButton" name="rbUseSystemProxy">
149
      <Properties>
178
      <Properties>
Lines 298-302 Link Here
298
        </Component>
327
        </Component>
299
      </SubComponents>
328
      </SubComponents>
300
    </Container>
329
    </Container>
330
    <Component class="javax.swing.JButton" name="bReloadProxy">
331
      <Properties>
332
        <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
333
          <ResourceString bundle="org/netbeans/core/ui/options/general/Bundle.properties" key="GeneralOptionsPanel.bReloadProxy.text" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, &quot;{key}&quot;)"/>
334
        </Property>
335
      </Properties>
336
      <Events>
337
        <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="bReloadProxyActionPerformed"/>
338
      </Events>
339
    </Component>
340
    <Component class="javax.swing.JButton" name="bTestConnection">
341
      <Properties>
342
        <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
343
          <ResourceString bundle="org/netbeans/core/ui/options/general/Bundle.properties" key="GeneralOptionsPanel.bTestConnection.text" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, &quot;{key}&quot;)"/>
344
        </Property>
345
      </Properties>
346
      <Events>
347
        <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="bTestConnectionActionPerformed"/>
348
      </Events>
349
    </Component>
350
    <Component class="javax.swing.JLabel" name="lblTestResult">
351
      <Properties>
352
        <Property name="text" type="java.lang.String" editor="org.netbeans.modules.i18n.form.FormI18nStringEditor">
353
          <ResourceString bundle="org/netbeans/core/ui/options/general/Bundle.properties" key="GeneralOptionsPanel.lblTestResult.text" replaceFormat="org.openide.util.NbBundle.getMessage({sourceFileName}.class, &quot;{key}&quot;)"/>
354
        </Property>
355
      </Properties>
356
    </Component>
301
  </SubComponents>
357
  </SubComponents>
302
</Form>
358
</Form>
(-)a/core.ui/src/org/netbeans/core/ui/options/general/GeneralOptionsPanel.java (-43 / +89 lines)
Lines 1-7 Link Here
1
/*
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
3
 *
4
 * Copyright 1997-2011 Oracle and/or its affiliates. All rights reserved.
4
 * Copyright 1997-2013 Oracle and/or its affiliates. All rights reserved.
5
 *
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
7
 * Other names may be trademarks of their respective owners.
Lines 52-57 Link Here
52
import java.awt.event.ActionListener;
52
import java.awt.event.ActionListener;
53
import java.net.MalformedURLException;
53
import java.net.MalformedURLException;
54
import java.net.URL;
54
import java.net.URL;
55
import java.util.prefs.Preferences;
55
import javax.swing.AbstractButton;
56
import javax.swing.AbstractButton;
56
import javax.swing.ButtonGroup;
57
import javax.swing.ButtonGroup;
57
import javax.swing.ImageIcon;
58
import javax.swing.ImageIcon;
Lines 71-76 Link Here
71
import org.openide.util.ImageUtilities;
72
import org.openide.util.ImageUtilities;
72
import org.openide.util.Lookup;
73
import org.openide.util.Lookup;
73
import org.openide.util.NbBundle;
74
import org.openide.util.NbBundle;
75
import org.openide.util.NbPreferences;
74
76
75
/**
77
/**
76
 * Implementation of one panel in Options Dialog.
78
 * Implementation of one panel in Options Dialog.
Lines 174-186 Link Here
174
            lblUsageInfo.setVisible(false);
176
            lblUsageInfo.setVisible(false);
175
            lblLearnMore.setVisible(false);
177
            lblLearnMore.setVisible(false);
176
        }
178
        }
177
        
178
        // if system proxy setting is not detectable, disable this radio
179
        // button
180
        // do not disable this radio button at all
181
        // it could use JDK detection sometime
182
        //if (System.getProperty("netbeans.system_http_proxy") == null) // NOI18N
183
            //rbUseSystemProxy.setEnabled(false);
184
    }
179
    }
185
    
180
    
186
    /** This method is called from within the constructor to
181
    /** This method is called from within the constructor to
Lines 212-217 Link Here
212
        lblUsageInfo = new javax.swing.JLabel();
207
        lblUsageInfo = new javax.swing.JLabel();
213
        jUsageCheck = new javax.swing.JCheckBox();
208
        jUsageCheck = new javax.swing.JCheckBox();
214
        lUsage = new javax.swing.JLabel();
209
        lUsage = new javax.swing.JLabel();
210
        bReloadProxy = new javax.swing.JButton();
211
        bTestConnection = new javax.swing.JButton();
212
        lblTestResult = new javax.swing.JLabel();
215
213
216
        lWebBrowser.setLabelFor(cbWebBrowser);
214
        lWebBrowser.setLabelFor(cbWebBrowser);
217
        org.openide.awt.Mnemonics.setLocalizedText(lWebBrowser, org.openide.util.NbBundle.getMessage(GeneralOptionsPanel.class, "GeneralOptionsPanel.lWebBrowser.text")); // NOI18N
215
        org.openide.awt.Mnemonics.setLocalizedText(lWebBrowser, org.openide.util.NbBundle.getMessage(GeneralOptionsPanel.class, "GeneralOptionsPanel.lWebBrowser.text")); // NOI18N
Lines 314-319 Link Here
314
        gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
312
        gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
315
        jPanel1.add(lUsage, gridBagConstraints);
313
        jPanel1.add(lUsage, gridBagConstraints);
316
314
315
        org.openide.awt.Mnemonics.setLocalizedText(bReloadProxy, org.openide.util.NbBundle.getMessage(GeneralOptionsPanel.class, "GeneralOptionsPanel.bReloadProxy.text")); // NOI18N
316
        bReloadProxy.addActionListener(new java.awt.event.ActionListener() {
317
            public void actionPerformed(java.awt.event.ActionEvent evt) {
318
                bReloadProxyActionPerformed(evt);
319
            }
320
        });
321
322
        org.openide.awt.Mnemonics.setLocalizedText(bTestConnection, org.openide.util.NbBundle.getMessage(GeneralOptionsPanel.class, "GeneralOptionsPanel.bTestConnection.text")); // NOI18N
323
        bTestConnection.addActionListener(new java.awt.event.ActionListener() {
324
            public void actionPerformed(java.awt.event.ActionEvent evt) {
325
                bTestConnectionActionPerformed(evt);
326
            }
327
        });
328
329
        org.openide.awt.Mnemonics.setLocalizedText(lblTestResult, org.openide.util.NbBundle.getMessage(GeneralOptionsPanel.class, "GeneralOptionsPanel.lblTestResult.text")); // NOI18N
330
317
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
331
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
318
        this.setLayout(layout);
332
        this.setLayout(layout);
319
        layout.setHorizontalGroup(
333
        layout.setHorizontalGroup(
Lines 332-355 Link Here
332
                        .addComponent(lWebProxy)
346
                        .addComponent(lWebProxy)
333
                        .addGap(18, 18, 18)
347
                        .addGap(18, 18, 18)
334
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
348
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
335
                            .addComponent(rbNoProxy)
336
                            .addComponent(rbUseSystemProxy)
337
                            .addComponent(rbHTTPProxy)
338
                            .addGroup(layout.createSequentialGroup()
349
                            .addGroup(layout.createSequentialGroup()
339
                                .addGap(17, 17, 17)
350
                                .addGap(90, 90, 90)
351
                                .addComponent(errorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 1313, Short.MAX_VALUE))
352
                            .addGroup(layout.createSequentialGroup()
340
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
353
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
341
                                    .addGroup(layout.createSequentialGroup()
354
                                    .addGroup(layout.createSequentialGroup()
342
                                        .addComponent(bMoreProxy)
355
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
356
                                            .addGroup(layout.createSequentialGroup()
357
                                                .addComponent(rbHTTPProxy)
358
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
359
                                                .addComponent(lProxyHost)
360
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
361
                                                .addComponent(tfProxyHost, javax.swing.GroupLayout.DEFAULT_SIZE, 1055, Short.MAX_VALUE))
362
                                            .addGroup(layout.createSequentialGroup()
363
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
364
                                                    .addComponent(rbNoProxy)
365
                                                    .addGroup(layout.createSequentialGroup()
366
                                                        .addComponent(rbUseSystemProxy)
367
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
368
                                                        .addComponent(bReloadProxy)))
369
                                                .addGap(0, 0, Short.MAX_VALUE)))
343
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
370
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
344
                                        .addComponent(errorLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 1279, Short.MAX_VALUE))
371
                                        .addComponent(lProxyPort)
372
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
373
                                        .addComponent(tfProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
374
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
375
                                        .addComponent(bMoreProxy))
345
                                    .addGroup(layout.createSequentialGroup()
376
                                    .addGroup(layout.createSequentialGroup()
346
                                        .addComponent(lProxyHost)
377
                                        .addComponent(bTestConnection)
347
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
378
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
348
                                        .addComponent(tfProxyHost, javax.swing.GroupLayout.DEFAULT_SIZE, 1137, Short.MAX_VALUE)
379
                                        .addComponent(lblTestResult)
349
                                        .addGap(12, 12, 12)
380
                                        .addGap(0, 0, Short.MAX_VALUE)))
350
                                        .addComponent(lProxyPort)
381
                                .addContainerGap())))
351
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
352
                                        .addComponent(tfProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))))
353
                    .addComponent(jSeparator3, javax.swing.GroupLayout.DEFAULT_SIZE, 1495, Short.MAX_VALUE)
382
                    .addComponent(jSeparator3, javax.swing.GroupLayout.DEFAULT_SIZE, 1495, Short.MAX_VALUE)
354
                    .addGroup(layout.createSequentialGroup()
383
                    .addGroup(layout.createSequentialGroup()
355
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
384
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
Lines 370-390 Link Here
370
                    .addGroup(layout.createSequentialGroup()
399
                    .addGroup(layout.createSequentialGroup()
371
                        .addComponent(rbNoProxy)
400
                        .addComponent(rbNoProxy)
372
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
401
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
373
                        .addComponent(rbUseSystemProxy)
402
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
403
                            .addComponent(rbUseSystemProxy)
404
                            .addComponent(bReloadProxy))
374
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
405
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
375
                        .addComponent(rbHTTPProxy))
406
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
407
                            .addComponent(rbHTTPProxy)
408
                            .addComponent(lProxyHost)
409
                            .addComponent(tfProxyHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
410
                            .addComponent(lProxyPort)
411
                            .addComponent(tfProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
412
                            .addComponent(bMoreProxy)))
376
                    .addComponent(lWebProxy))
413
                    .addComponent(lWebProxy))
414
                .addGap(30, 30, 30)
415
                .addComponent(errorLabel)
377
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
416
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
378
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
417
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
379
                    .addComponent(lProxyHost)
418
                    .addComponent(bTestConnection)
380
                    .addComponent(tfProxyPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
419
                    .addComponent(lblTestResult))
381
                    .addComponent(tfProxyHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
420
                .addGap(11, 11, 11)
382
                    .addComponent(lProxyPort))
383
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
384
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
385
                    .addComponent(bMoreProxy)
386
                    .addComponent(errorLabel))
387
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
388
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
421
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
389
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
422
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
390
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
423
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
Lines 475-484 Link Here
475
        }
508
        }
476
509
477
    }//GEN-LAST:event_lblLearnMoreMousePressed
510
    }//GEN-LAST:event_lblLearnMoreMousePressed
511
512
    private void bReloadProxyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bReloadProxyActionPerformed
513
        ProxySettings.reload();
514
        rbUseSystemProxy.setToolTipText(getUseSystemProxyToolTip());
515
    }//GEN-LAST:event_bReloadProxyActionPerformed
516
517
    private void bTestConnectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bTestConnectionActionPerformed
518
        
519
    }//GEN-LAST:event_bTestConnectionActionPerformed
478
    
520
    
479
    
521
    
480
    // Variables declaration - do not modify//GEN-BEGIN:variables
522
    // Variables declaration - do not modify//GEN-BEGIN:variables
481
    private javax.swing.JButton bMoreProxy;
523
    private javax.swing.JButton bMoreProxy;
524
    private javax.swing.JButton bReloadProxy;
525
    private javax.swing.JButton bTestConnection;
482
    private javax.swing.JComboBox cbWebBrowser;
526
    private javax.swing.JComboBox cbWebBrowser;
483
    private javax.swing.JButton editBrowserButton;
527
    private javax.swing.JButton editBrowserButton;
484
    private javax.swing.JLabel errorLabel;
528
    private javax.swing.JLabel errorLabel;
Lines 492-497 Link Here
492
    private javax.swing.JLabel lWebBrowser;
536
    private javax.swing.JLabel lWebBrowser;
493
    private javax.swing.JLabel lWebProxy;
537
    private javax.swing.JLabel lWebProxy;
494
    private javax.swing.JLabel lblLearnMore;
538
    private javax.swing.JLabel lblLearnMore;
539
    private javax.swing.JLabel lblTestResult;
495
    private javax.swing.JLabel lblUsageInfo;
540
    private javax.swing.JLabel lblUsageInfo;
496
    private javax.swing.JRadioButton rbHTTPProxy;
541
    private javax.swing.JRadioButton rbHTTPProxy;
497
    private javax.swing.JRadioButton rbNoProxy;
542
    private javax.swing.JRadioButton rbNoProxy;
Lines 542-559 Link Here
542
        return NbBundle.getMessage (GeneralOptionsPanel.class, key, params);
587
        return NbBundle.getMessage (GeneralOptionsPanel.class, key, params);
543
    }
588
    }
544
    
589
    
545
    private String getUseSystemProxyToolTip () {
590
    private String getUseSystemProxyToolTip() {
546
        if (rbUseSystemProxy.isSelected ()) {
591
        if (rbUseSystemProxy.isSelected()) {
547
            String toolTip;
592
            String toolTip;
548
            String sHost = System.getProperty ("http.proxyHost"); // NOI18N
593
            String sHost = getProxyPreferences().get(ProxySettings.SYSTEM_PROXY_HTTP_HOST, ""); // NOI18N            
549
            if (sHost == null || sHost.trim ().length () == 0) {
550
                toolTip = loc ("GeneralOptionsPanel_rbUseSystemProxy_Direct"); // NOI18N
551
            } else {
552
                String sPort = System.getProperty ("http.proxyPort"); // NOI18N
553
                toolTip = loc ("GeneralOptionsPanel_rbUseSystemProxy_Format", sHost, sPort);
554
            }
555
            if (GeneralOptionsModel.usePAC()) {
594
            if (GeneralOptionsModel.usePAC()) {
556
                toolTip = getPacFile();
595
                toolTip = getPacFile();
596
            } else if (sHost == null || sHost.trim().length() == 0) {
597
                toolTip = loc("GeneralOptionsPanel_rbUseSystemProxy_Direct"); // NOI18N
598
            } else {
599
                String sPort = getProxyPreferences().get(ProxySettings.SYSTEM_PROXY_HTTP_PORT, ""); // NOI18N
600
                toolTip = loc("GeneralOptionsPanel_rbUseSystemProxy_Format", sHost, sPort);
557
            }
601
            }
558
            return toolTip;
602
            return toolTip;
559
        } else {
603
        } else {
Lines 710-717 Link Here
710
    }
754
    }
711
755
712
    private static String getPacFile() {
756
    private static String getPacFile() {
713
        String init = System.getProperty("netbeans.system_http_proxy"); // NOI18N
757
        return getProxyPreferences().get(ProxySettings.SYSTEM_PAC, "");
714
        return init.substring(4).trim();
715
    }
758
    }
716
    
759
    
760
    private static Preferences getProxyPreferences() {
761
        return NbPreferences.forModule(ProxySettings.class);
762
    }
717
}
763
}
(-)a/libs.jna/nbproject/project.xml (-9 / +10 lines)
Lines 71-91 Link Here
71
                <friend>org.jruby</friend>
71
                <friend>org.jruby</friend>
72
                <friend>org.netbeans.core.browser.xulrunner</friend>
72
                <friend>org.netbeans.core.browser.xulrunner</friend>
73
                <friend>org.netbeans.core.nativeaccess</friend>
73
                <friend>org.netbeans.core.nativeaccess</friend>
74
                <friend>org.netbeans.core.network</friend>
75
                <friend>org.netbeans.libs.djnsswt.gtklinuxx64</friend>
76
                <friend>org.netbeans.libs.djnsswt.gtklinuxx86</friend>
77
                <friend>org.netbeans.libs.djnsswt.win32x64</friend>
78
                <friend>org.netbeans.libs.djnsswt.win32x86</friend>
79
                <friend>org.netbeans.libs.svnClientAdapter.svnkit</friend>
74
                <friend>org.netbeans.modules.dlight.nativeexecution</friend>
80
                <friend>org.netbeans.modules.dlight.nativeexecution</friend>
75
                <friend>org.netbeans.modules.extbrowser</friend>
81
                <friend>org.netbeans.modules.extbrowser</friend>
76
                <friend>org.netbeans.modules.extexecution.impl</friend>
82
                <friend>org.netbeans.modules.extexecution.impl</friend>
77
                <friend>org.netbeans.modules.keyring.impl</friend>
83
                <friend>org.netbeans.modules.keyring.impl</friend>
84
                <friend>org.netbeans.modules.libs.djnsswt</friend>
85
                <friend>org.netbeans.modules.masterfs.linux</friend>
86
                <friend>org.netbeans.modules.masterfs.macosx</friend>
87
                <friend>org.netbeans.modules.masterfs.solaris</friend>
78
                <friend>org.netbeans.modules.masterfs.windows</friend>
88
                <friend>org.netbeans.modules.masterfs.windows</friend>
79
                <friend>org.netbeans.modules.masterfs.linux</friend>
80
                <friend>org.netbeans.modules.masterfs.solaris</friend>
81
                <friend>org.netbeans.modules.masterfs.macosx</friend>
82
                <friend>org.netbeans.modules.python.qshell</friend>
89
                <friend>org.netbeans.modules.python.qshell</friend>
83
                <friend>org.netbeans.libs.svnClientAdapter.svnkit</friend>
84
                <friend>org.netbeans.modules.libs.djnsswt</friend>
85
                <friend>org.netbeans.libs.djnsswt.gtklinuxx86</friend>
86
                <friend>org.netbeans.libs.djnsswt.gtklinuxx64</friend>
87
                <friend>org.netbeans.libs.djnsswt.win32x86</friend>
88
                <friend>org.netbeans.libs.djnsswt.win32x64</friend>
89
                <package>com.sun.jna</package>
90
                <package>com.sun.jna</package>
90
                <package>com.sun.jna.ptr</package>
91
                <package>com.sun.jna.ptr</package>
91
                <package>com.sun.jna.win32</package>
92
                <package>com.sun.jna.win32</package>
(-)a/nbbuild/cluster.properties (+1 lines)
Lines 167-172 Link Here
167
        core.multiview,\
167
        core.multiview,\
168
        core.nativeaccess,\
168
        core.nativeaccess,\
169
        core.netigso,\
169
        core.netigso,\
170
        core.network,\
170
        core.osgi,\
171
        core.osgi,\
171
        core.output2,\
172
        core.output2,\
172
        core.startup,\
173
        core.startup,\
(-)3bff97f36acc (+102 lines)
Added Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<!--
3
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4
5
Copyright 1997-2013 Oracle and/or its affiliates. All rights reserved.
6
7
Oracle and Java are registered trademarks of Oracle and/or its affiliates.
8
Other names may be trademarks of their respective owners.
9
10
11
The contents of this file are subject to the terms of either the GNU
12
General Public License Version 2 only ("GPL") or the Common
13
Development and Distribution License("CDDL") (collectively, the
14
"License"). You may not use this file except in compliance with the
15
License. You can obtain a copy of the License at
16
http://www.netbeans.org/cddl-gplv2.html
17
or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
18
specific language governing permissions and limitations under the
19
License.  When distributing the software, include this License Header
20
Notice in each file and include the License file at
21
nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
22
particular file as subject to the "Classpath" exception as provided
23
by Oracle in the GPL Version 2 section of the License file that
24
accompanied this code. If applicable, add the following below the
25
License Header, with the fields enclosed by brackets [] replaced by
26
your own identifying information:
27
"Portions Copyrighted [year] [name of copyright owner]"
28
29
Contributor(s):
30
31
The Original Software is NetBeans. The Initial Developer of the Original
32
Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
33
Microsystems, Inc. All Rights Reserved.
34
35
If you wish your version of this file to be governed by only the CDDL
36
or only the GPL Version 2, indicate your decision by adding
37
"[Contributor] elects to include this software in this distribution
38
under the [CDDL or GPL Version 2] license." If you do not indicate a
39
single choice of license, a recipient has the option to distribute
40
your version of this file under either the CDDL, the GPL Version 2 or
41
to extend the choice of license to its licensees as provided above.
42
However, if you add GPL Version 2 code and therefore, elected the GPL
43
Version 2 license, then the option applies only if the new code is
44
made subject to such option by the copyright holder.
45
-->
46
<?xml-stylesheet type="text/xml" href="../nbbuild/javadoctools/apichanges.xsl"?>
47
<!DOCTYPE apichanges PUBLIC "-//NetBeans//DTD API changes list 1.0//EN" "../nbbuild/javadoctools/apichanges.dtd">
48
49
<apichanges>
50
51
  <apidefs>
52
    <apidef name="launcher-proxy-property">Startup Proxy System Property Devel API</apidef>
53
  </apidefs>
54
55
  <changes>
56
     <change id="system-proxy-reload">
57
        <api name="launcher-proxy-property"/>
58
        <summary>Launcher does not provide proxy setting properties.</summary>
59
        <version major="2" minor="60"/>
60
        <date day="2" month="4" year="2013"/>
61
        <author login="lfischme"/>
62
        <compatibility addition="no" binary="compatible" semantic="incompatible" />
63
        <description>
64
        <p>
65
            Launcher does not provide <code>netbeans.system_http_proxy</code> and
66
            <code>netbeans.system_http_non_proxy_hosts</code> properties anymore.
67
            Proxy settings are now detected in Core Network module.
68
        </p>
69
        </description>
70
        <issue number="201731"/>
71
    </change>
72
  </changes>
73
74
  <!-- Now the surrounding HTML text and document structure: -->
75
76
  <htmlcontents>
77
    <head>
78
      <title>Change History for the Friend Core APIs</title>
79
      <link rel="stylesheet" href="prose.css" type="text/css"/>
80
    </head>
81
    <body>
82
83
<p class="overviewlink"><a href="overview-summary.html">Overview</a></p>
84
85
<h1>Introduction</h1>
86
87
<p>
88
This document lists changes made to the API between core/startup and core
89
modules. It is a friend API so it does not need to be developed compatibly,
90
and indeed it is not. 
91
</p>
92
93
<!-- The actual lists of changes, as summaries and details: -->
94
95
      <hr/><standard-changelists module-code-name="org.netbeans.bootstrap"/>
96
97
      <hr/><p>@FOOTER@</p>
98
99
    </body>
100
  </htmlcontents>
101
102
</apichanges>
(-)a/o.n.bootstrap/arch.xml (-17 lines)
Lines 505-527 Link Here
505
                </api>
505
                </api>
506
            </li>
506
            </li>
507
            <li>
507
            <li>
508
                <api type="export" group="systemproperty" name="netbeans.system_http_proxy" category="devel">
509
                    System proxy setting in the format of hostname:port.  The
510
                    launcher does its best to detect the OS/desktop HTTP proxy
511
                    setting.  There is no guarantee that it succeeds.  The property
512
                    may not be set at all or its value may be totally wrong.
513
                </api>
514
            </li>
515
            <li>
516
                <api type="export" group="systemproperty" name="netbeans.system_http_non_proxy_hosts" category="devel">
517
                    List of addresses that are not accessed through proxy.  The
518
                    launcher attempts to detect the OS/desktop HTTP proxy
519
                    setting.  There is no guarantee that it succeeds.  The property
520
                    may not be set at all or its value may be totally wrong and 
521
                    its format is not defined.
522
                </api>
523
            </li>
524
            <li>
525
                <api type="export" group="systemproperty" name="netbeans.classpath" category="friend">
508
                <api type="export" group="systemproperty" name="netbeans.classpath" category="friend">
526
                    Classpath to prepend to core loader (normally just
509
                    Classpath to prepend to core loader (normally just
527
                    <samp>lib/*.jar</samp>). Possibly useful for testing
510
                    <samp>lib/*.jar</samp>). Possibly useful for testing
(-)a/o.n.bootstrap/launcher/unix/nbexec (-178 / +5 lines)
Lines 352-536 Link Here
352
    fi
352
    fi
353
}
353
}
354
354
355
# detect system http proxy setting
355
if [ "$KDE_FULL_SESSION" = "true" ] ; then
356
356
    jargs="-Dnetbeans.running.environment=kde $jargs"        
357
detect_system_proxy () {
357
else
358
    if [ ! -z "$http_proxy" ]; then
358
    if [ ! -z "$GNOME_DESKTOP_SESSION_ID" ] ; then
359
        http_proxy_tmp=$http_proxy
359
        jargs="-Dnetbeans.running.environment=gnome $jargs" 
360
    fi
360
    fi
361
    return 0
362
}
363
364
detect_gnome_proxy () {
365
    gsettings=/usr/bin/gsettings   
366
    if [ -x $gsettings ] ; then 
367
        translate=/usr/bin/tr
368
               
369
        proxy_mode=`$gsettings get org.gnome.system.proxy mode 2>/dev/null`
370
        if [ "$proxy_mode" = "'manual'" ] ; then
371
            http_proxy_host=`$gsettings get org.gnome.system.proxy.http host 2>/dev/null | $translate -d "'"`
372
            http_proxy_port=`$gsettings get org.gnome.system.proxy.http port 2>/dev/null`
373
            http_proxy_tmp=$http_proxy_host:$http_proxy_port
374
            http_non_proxy_hosts=`$gsettings get org.gnome.system.proxy ignore-hosts 2>/dev/null`
375
            if [ $? ] ; then
376
                http_non_proxy_hosts=`echo $http_non_proxy_hosts | $translate -d "[]' "`
377
            fi
378
            socks_proxy_host=`$gsettings get org.gnome.system.proxy.socks host 2>/dev/null | $translate -d "'"`
379
            socks_proxy_port=`$gsettings get org.gnome.system.proxy.socks port 2>/dev/null`
380
            socks_proxy_tmp=$socks_proxy_host:$socks_proxy_port
381
382
            return 0
383
        else
384
            if [ "$proxy_mode" = "'none'" ] ; then
385
                detect_system_proxy
386
                if [ -z "$http_proxy_tmp" ]; then
387
                    http_proxy_tmp="DIRECT"
388
                fi
389
                return 0
390
            else
391
                if [ "$proxy_mode" = "'auto'" ] ; then
392
                    detect_system_proxy
393
                    pac_file=`$gsettings get org.gnome.system.proxy autoconfig-url 2>/dev/null | $translate -d "'"`
394
                    if [ ! -z "$pac_file" ]; then
395
                        http_proxy_tmp="PAC "$pac_file
396
                    fi
397
                    return 0
398
                fi
399
            fi
400
        fi
401
    fi
402
403
    gconftool=/usr/bin/gconftool-2
404
    if [ -x  $gconftool ] ; then
405
        proxy_mode=`$gconftool --get /system/proxy/mode 2>/dev/null`
406
        if [ "$proxy_mode" = "manual" ] ; then
407
            http_proxy_host=`$gconftool --get /system/http_proxy/host 2>/dev/null`
408
            http_proxy_port=`$gconftool --get /system/http_proxy/port 2>/dev/null`
409
            http_proxy_tmp=$http_proxy_host:$http_proxy_port
410
            http_non_proxy_hosts=`$gconftool --get /system/http_proxy/ignore_hosts 2>/dev/null`
411
            if [ $? ] ; then
412
                http_non_proxy_hosts=`echo $http_non_proxy_hosts | /bin/sed 's/\]//'`
413
            fi
414
            socks_proxy_host=`$gconftool --get /system/proxy/socks_host 2>/dev/null`
415
            socks_proxy_port=`$gconftool --get /system/proxy/socks_port 2>/dev/null`
416
            socks_proxy_tmp=$socks_proxy_host:$socks_proxy_port
417
418
            return 0
419
        else
420
            if [ "$proxy_mode" = "none" ] ; then
421
                detect_system_proxy
422
                if [ -z "$http_proxy_tmp" ]; then
423
                    http_proxy_tmp="DIRECT"
424
                fi
425
                return 0
426
            else
427
                if [ "$proxy_mode" = "auto" ] ; then
428
                    detect_system_proxy
429
                    pac_file=`$gconftool --get /system/proxy/autoconfig_url 2>/dev/null`
430
                    if [ ! -z "$pac_file" ]; then
431
                        http_proxy_tmp="PAC "$pac_file
432
                    fi
433
                    return 0
434
                fi
435
            fi
436
        fi
437
    fi
438
    return 1
439
}
440
441
detect_kde_proxy () {
442
    kioslaverc="${HOME}/.kde/share/config/kioslaverc"
443
    if [ -f $kioslaverc ] ; then
444
        if /bin/grep 'ProxyType=1' "$kioslaverc" >/dev/null 2>&1; then
445
            http_proxy_tmp=`/bin/grep 'httpProxy=http://' "$kioslaverc"`
446
            if [ $? ] ; then
447
                http_proxy_tmp=`echo $http_proxy_tmp | /bin/sed 's/httpProxy=http:\/\///'`
448
                return 0
449
            fi
450
            http_non_proxy_hosts=`/bin/grep 'NoProxyFor=' "$kioslaverc"`
451
            if [ $? ] ; then
452
                http_non_proxy_hosts=`echo $http_non_proxy_hosts | /bin/sed 's/NoProxyFor=//'`
453
            fi
454
        else
455
            if /bin/grep 'ProxyType=0' "$kioslaverc" >/dev/null 2>&1; then
456
                detect_system_proxy
457
                if [ -z "$http_proxy_tmp" ]; then
458
                    http_proxy_tmp="DIRECT"
459
                fi
460
                return 0
461
            else
462
                if /bin/grep 'ProxyType=2' "$kioslaverc" >/dev/null 2>&1; then
463
                    pac_file=`grep "Proxy Config Script=" $kioslaverc  | cut -f 2 -d =`
464
                    http_proxy_tmp="PAC "$pac_file
465
                    return 0
466
                fi
467
            fi
468
        fi
469
    fi
470
    return 1
471
}
472
473
detect_macosx_proxy () {
474
    if [ ! -x /usr/sbin/scutil ] ; then
475
	return 1
476
    fi
477
478
    scutil_out=/tmp/nb-proxy-detection.$$
479
    cat <<EOF | /usr/sbin/scutil > ${scutil_out}
480
open
481
show State:/Network/Global/Proxies
482
close
483
EOF
484
485
    if /usr/bin/grep "ProxyAuto.*: *1" ${scutil_out} >/dev/null 2>&1; then
486
        if  /usr/bin/grep "ProxyAutoConfigEnable.*: *1" ${scutil_out} >/dev/null 2>&1; then
487
            http_proxy_tmp="PAC `/usr/bin/grep ProxyAutoConfigURLString ${scutil_out} | /usr/bin/awk 'END{print $3}'`"
488
            rm ${scutil_out}
489
            return 0
490
        fi
491
492
        rm ${scutil_out}
493
        return 1
494
    fi
495
496
    if /usr/bin/grep "HTTPEnable *: *1" ${scutil_out} >/dev/null 2>&1; then
497
	http_proxy_host=`/usr/bin/grep HTTPProxy ${scutil_out} | /usr/bin/awk 'END{print $3}'`
498
	http_proxy_port=`/usr/bin/grep HTTPPort ${scutil_out} | /usr/bin/awk 'END{print $3} '`
499
        http_proxy_tmp=$http_proxy_host:$http_proxy_port
500
        rm ${scutil_out}
501
        return 0
502
    fi
503
    
504
    http_proxy_tmp="DIRECT"
505
    rm ${scutil_out}
506
    return 0
507
}
508
509
unset http_proxy_tmp
510
511
if [ `uname` = Darwin ] ; then
512
    detect_macosx_proxy
513
else
514
    if [ "$KDE_FULL_SESSION" = "true" ] ; then
515
        detect_kde_proxy
516
    else
517
        if [ ! -z "$GNOME_DESKTOP_SESSION_ID" ] ; then
518
            detect_gnome_proxy
519
        fi
520
    fi
521
fi
522
523
# fall back to the environment-defined http_proxy if nothing found so far
524
if [ -z "$http_proxy_tmp" ]; then
525
    http_proxy_tmp=$http_proxy
526
fi
527
528
if [ ! -z "$http_proxy_tmp" ] ; then
529
	jargs="-Dnetbeans.system_http_proxy=\"$http_proxy_tmp\" -Dnetbeans.system_http_non_proxy_hosts=\"$http_non_proxy_hosts\" $jargs"
530
fi
531
532
if [ ! -z "$socks_proxy_tmp" ] ; then
533
	jargs="-Dnetbeans.system_socks_proxy=\"$socks_proxy_tmp\" $jargs"
534
fi
361
fi
535
362
536
if [ ! -z "${DEFAULT_USERDIR_ROOT}" ] ; then
363
if [ ! -z "${DEFAULT_USERDIR_ROOT}" ] ; then
(-)a/o.n.bootstrap/launcher/windows/platformlauncher.cpp (-95 / +1 lines)
Lines 72-80 Link Here
72
const char *PlatformLauncher::OPT_NB_CLUSTERS = "-Dnetbeans.dirs=";
72
const char *PlatformLauncher::OPT_NB_CLUSTERS = "-Dnetbeans.dirs=";
73
const char *PlatformLauncher::OPT_NB_USERDIR = "-Dnetbeans.user=";
73
const char *PlatformLauncher::OPT_NB_USERDIR = "-Dnetbeans.user=";
74
const char *PlatformLauncher::OPT_DEFAULT_USERDIR_ROOT = "-Dnetbeans.default_userdir_root=";
74
const char *PlatformLauncher::OPT_DEFAULT_USERDIR_ROOT = "-Dnetbeans.default_userdir_root=";
75
const char *PlatformLauncher::OPT_HTTP_PROXY = "-Dnetbeans.system_http_proxy=";
76
const char *PlatformLauncher::OPT_HTTP_NONPROXY = "-Dnetbeans.system_http_non_proxy_hosts=";
77
const char *PlatformLauncher::OPT_SOCKS_PROXY = "-Dnetbeans.system_socks_proxy=";
78
const char *PlatformLauncher::OPT_HEAP_DUMP = "-XX:+HeapDumpOnOutOfMemoryError";
75
const char *PlatformLauncher::OPT_HEAP_DUMP = "-XX:+HeapDumpOnOutOfMemoryError";
79
const char *PlatformLauncher::OPT_HEAP_DUMP_PATH = "-XX:HeapDumpPath=";
76
const char *PlatformLauncher::OPT_HEAP_DUMP_PATH = "-XX:HeapDumpPath=";
80
const char *PlatformLauncher::OPT_KEEP_WORKING_SET_ON_MINIMIZE = "-Dsun.awt.keepWorkingSetOnMinimize=true";
77
const char *PlatformLauncher::OPT_KEEP_WORKING_SET_ON_MINIMIZE = "-Dsun.awt.keepWorkingSetOnMinimize=true";
Lines 82-93 Link Here
82
const char *PlatformLauncher::OPT_SPLASH = "-splash:";
79
const char *PlatformLauncher::OPT_SPLASH = "-splash:";
83
const char *PlatformLauncher::OPT_SPLASH_PATH = "\\var\\cache\\splash.png";
80
const char *PlatformLauncher::OPT_SPLASH_PATH = "\\var\\cache\\splash.png";
84
81
85
const char *PlatformLauncher::REG_PROXY_KEY = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet settings";
86
const char *PlatformLauncher::REG_PROXY_ENABLED_NAME = "ProxyEnable";
87
const char *PlatformLauncher::REG_PROXY_SERVER_NAME = "ProxyServer";
88
const char *PlatformLauncher::REG_PROXY_OVERRIDE_NAME = "ProxyOverride";
89
const char *PlatformLauncher::REG_PAC_FILE = "AutoConfigURL";
90
const char *PlatformLauncher::PROXY_DIRECT = "DIRECT";
91
const char *PlatformLauncher::HEAP_DUMP_PATH =  "\\var\\log\\heapdump.hprof";
82
const char *PlatformLauncher::HEAP_DUMP_PATH =  "\\var\\log\\heapdump.hprof";
92
const char *PlatformLauncher::RESTART_FILE_PATH =  "\\var\\restart";
83
const char *PlatformLauncher::RESTART_FILE_PATH =  "\\var\\restart";
93
84
Lines 596-691 Link Here
596
            MoveFile (heapdumpfile.c_str(), heapdumpfileold.c_str());
587
            MoveFile (heapdumpfile.c_str(), heapdumpfileold.c_str());
597
        }
588
        }
598
    }
589
    }
599
590
    
600
    string proxy, nonProxy, socksProxy;
601
    if (!findHttpProxyFromEnv(proxy)) {
602
        findProxiesFromRegistry(proxy, nonProxy, socksProxy);
603
    }
604
    if (!proxy.empty()) {
605
        option = OPT_HTTP_PROXY;
606
        option += proxy;
607
        javaOptions.push_back(option);
608
    }
609
    if (!nonProxy.empty()) {
610
        option = OPT_HTTP_NONPROXY;
611
        option += nonProxy;
612
        javaOptions.push_back(option);
613
    }
614
    if (!socksProxy.empty()) {
615
        option = OPT_SOCKS_PROXY;
616
        option += socksProxy;
617
        javaOptions.push_back(option);
618
    }
619
620
    option = OPT_KEEP_WORKING_SET_ON_MINIMIZE;
591
    option = OPT_KEEP_WORKING_SET_ON_MINIMIZE;
621
    javaOptions.push_back(option);
592
    javaOptions.push_back(option);
622
}
593
}
623
594
624
// Reads value of http_proxy environment variable to use it as proxy setting
625
bool PlatformLauncher::findHttpProxyFromEnv(string &proxy) {
626
    logMsg("findHttpProxyFromEnv()");
627
    char *envVar = getenv("http_proxy");
628
    if (envVar) {
629
        // is it URL?
630
        int prefixLen = strlen("http://");
631
        if (strncmp(envVar, "http://", prefixLen) == 0 && envVar[strlen(envVar) - 1] == '/'
632
                && strlen(envVar) > strlen("http://")) {
633
            // trim URL part to keep only 'host[:port]'
634
            proxy = envVar + prefixLen;
635
            proxy.erase(proxy.size() - 1);
636
            logMsg("Found proxy in environment variable: %s", proxy.c_str());
637
            return true;
638
        }
639
    }
640
    return false;
641
}
642
643
bool PlatformLauncher::findProxiesFromRegistry(string &proxy, string &nonProxy, string &socksProxy) {
644
    logMsg("findProxiesFromRegistry()");
645
    socksProxy = nonProxy = proxy = "";
646
    DWORD proxyEnable = 0;
647
    if (!getDwordFromRegistry(HKEY_CURRENT_USER, REG_PROXY_KEY, REG_PROXY_ENABLED_NAME, proxyEnable)) {
648
        return false;
649
    }
650
651
    if (!proxyEnable) {
652
        logMsg("Manual Proxy disabled");
653
        string pacFile;
654
        if (getStringFromRegistry(HKEY_CURRENT_USER, REG_PROXY_KEY, REG_PAC_FILE, pacFile)) {
655
            logMsg("AutoConfigURL found.");
656
            proxy = "PAC " + pacFile;
657
        } else {
658
            proxy = PROXY_DIRECT;
659
        }
660
        return true;
661
    }
662
    
663
    string proxyServer;
664
    if (!getStringFromRegistry(HKEY_CURRENT_USER, REG_PROXY_KEY, REG_PROXY_SERVER_NAME, proxyServer)) {
665
        return false;
666
    }
667
668
    if (proxyServer.find('=') == string::npos) {
669
        proxy = proxyServer;
670
    } else {
671
        string::size_type pos = proxyServer.find("socks=");
672
        if (pos != string::npos) {
673
            if (proxyServer.size() > pos + 1 && proxyServer.at(pos) != ';') {
674
                string::size_type endPos = proxyServer.find(';', pos);
675
                socksProxy = proxyServer.substr(pos, endPos == string::npos ? string::npos : endPos - pos);
676
            }
677
        }
678
        pos = proxyServer.find("http=");
679
        if (pos != string::npos) {
680
            string::size_type endPos = proxyServer.find(';', pos);
681
            proxy = proxyServer.substr(pos, endPos == string::npos ? string::npos : endPos - pos);
682
        }
683
    }
684
    logMsg("Proxy servers:\n\tproxy: %s\n\tsocks proxy: %s\n\tnonProxy: %s", proxy.c_str(), socksProxy.c_str(), nonProxy.c_str());
685
    getStringFromRegistry(HKEY_CURRENT_USER, REG_PROXY_KEY, REG_PROXY_OVERRIDE_NAME, nonProxy);
686
    return true;
687
}
688
689
string & PlatformLauncher::constructClassPath(bool runUpdater) {
595
string & PlatformLauncher::constructClassPath(bool runUpdater) {
690
    logMsg("constructClassPath()");
596
    logMsg("constructClassPath()");
691
    addedToCP.clear();
597
    addedToCP.clear();
(-)a/o.n.bootstrap/launcher/windows/platformlauncher.h (-11 lines)
Lines 55-67 Link Here
55
class PlatformLauncher {
55
class PlatformLauncher {
56
    static const char *REQ_JAVA_VERSION;
56
    static const char *REQ_JAVA_VERSION;
57
    static const char *HELP_MSG;
57
    static const char *HELP_MSG;
58
    static const char *REG_PROXY_KEY;
59
    static const char *REG_PROXY_ENABLED_NAME;
60
    static const char *REG_PROXY_SERVER_NAME;
61
    static const char *REG_PROXY_OVERRIDE_NAME;
62
    static const char *REG_PAC_FILE;
63
58
64
    static const char *PROXY_DIRECT;
65
    static const char *HEAP_DUMP_PATH;
59
    static const char *HEAP_DUMP_PATH;
66
    static const char *RESTART_FILE_PATH;
60
    static const char *RESTART_FILE_PATH;
67
61
Lines 70-78 Link Here
70
    static const char *OPT_NB_CLUSTERS;
64
    static const char *OPT_NB_CLUSTERS;
71
    static const char *OPT_NB_USERDIR;
65
    static const char *OPT_NB_USERDIR;
72
    static const char *OPT_DEFAULT_USERDIR_ROOT;
66
    static const char *OPT_DEFAULT_USERDIR_ROOT;
73
    static const char *OPT_HTTP_PROXY;
74
    static const char *OPT_HTTP_NONPROXY;
75
    static const char *OPT_SOCKS_PROXY;
76
    static const char *OPT_HEAP_DUMP;
67
    static const char *OPT_HEAP_DUMP;
77
    static const char *OPT_HEAP_DUMP_PATH;
68
    static const char *OPT_HEAP_DUMP_PATH;
78
    static const char *OPT_KEEP_WORKING_SET_ON_MINIMIZE;
69
    static const char *OPT_KEEP_WORKING_SET_ON_MINIMIZE;
Lines 106-113 Link Here
106
    bool shouldAutoUpdate(bool firstStart, const char *basePath);
97
    bool shouldAutoUpdate(bool firstStart, const char *basePath);
107
    bool shouldAutoUpdateClusters(bool firstStart);
98
    bool shouldAutoUpdateClusters(bool firstStart);
108
    void prepareOptions();
99
    void prepareOptions();
109
    bool findHttpProxyFromEnv(std::string &proxy);
110
    bool findProxiesFromRegistry(std::string &proxy, std::string &nonProxy, std::string &socksProxy);
111
    std::string & constructClassPath(bool runUpdater);
100
    std::string & constructClassPath(bool runUpdater);
112
    void addFilesToClassPath(const char *dir, const char *subdir, const char *pattern);
101
    void addFilesToClassPath(const char *dir, const char *subdir, const char *pattern);
113
    void addToClassPath(const char *path, bool onlyIfExists = false);
102
    void addToClassPath(const char *path, bool onlyIfExists = false);
(-)a/o.n.bootstrap/manifest.mf (-1 / +1 lines)
Lines 1-6 Link Here
1
Manifest-Version: 1.0
1
Manifest-Version: 1.0
2
OpenIDE-Module: org.netbeans.bootstrap/1
2
OpenIDE-Module: org.netbeans.bootstrap/1
3
OpenIDE-Module-Specification-Version: 2.59
3
OpenIDE-Module-Specification-Version: 2.60
4
OpenIDE-Module-Localizing-Bundle: org/netbeans/Bundle.properties
4
OpenIDE-Module-Localizing-Bundle: org/netbeans/Bundle.properties
5
OpenIDE-Module-Recommends: org.netbeans.NetigsoFramework
5
OpenIDE-Module-Recommends: org.netbeans.NetigsoFramework
6
6
(-)a/o.n.bootstrap/nbproject/project.properties (-1 / +2 lines)
Lines 1-6 Link Here
1
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
1
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
2
#
2
#
3
# Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
3
# Copyright 1997-2013 Oracle and/or its affiliates. All rights reserved.
4
#
4
#
5
# Oracle and Java are registered trademarks of Oracle and/or its affiliates.
5
# Oracle and Java are registered trademarks of Oracle and/or its affiliates.
6
# Other names may be trademarks of their respective owners.
6
# Other names may be trademarks of their respective owners.
Lines 52-57 Link Here
52
nbm.executable.files=lib/nbexec
52
nbm.executable.files=lib/nbexec
53
53
54
javadoc.arch=${basedir}/arch.xml
54
javadoc.arch=${basedir}/arch.xml
55
javadoc.apichanges=${basedir}/apichanges.xml
55
56
56
# When changing this list, change 'verifyexcludes' param. of 'makejnlp' task in apisupport.harness/release/jnlp.xml as well
57
# When changing this list, change 'verifyexcludes' param. of 'makejnlp' task in apisupport.harness/release/jnlp.xml as well
57
jnlp.verify.excludes=lib/nbexec,lib/nbexec.exe,lib/nbexec64.exe,lib/nbexec.dll,lib/nbexec64.dll
58
jnlp.verify.excludes=lib/nbexec,lib/nbexec.exe,lib/nbexec64.exe,lib/nbexec.dll,lib/nbexec64.dll
(-)3bff97f36acc (+142 lines)
Added Link Here
1
<?xml version="1.0" encoding="UTF-8"?>
2
<!--
3
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4
5
Copyright 1997-2013 Oracle and/or its affiliates. All rights reserved.
6
7
Oracle and Java are registered trademarks of Oracle and/or its affiliates.
8
Other names may be trademarks of their respective owners.
9
10
11
The contents of this file are subject to the terms of either the GNU
12
General Public License Version 2 only ("GPL") or the Common
13
Development and Distribution License("CDDL") (collectively, the
14
"License"). You may not use this file except in compliance with the
15
License. You can obtain a copy of the License at
16
http://www.netbeans.org/cddl-gplv2.html
17
or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
18
specific language governing permissions and limitations under the
19
License.  When distributing the software, include this License Header
20
Notice in each file and include the License file at
21
nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
22
particular file as subject to the "Classpath" exception as provided
23
by Oracle in the GPL Version 2 section of the License file that
24
accompanied this code. If applicable, add the following below the
25
License Header, with the fields enclosed by brackets [] replaced by
26
your own identifying information:
27
"Portions Copyrighted [year] [name of copyright owner]"
28
29
Contributor(s):
30
31
The Original Software is NetBeans. The Initial Developer of the Original
32
Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
33
Microsystems, Inc. All Rights Reserved.
34
35
If you wish your version of this file to be governed by only the CDDL
36
or only the GPL Version 2, indicate your decision by adding
37
"[Contributor] elects to include this software in this distribution
38
under the [CDDL or GPL Version 2] license." If you do not indicate a
39
single choice of license, a recipient has the option to distribute
40
your version of this file under either the CDDL, the GPL Version 2 or
41
to extend the choice of license to its licensees as provided above.
42
However, if you add GPL Version 2 code and therefore, elected the GPL
43
Version 2 license, then the option applies only if the new code is
44
made subject to such option by the copyright holder.
45
-->
46
<?xml-stylesheet type="text/xml" href="../nbbuild/javadoctools/apichanges.xsl"?>
47
<!DOCTYPE apichanges PUBLIC "-//NetBeans//DTD API changes list 1.0//EN" "../nbbuild/javadoctools/apichanges.dtd">
48
49
<apichanges>
50
51
  <apidefs>
52
    <apidef name="friend">Bridge Core with Core Network Friend API</apidef>
53
  </apidefs>
54
55
  <changes>
56
      <change id="proxy-selector-brigde">
57
          <api name="friend"/>
58
          <summary>Core Network provides ProxySelector</summary>
59
          <version major="3" minor="40"/>
60
          <date day="2" month="4" year="2013"/>
61
          <author login="lfischme"/>
62
          <compatibility addition="yes" binary="compatible" semantic="compatible" />
63
          <description>
64
              <p>
65
                  The <code>o.n.core</code> module finds a instance of java.net.ProxySelector
66
                  in the default <code>org.openide.util.Lookup</code>. If some found
67
                  then will be registred as default <code>ProxySelector.setDedault()</code>.
68
              </p>
69
          </description>
70
          <class package="org.netbeans.core" name="ProxySettings"/>
71
          <issue number="201731"/>
72
      </change>
73
74
      <change id="system-proxy-reload-brigde">
75
          <api name="friend"/>
76
          <summary>ProxySettings.Reload allows reload the Network Proxy Settings</summary>
77
          <version major="3" minor="40"/>
78
          <date day="2" month="4" year="2013"/>
79
          <author login="lfischme"/>
80
          <compatibility addition="yes" binary="compatible" semantic="compatible" />
81
          <description>
82
              <p>
83
                  An implementation of this class brings a facility to reload Network 
84
                  Proxy Settings from underlying OS.
85
                  The module <code>core.network</code> provides a implementation
86
                  which may be accessible via <code>Lookup.getDefault()</code>. It's not guaranteed
87
                  any implementation is found on all distribution.
88
              </p>
89
          </description>
90
          <class package="org.netbeans.core" name="ProxySettings"/>
91
          <issue number="201731"/>
92
      </change>
93
94
      <change id="system-proxy-reload">
95
          <api name="friend"/>
96
          <summary>NbProxySelector and ProxyAutoConfig moved to new Core Network module.</summary>
97
          <version major="3" minor="40"/>
98
          <date day="2" month="4" year="2013"/>
99
          <author login="lfischme"/>
100
          <compatibility addition="no" binary="compatible" semantic="compatible" />
101
          <description>
102
              <p>
103
                  Classes <code>NbProxySelector</code> and <code>ProxyAutoConfig</code> have been
104
                  moved to Core Network module. Now the <code>NbProxySelector</code> can be accessed
105
                  via lookup - in <code>CoreBridgeImpl</code>.
106
              </p>
107
          </description>
108
          <class package="org.netbeans.core" name="NbProxySelector"/>
109
          <class package="org.netbeans.core" name="ProxyAutoConfig"/>
110
          <issue number="201731"/>
111
      </change>
112
  </changes>
113
114
  <!-- Now the surrounding HTML text and document structure: -->
115
116
  <htmlcontents>
117
    <head>
118
      <title>Change History for the Friend Core APIs</title>
119
      <link rel="stylesheet" href="prose.css" type="text/css"/>
120
    </head>
121
    <body>
122
123
<p class="overviewlink"><a href="overview-summary.html">Overview</a></p>
124
125
<h1>Introduction</h1>
126
127
<p>
128
This document lists changes made to the API between core/startup and core
129
modules. It is a friend API so it does not need to be developed compatibly,
130
and indeed it is not. 
131
</p>
132
133
<!-- The actual lists of changes, as summaries and details: -->
134
135
      <hr/><standard-changelists module-code-name="org.netbeans.core"/>
136
137
      <hr/><p>@FOOTER@</p>
138
139
    </body>
140
  </htmlcontents>
141
142
</apichanges>
(-)a/o.n.core/manifest.mf (-1 / +3 lines)
Lines 4-7 Link Here
4
OpenIDE-Module-Layer: org/netbeans/core/resources/mf-layer.xml
4
OpenIDE-Module-Layer: org/netbeans/core/resources/mf-layer.xml
5
AutoUpdate-Show-In-Client: false
5
AutoUpdate-Show-In-Client: false
6
AutoUpdate-Essential-Module: true
6
AutoUpdate-Essential-Module: true
7
OpenIDE-Module-Specification-Version: 3.39
7
OpenIDE-Module-Recommends: org.netbeans.core.ProxySettings.Reloader 
8
OpenIDE-Module-Specification-Version: 3.40
9
(-)a/o.n.core/nbproject/project.properties (-1 / +2 lines)
Lines 1-6 Link Here
1
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
1
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
2
#
2
#
3
# Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
3
# Copyright 1997-2013 Oracle and/or its affiliates. All rights reserved.
4
#
4
#
5
# Oracle and Java are registered trademarks of Oracle and/or its affiliates.
5
# Oracle and Java are registered trademarks of Oracle and/or its affiliates.
6
# Other names may be trademarks of their respective owners.
6
# Other names may be trademarks of their respective owners.
Lines 44-49 Link Here
44
javac.source=1.6
44
javac.source=1.6
45
45
46
javadoc.arch=${basedir}/arch.xml
46
javadoc.arch=${basedir}/arch.xml
47
javadoc.apichanges=${basedir}/apichanges.xml
47
48
48
release.external/nsProxyAutoConfig.js=modules/ext/nsProxyAutoConfig.js
49
release.external/nsProxyAutoConfig.js=modules/ext/nsProxyAutoConfig.js
49
jnlp.indirect.files=modules/ext/nsProxyAutoConfig.js
50
jnlp.indirect.files=modules/ext/nsProxyAutoConfig.js
(-)a/o.n.core/nbproject/project.xml (+1 lines)
Lines 278-283 Link Here
278
                <friend>org.netbeans.core.browser.webview</friend>
278
                <friend>org.netbeans.core.browser.webview</friend>
279
                <friend>org.netbeans.core.browser.xulrunner</friend>
279
                <friend>org.netbeans.core.browser.xulrunner</friend>
280
                <friend>org.netbeans.core.execution</friend>
280
                <friend>org.netbeans.core.execution</friend>
281
                <friend>org.netbeans.core.network</friend>
281
                <friend>org.netbeans.core.ui</friend>
282
                <friend>org.netbeans.core.ui</friend>
282
                <friend>org.netbeans.core.windows</friend>
283
                <friend>org.netbeans.core.windows</friend>
283
                <friend>org.netbeans.modules.jellytools.platform</friend>
284
                <friend>org.netbeans.modules.jellytools.platform</friend>
(-)a/o.n.core/src/org/netbeans/core/CoreBridgeImpl.java (-4 / +8 lines)
Lines 1-7 Link Here
1
/*
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
3
 *
4
 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
4
 * Copyright 1997-2013 Oracle and/or its affiliates. All rights reserved.
5
 *
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
7
 * Other names may be trademarks of their respective owners.
Lines 48-53 Link Here
48
import java.io.File;
48
import java.io.File;
49
import java.io.InputStream;
49
import java.io.InputStream;
50
import java.io.OutputStream;
50
import java.io.OutputStream;
51
import java.net.ProxySelector;
51
import java.util.logging.Level;
52
import java.util.logging.Level;
52
import java.util.logging.Logger;
53
import java.util.logging.Logger;
53
import java.util.prefs.Preferences;
54
import java.util.prefs.Preferences;
Lines 58-63 Link Here
58
import org.netbeans.swing.plaf.Startup;
59
import org.netbeans.swing.plaf.Startup;
59
import org.openide.nodes.NodeOp;
60
import org.openide.nodes.NodeOp;
60
import org.openide.util.Exceptions;
61
import org.openide.util.Exceptions;
62
import org.openide.util.Lookup;
61
import org.openide.util.NbBundle;
63
import org.openide.util.NbBundle;
62
import org.openide.util.NbPreferences;
64
import org.openide.util.NbPreferences;
63
import org.openide.util.RequestProcessor;
65
import org.openide.util.RequestProcessor;
Lines 204-212 Link Here
204
                NodeOp.registerPropertyEditors();
206
                NodeOp.registerPropertyEditors();
205
            }
207
            }
206
        });
208
        });
207
        
209
        ProxySelector selector = Lookup.getDefault().lookup(ProxySelector.class);
208
        // install java.net.ProxySelector
210
        if (selector != null) {
209
        NbProxySelector.register();
211
            // install java.net.ProxySelector
212
            ProxySelector.setDefault(selector);
213
        }
210
        
214
        
211
        editorsRegistered = true;
215
        editorsRegistered = true;
212
    }
216
    }
(-)a/o.n.core/src/org/netbeans/core/NbProxySelector.java (-446 lines)
Removed Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2011 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
package org.netbeans.core;
46
47
import java.io.IOException;
48
import java.lang.reflect.Method;
49
import java.net.*;
50
import java.util.*;
51
import java.util.logging.Level;
52
import java.util.logging.Logger;
53
import java.util.prefs.PreferenceChangeEvent;
54
import java.util.prefs.PreferenceChangeListener;
55
import java.util.regex.Pattern;
56
import java.util.regex.PatternSyntaxException;
57
58
/**
59
 *
60
 * @author Jiri Rechtacek
61
 */
62
public final class NbProxySelector extends ProxySelector {
63
    
64
    private final ProxySelector original;
65
    private static final Logger LOG = Logger.getLogger (NbProxySelector.class.getName ());
66
    private static Object useSystemProxies;
67
        
68
    /** Creates a new instance of NbProxySelector */
69
    private NbProxySelector (ProxySelector delegate) {
70
        original = delegate;
71
        LOG.fine ("java.net.useSystemProxies has been set to " + useSystemProxies ());
72
        LOG.fine ("In launcher was detected netbeans.system_http_proxy: " + System.getProperty ("netbeans.system_http_proxy", "N/A"));
73
        LOG.fine ("In launcher was detected netbeans.system_socks_proxy: " + System.getProperty ("netbeans.system_socks_proxy", "N/A"));
74
        ProxySettings.addPreferenceChangeListener (new ProxySettingsListener ());
75
        copySettingsToSystem ();
76
    }
77
    
78
    static ProxySelector create(ProxySelector delegate) {
79
        return new NbProxySelector(delegate);
80
    }
81
    
82
    static void register() {
83
        ProxySelector prev = ProxySelector.getDefault();
84
        if (prev == null) {
85
            LOG.warning("No default system ProxySelector was found thus NetBeans ProxySelector won't delegate on it");
86
        } else {
87
            LOG.log(Level.FINE, "Override the original ProxySelector: {0}", prev);
88
        }
89
        ProxySelector.setDefault(create(prev));
90
    }
91
    
92
    @Override
93
    public List<Proxy> select(URI uri) {
94
        List<Proxy> res = new ArrayList<Proxy> ();
95
        int proxyType = ProxySettings.getProxyType ();
96
        switch (proxyType) {
97
            case ProxySettings.DIRECT_CONNECTION:
98
                res = Collections.singletonList (Proxy.NO_PROXY);
99
                break;
100
            case ProxySettings.AUTO_DETECT_PROXY:
101
                if (useSystemProxies ()) {
102
                    if (original != null) {
103
                        res = original.select (uri);                   
104
                    }
105
                } else {
106
                    String protocol = uri.getScheme ();
107
                    assert protocol != null : "Invalid scheme of uri " + uri + ". Scheme cannot be null!";
108
                    if (dontUseProxy (ProxySettings.SystemProxySettings.getNonProxyHosts (), uri.getHost ())) {
109
                        res.add (Proxy.NO_PROXY);
110
                        break;
111
                    }
112
                    if (protocol.toLowerCase (Locale.US).startsWith("http")) {
113
                        String ports = ProxySettings.SystemProxySettings.getHttpPort ();
114
                        if (ports != null && ports.length () > 0 && ProxySettings.SystemProxySettings.getHttpHost ().length () > 0) {
115
                            int porti = Integer.parseInt(ports);
116
                            Proxy p = new Proxy (Proxy.Type.HTTP,  new InetSocketAddress (ProxySettings.SystemProxySettings.getHttpHost (), porti));
117
                            res.add (p);
118
                        }
119
                    } else { // supposed SOCKS
120
                        String ports = ProxySettings.SystemProxySettings.getSocksPort ();
121
                        String hosts = ProxySettings.SystemProxySettings.getSocksHost ();
122
                        if (ports != null && ports.length () > 0 && hosts.length () > 0) {
123
                            int porti = Integer.parseInt(ports);
124
                            Proxy p = new Proxy (Proxy.Type.SOCKS,  new InetSocketAddress (hosts, porti));
125
                            res.add (p);
126
                        }
127
                    }
128
                    if (original != null) {
129
                        res.addAll (original.select (uri));
130
                    }
131
                }
132
                break;
133
            case ProxySettings.MANUAL_SET_PROXY:
134
                String protocol = uri.getScheme ();
135
                assert protocol != null : "Invalid scheme of uri " + uri + ". Scheme cannot be null!";
136
137
                // handling nonProxyHosts first
138
                if (dontUseProxy (ProxySettings.getNonProxyHosts (), uri.getHost ())) {
139
                    res.add (Proxy.NO_PROXY);
140
                    break;
141
                }
142
                if (protocol.toLowerCase (Locale.US).startsWith("http")) {
143
                    String hosts = ProxySettings.getHttpHost ();
144
                    String ports = ProxySettings.getHttpPort ();
145
                    if (ports != null && ports.length () > 0 && hosts.length () > 0) {
146
                        int porti = Integer.parseInt(ports);
147
                        Proxy p = new Proxy (Proxy.Type.HTTP,  new InetSocketAddress (hosts, porti));
148
                        res.add (p);
149
                    } else {
150
                        LOG.fine ("Incomplete HTTP Proxy [" + hosts + "/" + ports + "] found in ProxySelector[Type: " + ProxySettings.getProxyType () + "] for uri " + uri + ". ");
151
                        if (original != null) {
152
                            LOG.finest ("Fallback to the default ProxySelector which returns " + original.select (uri));
153
                            res.addAll (original.select (uri));
154
                        }
155
                    }
156
                } else { // supposed SOCKS
157
                    String ports = ProxySettings.getSocksPort ();
158
                    String hosts = ProxySettings.getSocksHost ();
159
                    if (ports != null && ports.length () > 0 && hosts.length () > 0) {
160
                        int porti = Integer.parseInt(ports);
161
                        Proxy p = new Proxy (Proxy.Type.SOCKS,  new InetSocketAddress (hosts, porti));
162
                        res.add (p);
163
                    } else {
164
                        LOG.fine ("Incomplete SOCKS Server [" + hosts + "/" + ports + "] found in ProxySelector[Type: " + ProxySettings.getProxyType () + "] for uri " + uri + ". ");
165
                        if (original != null) {
166
                            LOG.finest ("Fallback to the default ProxySelector which returns " + original.select (uri));
167
                            res.addAll (original.select (uri));
168
                        }
169
                    }
170
                }
171
                res.add (Proxy.NO_PROXY);
172
                break;
173
            case ProxySettings.AUTO_DETECT_PAC:
174
                if (useSystemProxies ()) {
175
                    if (original != null) {
176
                        res = original.select (uri);                   
177
                    }
178
                } else {
179
                    // handling nonProxyHosts first
180
                    if (dontUseProxy (ProxySettings.getNonProxyHosts (), uri.getHost ())) {
181
                        res.add (Proxy.NO_PROXY);
182
                        break;
183
                    }
184
                    ProxyAutoConfig pac = ProxyAutoConfig.get(getPacFile());
185
                    assert pac != null : "Instance of ProxyAutoConfig found for " + getPacFile();
186
                    if (pac == null) {
187
                        LOG.finest ("No instance of ProxyAutoConfig(" + getPacFile() + ") for URI " + uri);
188
                        res.add(Proxy.NO_PROXY);
189
                    }
190
                    if (pac.getPacURI().getHost() == null) {
191
                        LOG.log(Level.FINEST, "Identifying proxy for URI {0}---{1}, PAC LOCAL URI: {2}", //NOI18N
192
                                new Object[] { uri.toString(), uri.getHost(), pac.getPacURI().toString() });
193
                        res.addAll(pac.findProxyForURL(uri));
194
                    } else if (pac.getPacURI().getHost().equals(uri.getHost())) {
195
                        // don't proxy PAC files
196
                        res.add(Proxy.NO_PROXY);
197
                    } else {
198
                        LOG.log(Level.FINEST, "Identifying proxy for URI {0}---{1}, PAC URI: {2}---{3}", //NOI18N
199
                                new Object[] { uri.toString(), uri.getHost(), pac.getPacURI().toString(), pac.getPacURI().getHost() });
200
                        res.addAll(pac.findProxyForURL(uri)); // NOI18N
201
                    }
202
                }
203
                res.add (Proxy.NO_PROXY);
204
                break;
205
            case ProxySettings.MANUAL_SET_PAC:
206
                // handling nonProxyHosts first
207
                if (dontUseProxy (ProxySettings.getNonProxyHosts (), uri.getHost ())) {
208
                    res.add (Proxy.NO_PROXY);
209
                    break;
210
                }
211
                ProxyAutoConfig pac = ProxyAutoConfig.get(getPacFile());
212
                assert pac != null : "Instance of ProxyAutoConfig found for " + getPacFile();
213
                if (pac == null) {
214
                    LOG.finest ("No instance of ProxyAutoConfig(" + getPacFile() + ") for URI " + uri);
215
                    res.add(Proxy.NO_PROXY);
216
                }
217
                if (pac.getPacURI().getHost() == null) {
218
                        LOG.log(Level.FINEST, "Identifying proxy for URI {0}---{1}, PAC LOCAL URI: {2}", //NOI18N
219
                                new Object[] { uri.toString(), uri.getHost(), pac.getPacURI().toString() });
220
                        res.addAll(pac.findProxyForURL(uri));
221
                } else if (pac.getPacURI().getHost().equals(uri.getHost())) {
222
                    // don't proxy PAC files
223
                    res.add(Proxy.NO_PROXY);
224
                } else {
225
                    LOG.log(Level.FINEST, "Identifying proxy for URI {0}---{1}, PAC URI: {2}---{3}", //NOI18N
226
                            new Object[] { uri.toString(), uri.getHost(), pac.getPacURI().toString(), pac.getPacURI().getHost() });
227
                    res.addAll(pac.findProxyForURL(uri)); // NOI18N
228
                }
229
                res.add (Proxy.NO_PROXY);
230
                break;
231
            default:
232
                assert false : "Invalid proxy type: " + proxyType;
233
        }
234
        LOG.finest ("NbProxySelector[Type: " + ProxySettings.getProxyType () +
235
                ", Use HTTP for all protocols: " + ProxySettings.useProxyAllProtocols ()+
236
                "] returns " + res + " for URI " + uri);
237
        return res;
238
    }
239
    
240
    @Override
241
    public void connectFailed (URI arg0, SocketAddress arg1, IOException arg2) {
242
        LOG.log  (Level.INFO, "connectionFailed(" + arg0 + ", " + arg1 +")", arg2);
243
    }
244
245
    // several modules listenes on these properties and propagates it futher
246
    private class ProxySettingsListener implements PreferenceChangeListener {
247
        @Override
248
        public void preferenceChange(PreferenceChangeEvent evt) {
249
            if (evt.getKey ().startsWith ("proxy") || evt.getKey ().startsWith ("useProxy")) {
250
                copySettingsToSystem ();
251
            }
252
        }
253
    }
254
    
255
    private void copySettingsToSystem () {
256
        String host = null, port = null, nonProxyHosts = null;
257
        String sHost = null, sPort = null;
258
        String httpsHost = null, httpsPort = null;
259
        int proxyType = ProxySettings.getProxyType ();
260
        switch (proxyType) {
261
            case ProxySettings.DIRECT_CONNECTION:
262
                host = null;
263
                port = null;
264
                httpsHost = null;
265
                httpsPort = null;
266
                nonProxyHosts = null;
267
                sHost = null;
268
                sPort = null;
269
                break;
270
            case ProxySettings.AUTO_DETECT_PROXY:
271
                host = ProxySettings.SystemProxySettings.getHttpHost ();
272
                port = ProxySettings.SystemProxySettings.getHttpPort ();
273
                httpsHost = ProxySettings.SystemProxySettings.getHttpsHost ();
274
                httpsPort = ProxySettings.SystemProxySettings.getHttpsPort ();
275
                sHost = ProxySettings.SystemProxySettings.getSocksHost ();
276
                sPort = ProxySettings.SystemProxySettings.getSocksPort ();
277
                ProxySettings.SystemProxySettings.getNonProxyHosts ();
278
                break;
279
            case ProxySettings.MANUAL_SET_PROXY:
280
                host = ProxySettings.getHttpHost ();
281
                port = ProxySettings.getHttpPort ();
282
                httpsHost = ProxySettings.getHttpsHost ();
283
                httpsPort = ProxySettings.getHttpsPort ();
284
                nonProxyHosts = ProxySettings.getNonProxyHosts ();
285
                sHost = ProxySettings.getSocksHost ();
286
                sPort = ProxySettings.getSocksPort ();
287
                break;
288
            case ProxySettings.AUTO_DETECT_PAC:
289
                host = null;
290
                port = null;
291
                httpsHost = null;
292
                httpsPort = null;
293
                ProxySettings.SystemProxySettings.getNonProxyHosts ();
294
                sHost = null;
295
                sPort = null;
296
                break;
297
            case ProxySettings.MANUAL_SET_PAC:
298
                host = null;
299
                port = null;
300
                httpsHost = null;
301
                httpsPort = null;
302
                ProxySettings.getNonProxyHosts ();
303
                sHost = null;
304
                sPort = null;
305
                break;
306
            default:
307
                assert false : "Invalid proxy type: " + proxyType;
308
        }
309
        setOrClearProperty ("http.proxyHost", host, false);
310
        setOrClearProperty ("http.proxyPort", port, true);
311
        setOrClearProperty ("http.nonProxyHosts", nonProxyHosts, false);
312
        setOrClearProperty ("https.proxyHost", httpsHost, false);
313
        setOrClearProperty ("https.proxyPort", httpsPort, true);
314
        setOrClearProperty ("https.nonProxyHosts", nonProxyHosts, false);
315
        setOrClearProperty ("socksProxyHost", sHost, false);
316
        setOrClearProperty ("socksProxyPort", sPort, true);
317
        LOG.fine ("Set System's http.proxyHost/Port/NonProxyHost to " + host + "/" + port + "/" + nonProxyHosts);
318
        LOG.fine ("Set System's https.proxyHost/Port to " + httpsHost + "/" + httpsPort);
319
        LOG.fine ("Set System's socksProxyHost/Port to " + sHost + "/" + sPort);
320
    }
321
    
322
    private void setOrClearProperty (String key, String value, boolean isInteger) {
323
        assert key != null;
324
        if (value == null || value.length () == 0) {
325
            System.clearProperty (key);
326
        } else {
327
            if (isInteger) {
328
                try {
329
                    Integer.parseInt (value);
330
                } catch (NumberFormatException nfe) {
331
                    LOG.log (Level.INFO, nfe.getMessage(), nfe);
332
                }
333
            }
334
            System.setProperty (key, value);
335
        }
336
    }
337
338
    // package-private for unit-testing
339
    static boolean dontUseProxy (String nonProxyHosts, String host) {
340
        if (host == null) return false;
341
        
342
        // try IP adress first
343
        if (dontUseIp (nonProxyHosts, host)) {
344
            return true;
345
        } else {
346
            return dontUseHostName (nonProxyHosts, host);
347
        }
348
349
    }
350
    
351
    private static boolean dontUseHostName (String nonProxyHosts, String host) {
352
        if (host == null) return false;
353
        
354
        boolean dontUseProxy = false;
355
        StringTokenizer st = new StringTokenizer (nonProxyHosts, "|", false);
356
        while (st.hasMoreTokens () && !dontUseProxy) {
357
            String token = st.nextToken ().trim();
358
            int star = token.indexOf ("*");
359
            if (star == -1) {
360
                dontUseProxy = token.equals (host);
361
                if (dontUseProxy) {
362
                    LOG.finest ("NbProxySelector[Type: " + ProxySettings.getProxyType () + "]. Host " + host + " found in nonProxyHosts: " + nonProxyHosts);
363
                }
364
            } else {
365
                String start = token.substring (0, star - 1 < 0 ? 0 : star - 1);
366
                String end = token.substring (star + 1 > token.length () ? token.length () : star + 1);
367
368
                //Compare left of * if and only if * is not first character in token
369
                boolean compareStart = star > 0; // not first character
370
                //Compare right of * if and only if * is not the last character in token
371
                boolean compareEnd = star < (token.length() - 1); // not last character
372
                dontUseProxy = (compareStart && host.startsWith(start)) || (compareEnd && host.endsWith(end));
373
374
                if (dontUseProxy) {
375
                    LOG.finest ("NbProxySelector[Type: " + ProxySettings.getProxyType () + "]. Host " + host + " found in nonProxyHosts: " + nonProxyHosts);
376
                }
377
            }
378
        }
379
        return dontUseProxy;
380
    }
381
    
382
    private static boolean dontUseIp (String nonProxyHosts, String host) {
383
        if (host == null) return false;
384
        
385
        String ip = null;
386
        try {
387
            ip = InetAddress.getByName (host).getHostAddress ();
388
        } catch (UnknownHostException ex) {
389
            LOG.log (Level.FINE, ex.getLocalizedMessage (), ex);
390
        }
391
        
392
        if (ip == null) {
393
            return false;
394
        }
395
396
        boolean dontUseProxy = false;
397
        StringTokenizer st = new StringTokenizer (nonProxyHosts, "|", false);
398
        while (st.hasMoreTokens () && !dontUseProxy) {
399
            String nonProxyHost = st.nextToken ().trim();
400
            int star = nonProxyHost.indexOf ("*");
401
            if (star == -1) {
402
                dontUseProxy = nonProxyHost.equals (ip);
403
                if (dontUseProxy) {
404
                    LOG.finest ("NbProxySelector[Type: " + ProxySettings.getProxyType () + "]. Host's IP " + ip + " found in nonProxyHosts: " + nonProxyHosts);
405
                }
406
            } else {
407
                // match with given dotted-quad IP
408
                try {
409
                    dontUseProxy = Pattern.matches (nonProxyHost, ip);
410
                    if (dontUseProxy) {
411
                        LOG.finest ("NbProxySelector[Type: " + ProxySettings.getProxyType () + "]. Host's IP" + ip + " found in nonProxyHosts: " + nonProxyHosts);
412
                    }
413
                } catch (PatternSyntaxException pse) {
414
                    // may ignore it here
415
                }
416
            }
417
        }
418
        return dontUseProxy;
419
    }
420
    
421
    // NetProperties is JDK vendor specific, access only by reflection
422
    static boolean useSystemProxies () {
423
        if (useSystemProxies == null) {
424
            try {
425
                Class<?> clazz = Class.forName ("sun.net.NetProperties");
426
                Method getBoolean = clazz.getMethod ("getBoolean", String.class);
427
                useSystemProxies = getBoolean.invoke (null, "java.net.useSystemProxies");
428
            } catch (Exception x) {
429
                LOG.log (Level.FINEST, "Cannot get value of java.net.useSystemProxies bacause " + x.getMessage(), x);
430
            }
431
        }
432
        return useSystemProxies != null && "true".equalsIgnoreCase (useSystemProxies.toString ());
433
    }
434
    
435
    static boolean usePAC() {
436
        String s = System.getProperty ("netbeans.system_http_proxy"); // NOI18N
437
        boolean usePAC = s != null && s.startsWith(ProxySettings.PAC);
438
        return usePAC;
439
    }
440
    
441
    private static String getPacFile() {
442
        String init = System.getProperty("netbeans.system_http_proxy"); // NOI18N
443
        return init.substring(4).trim();
444
    }
445
    
446
}
(-)a/o.n.core/src/org/netbeans/core/ProxyAutoConfig.java (-348 lines)
Removed Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011-2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2011 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.core;
43
44
import java.io.*;
45
import java.net.*;
46
import java.util.*;
47
import java.util.logging.Level;
48
import java.util.logging.Logger;
49
import javax.script.Invocable;
50
import javax.script.ScriptEngine;
51
import javax.script.ScriptEngineManager;
52
import javax.script.ScriptException;
53
import org.openide.filesystems.FileObject;
54
import org.openide.filesystems.FileUtil;
55
import org.openide.filesystems.URLMapper;
56
import org.openide.util.RequestProcessor;
57
import org.openide.util.RequestProcessor.Task;
58
import org.openide.util.Utilities;
59
60
/**
61
 *
62
 * @author Jirka Rechtacek
63
 */
64
public class ProxyAutoConfig {
65
66
    private static final Map<String, ProxyAutoConfig> file2pac = new HashMap<String, ProxyAutoConfig>(2);
67
    private static RequestProcessor RP = new RequestProcessor(ProxyAutoConfig.class);
68
    private static final String NS_PROXY_AUTO_CONFIG_URL = "nbinst://org.netbeans.core/modules/ext/nsProxyAutoConfig.js"; // NOI18N
69
    private static final String PROTO_FILE = "file://";
70
71
    /**
72
     * 
73
     * @param pacFile The string to be parsed into a URI
74
     * @return ProxyAutoConfig for given pacFile or <code>null</code> if constructor failed
75
     */
76
    public static synchronized ProxyAutoConfig get(String pacFile) {
77
        if (file2pac.get(pacFile) == null) {
78
            LOGGER.fine("Init ProxyAutoConfig for " + pacFile);
79
            ProxyAutoConfig instance = null;
80
            try {
81
                instance = new ProxyAutoConfig(pacFile);
82
            } catch (URISyntaxException ex) {
83
                Logger.getLogger(ProxyAutoConfig.class.getName()).warning("Parsing " + pacFile + " to URI throws " + ex);
84
            } finally {
85
                file2pac.put(pacFile, instance);
86
            }
87
        }
88
        return file2pac.get(pacFile);
89
    }
90
    private static final Logger LOGGER = Logger.getLogger(ProxyAutoConfig.class.getName());
91
    private Invocable inv = null;
92
    private final Task initTask;
93
    private final URI pacURI;
94
95
    private ProxyAutoConfig(final String pacURL) throws URISyntaxException {
96
        assert file2pac.get(pacURL) == null : "Only once object for " + pacURL + " must exist.";
97
        String normPAC = normalizePAC(pacURL);
98
        pacURI = new URI(normPAC);
99
        initTask = RP.post(new Runnable() {
100
101
            @Override
102
            public void run() {
103
                initEngine();
104
            }
105
        });
106
    }
107
108
    public URI getPacURI() {
109
        return pacURI;
110
    }
111
112
    private void initEngine() {
113
        InputStream pacIS;
114
        try {
115
            if (pacURI.isAbsolute()) {
116
                pacIS = downloadPAC(pacURI.toURL());
117
            } else {
118
                pacIS = null;
119
            }
120
        } catch (IOException ex) {
121
            LOGGER.log(Level.INFO, "InputStream for " + pacURI + " throws " + ex, ex);
122
            return;
123
        }
124
        if (pacIS == null) {
125
            return ;
126
        }
127
        String utils = downloadUtils();
128
        ScriptEngine eng;
129
        try {
130
            eng = evalPAC(pacIS, utils);
131
        } catch (FileNotFoundException ex) {
132
            LOGGER.log(Level.FINE, "While constructing ProxyAutoConfig thrown " + ex, ex);
133
            return ;
134
        } catch (ScriptException ex) {
135
            LOGGER.log(Level.FINE, "While constructing ProxyAutoConfig thrown " + ex, ex);
136
            return ;
137
        } finally {
138
            if (pacIS != null) {
139
                try {
140
                    pacIS.close();
141
                } catch (IOException ex) {
142
                    LOGGER.log(Level.FINE, "While closing PAC input stream thrown " + ex, ex);
143
                }
144
            }
145
        }
146
        assert eng != null : "JavaScri5pt engine cannot be null";
147
        if (eng == null) {
148
            LOGGER.log(Level.WARNING, "JavaScript engine cannot be null");
149
            return ;
150
        }
151
        inv = (Invocable) eng;
152
    }
153
154
    @SuppressWarnings("unchecked")
155
    public List<Proxy> findProxyForURL(URI u) {
156
        assert initTask != null : "initTask has be to posted.";
157
        if (!initTask.isFinished()) {
158
            while (!initTask.isFinished()) {
159
                try {
160
                    RP.post(new Runnable() {
161
162
                        @Override
163
                        public void run() {
164
                        }
165
                    }).waitFinished(100);
166
                } catch (InterruptedException ex) {
167
                    LOGGER.log(Level.FINEST, ex.getMessage(), ex);
168
                }
169
            }
170
        }
171
        if (inv == null) {
172
            return Collections.singletonList(Proxy.NO_PROXY);
173
        }
174
        Object proxies = null;
175
        try {
176
            proxies = inv.invokeFunction("FindProxyForURL", u.toString(), u.getHost()); // NOI18N
177
        } catch (ScriptException ex) {
178
            LOGGER.log(Level.FINE, "While invoking FindProxyForURL(" + u + ", " + u.getHost() + " thrown " + ex, ex);
179
        } catch (NoSuchMethodException ex) {
180
            LOGGER.log(Level.FINE, "While invoking FindProxyForURL(" + u + ", " + u.getHost() + " thrown " + ex, ex);
181
        }
182
        List<Proxy> res = analyzeResult(u, proxies);
183
        if (res == null) {
184
            LOGGER.info("findProxyForURL(" + u + ") returns null.");
185
            res = Collections.emptyList();
186
        }
187
        LOGGER.fine("findProxyForURL(" + u + ") returns " + Arrays.asList(res));
188
        return res;
189
    }
190
191
    private static InputStream downloadPAC (URL pacURL) throws IOException {
192
        InputStream is;
193
        URLConnection conn = pacURL.openConnection(Proxy.NO_PROXY);
194
        is = conn.getInputStream();
195
        return is;
196
    }
197
198
    private static ScriptEngine evalPAC(InputStream is, String utils) throws FileNotFoundException, ScriptException {
199
        ScriptEngineManager factory = new ScriptEngineManager();
200
        ScriptEngine engine = factory.getEngineByName("JavaScript");
201
        Reader pacReader = new InputStreamReader(is);
202
        engine.eval(pacReader);
203
        engine.eval(utils);
204
        return engine;
205
    }
206
207
    private List<Proxy> analyzeResult(URI uri, Object proxiesString) {
208
        if (proxiesString == null) {
209
            LOGGER.fine("Null result for " + uri);
210
            return null;
211
        }
212
        Proxy.Type proxyType;
213
        String protocol = uri.getScheme();
214
        assert protocol != null : "Invalid scheme of uri " + uri + ". Scheme cannot be null!";
215
        if (protocol == null) {
216
            return null;
217
        } else {
218
            if (("http".equals(protocol)) || ("https".equals(protocol))) { // NOI18N
219
                proxyType = Proxy.Type.HTTP;
220
            } else {
221
                proxyType = Proxy.Type.SOCKS;
222
            }
223
        }
224
        StringTokenizer st = new StringTokenizer(proxiesString.toString(), ";"); //NOI18N
225
        List<Proxy> proxies = new LinkedList<Proxy>();
226
        while (st.hasMoreTokens()) {
227
            String proxy = st.nextToken();
228
            if (ProxySettings.DIRECT.equals(proxy.trim())) {
229
                proxies.add(Proxy.NO_PROXY);
230
            } else {
231
                String host = getHost(proxy);
232
                Integer port = getPort(proxy);
233
                if (host != null && port != null) {
234
                    proxies.add(new Proxy(proxyType, new InetSocketAddress(host, port)));
235
                }
236
            }
237
        }
238
        return proxies;
239
    }
240
241
    private static String getHost(String proxy) {
242
        if (proxy.startsWith("PROXY ")) {
243
            proxy = proxy.substring(6);
244
        }
245
        int i = proxy.lastIndexOf(":"); // NOI18N
246
        if (i <= 0 || i >= proxy.length() - 1) {
247
            LOGGER.info("No port in " + proxy);
248
            return null;
249
        }
250
251
        String host = proxy.substring(0, i);
252
253
        return ProxySettings.normalizeProxyHost(host);
254
    }
255
256
    private static Integer getPort(String proxy) {
257
        if (proxy.startsWith("PROXY ")) {
258
            proxy = proxy.substring(6);
259
        }
260
        int i = proxy.lastIndexOf(":"); // NOI18N
261
        if (i <= 0 || i >= proxy.length() - 1) {
262
            LOGGER.info("No port in " + proxy);
263
            return null;
264
        }
265
266
        String port = proxy.substring(i + 1);
267
        if (port.indexOf('/') >= 0) {
268
            port = port.substring(0, port.indexOf('/'));
269
        }
270
271
        try {
272
            return Integer.parseInt(port);
273
        } catch (NumberFormatException ex) {
274
            LOGGER.log(Level.INFO, ex.getLocalizedMessage(), ex);
275
            return null;
276
        }
277
    }
278
279
    private static String downloadUtils() {
280
        StringBuilder builder = new StringBuilder();
281
        BufferedReader reader = null;
282
        // XXX why is the below not more simply:
283
        // reader = new BufferedReader(new URL(NS_PROXY_AUTO_CONFIG_URL).openStream());
284
        FileObject fo = null;
285
        try {
286
            try {
287
                fo = URLMapper.findFileObject(new URL(NS_PROXY_AUTO_CONFIG_URL));
288
            } catch (MalformedURLException ex) {
289
                LOGGER.log(Level.INFO, ex.getMessage(), ex);
290
            }
291
            reader = new BufferedReader(new java.io.FileReader(FileUtil.toFile(fo)));
292
        } catch (FileNotFoundException ex) {
293
            LOGGER.log(Level.INFO, ex.getMessage(), ex);
294
        }
295
        try {
296
            String line;
297
            boolean doAppend = false;
298
            while ((line = reader.readLine()) != null) {
299
                line = line.trim();
300
                if( line.startsWith("var pacUtils =") ) { //NOI18N
301
                    doAppend = true;
302
                }
303
                if( !doAppend )
304
                    continue;
305
                if (line.endsWith("+")) { // NOI18N
306
                    line = line.substring(0, line.length() - 1);
307
                }
308
                builder.append(line.replaceAll("\"", "").replaceAll("\\\\n", "").replaceAll("\\\\\\\\", "\\\\")); // NOI18N
309
                builder.append(System.getProperty("line.separator")); // NOI18N
310
            }
311
        } catch (IOException ex) {
312
            LOGGER.log(Level.INFO, "While downloading nsProxyAutoConfig.js thrown " + ex.getMessage(), ex);
313
        } finally {
314
            if (reader != null) {
315
                try {
316
                    reader.close();
317
                } catch (IOException ex) {
318
                    LOGGER.log(Level.FINE, ex.getMessage(), ex);
319
                }
320
            }
321
        }
322
        return builder.toString();
323
    }
324
325
    private String normalizePAC(String pacURL) {
326
        int index;
327
        if ((index = pacURL.indexOf("\n")) != -1) { // NOI18N
328
            pacURL = pacURL.substring(0, index);
329
        }
330
        if ((index = pacURL.indexOf("\r")) != -1) { // NOI18N
331
            pacURL = pacURL.substring(0, index);
332
        }
333
        String fileLocation = pacURL;
334
        if (fileLocation.startsWith(PROTO_FILE)) {
335
            fileLocation = fileLocation.substring(PROTO_FILE.length());
336
        }
337
        File f = new File(fileLocation);
338
        if (f.canRead()) {
339
            pacURL = Utilities.toURI(f).toString();
340
        } else {
341
            pacURL = pacURL.replaceAll("\\\\", "/"); //NOI18N
342
        }
343
        if ((index = pacURL.indexOf(" ")) != -1) { // NOI18N
344
            pacURL = pacURL.substring(0, index);
345
        }
346
        return pacURL.trim();
347
    }
348
}
(-)a/o.n.core/src/org/netbeans/core/ProxySettings.java (-145 / +70 lines)
Lines 1-7 Link Here
1
/*
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
3
 *
4
 * Copyright 1997-2012 Oracle and/or its affiliates. All rights reserved.
4
 * Copyright 1997-2013 Oracle and/or its affiliates. All rights reserved.
5
 *
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
7
 * Other names may be trademarks of their respective owners.
Lines 75-80 Link Here
75
    public static final String DIRECT = "DIRECT";
75
    public static final String DIRECT = "DIRECT";
76
    public static final String PAC = "PAC";
76
    public static final String PAC = "PAC";
77
    
77
    
78
    public static final String SYSTEM_PROXY_HTTP_HOST = "systemProxyHttpHost";
79
    public static final String SYSTEM_PROXY_HTTP_PORT = "systemProxyHttpPort";
80
    public static final String SYSTEM_PROXY_HTTPS_HOST = "systemProxyHttpsHost";
81
    public static final String SYSTEM_PROXY_HTTPS_PORT = "systemProxyHttpsPort";
82
    public static final String SYSTEM_PROXY_SOCKS_HOST = "systemProxySocksHost";
83
    public static final String SYSTEM_PROXY_SOCKS_PORT = "systemProxySocksPort";
84
    public static final String SYSTEM_NON_PROXY_HOSTS = "systemProxyNonProxyHosts";
85
    public static final String SYSTEM_PAC = "systemPAC";
86
    
87
    
88
    // TODO move to proper place
89
    public static String getSystemHttpHost() {
90
        return getPreferences().get(SYSTEM_PROXY_HTTP_HOST, "");
91
    }
92
    
93
    public static String getSystemHttpPort() {
94
        return getPreferences().get(SYSTEM_PROXY_HTTP_PORT, "");
95
    }
96
    
97
    public static String getSystemHttpsHost() {
98
        return getPreferences().get(SYSTEM_PROXY_HTTPS_HOST, "");
99
    }
100
    
101
    public static String getSystemHttpsPort() {
102
        return getPreferences().get(SYSTEM_PROXY_HTTPS_PORT, "");
103
    }
104
    
105
    public static String getSystemSocksHost() {
106
        return getPreferences().get(SYSTEM_PROXY_SOCKS_HOST, "");
107
    }
108
    
109
    public static String getSystemSocksPort() {
110
        return getPreferences().get(SYSTEM_PROXY_SOCKS_PORT, "");
111
    }
112
    
113
    public static String getSystemNonProxyHosts() {
114
        return getPreferences().get(SYSTEM_NON_PROXY_HOSTS, "");
115
    }
116
    
117
    public static String getSystemPac() {
118
        return getPreferences().get(SYSTEM_PAC, null);
119
    }
120
    
121
    
122
    
78
    private static String presetNonProxyHosts;
123
    private static String presetNonProxyHosts;
79
124
80
    /** No proxy is used to connect. */
125
    /** No proxy is used to connect. */
Lines 146-152 Link Here
146
    public static int getProxyType () {
191
    public static int getProxyType () {
147
        int type = getPreferences ().getInt (PROXY_TYPE, AUTO_DETECT_PROXY);
192
        int type = getPreferences ().getInt (PROXY_TYPE, AUTO_DETECT_PROXY);
148
        if (AUTO_DETECT_PROXY == type) {
193
        if (AUTO_DETECT_PROXY == type) {
149
            type = NbProxySelector.usePAC() ? AUTO_DETECT_PAC : AUTO_DETECT_PROXY;
194
            type = ProxySettings.getSystemPac() != null ? AUTO_DETECT_PAC : AUTO_DETECT_PROXY;
150
        }
195
        }
151
        return type;
196
        return type;
152
    }
197
    }
Lines 179-332 Link Here
179
                NbBundle.getMessage(ProxySettings.class, "ProxySettings.password.description"));
224
                NbBundle.getMessage(ProxySettings.class, "ProxySettings.password.description"));
180
    }
225
    }
181
226
182
    static void addPreferenceChangeListener (PreferenceChangeListener l) {
227
    public static void addPreferenceChangeListener (PreferenceChangeListener l) {
183
        getPreferences ().addPreferenceChangeListener (l);
228
        getPreferences ().addPreferenceChangeListener (l);
184
    }
229
    }
185
    
230
    
186
    static void removePreferenceChangeListener (PreferenceChangeListener l) {
231
    public static void removePreferenceChangeListener (PreferenceChangeListener l) {
187
        getPreferences ().removePreferenceChangeListener (l);
232
        getPreferences ().removePreferenceChangeListener (l);
188
    }
233
    }
189
190
    static class SystemProxySettings extends ProxySettings {
191
        
192
        public static String getHttpHost () {
193
            if (isSystemProxyDetect ()) {
194
                return getSystemProxyHost ();
195
            } else {
196
                return "";
197
            }
198
        }
199
200
        public static String getHttpPort () {
201
            if (isSystemProxyDetect ()) {
202
                return getSystemProxyPort ();
203
            } else {
204
                return "";
205
            }
206
        }
207
208
        public static String getHttpsHost () {
209
            if (isSystemProxyDetect ()) {
210
                return getSystemProxyHost ();
211
            } else {
212
                return "";
213
            }
214
        }
215
216
        public static String getHttpsPort () {
217
            if (isSystemProxyDetect ()) {
218
                return getSystemProxyPort ();
219
            } else {
220
                return "";
221
            }
222
        }
223
224
        public static String getSocksHost () {
225
            if (isSystemSocksServerDetect ()) {
226
                return getSystemSocksServerHost ();
227
            } else {
228
                return "";
229
            }
230
        }
231
232
        public static String getSocksPort () {
233
            if (isSystemSocksServerDetect ()) {
234
                return getSystemSocksServerPort ();
235
            } else {
236
                return "";
237
            }
238
        }
239
240
        public static String getNonProxyHosts () {
241
            return getDefaultUserNonProxyHosts ();
242
        }
243
244
        // helper methods
245
        private static boolean isSystemProxyDetect () {
246
            if (NbProxySelector.useSystemProxies ()) {
247
                return true;
248
            }
249
            String s = System.getProperty ("netbeans.system_http_proxy"); // NOI18N
250
            return s != null && ! DIRECT.equals (s); // NOI18N
251
        }
252
253
        private static String getSystemProxyHost () {
254
            String systemProxy = System.getProperty ("netbeans.system_http_proxy"); // NOI18N
255
            if (systemProxy == null) {
256
                return ""; // NOI18N
257
            }
258
259
            int i = systemProxy.lastIndexOf (":"); // NOI18N
260
            if (i <= 0 || i >= systemProxy.length () - 1) {
261
                return ""; // NOI18N
262
            }
263
264
            return normalizeProxyHost (systemProxy.substring (0, i));
265
        }
266
267
        private static String getSystemProxyPort () {
268
            String systemProxy = System.getProperty ("netbeans.system_http_proxy"); // NOI18N
269
            if (systemProxy == null) {
270
                return ""; // NOI18N
271
             }
272
273
            int i = systemProxy.lastIndexOf (":"); // NOI18N
274
            if (i <= 0 || i >= systemProxy.length () - 1) {
275
                return ""; // NOI18N
276
            }
277
            
278
            String p = systemProxy.substring (i + 1);
279
            if (p.indexOf ('/') >= 0) {
280
                p = p.substring (0, p.indexOf ('/'));
281
            }
282
283
            return p;
284
        }
285
286
        private static boolean isSystemSocksServerDetect () {
287
            return isSystemProxyDetect () && System.getProperty ("netbeans.system_socks_proxy") != null; // NOI18N
288
        }
289
        
290
        private static String getSystemSocksServerHost () {
291
            String systemProxy = System.getProperty ("netbeans.system_socks_proxy"); // NOI18N
292
            if (systemProxy == null) {
293
                return ""; // NOI18N
294
            }
295
296
            int i = systemProxy.lastIndexOf (":"); // NOI18N
297
            if (i <= 0 || i >= systemProxy.length () - 1) {
298
                return ""; // NOI18N
299
            }
300
301
            return normalizeProxyHost (systemProxy.substring (0, i));
302
        }
303
304
        private static String getSystemSocksServerPort () {
305
            String systemProxy = System.getProperty ("netbeans.system_socks_proxy"); // NOI18N
306
            if (systemProxy == null) {
307
                return ""; // NOI18N
308
             }
309
310
            int i = systemProxy.lastIndexOf (":"); // NOI18N
311
            if (i <= 0 || i >= systemProxy.length () - 1) {
312
                return ""; // NOI18N
313
            }
314
            
315
            String p = systemProxy.substring (i + 1);
316
            if (p.indexOf ('/') >= 0) {
317
                p = p.substring (0, p.indexOf ('/'));
318
            }
319
320
            return p;
321
        }
322
323
    }
324
325
    private static String getSystemNonProxyHosts () {
326
        String systemProxy = System.getProperty ("netbeans.system_http_non_proxy_hosts"); // NOI18N
327
328
        return systemProxy == null ? "" : systemProxy;
329
    }
330
    
234
    
331
    private static String getPresetNonProxyHosts () {
235
    private static String getPresetNonProxyHosts () {
332
        if (presetNonProxyHosts == null) {
236
        if (presetNonProxyHosts == null) {
Lines 478-483 Link Here
478
            }
382
            }
479
        }
383
        }
480
    }
384
    }
385
    
386
    public static void reload() {
387
        Reloader reloader = Lookup.getDefault().lookup(Reloader.class);
388
        reloader.reload();
389
    }
481
390
482
    @ServiceProvider(service = NetworkSettings.ProxyCredentialsProvider.class, position = 1000)
391
    @ServiceProvider(service = NetworkSettings.ProxyCredentialsProvider.class, position = 1000)
483
    public static class NbProxyCredentialsProvider extends NetworkSettings.ProxyCredentialsProvider {
392
    public static class NbProxyCredentialsProvider extends NetworkSettings.ProxyCredentialsProvider {
Lines 525-528 Link Here
525
        }
434
        }
526
435
527
    }
436
    }
437
    
438
    /** A bridge between <code>o.n.core</code> and <code>core.network</code>.
439
     * An implementation of this class brings a facility to reload Network Proxy Settings
440
     * from underlying OS.
441
     * The module <code>core.network</code> provides a implementation which may be accessible
442
     * via <code>Lookup.getDefault()</code>. It's not guaranteed any implementation is found on all distribution. 
443
     * 
444
     * @since 3.40
445
     */
446
    public abstract static class Reloader {
447
        
448
        /** Reloads Network Proxy Settings from underlying system.
449
         *
450
         */
451
        public abstract void reload();
452
    }
528
}
453
}
(-)a/o.n.core/test/unit/data/pacFiles/wpad space.dat (-8 lines)
Removed Link Here
1
function FindProxyForURL(url, host)
2
{
3
    // Make everything lower case.
4
    url = url.toLowerCase();
5
    host = host.toLowerCase();
6
    if (isPlainHostName(host)) return "DIRECT";
7
    return "PROXY www-proxy.us.oracle.com:80";
8
};
(-)a/o.n.core/test/unit/data/pacFiles/wpad.dat (-8 lines)
Removed Link Here
1
function FindProxyForURL(url, host)
2
{
3
    // Make everything lower case.
4
    url = url.toLowerCase();
5
    host = host.toLowerCase();
6
    if (isPlainHostName(host)) return "DIRECT";
7
    return "PROXY www-proxy.us.oracle.com:80";
8
};
(-)a/o.n.core/test/unit/src/org/netbeans/core/CanProxyToLocalhostTest.java (-113 lines)
Removed Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
package org.netbeans.core;
46
47
import java.io.IOException;
48
import java.net.InetAddress;
49
import java.net.InetSocketAddress;
50
import java.net.Proxy;
51
import java.net.ProxySelector;
52
import java.net.SocketAddress;
53
import java.net.URI;
54
import java.util.Collections;
55
import java.util.List;
56
import java.util.Locale;
57
import java.util.Locale;
58
import org.netbeans.junit.NbTestCase;
59
import org.openide.util.NetworkSettings;
60
import org.openide.util.lookup.ServiceProvider;
61
62
/** Check whether we can proxy to localhost.
63
 */
64
public class CanProxyToLocalhostTest extends NbTestCase {
65
    private static String USER_PROXY_HOST = "my.webcache";
66
    private static int USER_PROXY_PORT = 8080;
67
68
    private ProxySelector selector;
69
    private static URI TO_LOCALHOST;
70
    private static URI TO_NB;
71
    private MyPS myPS;
72
73
    public CanProxyToLocalhostTest (String name) {
74
        super (name);
75
    }
76
    
77
    @Override
78
    protected void setUp () throws Exception {
79
        myPS = new MyPS();
80
        selector = NbProxySelector.create(myPS);
81
        TO_LOCALHOST = new URI ("http://localhost");
82
        TO_NB = new URI ("http://netbeans.org");
83
    }
84
    
85
    public void testNoProxyForLocalhost() {
86
        Locale.setDefault(Locale.US);
87
        assertEquals ("Connect TO_LOCALHOST DIRECT.", "DIRECT", selector.select (TO_LOCALHOST).get(0).toString());
88
    }
89
    public void testProxyForLocalhost() {
90
        Locale.setDefault(new Locale("te", "ST"));
91
        assertEquals ("Connect TO_LOCALHOST provided by MyPS", "HTTP @ my.webcache:8080", selector.select (TO_LOCALHOST).get(0).toString());
92
        assertEquals("One call to my ps", 1, myPS.called);
93
    }
94
    public void testAlwaysProxyForNonLocalhost() {
95
        Locale.setDefault(Locale.US);
96
        assertEquals ("Connect TO_LOCALHOST DIRECT.", "HTTP @ my.webcache:8080", selector.select (TO_NB).get(0).toString());
97
        assertEquals("One call to my ps", 1, myPS.called);
98
    }
99
    
100
    private static class MyPS extends ProxySelector {
101
        int called;
102
        
103
        @Override
104
        public List<Proxy> select(URI uri) {
105
            called++;
106
            return Collections.singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(USER_PROXY_HOST, USER_PROXY_PORT)));
107
        }
108
109
        @Override
110
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
111
        }
112
    }
113
}
(-)a/o.n.core/test/unit/src/org/netbeans/core/DontUseProxyTest.java (-97 lines)
Removed Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
package org.netbeans.core;
46
47
import org.netbeans.junit.*;
48
49
/** Tests HTTP Proxy settings.
50
 *
51
 * @author Jiri Rechtacek
52
 * @see http://www.netbeans.org/issues/show_bug.cgi?id=125588
53
 */
54
public class DontUseProxyTest extends NbTestCase {
55
    public DontUseProxyTest (String name) {
56
        super (name);
57
    }
58
    
59
    public void testFullIpAdress () {
60
        String nonProxyHosts = "192.168.1.0|200.100.200.100";
61
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.0"));
62
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.1"));
63
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.2.0"));
64
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.169.1.0"));
65
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "193.168.1.0"));
66
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168"));
67
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.0/1"));
68
        
69
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "200.100.200.100"));
70
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "200.100.200.200"));
71
    }
72
    
73
    public void testWildcardIpAdress () {
74
        String nonProxyHosts = "192.*|200.100.200.*";
75
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.0"));
76
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.1"));
77
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.2.0"));
78
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.169.1.0"));
79
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "193.168.1.0"));
80
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168"));
81
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "192.168.1.0/1"));
82
        
83
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "200.100.200.100"));
84
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "200.100.200.200"));
85
    }
86
    
87
    public void testWildcardHostName () {
88
        String nonProxyHosts = "*.netbeans.org|*.other.org|*netbeans.com|netbeans.org|*.our.intranet|private.*";
89
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "www.netbeans.org"));
90
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "www.netbeans.com"));
91
        assertFalse (NbProxySelector.dontUseProxy (nonProxyHosts, "www.dummynetbeans.org"));
92
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "subversion.our.intranet"));
93
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "private"));
94
        assertTrue (NbProxySelector.dontUseProxy (nonProxyHosts, "private.all"));
95
    }
96
97
}
(-)a/o.n.core/test/unit/src/org/netbeans/core/HttpSettingsTest.java (-417 lines)
Removed Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
package org.netbeans.core;
46
47
import java.lang.reflect.Field;
48
import java.util.prefs.AbstractPreferences;
49
import java.util.prefs.PreferenceChangeEvent;
50
import java.util.prefs.PreferenceChangeListener;
51
import java.util.prefs.Preferences;
52
import junit.framework.TestResult;
53
import org.netbeans.junit.NbTestCase;
54
import org.netbeans.junit.RandomlyFails;
55
import org.openide.util.NbPreferences;
56
57
/** Tests HTTP Proxy settings.
58
 *
59
 * @author Jiri Rechtacek
60
 * @see http://www.netbeans.org/issues/show_bug.cgi?id=51641
61
 */
62
@RandomlyFails
63
public class HttpSettingsTest extends NbTestCase {
64
    private final Object sync = getEventQueueSync ();
65
    private static String SYSTEM_PROXY_HOST = "system.cache.org";
66
    private static String SYSTEM_PROXY_PORT = "777";
67
    private static String USER_PROXY_HOST = "my.webcache";
68
    private static String USER_PROXY_PORT = "8080";
69
    private static String USER_HTTPS_PROXY_HOST = "secure.webcache";
70
    private static String USER_HTTPS_PROXY_PORT = "8080";
71
72
    private Preferences proxyPreferences;
73
    private static String SILLY_USER_PROXY_HOST = "http://my.webcache";
74
    private static String SILLY_SYSTEM_PROXY_HOST = "http://system.cache.org";
75
    private static String SILLY_SYSTEM_PROXY_PORT = "777//";
76
    private static String MY_NON_PROXY_HOSTS = "myhost.mydomain.net";
77
    
78
    private static String NETBEANS_ORG = "*.netbeans.org";
79
    private static String OTHER_ORG = "*.other.org";
80
    
81
    public HttpSettingsTest (String name) {
82
        super (name);
83
    }
84
    
85
    @Override
86
    public void run (final TestResult result) {
87
        //just initialize Preferences before code NbTestCase
88
        Preferences.userRoot ();                        
89
        super.run (result);
90
    }
91
    
92
    @Override
93
    protected int timeOut () {
94
        return 20 * 1000;
95
    }
96
    
97
    @Override
98
    protected void setUp () throws Exception {
99
        super.setUp ();
100
        System.setProperty ("http.nonProxyHosts", NETBEANS_ORG + ',' + NETBEANS_ORG);
101
        NbProxySelector.register();
102
        proxyPreferences  = NbPreferences.root ().node ("/org/netbeans/core");
103
        proxyPreferences.addPreferenceChangeListener (new PreferenceChangeListener() {
104
            @Override
105
            public void preferenceChange(PreferenceChangeEvent arg0) {
106
                synchronized (sync) {
107
                    sync.notifyAll ();
108
                }
109
            }
110
        });
111
        System.setProperty ("netbeans.system_http_proxy", SYSTEM_PROXY_HOST + ":" + SYSTEM_PROXY_PORT);
112
        System.setProperty ("netbeans.system_http_non_proxy_hosts", OTHER_ORG);
113
        synchronized (sync) {
114
            if (! USER_PROXY_HOST.equals (proxyPreferences.get ("proxyHttpHost", ""))) {
115
                proxyPreferences.put ("proxyHttpHost", USER_PROXY_HOST);
116
                sync.wait (10000);
117
            }
118
        }
119
        synchronized (sync) {
120
            if (! USER_PROXY_PORT.equals (proxyPreferences.get ("proxyHttpPort", ""))) {
121
                proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT);
122
                sync.wait (10000);
123
            }
124
        }
125
        synchronized (sync) {
126
            if (! USER_HTTPS_PROXY_HOST.equals (proxyPreferences.get ("proxyHttpsHost", ""))) {
127
                proxyPreferences.put ("proxyHttpsHost", USER_HTTPS_PROXY_HOST);
128
                sync.wait (10000);
129
            }
130
        }
131
        synchronized (sync) {
132
            if (! USER_HTTPS_PROXY_PORT.equals (proxyPreferences.get ("proxyHttpsPort", ""))) {
133
                proxyPreferences.put ("proxyHttpsPort", USER_HTTPS_PROXY_PORT);
134
                sync.wait (10000);
135
            }
136
        }
137
    }
138
    
139
    private void sillySetUp () throws Exception {
140
        synchronized (sync) {
141
            if (ProxySettings.DIRECT_CONNECTION != (proxyPreferences.getInt ("proxyType", -1))) {
142
                proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION);
143
                sync.wait ();
144
            }
145
        }
146
        
147
        System.setProperty ("netbeans.system_http_proxy", SILLY_SYSTEM_PROXY_HOST + ":" + SILLY_SYSTEM_PROXY_PORT);
148
        synchronized (sync) {
149
            if (! SILLY_USER_PROXY_HOST.equals (proxyPreferences.get ("proxyHttpHost", ""))) {
150
                proxyPreferences.put ("proxyHttpHost", SILLY_USER_PROXY_HOST);
151
                sync.wait (10000);
152
            }
153
        }
154
        proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT);
155
        synchronized (sync) {
156
            if (! USER_PROXY_PORT.equals (proxyPreferences.get ("proxyHttpPort", ""))) {
157
                proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT);
158
                sync.wait (10000);
159
            }
160
        }
161
    }
162
    
163
    private void setUpAutoDirect () throws Exception {
164
        synchronized (sync) {
165
            if (ProxySettings.DIRECT_CONNECTION != (proxyPreferences.getInt ("proxyType", -1))) {
166
                proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION);
167
                sync.wait ();
168
            }
169
        }
170
        System.setProperty ("netbeans.system_http_proxy", "DIRECT");
171
        synchronized (sync) {
172
            if (! "".equals (proxyPreferences.get ("proxyHttpHost", ""))) {
173
                proxyPreferences.put ("proxyHttpHost", "");
174
                sync.wait (10000);
175
            }
176
        }
177
        synchronized (sync) {
178
            if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
179
                proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY);
180
                sync.wait ();
181
            }
182
        }
183
    }
184
    
185
    public void testDirectConnection () throws InterruptedException {
186
        System.setProperty ("http.proxyHost", "");
187
        System.setProperty ("http.proxyPort", "");
188
        synchronized (sync) {
189
            if (ProxySettings.DIRECT_CONNECTION != (proxyPreferences.getInt ("proxyType", -1))) {
190
                proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION);
191
                sync.wait ();
192
            }
193
        }
194
        assertEquals ("Proxy type DIRECT_CONNECTION.", ProxySettings.DIRECT_CONNECTION, ProxySettings.getProxyType ());
195
        assertEquals ("No Proxy Host set.", null, System.getProperty ("http.proxyHost"));
196
        assertEquals ("No Proxy Port set.", null, System.getProperty ("http.proxyPort"));
197
    }
198
    
199
    public void testAutoDetectProxy () throws InterruptedException {
200
        System.setProperty ("http.proxyHost", "");
201
        System.setProperty ("http.proxyPort", "");
202
        synchronized (sync) {
203
            if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
204
                proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY);
205
                sync.wait ();
206
            }
207
        }
208
        assertEquals("Proxy type AUTO_DETECT_PROXY.",
209
                     ProxySettings.AUTO_DETECT_PROXY,
210
                     ProxySettings.getProxyType());
211
        assertEquals("System Proxy Host: ", SYSTEM_PROXY_HOST,
212
                     System.getProperty("http.proxyHost"));
213
        assertEquals("System Proxy Port: ", SYSTEM_PROXY_PORT,
214
                     System.getProperty("http.proxyPort"));
215
    }
216
    
217
    public void testManualSetProxy () throws InterruptedException {
218
        synchronized (sync) {
219
            if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
220
                proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY);
221
                sync.wait ();
222
            }
223
        }
224
        assertEquals ("Proxy type MANUAL_SET_PROXY.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ());
225
        assertEquals ("Manual Set Proxy Host from ProxySettings: ", USER_PROXY_HOST, ProxySettings.getHttpHost ());
226
        assertEquals ("Manual Set Proxy Port from ProxySettings: ", USER_PROXY_PORT, ProxySettings.getHttpPort ());
227
        assertEquals ("Manual Set Proxy Host from System.getProperty(): ", USER_PROXY_HOST, System.getProperty ("http.proxyHost"));
228
        assertEquals ("Manual Set Proxy Port from System.getProperty(): ", USER_PROXY_PORT, System.getProperty ("http.proxyPort"));
229
    }
230
    
231
    public void testHttpsManualSetProxy () throws InterruptedException {
232
        synchronized (sync) {
233
            if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
234
                proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY);
235
                sync.wait ();
236
            }
237
        }
238
        assertEquals ("Proxy type MANUAL_SET_PROXY.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ());
239
        
240
        // HTTP
241
        assertEquals ("Manual Set Proxy Host from ProxySettings: ", USER_PROXY_HOST, ProxySettings.getHttpHost ());
242
        assertEquals ("Manual Set Proxy Port from ProxySettings: ", USER_PROXY_PORT, ProxySettings.getHttpPort ());
243
        assertEquals ("Manual Set Proxy Host from System.getProperty(): ", USER_PROXY_HOST, System.getProperty ("http.proxyHost"));
244
        assertEquals ("Manual Set Proxy Port from System.getProperty(): ", USER_PROXY_PORT, System.getProperty ("http.proxyPort"));
245
        
246
        // HTTPS
247
        assertEquals ("Manual Set HTTPS Proxy Host from ProxySettings: ", USER_HTTPS_PROXY_HOST, ProxySettings.getHttpsHost ());
248
        assertEquals ("Manual Set HTTPS Proxy Port from ProxySettings: ", USER_HTTPS_PROXY_PORT, ProxySettings.getHttpsPort ());
249
        assertEquals ("Manual Set HTTPS Proxy Host from System.getProperty(): ", USER_HTTPS_PROXY_HOST, System.getProperty ("https.proxyHost"));
250
        assertEquals ("Manual Set HTTPS Proxy Port from System.getProperty(): ", USER_HTTPS_PROXY_PORT, System.getProperty ("https.proxyPort"));
251
    }
252
    
253
    public void testIfTakeUpNonProxyFromProperty () {
254
        assertTrue (NETBEANS_ORG + " in one of Non-Proxy hosts.", ProxySettings.getNonProxyHosts ().indexOf (NETBEANS_ORG) != -1);
255
    }
256
    
257
    public void testNonProxy () throws InterruptedException {
258
        assertEquals ("The ProxySettings takes as same value as System properties in initial.", System.getProperty ("http.nonProxyHosts"), ProxySettings.getNonProxyHosts ());
259
        
260
        // change value in ProxySettings
261
        synchronized (sync) {
262
            if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
263
                proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY);
264
                sync.wait ();
265
            }
266
        }
267
        synchronized (sync) {
268
            if (! MY_NON_PROXY_HOSTS.equals (proxyPreferences.get ("proxyNonProxyHosts", ""))) {
269
                proxyPreferences.put ("proxyNonProxyHosts", MY_NON_PROXY_HOSTS);
270
                sync.wait ();
271
            }
272
        }
273
        assertEquals ("ProxySettings returns new value.", "myhost.mydomain.net", ProxySettings.getNonProxyHosts ());
274
        assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.getNonProxyHosts (), System.getProperty ("http.nonProxyHosts"));
275
        
276
        // switch proxy type to DIRECT_CONNECTION
277
        //System.setProperty ("http.nonProxyHosts", "");
278
        synchronized (sync) {
279
            if (ProxySettings.DIRECT_CONNECTION != (proxyPreferences.getInt ("proxyType", -1))) {
280
                proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION);
281
                sync.wait ();
282
            }
283
        }
284
        Thread.sleep (1000); // XXX: tunning test on Windows platform, other platforms are passing
285
        assertEquals ("System.getProperty() doesn't return new value if DIRECT_CONNECTION set.", null, System.getProperty ("http.nonProxyHosts"));
286
        
287
        // switch proxy type back to MANUAL_SET_PROXY
288
        synchronized (sync) {
289
            if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
290
                proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY);
291
                sync.wait ();
292
            }
293
        }
294
        assertEquals ("ProxySettings again returns new value.", "myhost.mydomain.net", ProxySettings.getNonProxyHosts ());
295
        assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.getNonProxyHosts (), System.getProperty ("http.nonProxyHosts"));
296
        
297
        // switch proxy type to AUTO_DETECT_PROXY
298
        synchronized (sync) {
299
            if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
300
                proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY);
301
                sync.wait ();
302
            }
303
        }
304
        log ("AUTO_DETECT_PROXY: ProxySettings.SystemProxySettings.getNonProxyHosts (): " + ProxySettings.SystemProxySettings.getNonProxyHosts ());
305
        log ("AUTO_DETECT_PROXY: System.getProperty (\"http.nonProxyHosts\"): " + System.getProperty ("http.nonProxyHosts"));
306
        assertTrue ("ProxySettings contains OTHER_ORG if AUTO_DETECT_PROXY set.", System.getProperty ("http.nonProxyHosts").indexOf (OTHER_ORG) > 0);
307
                
308
        // switch proxy type back to MANUAL_SET_PROXY
309
        synchronized (sync) {
310
            if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
311
                proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY);
312
                sync.wait ();
313
            }
314
        }
315
        assertEquals ("ProxySettings again returns new value.", "myhost.mydomain.net", ProxySettings.getNonProxyHosts ());
316
        assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.getNonProxyHosts (), System.getProperty ("http.nonProxyHosts"));
317
    }
318
    
319
    public void testAvoidDuplicateNonProxySetting () throws InterruptedException {
320
        synchronized (sync) {
321
            if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
322
                proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY);
323
                sync.wait ();
324
            }
325
        }
326
        assertTrue (NETBEANS_ORG + " is among Non-proxy hosts detect from OS.", ProxySettings.SystemProxySettings.getNonProxyHosts ().indexOf (NETBEANS_ORG) != -1);
327
        assertFalse (NETBEANS_ORG + " is in Non-Proxy hosts only once.", ProxySettings.SystemProxySettings.getNonProxyHosts ().indexOf (NETBEANS_ORG) < ProxySettings.getNonProxyHosts ().lastIndexOf (NETBEANS_ORG));
328
        assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.SystemProxySettings.getNonProxyHosts (), System.getProperty ("http.nonProxyHosts"));
329
    }
330
    
331
    public void testReadNonProxySettingFromSystem () throws InterruptedException {
332
        synchronized (sync) {
333
            if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
334
                proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY);
335
                sync.wait ();
336
            }
337
        }
338
        assertTrue (OTHER_ORG + " is among Non-proxy hosts detect from OS.", ProxySettings.SystemProxySettings.getNonProxyHosts ().indexOf (OTHER_ORG) != -1);
339
        assertEquals ("System property http.nonProxyHosts was changed as well.", ProxySettings.SystemProxySettings.getNonProxyHosts (), System.getProperty ("http.nonProxyHosts"));
340
    }
341
    
342
    public void testSillySetManualProxy () throws Exception {
343
        sillySetUp ();
344
        synchronized (sync) {
345
            if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
346
                proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY);
347
                sync.wait ();
348
            }
349
        }
350
        assertEquals ("Proxy type MANUAL_SET_PROXY.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ());
351
        assertEquals ("Manual Set Proxy Host from ProxySettings doesn't return SILLY_USER_PROXY_HOST anymore.", USER_PROXY_HOST, ProxySettings.getHttpHost ());
352
        assertEquals ("Manual Set Proxy Port from ProxySettings doesn't return SILLY_USER_PROXY_PORT anymore.", USER_PROXY_PORT, ProxySettings.getHttpPort ());
353
        assertEquals ("Manual Set Proxy Host from System.getProperty(): ", USER_PROXY_HOST, System.getProperty ("http.proxyHost"));
354
        assertEquals ("Manual Set Proxy Port from System.getProperty(): ", USER_PROXY_PORT, System.getProperty ("http.proxyPort"));
355
    }
356
    
357
    public void testAutoDetectSillySetProxy () throws Exception {
358
        sillySetUp ();
359
        synchronized (sync) {
360
            if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
361
                proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY);
362
                sync.wait ();
363
            }
364
        }
365
        assertEquals ("Proxy type AUTO_DETECT_PROXY.", ProxySettings.AUTO_DETECT_PROXY, ProxySettings.getProxyType ());
366
        assertEquals ("Auto Detected Proxy Host from ProxySettings doesn't return SILLY_SYSTEM_PROXY_HOST anymore.", SYSTEM_PROXY_HOST, ProxySettings.SystemProxySettings.getHttpHost ());
367
        assertEquals ("Auto Detected Proxy Port from ProxySettings doesn't return SILLY_SYSTEM_PROXY_PORT anymore.", SYSTEM_PROXY_PORT, ProxySettings.SystemProxySettings.getHttpPort ());
368
        assertEquals ("System Proxy Host: ", SYSTEM_PROXY_HOST, System.getProperty ("http.proxyHost"));
369
        assertEquals ("System Proxy Port: ", SYSTEM_PROXY_PORT, System.getProperty ("http.proxyPort"));
370
    }    
371
    
372
    public void testSwitchAutoAndManualMode () throws Exception {
373
        setUpAutoDirect ();
374
        
375
        // ensure auto detect mode
376
        assertEquals("Proxy type AUTO_DETECT_PROXY.",
377
                     ProxySettings.AUTO_DETECT_PROXY,
378
                     ProxySettings.getProxyType());
379
        assertEquals ("Auto Proxy Host from System.getProperty(): ", null, System.getProperty ("http.proxyHost"));
380
        assertEquals ("Auto Proxy Port from System.getProperty(): ", null, System.getProperty ("http.proxyPort"));
381
        
382
        // switch to manual
383
        proxyPreferences.put ("proxyHttpHost", "foo");
384
        synchronized (sync) {
385
            if (ProxySettings.MANUAL_SET_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
386
                proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY);
387
                sync.wait ();
388
            }
389
        }
390
        assertEquals ("Proxy type MANUAL_SET_PROXY.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ());
391
        assertEquals ("Auto Proxy Host from System.getProperty(): ", "foo", System.getProperty ("http.proxyHost"));
392
        
393
        // switch back to auto detect
394
        synchronized (sync) {
395
            if (ProxySettings.AUTO_DETECT_PROXY != (proxyPreferences.getInt ("proxyType", -1))) {
396
                proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY);
397
                sync.wait ();
398
            }
399
        }
400
        assertEquals("Proxy type AUTO_DETECT_PROXY.",
401
                     ProxySettings.AUTO_DETECT_PROXY,
402
                     ProxySettings.getProxyType());
403
        assertEquals ("Auto Proxy Host from System.getProperty(): ", null, System.getProperty ("http.proxyHost"));
404
        assertEquals ("Auto Proxy Port from System.getProperty(): ", null, System.getProperty ("http.proxyPort"));
405
        
406
    }
407
    
408
    private Object getEventQueueSync() {
409
        try {
410
            Field f = AbstractPreferences.class.getDeclaredField("eventQueue");
411
            f.setAccessible(true);
412
            return f.get(null);
413
        } catch (Exception ex) {
414
            throw new ExceptionInInitializerError(ex);
415
        }
416
    }
417
}
(-)a/o.n.core/test/unit/src/org/netbeans/core/NonProxyHostsTest.java (-172 lines)
Removed Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 1997-2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * Contributor(s):
28
 *
29
 * The Original Software is NetBeans. The Initial Developer of the Original
30
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun
31
 * Microsystems, Inc. All Rights Reserved.
32
 *
33
 * If you wish your version of this file to be governed by only the CDDL
34
 * or only the GPL Version 2, indicate your decision by adding
35
 * "[Contributor] elects to include this software in this distribution
36
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
37
 * single choice of license, a recipient has the option to distribute
38
 * your version of this file under either the CDDL, the GPL Version 2 or
39
 * to extend the choice of license to its licensees as provided above.
40
 * However, if you add GPL Version 2 code and therefore, elected the GPL
41
 * Version 2 license, then the option applies only if the new code is
42
 * made subject to such option by the copyright holder.
43
 */
44
45
package org.netbeans.core;
46
47
import java.net.Proxy;
48
import java.net.ProxySelector;
49
import java.net.URI;
50
import java.util.prefs.PreferenceChangeEvent;
51
import java.util.prefs.PreferenceChangeListener;
52
import java.util.prefs.Preferences;
53
import org.netbeans.junit.NbTestCase;
54
import org.netbeans.junit.RandomlyFails;
55
import org.openide.util.NbPreferences;
56
57
/** Tests Detect OS nonProxyHosts settings.
58
 *
59
 * @author Jiri Rechtacek
60
 * @see http://www.netbeans.org/issues/show_bug.cgi?id=77053
61
 */
62
@RandomlyFails // NB-Core-Build #1247, 1248
63
public class NonProxyHostsTest extends NbTestCase {
64
    private static String SYSTEM_PROXY_HOST = "system.cache.org";
65
    private static String SYSTEM_PROXY_PORT = "777";
66
    private static String USER_PROXY_HOST = "my.webcache";
67
    private static String USER_PROXY_PORT = "8080";
68
69
    private Preferences proxyPreferences;
70
    private ProxySelector selector;
71
    private static URI TO_LOCALHOST;
72
    private static URI TO_LOCAL_DOMAIN_1;
73
    private static URI TO_LOCAL_DOMAIN_2;
74
    private static URI TO_EXTERNAL;
75
    private static URI SOCKS_TO_LOCALHOST;
76
    private static URI SOCKS_TO_LOCAL_DOMAIN_1;
77
    private static URI SOCKS_TO_LOCAL_DOMAIN_2;
78
    private static URI SOCKS_TO_EXTERNAL;
79
80
    private boolean isWaiting = false;
81
    
82
    public NonProxyHostsTest (String name) {
83
        super (name);
84
    }
85
    
86
    @Override
87
    protected void setUp () throws Exception {
88
        super.setUp ();
89
        System.setProperty ("netbeans.system_http_proxy", SYSTEM_PROXY_HOST + ":" + SYSTEM_PROXY_PORT);
90
        System.setProperty ("netbeans.system_socks_proxy", SYSTEM_PROXY_HOST + ":" + SYSTEM_PROXY_PORT);
91
        System.setProperty ("netbeans.system_http_non_proxy_hosts", "*.other.org");
92
        System.setProperty ("http.nonProxyHosts", "*.netbeans.org");
93
        NbProxySelector.register();
94
        selector = ProxySelector.getDefault ();
95
        proxyPreferences  = NbPreferences.root ().node ("/org/netbeans/core");
96
        proxyPreferences.addPreferenceChangeListener (new PreferenceChangeListener () {
97
            public void preferenceChange (PreferenceChangeEvent arg0) {
98
                isWaiting = false;
99
            }
100
        });
101
        proxyPreferences.put ("proxyHttpHost", USER_PROXY_HOST);
102
        proxyPreferences.put ("proxyHttpPort", USER_PROXY_PORT);
103
        proxyPreferences.put ("proxySocksHost", USER_PROXY_HOST);
104
        proxyPreferences.put ("proxySocksPort", USER_PROXY_PORT);
105
        while (isWaiting);
106
        isWaiting = true;
107
        TO_LOCALHOST = new URI ("http://localhost");
108
        TO_LOCAL_DOMAIN_1 = new URI ("http://core.netbeans.org");
109
        TO_LOCAL_DOMAIN_2 = new URI ("http://core.other.org");
110
        TO_EXTERNAL = new URI ("http://worldwide.net");
111
        
112
        SOCKS_TO_LOCALHOST = new URI ("socket://localhost:8041");
113
        SOCKS_TO_LOCAL_DOMAIN_1 = new URI ("socket://core.netbeans.org");
114
        SOCKS_TO_LOCAL_DOMAIN_2 = new URI ("socket://core.other.org");
115
        SOCKS_TO_EXTERNAL = new URI ("socket://worldwide.net");
116
    }
117
    
118
    public void testDirectProxySetting () {
119
        proxyPreferences.putInt ("proxyType", ProxySettings.DIRECT_CONNECTION);
120
        while (isWaiting);
121
        assertEquals ("Proxy type DIRECT_CONNECTION.", ProxySettings.DIRECT_CONNECTION, ProxySettings.getProxyType ());
122
        assertEquals ("Connect " + TO_LOCALHOST + " DIRECT.", "[DIRECT]", selector.select (TO_LOCALHOST).toString ());
123
        assertEquals ("Connect " + SOCKS_TO_LOCALHOST + " DIRECT.", Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCALHOST).get(0));
124
        assertEquals ("Connect " + TO_LOCAL_DOMAIN_1 + " DIRECT.", "[DIRECT]", selector.select (TO_LOCAL_DOMAIN_1).toString ());
125
        assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_1 + " DIRECT.", "[DIRECT]", selector.select (SOCKS_TO_LOCAL_DOMAIN_1).toString ());
126
        assertEquals ("Connect " + TO_LOCAL_DOMAIN_2 + " DIRECT.", "[DIRECT]", selector.select (TO_LOCAL_DOMAIN_2).toString ());
127
        assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_2 + " DIRECT.", "[DIRECT]", selector.select (SOCKS_TO_LOCAL_DOMAIN_2).toString ());
128
        assertEquals ("Connect " + TO_EXTERNAL + " DIRECT.", "[DIRECT]", selector.select (TO_EXTERNAL).toString ());
129
        assertEquals ("Connect " + SOCKS_TO_EXTERNAL + " DIRECT.", "[DIRECT]", selector.select (SOCKS_TO_EXTERNAL).toString ());
130
    }
131
    
132
    @RandomlyFails
133
    public void testManualProxySettins () {
134
        proxyPreferences.put (ProxySettings.NOT_PROXY_HOSTS, "localhost|" + "*.netbeans.org");
135
        proxyPreferences.putInt ("proxyType", ProxySettings.MANUAL_SET_PROXY);
136
        while (isWaiting);
137
        assertEquals ("Proxy type DIRECT_CONNECTION.", ProxySettings.MANUAL_SET_PROXY, ProxySettings.getProxyType ());
138
        assertEquals ("Connect TO_LOCALHOST DIRECT.", Proxy.NO_PROXY, selector.select (TO_LOCALHOST).get(0));
139
        assertEquals ("Connect " + SOCKS_TO_LOCALHOST + " DIRECT.", Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCALHOST).get(0));
140
        assertEquals ("Connect " + TO_LOCAL_DOMAIN_1 + " DIRECT.", Proxy.NO_PROXY, selector.select (TO_LOCAL_DOMAIN_1).get (0));
141
        assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_1 + " DIRECT.",
142
                Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCAL_DOMAIN_1).get (0));
143
        assertEquals ("Connect " + TO_LOCAL_DOMAIN_2 + " via my.webcache:8080 proxy.",
144
                "HTTP @ my.webcache:8080", selector.select (TO_LOCAL_DOMAIN_2).get (0).toString ());
145
        assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_2 + " via my.webcache:8080 proxy.",
146
                "SOCKS @ my.webcache:8080", selector.select (SOCKS_TO_LOCAL_DOMAIN_2).get (0).toString ());
147
        assertEquals ("Connect TO_EXTERNAL via my.webcache:8080 proxy.", "HTTP @ my.webcache:8080", selector.select (TO_EXTERNAL).get (0).toString ());
148
        assertEquals ("Connect SOCKS_TO_EXTERNAL via my.webcache:8080 proxy.",
149
                "SOCKS @ my.webcache:8080", selector.select (SOCKS_TO_EXTERNAL).get (0).toString ());
150
    }
151
    
152
    @RandomlyFails
153
    public void testSystemProxySettings () {
154
        proxyPreferences.putInt ("proxyType", ProxySettings.AUTO_DETECT_PROXY);
155
        while (isWaiting);
156
        log ("Value of System.getProperty (\"http.nonProxyHosts\"): " + System.getProperty ("http.nonProxyHosts"));
157
        assertTrue ("*.other.org is one of non-proxy hosts", System.getProperty ("http.nonProxyHosts").indexOf ("*.other.org") != -1);
158
        assertEquals ("Proxy type DIRECT_CONNECTION.", ProxySettings.AUTO_DETECT_PROXY, ProxySettings.getProxyType ());
159
        assertEquals ("Connect TO_LOCALHOST DIRECT.", Proxy.NO_PROXY, selector.select (TO_LOCALHOST).get(0));
160
        assertEquals ("Connect " + SOCKS_TO_LOCALHOST + " DIRECT.", Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCALHOST).get(0));
161
        assertEquals ("Connect " + TO_LOCAL_DOMAIN_1 + " DIRECT.", Proxy.NO_PROXY, selector.select (TO_LOCAL_DOMAIN_1).get (0));
162
        assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_1 + " DIRECT.",
163
                Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCAL_DOMAIN_1).get (0));
164
        assertEquals ("Connect " + TO_LOCAL_DOMAIN_2 + " DIRECT ignoring settings " + System.getProperty ("http.nonProxyHosts"), Proxy.NO_PROXY, selector.select (TO_LOCAL_DOMAIN_2).get (0));
165
        assertEquals ("Connect " + SOCKS_TO_LOCAL_DOMAIN_2 + " DIRECT ignoring settings " + System.getProperty ("http.nonProxyHosts"),
166
                Proxy.NO_PROXY, selector.select (SOCKS_TO_LOCAL_DOMAIN_2).get (0));
167
        assertEquals ("Connect TO_EXTERNAL via system.cache.org:777 proxy.", "HTTP @ system.cache.org:777", selector.select (TO_EXTERNAL).get (0).toString ());
168
        assertEquals ("Connect SOCKS_TO_EXTERNAL via system.cache.org:777 proxy.", "SOCKS @ system.cache.org:777",
169
                selector.select (SOCKS_TO_EXTERNAL).get (0).toString ());
170
    }
171
172
}
(-)a/o.n.core/test/unit/src/org/netbeans/core/ProxyAutoConfigTest.java (-160 lines)
Removed Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2011 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.core;
43
44
import java.io.File;
45
import java.net.Proxy;
46
import java.net.URI;
47
import java.net.URISyntaxException;
48
import java.util.LinkedList;
49
import java.util.List;
50
import junit.framework.Test;
51
import org.netbeans.junit.NbModuleSuite;
52
import org.netbeans.junit.NbTestCase;
53
import org.openide.util.Utilities;
54
55
/**
56
 *
57
 * @author Jirka Rechtacek
58
 */
59
public class ProxyAutoConfigTest extends NbTestCase {
60
    
61
    public static Test suite() {
62
        return NbModuleSuite
63
                .emptyConfiguration()
64
                .gui(false)
65
                .addTest(ProxyAutoConfigTest.class)
66
                .suite();
67
    }
68
    
69
    public ProxyAutoConfigTest(String name) {
70
        super(name);
71
    }
72
    
73
    public void testGetProxyAutoConfig() {
74
        assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt"));
75
    }
76
    
77
    // #issue 201995
78
    public void testGetProxyAutoConfigWithMultipleURL() {
79
        assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt http://pac/pac.txt http://pac/pac.txt"));
80
    }
81
    
82
    public void testGetProxyAutoConfigWithNewLineURL() {
83
        assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt\nhttp://pac/pac.txt"));
84
    }
85
    
86
    public void testGetProxyAutoConfigWithLineTerminatorURL() {
87
        assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt\rhttp://pac/pac.txt"));
88
    }
89
    
90
    public void testGetProxyAutoConfigWithBothTerminatorsURL() {
91
        assertNotNull(ProxyAutoConfig.get("http://pac/pac.txt\r\nhttp://pac/pac.txt"));
92
    }
93
    
94
    public void testGetProxyAutoConfigWithInvalidURL() {
95
        assertNotNull(ProxyAutoConfig.get("http:\\\\pac\\pac.txt"));
96
    }
97
    
98
    public void testGetProxyAutoConfigWithRelativePath() {
99
        assertNotNull(ProxyAutoConfig.get("http://pac/../pac/pac.txt"));
100
    }
101
    
102
    public void testGetProxyAutoConfigWithLocalPAC() throws URISyntaxException {
103
        List<String> pacFileLocations = new LinkedList<String>();
104
        for (File pacFile : new File(getDataDir(), "pacFiles").listFiles()) {
105
            pacFileLocations.add(pacFile.getAbsolutePath());
106
            pacFileLocations.add("file://" + pacFile.getAbsolutePath());
107
            pacFileLocations.add(pacFile.toURI().toString());
108
        }
109
        for (String pacFileLoc : pacFileLocations) {
110
            ProxyAutoConfig pac = ProxyAutoConfig.get(pacFileLoc);
111
            assertNotNull(pac);
112
            URI uri = pac.getPacURI();
113
            assertNotNull(uri);
114
            assertNull(uri.getHost());
115
            List<Proxy> proxies = pac.findProxyForURL(new URI("http://netbeans.org"));
116
            assertEquals(1, proxies.size());
117
            assertTrue(pacFileLoc + ": " + proxies.get(0).toString(), proxies.get(0).toString().startsWith("HTTP @ www-proxy.us.oracle.com/"));
118
            System.setProperty("netbeans.system_http_proxy", "PAC " + pacFileLoc);
119
            proxies = NbProxySelector.getDefault().select(new URI("http://netbeans.org"));
120
            assertTrue(pacFileLoc + ": " + proxies.get(0).toString(), proxies.get(0).toString().startsWith("HTTP @ www-proxy.us.oracle.com/"));
121
            
122
            proxies = pac.findProxyForURL(new URI("https://netbeans.org"));
123
            assertEquals(1, proxies.size());
124
            assertTrue(pacFileLoc + ": " + proxies.get(0).toString(), proxies.get(0).toString().startsWith("HTTP @ www-proxy.us.oracle.com/"));
125
            System.setProperty("netbeans.system_http_proxy", "PAC " + pacFileLoc);
126
            proxies = NbProxySelector.getDefault().select(new URI("https://netbeans.org"));
127
            assertTrue(pacFileLoc + ": " + proxies.get(0).toString(), proxies.get(0).toString().startsWith("HTTP @ www-proxy.us.oracle.com/"));
128
            
129
            proxies = pac.findProxyForURL(new URI("http://localhost"));
130
            assertEquals(1, proxies.size());
131
            assertEquals(pacFileLoc + ": " + proxies.get(0).toString(), "DIRECT", proxies.get(0).toString());
132
            proxies = NbProxySelector.getDefault().select(new URI("http://localhost"));
133
            assertEquals(pacFileLoc + ": " + proxies.get(0).toString(), "DIRECT", proxies.get(0).toString());
134
        }
135
    }
136
    
137
    public void testGetProxyAutoConfigWithLocalInvalidPAC() throws URISyntaxException {
138
        List<String> pacFileLocations = new LinkedList<String>();
139
        for (File pacFile : new File[] {
140
            new File(getDataDir(), "pacFiles"),
141
            new File(getDataDir(), "doesNotExist")
142
        }) {
143
            pacFileLocations.add(pacFile.getAbsolutePath());
144
            pacFileLocations.add("file://" + pacFile.getAbsolutePath());
145
            pacFileLocations.add(pacFile.toURI().toString());
146
        }
147
        for (String pacFileLoc : pacFileLocations) {
148
            ProxyAutoConfig pac = ProxyAutoConfig.get(pacFileLoc);
149
            assertNotNull(pac);
150
            URI uri = pac.getPacURI();
151
            assertNotNull(uri);
152
            List<Proxy> proxies = pac.findProxyForURL(new URI("http://netbeans.org"));
153
            assertEquals(1, proxies.size());
154
            assertEquals("DIRECT", proxies.get(0).toString());
155
            System.setProperty("netbeans.system_http_proxy", "PAC " + pacFileLoc);
156
            proxies = NbProxySelector.getDefault().select(new URI("http://netbeans.org"));
157
            assertEquals(pacFileLoc + ": " + proxies.get(0).toString(), "DIRECT", proxies.get(0).toString());
158
        }
159
    }
160
}

Return to bug 201731