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 201662
Collapse All | Expand All

(-)a/o.n.core/nbproject/project.xml (-1 / +1 lines)
Lines 160-166 Link Here
160
                    <build-prerequisite/>
160
                    <build-prerequisite/>
161
                    <compile-dependency/>
161
                    <compile-dependency/>
162
                    <run-dependency>
162
                    <run-dependency>
163
                        <specification-version>8.0</specification-version>
163
                        <specification-version>8.17</specification-version>
164
                    </run-dependency>
164
                    </run-dependency>
165
                </dependency>
165
                </dependency>
166
                <dependency>
166
                <dependency>
(-)a/o.n.core/src/org/netbeans/core/NbAuthenticator.java (-1 / +26 lines)
Lines 44-49 Link Here
44
package org.netbeans.core;
44
package org.netbeans.core;
45
45
46
import java.net.PasswordAuthentication;
46
import java.net.PasswordAuthentication;
47
import java.net.URL;
47
import java.util.logging.Level;
48
import java.util.logging.Level;
48
import java.util.logging.Logger;
49
import java.util.logging.Logger;
49
import java.util.prefs.Preferences;
50
import java.util.prefs.Preferences;
Lines 51-56 Link Here
51
import org.openide.DialogDisplayer;
52
import org.openide.DialogDisplayer;
52
import org.openide.util.NbBundle;
53
import org.openide.util.NbBundle;
53
import org.openide.util.NbPreferences;
54
import org.openide.util.NbPreferences;
55
import org.openide.util.NetworkSettings;
54
56
55
/** Global password protected sites Authenticator for IDE
57
/** Global password protected sites Authenticator for IDE
56
 *
58
 *
Lines 61-67 Link Here
61
    private static final long TIMEOUT = 3000;
63
    private static final long TIMEOUT = 3000;
62
    private static long lastTry = 0;
64
    private static long lastTry = 0;
63
65
64
65
    private NbAuthenticator() {
66
    private NbAuthenticator() {
66
        Preferences proxySettingsNode = NbPreferences.root().node("/org/netbeans/core"); //NOI18N
67
        Preferences proxySettingsNode = NbPreferences.root().node("/org/netbeans/core"); //NOI18N
67
        assert proxySettingsNode != null;
68
        assert proxySettingsNode != null;
Lines 73-78 Link Here
73
        }
74
        }
74
    }
75
    }
75
76
77
    static void install4test() {
78
        setDefault(new NbAuthenticator());
79
    }
80
76
    @Override
81
    @Override
77
    protected PasswordAuthentication getPasswordAuthentication() {
82
    protected PasswordAuthentication getPasswordAuthentication() {
78
        Logger.getLogger(NbAuthenticator.class.getName()).log(Level.FINER, "Authenticator.getPasswordAuthentication() with prompt " + this.getRequestingPrompt()); //NOI18N
83
        Logger.getLogger(NbAuthenticator.class.getName()).log(Level.FINER, "Authenticator.getPasswordAuthentication() with prompt " + this.getRequestingPrompt()); //NOI18N
Lines 85-90 Link Here
85
                if (getRequestingProtocol().startsWith("SOCKS")&&(ProxySettings.getAuthenticationUsername().length()>0)) { //NOI18N
90
                if (getRequestingProtocol().startsWith("SOCKS")&&(ProxySettings.getAuthenticationUsername().length()>0)) { //NOI18N
86
                    return new java.net.PasswordAuthentication(ProxySettings.getAuthenticationUsername(), ProxySettings.getAuthenticationPassword());
91
                    return new java.net.PasswordAuthentication(ProxySettings.getAuthenticationUsername(), ProxySettings.getAuthenticationPassword());
87
                }
92
                }
93
                if (NetworkSettings.isAuthenticationDialogSuppressed()) {
94
                    return null;
95
                }
96
                PasswordAuthentication auth = getAuthenticationFromURL();
97
                if (auth != null) {
98
                    return auth;
99
                }
88
                NbAuthenticatorPanel ui = new NbAuthenticatorPanel(getRequestingPrompt());
100
                NbAuthenticatorPanel ui = new NbAuthenticatorPanel(getRequestingPrompt());
89
                Object result = DialogDisplayer.getDefault().notify(
101
                Object result = DialogDisplayer.getDefault().notify(
90
                        new DialogDescriptor(ui, NbBundle.getMessage(NbAuthenticator.class, "CTL_Authentication"))); //NOI18N
102
                        new DialogDescriptor(ui, NbBundle.getMessage(NbAuthenticator.class, "CTL_Authentication"))); //NOI18N
Lines 101-104 Link Here
101
        return null;
113
        return null;
102
    }
114
    }
103
115
116
    private PasswordAuthentication getAuthenticationFromURL() {
117
        URL u = this.getRequestingURL();
118
        if (u != null) {
119
            String auth = u.getUserInfo();
120
            if (auth != null) {
121
                int i = auth.indexOf(':');
122
                String user = (i == -1) ? auth : auth.substring(0, i);
123
                String pwd = (i == -1) ? "" : auth.substring(i + 1);
124
                return new PasswordAuthentication(user, pwd.toCharArray());
125
            }
126
        }
127
        return null;
128
    }
104
}
129
}
(-)a/o.n.core/src/org/netbeans/core/ProxySettings.java (+79 lines)
Lines 45-61 Link Here
45
package org.netbeans.core;
45
package org.netbeans.core;
46
46
47
import java.net.InetAddress;
47
import java.net.InetAddress;
48
import java.net.InetSocketAddress;
49
import java.net.Proxy;
50
import java.net.ProxySelector;
51
import java.net.URI;
48
import java.net.UnknownHostException;
52
import java.net.UnknownHostException;
49
import java.util.HashSet;
53
import java.util.HashSet;
54
import java.util.List;
50
import java.util.Locale;
55
import java.util.Locale;
51
import java.util.Set;
56
import java.util.Set;
52
import java.util.StringTokenizer;
57
import java.util.StringTokenizer;
58
import java.util.logging.Level;
59
import java.util.logging.Logger;
53
import java.util.prefs.PreferenceChangeListener;
60
import java.util.prefs.PreferenceChangeListener;
54
import java.util.prefs.Preferences;
61
import java.util.prefs.Preferences;
55
import org.netbeans.api.keyring.Keyring;
62
import org.netbeans.api.keyring.Keyring;
56
import org.openide.util.NbBundle;
63
import org.openide.util.NbBundle;
57
import org.openide.util.NbPreferences;
64
import org.openide.util.NbPreferences;
65
import org.openide.util.NetworkSettings;
66
import org.openide.util.Parameters;
58
import org.openide.util.Utilities;
67
import org.openide.util.Utilities;
68
import org.openide.util.lookup.ServiceProvider;
59
69
60
/**
70
/**
61
 *
71
 *
Lines 95-100 Link Here
95
    /** Proxy PAC file manually set. */
105
    /** Proxy PAC file manually set. */
96
    public static final int MANUAL_SET_PAC = 4;
106
    public static final int MANUAL_SET_PAC = 4;
97
    
107
    
108
    private static final Logger LOGGER = Logger.getLogger(ProxySettings.class.getName());
109
    
98
    private static Preferences getPreferences() {
110
    private static Preferences getPreferences() {
99
        return NbPreferences.forModule (ProxySettings.class);
111
        return NbPreferences.forModule (ProxySettings.class);
100
    }
112
    }
Lines 437-440 Link Here
437
        }
449
        }
438
    }
450
    }
439
    
451
    
452
    private static InetSocketAddress analyzeProxy(URI uri) {
453
        Parameters.notNull("uri", uri);
454
        List<Proxy> proxies = ProxySelector.getDefault().select(uri);
455
        assert proxies != null : "ProxySelector cannot return null for " + uri;
456
        assert !proxies.isEmpty() : "ProxySelector cannot return empty list for " + uri;
457
        Proxy p = proxies.get(0);
458
        if (Proxy.Type.DIRECT == p.type()) {
459
            // return null for DIRECT proxy
460
            return null;
461
        } else {
462
            if (p.address() instanceof InetSocketAddress) {
463
                // check is
464
                //assert ! ((InetSocketAddress) p.address()).isUnresolved() : p.address() + " must be resolved address.";
465
                return (InetSocketAddress) p.address();
466
            } else {
467
                LOGGER.log(Level.INFO, p.address() + " is not instanceof InetSocketAddress but " + p.address().getClass());
468
                return null;
469
            }
470
        }
471
    }
472
473
    @ServiceProvider(service = NetworkSettings.ProxyCredentialsProvider.class, position = 1000)
474
    public static class NbProxyCredentialsProvider extends NetworkSettings.ProxyCredentialsProvider {
475
476
        @Override
477
        public String getProxyHost(URI u) {
478
            if (getPreferences() == null) {
479
                return null;
480
            }
481
            InetSocketAddress sa = analyzeProxy(u);
482
            return sa == null ? null : sa.getHostName();
483
        }
484
485
        @Override
486
        public String getProxyPort(URI u) {
487
            if (getPreferences() == null) {
488
                return null;
489
            }
490
            InetSocketAddress sa = analyzeProxy(u);
491
            return sa == null ? null : Integer.toString(sa.getPort());
492
        }
493
494
        @Override
495
        protected String getProxyUserName(URI u) {
496
            if (getPreferences() == null) {
497
                return null;
498
            }
499
            return ProxySettings.getAuthenticationUsername();
500
        }
501
502
        @Override
503
        protected char[] getProxyPassword(URI u) {
504
            if (getPreferences() == null) {
505
                return null;
506
            }
507
            return ProxySettings.getAuthenticationPassword();
508
        }
509
510
        @Override
511
        protected boolean isProxyAuthentication(URI u) {
512
            if (getPreferences() == null) {
513
                return false;
514
            }
515
            return getPreferences().getBoolean(USE_PROXY_AUTHENTICATION, false);
516
        }
517
518
    }
440
}
519
}
(-)db7aba84ef7e (+84 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;
43
44
import java.net.Authenticator;
45
import java.net.Inet4Address;
46
import java.net.PasswordAuthentication;
47
import java.net.URL;
48
import java.util.concurrent.Callable;
49
import org.netbeans.junit.NbTestCase;
50
import org.openide.util.NetworkSettings;
51
52
/**
53
 *
54
 * @author Ondrej Vrabec
55
 */
56
public class NbAuthenticatorTest extends NbTestCase {
57
    
58
    public NbAuthenticatorTest(String name) {
59
        super(name);
60
    }
61
62
    public void testUserInfoInUrl () throws Exception {
63
        NbAuthenticator.install4test();
64
        PasswordAuthentication auth = Authenticator.requestPasswordAuthentication("localhost", Inet4Address.getLocalHost(), 1234, "http", null, "http",
65
                new URL("http://user:password@localhost/resource"), Authenticator.RequestorType.SERVER);
66
        
67
        assertNotNull(auth);
68
        assertEquals("user", auth.getUserName());
69
        assertEquals("password", new String(auth.getPassword()));
70
    }
71
72
    public void testSupressedAuthenticator () throws Exception {
73
        NbAuthenticator.install4test();
74
        PasswordAuthentication auth =
75
            NetworkSettings.suppressAuthenticationDialog(new Callable<PasswordAuthentication>() {
76
                @Override
77
                public PasswordAuthentication call () throws Exception {
78
                    return Authenticator.requestPasswordAuthentication("localhost", Inet4Address.getLocalHost(), 1234, "http", null, "http",
79
                            new URL("http://user:password@localhost/resource"), Authenticator.RequestorType.SERVER);
80
                }
81
            });
82
        assertNull(auth);
83
    }
84
}
(-)a/openide.util/apichanges.xml (+42 lines)
Lines 51-56 Link Here
51
    <apidef name="actions">Actions API</apidef>
51
    <apidef name="actions">Actions API</apidef>
52
</apidefs>
52
</apidefs>
53
<changes>
53
<changes>
54
    <change id="ProxyCredentialsProvider">
55
        <api name="util"/>
56
        <summary>SPI <code>NetworkSettings.ProxyCredentialsProvider</code> added</summary>
57
        <version major="8" minor="17"/>
58
        <date day="20" month="9" year="2011"/>
59
        <author login="jrechtacek"/>
60
        <compatibility addition="yes"/>
61
        <description>
62
            <p>
63
                Most of the proxy and network credentials are currently read
64
                from a default NetBeans storage. This may not be ideal
65
                for other Platform aplications storing the settings in a different
66
                way or computing them dynamically. 
67
                A SPI <a href="@TOP@/org/openide/util/NetworkSettings.ProxyCredentialsProvider.html">
68
                NetworkSettings.ProxyCredentialsProvider</a> allows NetBeans Platform
69
                users to provide proxy and network credentials separately.
70
                See <a href="http://wiki.netbeans.org/Authenticator">http://wiki.netbeans.org/Authenticator</a>
71
            </p>
72
        </description>
73
        <class package="org.openide.util" name="NetworkSettings"/>
74
        <issue number="201662"/>
75
    </change>
76
    <change id="SuppressAuthentication">
77
        <api name="util"/>
78
        <summary><code>NetworkSettings.suppressAuthenticationDialog</code> added</summary>
79
        <version major="8" minor="17"/>
80
        <date day="20" month="9" year="2011"/>
81
        <author login="jrechtacek"/>
82
        <compatibility addition="yes"/>
83
        <description>
84
            <p>
85
                Some plugins needs a way to suppress <a href="http://download.oracle.com/javase/6/docs/api/java/net/Authenticator.html">
86
                    Authenticator</a> without asking
87
                user a question about the credentials. 
88
                Invoke <a href="@TOP@/org/openide/util/NetworkSettings.html#suppressAuthenticationDialog(java.util.concurrent.Callable)">
89
                suppressAuthenticationDialog</a> with a block of code where authentication dialog will be suppressed.                
90
                See <a href="http://wiki.netbeans.org/Authenticator">http://wiki.netbeans.org/Authenticator</a>
91
            </p>
92
        </description>
93
        <class package="org.openide.util" name="NetworkSettings"/>
94
        <issue number="201662"/>
95
    </change>
54
    <change id="NetworkSettings">
96
    <change id="NetworkSettings">
55
        <api name="util"/>
97
        <api name="util"/>
56
        <summary><code>NetworkSettings</code> added</summary>
98
        <summary><code>NetworkSettings</code> added</summary>
(-)a/openide.util/manifest.mf (-1 / +1 lines)
Lines 1-5 Link Here
1
Manifest-Version: 1.0
1
Manifest-Version: 1.0
2
OpenIDE-Module: org.openide.util
2
OpenIDE-Module: org.openide.util
3
OpenIDE-Module-Localizing-Bundle: org/openide/util/Bundle.properties
3
OpenIDE-Module-Localizing-Bundle: org/openide/util/Bundle.properties
4
OpenIDE-Module-Specification-Version: 8.16
4
OpenIDE-Module-Specification-Version: 8.17
5
5
(-)a/openide.util/src/org/openide/util/NetworkSettings.java (-51 / +105 lines)
Lines 41-54 Link Here
41
 */
41
 */
42
package org.openide.util;
42
package org.openide.util;
43
43
44
import java.net.InetSocketAddress;
45
import java.net.Proxy;
46
import java.net.ProxySelector;
47
import java.net.URI;
44
import java.net.URI;
48
import java.util.List;
45
import java.util.concurrent.Callable;
49
import java.util.logging.Level;
50
import java.util.logging.Logger;
46
import java.util.logging.Logger;
51
import java.util.prefs.Preferences;
52
47
53
/** Useful static methods for getting Network Proxy required for make network
48
/** Useful static methods for getting Network Proxy required for make network
54
 * connection for specified resource.
49
 * connection for specified resource.
Lines 58-81 Link Here
58
 */
53
 */
59
public final class NetworkSettings {
54
public final class NetworkSettings {
60
55
61
    private static final String PROXY_AUTHENTICATION_USERNAME = "proxyAuthenticationUsername";
62
    private static final String PROXY_AUTHENTICATION_PASSWORD = "proxyAuthenticationPassword";
56
    private static final String PROXY_AUTHENTICATION_PASSWORD = "proxyAuthenticationPassword";
63
    private static final String USE_PROXY_AUTHENTICATION = "useProxyAuthentication";
64
    private static final Logger LOGGER = Logger.getLogger(NetworkSettings.class.getName());
57
    private static final Logger LOGGER = Logger.getLogger(NetworkSettings.class.getName());
58
    private static ThreadLocal<Boolean> authenticationDialogSuppressed = new ThreadLocal<Boolean>();
65
59
66
    /** Returns the <code>hostname</code> part of network proxy address 
60
    /** Returns the <code>hostname</code> part of network proxy address 
67
     * based on given URI to access the resource at.
61
     * based on given URI to access the resource at.
68
     * Returns <code>null</code> for direct connection.
62
     * Returns <code>null</code> for direct connection.
69
     * 
63
     * 
70
     * @param u The URI that a connection is required to
64
     * @param u The URI that a connection is required to
71
     * @return the hostname part of the Proxy address
65
     * @return the hostname part of the Proxy address or <code>null</code>
72
     */
66
     */
73
    public static String getProxyHost(URI u) {
67
    public static String getProxyHost(URI u) {
74
        if (getPreferences() == null) {
68
        ProxyCredentialsProvider provider = Lookup.getDefault().lookup(ProxyCredentialsProvider.class);
75
            return null;
69
        if (provider == null) {
70
            LOGGER.warning("No ProxyCredentialsProvider found in lookup " + Lookup.getDefault() + " thus no proxy information will provide!");
76
        }
71
        }
77
        InetSocketAddress sa = analyzeProxy(u);
72
        return provider == null ? null : provider.getProxyHost(u);
78
        return sa == null ? null : sa.getHostName();
79
    }
73
    }
80
74
81
    /** Returns the <code>port</code> part of network proxy address 
75
    /** Returns the <code>port</code> part of network proxy address 
Lines 83-153 Link Here
83
     * Returns <code>null</code> for direct connection.
77
     * Returns <code>null</code> for direct connection.
84
     * 
78
     * 
85
     * @param u The URI that a connection is required to
79
     * @param u The URI that a connection is required to
86
     * @return the port part of the Proxy address
80
     * @return the port part of the Proxy address or <code>null</code>
87
     */
81
     */
88
    public static String getProxyPort(URI u) {
82
    public static String getProxyPort(URI u) {
89
        if (getPreferences() == null) {
83
        ProxyCredentialsProvider provider = Lookup.getDefault().lookup(ProxyCredentialsProvider.class);
90
            return null;
84
        if (provider == null) {
85
            LOGGER.warning("No ProxyCredentialsProvider found in lookup " + Lookup.getDefault() + " thus no proxy information will provide!");
91
        }
86
        }
92
        InetSocketAddress sa = analyzeProxy(u);
87
        return provider == null ? null : provider.getProxyPort(u);
93
        return sa == null ? null : Integer.toString(sa.getPort());
94
    }
88
    }
95
89
96
    /** Returns the <code>username</code> for Proxy Authentication.
90
    /** Returns the <code>username</code> for Proxy Authentication.
97
     * Returns <code>null</code> if no authentication required.
91
     * Returns <code>null</code> if no authentication required.
98
     * 
92
     * 
99
     * @param u The URI that a connection is required to
93
     * @param u The URI that a connection is required to
100
     * @return username for Proxy Authentication
94
     * @return username for Proxy Authentication or <code>null</code>
101
     */
95
     */
102
    public static String getAuthenticationUsername(URI u) {
96
    public static String getAuthenticationUsername(URI u) {
103
        if (getPreferences() == null) {
97
        ProxyCredentialsProvider provider = Lookup.getDefault().lookup(ProxyCredentialsProvider.class);
104
            return null;
98
        if (provider == null) {
99
            LOGGER.warning("No ProxyCredentialsProvider found in lookup " + Lookup.getDefault() + " thus no proxy information will provide!");
105
        }
100
        }
106
        if (getPreferences().getBoolean(USE_PROXY_AUTHENTICATION, false)) {
101
        if (provider != null && provider.isProxyAuthentication(u)) {
107
            return getPreferences().get(PROXY_AUTHENTICATION_USERNAME, "");
102
            return provider.getProxyUserName(u);
108
        }
103
        }
109
        return null;
104
        return null;
110
    }
105
    }
111
    
106
112
    /** Returns the <code>key</code> for reading password for Proxy Authentication.
107
    /** Returns the <code>key</code> for reading password for Proxy Authentication.
113
     * Use {@link Keyring} for reading the password from the ring.
108
     * Use {@link org.netbeans.api.Keyring} for reading the password from the ring.
114
     * Returns <code>null</code> if no authentication required.
109
     * Returns <code>null</code> if no authentication required.
115
     * 
110
     * 
116
     * @param u The URI that a connection is required to
111
     * @param u The URI that a connection is required to
117
     * @return the key for reading password for Proxy Authentication from the ring
112
     * @return the key for reading password for Proxy Authentication from the ring or <code>null</code>
118
     */
113
     */
119
    public static String getKeyForAuthenticationPassword(URI u) {
114
    public static String getKeyForAuthenticationPassword(URI u) {
120
        if (getPreferences() == null) {
115
        ProxyCredentialsProvider provider = Lookup.getDefault().lookup(ProxyCredentialsProvider.class);
121
            return null;
116
        if (provider == null) {
117
            LOGGER.warning("No ProxyCredentialsProvider found in lookup " + Lookup.getDefault() + " thus no proxy information will provide!");
122
        }
118
        }
123
        if (getPreferences().getBoolean(USE_PROXY_AUTHENTICATION, false)) {
119
        if (provider != null && provider.isProxyAuthentication(u)) {
124
            return PROXY_AUTHENTICATION_PASSWORD;
120
            return PROXY_AUTHENTICATION_PASSWORD;
125
        }
121
        }
126
        return null;
122
        return null;
127
    }
123
    }
128
124
129
    private static Preferences getPreferences() {
125
    /** Suppress asking user a question about the authentication credentials while
130
        return NbPreferences.root().node("org/netbeans/core"); // NOI18N
126
     * running <code>blockOfCode</code>. It's a contract with NetBeans implementation
131
    }
127
     * of <a href="http://download.oracle.com/javase/6/docs/api/java/net/Authenticator.html">Authenticator</a>.
132
    
128
     * In case a system is using other Authenticator implementation, it must call {@link #isAuthenticationDialogSuppressed} method. 
133
    private static InetSocketAddress analyzeProxy(URI uri) {
129
     * 
134
        Parameters.notNull("uri", uri);
130
     * @param blockOfCode {@link Callable} containing code which will be executed while authentication is suppressed
135
        List<Proxy> proxies = ProxySelector.getDefault().select(uri);
131
     * @return a result of calling of <code>blockOfCode</code> and may throw an exception.
136
        assert proxies != null : "ProxySelector cannot return null for " + uri;
132
     * @throws Exception 
137
        assert ! proxies.isEmpty() : "ProxySelector cannot return empty list for " + uri;
133
     * @see #isAuthenticationDialogSuppressed
138
        Proxy p = proxies.get(0);
134
     * @since 8.17
139
        if (Proxy.Type.DIRECT == p.type()) {
135
     */
140
            // return null for DIRECT proxy
136
    public static <R> R suppressAuthenticationDialog(Callable<R> blockOfCode) throws Exception {
141
            return null;
137
        try {
142
        } else {
138
            authenticationDialogSuppressed.set(Boolean.TRUE);
143
            if (p.address() instanceof InetSocketAddress) {
139
            return blockOfCode.call();
144
                // check is
140
        } finally {
145
                //assert ! ((InetSocketAddress) p.address()).isUnresolved() : p.address() + " must be resolved address.";
141
            authenticationDialogSuppressed.remove();
146
                return (InetSocketAddress) p.address();
147
            } else {
148
                LOGGER.log(Level.INFO, p.address() + " is not instanceof InetSocketAddress but " + p.address().getClass());
149
                return null;
150
            }
151
        }
142
        }
152
    }
143
    }
144
145
    /** A utility method for implementations of <a href="http://download.oracle.com/javase/6/docs/api/java/net/Authenticator.html">Authenticator</a>
146
     * to suppress asking users a authentication question while running code posted
147
     * in {@link #authenticationDialogSuppressed}.
148
     * 
149
     * @return true while running code posted in {@link #authenticationDialogSuppressed} method.
150
     * @since 8.17
151
     * @see #authenticationDialogSuppressed
152
     */
153
    public static boolean isAuthenticationDialogSuppressed() {
154
        return Boolean.TRUE.equals(authenticationDialogSuppressed.get());
155
    }
156
157
    /** A SPI abstract class {@link NetworkSettings.ProxyCredentialsProvider} allows
158
     * NetBeans Platform users to provide own proxy and network credentials separately.
159
     * 
160
     * @see <a href="http://wiki.netbeans.org/Authenticator">http://wiki.netbeans.org/Authenticator</a>
161
     * @author Jiri Rechtacek, Ondrej Vrabec
162
     * @since 8.17
163
     */
164
    public static abstract class ProxyCredentialsProvider {
165
166
        /** Returns the <code>username</code> for Proxy Authentication.
167
         * Returns <code>null</code> if no authentication required.
168
         * 
169
         * @param u The URI that a connection is required to
170
         * @return username for Proxy Authentication
171
         */
172
        protected abstract String getProxyUserName(URI u);
173
174
        /** Returns the <code>password</code> for Proxy Authentication.
175
         * Returns <code>null</code> if no authentication required.
176
         * 
177
         * @param u The URI that a connection is required to
178
         * @return password for Proxy Authentication
179
         */
180
        protected abstract char[] getProxyPassword(URI u);
181
182
        /** Returns <code>true</code> if Proxy Authentication is required.
183
         * 
184
         * @param u The URI that a connection is required to
185
         * @return <code>true</code> if authentication required.
186
         */
187
        protected abstract boolean isProxyAuthentication(URI u);
188
189
        /** Returns the <code>hostname</code> part of network proxy address 
190
         * based on given URI to access the resource at.
191
         * Returns <code>null</code> for direct connection.
192
         * 
193
         * @param u The URI that a connection is required to
194
         * @return the hostname part of the Proxy address or <code>null</code>
195
         */
196
        protected abstract String getProxyHost(URI u);
197
198
        /** Returns the <code>port</code> part of network proxy address 
199
         * based on given URI to access the resource at.
200
         * Returns <code>null</code> for direct connection.
201
         * 
202
         * @param u The URI that a connection is required to
203
         * @return the port part of the Proxy address or <code>null</code>
204
         */
205
        protected abstract String getProxyPort(URI u);
206
    }
153
}
207
}
(-)a/openide.util/test/unit/src/org/openide/util/NetworkSettingsTest.java (-7 / +159 lines)
Lines 39-63 Link Here
39
 *
39
 *
40
 * Portions Copyrighted 2011 Sun Microsystems, Inc.
40
 * Portions Copyrighted 2011 Sun Microsystems, Inc.
41
 */
41
 */
42
43
package org.openide.util;
42
package org.openide.util;
44
43
44
import java.io.IOException;
45
import java.net.Authenticator;
46
import java.net.Inet4Address;
45
import java.net.InetSocketAddress;
47
import java.net.InetSocketAddress;
46
import java.net.URISyntaxException;
48
import java.net.PasswordAuthentication;
47
import java.util.Collections;
48
import java.io.IOException;
49
import java.net.Proxy;
49
import java.net.Proxy;
50
import java.net.ProxySelector;
50
import java.net.ProxySelector;
51
import java.net.SocketAddress;
51
import java.net.SocketAddress;
52
import java.net.URI;
52
import java.net.URI;
53
import java.net.URISyntaxException;
54
import java.net.UnknownHostException;
55
import java.util.Collections;
53
import java.util.List;
56
import java.util.List;
57
import java.util.concurrent.Callable;
58
import java.util.concurrent.CountDownLatch;
54
import junit.framework.TestCase;
59
import junit.framework.TestCase;
60
import org.netbeans.junit.MockServices;
61
import org.openide.util.NetworkSettings.ProxyCredentialsProvider;
55
62
56
/**
63
/**
57
 *
64
 *
58
 * @author Jiri Rechtacek
65
 * @author Jiri Rechtacek, Ondrej Vrabec
59
 */
66
 */
60
public class NetworkSettingsTest extends TestCase {
67
public class NetworkSettingsTest extends TestCase {
68
61
    private static ProxySelector defaultPS;
69
    private static ProxySelector defaultPS;
62
70
63
    public NetworkSettingsTest(String name) {
71
    public NetworkSettingsTest(String name) {
Lines 91-96 Link Here
91
            }
99
            }
92
        };
100
        };
93
        ProxySelector.setDefault(ps);
101
        ProxySelector.setDefault(ps);
102
        MockServices.setServices(MyProxyCredentialsProvider.class);
94
    }
103
    }
95
104
96
    @Override
105
    @Override
Lines 105-111 Link Here
105
    }
114
    }
106
115
107
    public void testGetProxyForRemote() throws URISyntaxException {
116
    public void testGetProxyForRemote() throws URISyntaxException {
108
        URI u = new URI("http://remove.org");
117
        URI u = new URI("http://remote.org");
109
        assertEquals("Check NetworkSettings.getProxyHost() for " + u, "corpcache.cache", NetworkSettings.getProxyHost(u));
118
        assertEquals("Check NetworkSettings.getProxyHost() for " + u, "corpcache.cache", NetworkSettings.getProxyHost(u));
110
        assertEquals("Check NetworkSettings.getProxyPort() for " + u, "1234", NetworkSettings.getProxyPort(u));
119
        assertEquals("Check NetworkSettings.getProxyPort() for " + u, "1234", NetworkSettings.getProxyPort(u));
111
    }
120
    }
Lines 116-119 Link Here
116
        assertNull("NetworkSettings.getProxyPort() returns null for " + u, NetworkSettings.getProxyPort(u));
125
        assertNull("NetworkSettings.getProxyPort() returns null for " + u, NetworkSettings.getProxyPort(u));
117
    }
126
    }
118
127
119
}
128
    public void testIsAuthenticationDialogNotSuppressed() throws Exception {
129
        final boolean[] suppressed = new boolean[1];
130
        Authenticator.setDefault(new Authenticator() {
131
132
            @Override
133
            protected PasswordAuthentication getPasswordAuthentication() {
134
                suppressed[0] = NetworkSettings.isAuthenticationDialogSuppressed();
135
                return super.getPasswordAuthentication();
136
            }
137
        });
138
139
        Authenticator.requestPasswordAuthentication("localhost", Inet4Address.getLocalHost(), 1234, "http", null, "http");
140
        assertFalse(suppressed[0]);
141
    }
142
143
    public void testIsAuthenticationDialogSuppressed() throws Exception {
144
        final boolean[] suppressed = new boolean[1];
145
        Authenticator.setDefault(new Authenticator() {
146
147
            @Override
148
            protected PasswordAuthentication getPasswordAuthentication() {
149
                suppressed[0] = NetworkSettings.isAuthenticationDialogSuppressed();
150
                return super.getPasswordAuthentication();
151
            }
152
        });
153
154
        Callable<Void> callable = new Callable<Void>() {
155
156
            @Override
157
            public Void call() throws Exception {
158
                Authenticator.requestPasswordAuthentication("localhost", Inet4Address.getLocalHost(), 1234, "http", null, "http");
159
                return null;
160
            }
161
        };
162
        NetworkSettings.suppressAuthenticationDialog(callable);
163
        assertTrue(suppressed[0]);
164
    }
165
166
    @SuppressWarnings("SleepWhileInLoop")
167
    public void testIsAuthenticationDialogSuppressedExclusive() throws InterruptedException, UnknownHostException {
168
        final boolean[] suppressed = new boolean[1];
169
        Authenticator.setDefault(new Authenticator() {
170
171
            @Override
172
            protected PasswordAuthentication getPasswordAuthentication() {
173
                suppressed[0] = NetworkSettings.isAuthenticationDialogSuppressed();
174
                return super.getPasswordAuthentication();
175
            }
176
        });
177
178
        final CountDownLatch doneSignal1 = new CountDownLatch(1);
179
        final CountDownLatch doneSignal2 = new CountDownLatch(1);
180
        Thread t = new Thread(new Runnable() {
181
            @Override
182
            public void run() {
183
                Callable<Void> callable = new Callable<Void>() {
184
185
                    @Override
186
                    public Void call() throws Exception {
187
                        doneSignal1.countDown();
188
                        doneSignal2.await();
189
                        Authenticator.requestPasswordAuthentication("localhost", Inet4Address.getLocalHost(), 1234, "http", null, "http");
190
                        return null;
191
                    }
192
                };
193
                try {
194
                    NetworkSettings.suppressAuthenticationDialog(callable);
195
                } catch (Exception ex) {
196
                    Exceptions.printStackTrace(ex);
197
                }
198
            }
199
        });
200
        t.start();
201
        doneSignal1.await();
202
        Authenticator.requestPasswordAuthentication("localhost", Inet4Address.getLocalHost(), 1234, "http", null, "http");
203
        assertFalse(suppressed[0]);
204
        doneSignal2.countDown();
205
        t.join();
206
        assertTrue(suppressed[0]);
207
    }
208
    
209
    public void testNoProxyCredentialsProviderFound() throws URISyntaxException {
210
        MockServices.setServices();
211
        URI localURI = new URI("http://localhost");
212
        assertNull("NetworkSettings.getProxyHost() returns null for " + localURI, NetworkSettings.getProxyHost(localURI));
213
        assertNull("NetworkSettings.getProxyPort() returns null for " + localURI, NetworkSettings.getProxyPort(localURI));
214
        URI remoteURI = new URI("http://remove.org");
215
        assertNull("NetworkSettings.getProxyHost() returns null for " + remoteURI, NetworkSettings.getProxyHost(localURI));
216
        assertNull("NetworkSettings.getProxyHost() returns null for " + remoteURI, NetworkSettings.getProxyHost(localURI));
217
        URI intraURI = new URI("http://inner.private.web");
218
        assertNull("NetworkSettings.getProxyHost() returns null for " + intraURI, NetworkSettings.getProxyHost(intraURI));
219
        assertNull("NetworkSettings.getProxyPort() returns null for " + intraURI, NetworkSettings.getProxyPort(intraURI));
220
    }
221
    
222
    public static class MyProxyCredentialsProvider extends ProxyCredentialsProvider {
223
224
        @Override
225
        protected String getProxyUserName(URI u) {
226
            throw new UnsupportedOperationException("Not supported yet.");
227
        }
228
229
        @Override
230
        protected char[] getProxyPassword(URI u) {
231
            throw new UnsupportedOperationException("Not supported yet.");
232
        }
233
234
        @Override
235
        protected boolean isProxyAuthentication(URI u) {
236
            return false;
237
        }
238
239
        @Override
240
        protected String getProxyHost(URI u) {
241
            InetSocketAddress sa = analyzeProxy(u);
242
            return sa == null ? null : sa.getHostName();
243
        }
244
245
        @Override
246
        protected String getProxyPort(URI u) {
247
            InetSocketAddress sa = analyzeProxy(u);
248
            return sa == null ? null : Integer.toString(sa.getPort());
249
        }
250
    }
251
252
    private static InetSocketAddress analyzeProxy(URI uri) {
253
        Parameters.notNull("uri", uri);
254
        List<Proxy> proxies = ProxySelector.getDefault().select(uri);
255
        assert proxies != null : "ProxySelector cannot return null for " + uri;
256
        assert !proxies.isEmpty() : "ProxySelector cannot return empty list for " + uri;
257
        Proxy p = proxies.get(0);
258
        if (Proxy.Type.DIRECT == p.type()) {
259
            // return null for DIRECT proxy
260
            return null;
261
        } else {
262
            if (p.address() instanceof InetSocketAddress) {
263
                // check is
264
                //assert ! ((InetSocketAddress) p.address()).isUnresolved() : p.address() + " must be resolved address.";
265
                return (InetSocketAddress) p.address();
266
            } else {
267
                return null;
268
            }
269
        }
270
    }
271
}

Return to bug 201662