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

(-)a/core.startup/src/org/netbeans/core/startup/NbURLStreamHandlerFactory.java (-36 / +5 lines)
Lines 47-93 Link Here
47
import java.net.URL;
47
import java.net.URL;
48
import java.net.URLConnection;
48
import java.net.URLConnection;
49
import java.net.URLStreamHandler;
49
import java.net.URLStreamHandler;
50
import java.net.URLStreamHandlerFactory;
51
import java.util.Iterator;
50
import java.util.Iterator;
52
import java.util.logging.Level;
51
import java.util.logging.Level;
53
import java.util.logging.Logger;
52
import java.util.logging.Logger;
54
import org.openide.filesystems.FileUtil;
55
import org.openide.util.Lookup;
53
import org.openide.util.Lookup;
56
import org.openide.util.NbBundle;
54
import org.openide.util.NbBundle;
55
import org.openide.util.URLStreamHandlerRegistration;
57
56
58
/**
59
 * Proxying stream handler factory. Currently searches Lookup for registered
60
 * factories and delegates to them. But #20838 suggests using JNDI instead,
61
 * in which case registering them via Lookup would be deprecated.
62
 * @author Jesse Glick
63
 */
64
@org.openide.util.lookup.ServiceProvider(service=java.net.URLStreamHandlerFactory.class)
65
public final class NbURLStreamHandlerFactory implements URLStreamHandlerFactory {
66
    
67
    /** public for lookup */
68
    public NbURLStreamHandlerFactory() {}
69
    
70
    public URLStreamHandler createURLStreamHandler(String protocol) {
71
        if (protocol.equals("nbfs")) { // NOI18N
72
             return FileUtil.nbfsURLStreamHandler();
73
        }
74
        
75
        if (protocol.equals(NbResourceStreamHandler.PROTOCOL_SYSTEM_RESOURCE) ||
76
                   protocol.equals(NbResourceStreamHandler.PROTOCOL_LOCALIZED_SYSTEM_RESOURCE)) {
77
           return new NbResourceStreamHandler();
78
        }
79
        
80
        return null;
81
    }
82
    
83
    /** Stream handler for internal resource-based URLs.
57
    /** Stream handler for internal resource-based URLs.
84
     * Copied with modifications from org.openide.execution - that version is now
85
     * deprecated and handles only deprecated protocols.
86
     * @author Jesse Glick
58
     * @author Jesse Glick
87
     */
59
     */
88
    private static final class NbResourceStreamHandler extends URLStreamHandler {
60
    @URLStreamHandlerRegistration(protocol={NbResourceStreamHandler.PROTOCOL_SYSTEM_RESOURCE, NbResourceStreamHandler.PROTOCOL_LOCALIZED_SYSTEM_RESOURCE})
89
        
61
    public final class NbResourceStreamHandler extends URLStreamHandler {
90
        public NbResourceStreamHandler() {}
91
        
62
        
92
        public static final String PROTOCOL_SYSTEM_RESOURCE = "nbres"; // NOI18N
63
        public static final String PROTOCOL_SYSTEM_RESOURCE = "nbres"; // NOI18N
93
        public static final String PROTOCOL_LOCALIZED_SYSTEM_RESOURCE = "nbresloc"; // NOI18N
64
        public static final String PROTOCOL_LOCALIZED_SYSTEM_RESOURCE = "nbresloc"; // NOI18N
Lines 133-139 Link Here
133
                    if (resource.length() > 0 && resource.charAt(0) == '/') { // NOI18N
104
                    if (resource.length() > 0 && resource.charAt(0) == '/') { // NOI18N
134
                        resource = resource.substring(1);
105
                        resource = resource.substring(1);
135
                    } else {
106
                    } else {
136
                        Logger.getLogger(NbURLStreamHandlerFactory.class.getName()).log(Level.WARNING, "URL path should begin with a slash: " + url);
107
                        Logger.getLogger(NbResourceStreamHandler.class.getName()).log(Level.WARNING, "URL path should begin with a slash: " + url);
137
                    }
108
                    }
138
                    ClassLoader loader = Lookup.getDefault().lookup(ClassLoader.class);
109
                    ClassLoader loader = Lookup.getDefault().lookup(ClassLoader.class);
139
                    URL target;
110
                    URL target;
Lines 166-172 Link Here
166
                        target = t1;
137
                        target = t1;
167
                    }
138
                    }
168
                    if (target == null) {
139
                    if (target == null) {
169
                        throw new IOException(NbBundle.getMessage(NbURLStreamHandlerFactory.class, "EXC_nbres_cannot_connect", url));
140
                        throw new IOException(NbBundle.getMessage(NbResourceStreamHandler.class, "EXC_nbres_cannot_connect", url));
170
                    }
141
                    }
171
                    real = target.openConnection();
142
                    real = target.openConnection();
172
                    real.connect();
143
                    real.connect();
Lines 267-271 Link Here
267
        }
238
        }
268
        
239
        
269
    }
240
    }
270
    
271
}
(-)a/core.startup/src/org/netbeans/core/startup/layers/NbinstURLStreamHandlerFactory.java (-30 / +6 lines)
Lines 47-89 Link Here
47
import java.net.URL;
47
import java.net.URL;
48
import java.net.URLConnection;
48
import java.net.URLConnection;
49
import java.net.URLStreamHandler;
49
import java.net.URLStreamHandler;
50
import java.net.URLStreamHandlerFactory;
51
import java.net.UnknownServiceException;
50
import java.net.UnknownServiceException;
52
import org.openide.filesystems.FileObject;
51
import org.openide.filesystems.FileObject;
53
import org.openide.util.Exceptions;
52
import org.openide.util.Exceptions;
53
import org.openide.util.URLStreamHandlerRegistration;
54
54
55
/**
55
/**
56
 * StreamHandlerFactory for nbinst protocol
56
 * URLStreamHandler for nbinst protocol
57
 */
57
 */
58
@org.openide.util.lookup.ServiceProvider(service=java.net.URLStreamHandlerFactory.class)
58
@URLStreamHandlerRegistration(protocol=NbinstURLMapper.PROTOCOL)
59
public class NbinstURLStreamHandlerFactory implements URLStreamHandlerFactory {
59
public class NbinstURLStreamHandler extends URLStreamHandler {
60
60
61
    /**
61
    protected URLConnection openConnection(URL u) throws IOException {
62
     * Creates URLStreamHandler for nbinst protocol
62
        return new NbinstURLConnection(u);
63
     * @param protocol
64
     * @return NbinstURLStreamHandler if the protocol is nbinst otherwise null
65
     */
66
    public URLStreamHandler createURLStreamHandler(String protocol) {
67
        if (NbinstURLMapper.PROTOCOL.equals(protocol)) {
68
            return new NbinstURLStreamHandler ();
69
        }
70
        return null;
71
    }
72
73
    /**
74
     * URLStreamHandler for nbinst protocol
75
     */
76
    private static class NbinstURLStreamHandler extends URLStreamHandler {
77
78
        /**
79
         * Creates URLConnection for URL with nbinst protocol.
80
         * @param u URL for which the URLConnection should be created
81
         * @return URLConnection
82
         * @throws IOException
83
         */
84
        protected URLConnection openConnection(URL u) throws IOException {
85
            return new NbinstURLConnection (u);
86
        }
87
    }
63
    }
88
64
89
    /** URLConnection for URL with nbinst protocol.
65
    /** URLConnection for URL with nbinst protocol.
(-)a/core.startup/test/unit/src/org/netbeans/core/startup/layers/NbinstURLMapperTest.java (-1 lines)
Lines 77-83 Link Here
77
        
77
        
78
        MockServices.setServices(
78
        MockServices.setServices(
79
                TestInstalledFileLocator.class,
79
                TestInstalledFileLocator.class,
80
                NbinstURLStreamHandlerFactory.class,
81
                NbinstURLMapper.class);
80
                NbinstURLMapper.class);
82
81
83
        org.netbeans.core.startup.Main.initializeURLFactory ();
82
        org.netbeans.core.startup.Main.initializeURLFactory ();
(-)a/ide.ergonomics/src/org/netbeans/modules/ide/ergonomics/fod/FoDURLStreamHandlerFactory.java (-13 / +4 lines)
Lines 46-69 Link Here
46
import java.net.URL;
46
import java.net.URL;
47
import java.net.URLConnection;
47
import java.net.URLConnection;
48
import java.net.URLStreamHandler;
48
import java.net.URLStreamHandler;
49
import java.net.URLStreamHandlerFactory;
50
import org.openide.util.NbBundle;
49
import org.openide.util.NbBundle;
51
import org.openide.util.lookup.ServiceProvider;
50
import org.openide.util.URLStreamHandlerRegistration;
52
51
53
/**
52
/**
54
 *
53
 *
55
 * @author Jaroslav Tulach <jtulach@netbeans.org>
54
 * @author Jaroslav Tulach <jtulach@netbeans.org>
56
 */
55
 */
57
@ServiceProvider(service=URLStreamHandlerFactory.class, position=99999)
56
@URLStreamHandlerRegistration(protocol="ergoloc")
58
public class FoDURLStreamHandlerFactory implements URLStreamHandlerFactory {
57
public class FoDURLStreamHandler extends URLStreamHandler {
59
58
60
    public URLStreamHandler createURLStreamHandler(String protocol) {
61
        if (protocol.equals("ergoloc")) {
62
            return new FoDSH();
63
        }
64
        return null;
65
    }
66
    private static final class FoDSH extends URLStreamHandler {
67
        @Override
59
        @Override
68
        protected URLConnection openConnection(URL u) throws IOException {
60
        protected URLConnection openConnection(URL u) throws IOException {
69
            URL orig = new URL("nbresloc", u.getHost(), u.getPort(), u.getFile()); // NOI18N
61
            URL orig = new URL("nbresloc", u.getHost(), u.getPort(), u.getFile()); // NOI18N
Lines 79-85 Link Here
79
                throw new IOException();
71
                throw new IOException();
80
            }
72
            }
81
            String head = new String(arr, 0, len, "UTF-8"); // NOI18N
73
            String head = new String(arr, 0, len, "UTF-8"); // NOI18N
82
            String newHead = head.replaceFirst("<[bB][oO][dD][yY]>", NbBundle.getMessage(FoDSH.class, "MSG_NotEnabled")); // NOI18N
74
            String newHead = head.replaceFirst("<[bB][oO][dD][yY]>", NbBundle.getMessage(FoDURLStreamHandler.class, "MSG_NotEnabled")); // NOI18N
83
            ByteArrayInputStream headIS = new ByteArrayInputStream(newHead.getBytes("UTF-8")); // NOI18N
75
            ByteArrayInputStream headIS = new ByteArrayInputStream(newHead.getBytes("UTF-8")); // NOI18N
84
76
85
            final SequenceInputStream seq = new SequenceInputStream(headIS, is);
77
            final SequenceInputStream seq = new SequenceInputStream(headIS, is);
Lines 97-101 Link Here
97
            };
89
            };
98
        }
90
        }
99
91
100
    }
101
}
92
}
(-)a/javahelp/src/org/netbeans/modules/javahelp/NbDocsStreamHandler.java (-12 / +3 lines)
Lines 50-71 Link Here
50
import org.openide.util.Exceptions;
50
import org.openide.util.Exceptions;
51
import org.openide.util.Lookup;
51
import org.openide.util.Lookup;
52
import org.openide.util.NbBundle;
52
import org.openide.util.NbBundle;
53
import org.openide.util.URLStreamHandlerRegistration;
53
54
54
/** Handler & connection cribbed from NbResourceStreamHandler.
55
/** Handler & connection cribbed from NbResourceStreamHandler.
55
 * @author Jesse Glick
56
 * @author Jesse Glick
56
 */
57
 */
57
final class NbDocsStreamHandler extends URLStreamHandler {
58
@URLStreamHandlerRegistration(protocol="nbdocs")
58
59
public final class NbDocsStreamHandler extends URLStreamHandler {
59
    @org.openide.util.lookup.ServiceProvider(service=java.net.URLStreamHandlerFactory.class)
60
    public static final class Factory implements URLStreamHandlerFactory {
61
        public URLStreamHandler createURLStreamHandler(String protocol) {
62
            if (protocol.equals("nbdocs")) { // NOI18N
63
                return new NbDocsStreamHandler();
64
            } else {
65
                return null;
66
            }
67
        }
68
    }
69
60
70
    /** Make a URLConnection for nbdocs: URLs.
61
    /** Make a URLConnection for nbdocs: URLs.
71
     * @param u the URL
62
     * @param u the URL
(-)a/o.n.bootstrap/src/org/netbeans/ProxyURLStreamHandlerFactory.java (-1 / +3 lines)
Lines 53-58 Link Here
53
import org.openide.util.Lookup;
53
import org.openide.util.Lookup;
54
import org.openide.util.LookupEvent;
54
import org.openide.util.LookupEvent;
55
import org.openide.util.LookupListener;
55
import org.openide.util.LookupListener;
56
import org.openide.util.URLStreamHandlerRegistration;
56
import org.openide.util.Utilities;
57
import org.openide.util.Utilities;
57
58
58
/**
59
/**
Lines 154-160 Link Here
154
    public void resultChanged(LookupEvent ev) {
155
    public void resultChanged(LookupEvent ev) {
155
        Collection<? extends URLStreamHandlerFactory> c = r.allInstances();
156
        Collection<? extends URLStreamHandlerFactory> c = r.allInstances();
156
        synchronized (this) {
157
        synchronized (this) {
157
            handlers = c.toArray(new URLStreamHandlerFactory[0]);
158
            handlers = c.toArray(new URLStreamHandlerFactory[c.size() + 1]);
159
            handlers[c.size()] = new URLStreamHandlerRegistration.ProxyURLStreamHandlerFactory();
158
        }
160
        }
159
    }
161
    }
160
    
162
    
(-)a/openide.filesystems/src/org/netbeans/modules/openide/filesystems/RecognizeInstanceFiles.java (+11 lines)
Lines 69-74 Link Here
69
    
69
    
70
    
70
    
71
    public Lookup create(String path) {
71
    public Lookup create(String path) {
72
        if (path.equals("URLStreamHandler/nbres/")) { // NOI18N
73
            // Need to avoid a stack overflow during initialization.
74
            ClassLoader l = Lookup.getDefault().lookup(ClassLoader.class);
75
            if (l == null) {
76
                l = Thread.currentThread().getContextClassLoader();
77
                if (l == null) {
78
                    l = RecognizeInstanceFiles.class.getClassLoader();
79
                }
80
            }
81
            return Lookups.metaInfServices(l, "META-INF/namedservices/URLStreamHandler/nbres/"); // NOI18N
82
        }
72
        return new OverFiles(path);
83
        return new OverFiles(path);
73
    }        
84
    }        
74
    
85
    
(-)a/openide.filesystems/src/org/openide/filesystems/FileURL.java (-14 / +10 lines)
Lines 54-59 Link Here
54
import java.net.URLStreamHandler;
54
import java.net.URLStreamHandler;
55
import java.net.UnknownServiceException;
55
import java.net.UnknownServiceException;
56
import java.security.Permission;
56
import java.security.Permission;
57
import org.openide.util.URLStreamHandlerRegistration;
57
58
58
/** Special URL connection directly accessing an internal file object.
59
/** Special URL connection directly accessing an internal file object.
59
*
60
*
Lines 65-84 Link Here
65
66
66
    /** Default implemenatation of handler for this type of URL.
67
    /** Default implemenatation of handler for this type of URL.
67
     */
68
     */
68
    static URLStreamHandler HANDLER = new URLStreamHandler() {
69
    @URLStreamHandlerRegistration(protocol=PROTOCOL)
69
            /**
70
    public static class Handler extends URLStreamHandler {
70
            * @param u - URL to open connection to.
71
        public URLConnection openConnection(URL u) throws IOException {
71
            * @return new URLConnection.
72
            return new FileURL(u);
72
            */
73
        }
73
            public URLConnection openConnection(URL u)
74
        protected @Override synchronized InetAddress getHostAddress(URL u) {
74
            throws IOException {
75
            return null;
75
                return new FileURL(u);
76
        }
76
            }
77
    }
77
78
            protected synchronized InetAddress getHostAddress(URL u) {
79
                return null;
80
            }
81
        };
82
78
83
    /** 1 URLConnection == 1 InputSteam*/
79
    /** 1 URLConnection == 1 InputSteam*/
84
    InputStream iStream = null;
80
    InputStream iStream = null;
(-)a/openide.filesystems/src/org/openide/filesystems/FileUtil.java (-8 / +3 lines)
Lines 1492-1507 Link Here
1492
    }
1492
    }
1493
1493
1494
    /**
1494
    /**
1495
     * Construct a stream handler that handles the <code>nbfs</code> URL protocol
1495
     * @deprecated No longer used.
1496
     * used for accessing file objects directly.
1497
     * This method is not intended for module use; only the core
1498
     * should need to call it.
1499
     * Modules probably need only use {@link URLMapper} to create and decode such
1500
     * URLs.
1501
     * @since 3.17
1502
     */
1496
     */
1497
    @Deprecated
1503
    public static URLStreamHandler nbfsURLStreamHandler() {
1498
    public static URLStreamHandler nbfsURLStreamHandler() {
1504
        return FileURL.HANDLER;
1499
        return new FileURL.Handler();
1505
    }
1500
    }
1506
1501
1507
    /** Recursively checks whether the file is underneath the folder. It checks whether
1502
    /** Recursively checks whether the file is underneath the folder. It checks whether
(-)a/openide.filesystems/src/org/openide/filesystems/NbfsUtil.java (-1 / +1 lines)
Lines 80-86 Link Here
80
                new PrivilegedExceptionAction<URL>() {
80
                new PrivilegedExceptionAction<URL>() {
81
                    public URL run() throws Exception {
81
                    public URL run() throws Exception {
82
                        // #30397: the fsPart name cannot be null
82
                        // #30397: the fsPart name cannot be null
83
                        return new URL(FileURL.PROTOCOL, host, -1, file, FileURL.HANDLER); // NOI18N
83
                        return new URL(FileURL.PROTOCOL, host, -1, file, new FileURL.Handler());
84
                    }
84
                    }
85
                }
85
                }
86
            );
86
            );
(-)a/openide.util/src/org/netbeans/modules/openide/util/ServiceProviderProcessor.java (-8 / +31 lines)
Lines 48-53 Link Here
48
import java.io.OutputStreamWriter;
48
import java.io.OutputStreamWriter;
49
import java.io.PrintWriter;
49
import java.io.PrintWriter;
50
import java.lang.annotation.Annotation;
50
import java.lang.annotation.Annotation;
51
import java.net.URLStreamHandler;
51
import java.util.ArrayList;
52
import java.util.ArrayList;
52
import java.util.Collection;
53
import java.util.Collection;
53
import java.util.Collections;
54
import java.util.Collections;
Lines 75-87 Link Here
75
import javax.tools.Diagnostic.Kind;
76
import javax.tools.Diagnostic.Kind;
76
import javax.tools.FileObject;
77
import javax.tools.FileObject;
77
import javax.tools.StandardLocation;
78
import javax.tools.StandardLocation;
79
import org.openide.util.URLStreamHandlerRegistration;
78
import org.openide.util.lookup.ServiceProvider;
80
import org.openide.util.lookup.ServiceProvider;
79
import org.openide.util.lookup.ServiceProviders;
81
import org.openide.util.lookup.ServiceProviders;
80
82
81
@SupportedSourceVersion(SourceVersion.RELEASE_6)
83
@SupportedSourceVersion(SourceVersion.RELEASE_6)
82
@SupportedAnnotationTypes({"org.openide.util.lookup.ServiceProvider", "org.openide.util.lookup.ServiceProviders"})
84
@SupportedAnnotationTypes({
85
    "org.openide.util.lookup.ServiceProvider",
86
    "org.openide.util.lookup.ServiceProviders",
87
    "org.openide.util.URLStreamHandlerRegistration"
88
})
83
public class ServiceProviderProcessor extends AbstractProcessor {
89
public class ServiceProviderProcessor extends AbstractProcessor {
84
90
91
    public static final String URL_STREAM_HANDLER_REGISTRATION_PREFIX = "URLStreamHandler/"; // NOI18N
92
85
    /** public for ServiceLoader */
93
    /** public for ServiceLoader */
86
    public ServiceProviderProcessor() {}
94
    public ServiceProviderProcessor() {}
87
95
Lines 115-133 Link Here
115
                    register(clazz, sp);
123
                    register(clazz, sp);
116
                }
124
                }
117
            }
125
            }
126
            for (Element el : roundEnv.getElementsAnnotatedWith(URLStreamHandlerRegistration.class)) {
127
                TypeElement clazz = (TypeElement) el;
128
                if (!verifyServiceProviderSignature(clazz)) {
129
                    continue;
130
                }
131
                URLStreamHandlerRegistration r = clazz.getAnnotation(URLStreamHandlerRegistration.class);
132
                TypeMirror type = processingEnv.getTypeUtils().getDeclaredType(
133
                        processingEnv.getElementUtils().getTypeElement(URLStreamHandler.class.getName()));
134
                for (String protocol : r.protocol()) {
135
                    register(clazz, type, URL_STREAM_HANDLER_REGISTRATION_PREFIX + protocol, r.position(), new String[0]);
136
                }
137
            }
118
            return true;
138
            return true;
119
        }
139
        }
120
    }
140
    }
121
141
122
    private void register(TypeElement clazz, ServiceProvider svc) {
142
    private void register(TypeElement clazz, ServiceProvider svc) {
123
        TypeMirror type;
124
        try {
143
        try {
125
            svc.service();
144
            svc.service();
126
            assert false;
145
            assert false;
127
            return;
146
            return;
128
        } catch (MirroredTypeException e) {
147
        } catch (MirroredTypeException e) {
129
            type = e.getTypeMirror();
148
            register(clazz, e.getTypeMirror(), svc.path(), svc.position(), svc.supersedes());
130
        }
149
        }
150
    }
151
152
    private void register(TypeElement clazz, TypeMirror type, String path, int position, String[] supersedes) {
131
        String impl = processingEnv.getElementUtils().getBinaryName(clazz).toString();
153
        String impl = processingEnv.getElementUtils().getBinaryName(clazz).toString();
132
        String xface = processingEnv.getElementUtils().getBinaryName((TypeElement) processingEnv.getTypeUtils().asElement(type)).toString();
154
        String xface = processingEnv.getElementUtils().getBinaryName((TypeElement) processingEnv.getTypeUtils().asElement(type)).toString();
133
        if (!processingEnv.getTypeUtils().isAssignable(clazz.asType(), type)) {
155
        if (!processingEnv.getTypeUtils().isAssignable(clazz.asType(), type)) {
Lines 136-143 Link Here
136
                    clazz, ann, findAnnotationValue(ann, "service"));
158
                    clazz, ann, findAnnotationValue(ann, "service"));
137
            return;
159
            return;
138
        }
160
        }
139
        processingEnv.getMessager().printMessage(Kind.NOTE, impl + " to be registered as a " + xface);
161
        processingEnv.getMessager().printMessage(Kind.NOTE,
140
        String rsrc = (svc.path().length() > 0 ? "META-INF/namedservices/" + svc.path() + "/" : "META-INF/services/") + xface;
162
                impl + " to be registered as a " + xface + (path.length() > 0 ? " under " + path : ""));
163
        String rsrc = (path.length() > 0 ? "META-INF/namedservices/" + path + "/" : "META-INF/services/") + xface;
141
        {
164
        {
142
            List<Element> origEls = originatingElements.get(rsrc);
165
            List<Element> origEls = originatingElements.get(rsrc);
143
            if (origEls == null) {
166
            if (origEls == null) {
Lines 188-197 Link Here
188
            }
211
            }
189
        }
212
        }
190
        lines.add(impl);
213
        lines.add(impl);
191
        if (svc.position() != Integer.MAX_VALUE) {
214
        if (position != Integer.MAX_VALUE) {
192
            lines.add("#position=" + svc.position());
215
            lines.add("#position=" + position);
193
        }
216
        }
194
        for (String exclude : svc.supersedes()) {
217
        for (String exclude : supersedes) {
195
            lines.add("#-" + exclude);
218
            lines.add("#-" + exclude);
196
        }
219
        }
197
    }
220
    }
(-)a/openide.util/src/org/openide/util/URLStreamHandlerRegistration.java (+114 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of either the GNU
7
 * General Public License Version 2 only ("GPL") or the Common
8
 * Development and Distribution License("CDDL") (collectively, the
9
 * "License"). You may not use this file except in compliance with the
10
 * License. You can obtain a copy of the License at
11
 * http://www.netbeans.org/cddl-gplv2.html
12
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
13
 * specific language governing permissions and limitations under the
14
 * License.  When distributing the software, include this License Header
15
 * Notice in each file and include the License file at
16
 * nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
17
 * particular file as subject to the "Classpath" exception as provided
18
 * by Sun in the GPL Version 2 section of the License file that
19
 * accompanied this code. If applicable, add the following below the
20
 * License Header, with the fields enclosed by brackets [] replaced by
21
 * your own identifying information:
22
 * "Portions Copyrighted [year] [name of copyright owner]"
23
 *
24
 * If you wish your version of this file to be governed by only the CDDL
25
 * or only the GPL Version 2, indicate your decision by adding
26
 * "[Contributor] elects to include this software in this distribution
27
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
28
 * single choice of license, a recipient has the option to distribute
29
 * your version of this file under either the CDDL, the GPL Version 2 or
30
 * to extend the choice of license to its licensees as provided above.
31
 * However, if you add GPL Version 2 code and therefore, elected the GPL
32
 * Version 2 license, then the option applies only if the new code is
33
 * made subject to such option by the copyright holder.
34
 *
35
 * Contributor(s):
36
 *
37
 * Portions Copyrighted 2009 Sun Microsystems, Inc.
38
 */
39
40
package org.openide.util;
41
42
import java.lang.annotation.ElementType;
43
import java.lang.annotation.Retention;
44
import java.lang.annotation.RetentionPolicy;
45
import java.lang.annotation.Target;
46
import java.net.URL;
47
import java.net.URLStreamHandler;
48
import java.net.URLStreamHandlerFactory;
49
import java.util.Collection;
50
import java.util.HashMap;
51
import java.util.Map;
52
import org.netbeans.modules.openide.util.ServiceProviderProcessor;
53
import org.openide.util.lookup.Lookups;
54
55
/**
56
 * Replacement for {@link URLStreamHandlerFactory} within the NetBeans platform.
57
 * (The JVM only permits one factory, whereas various independent modules may wish to register handlers.)
58
 * May be placed on a {@link URLStreamHandler} implementation to register it.
59
 * @since XXX
60
 */
61
@Retention(RetentionPolicy.SOURCE)
62
@Target(ElementType.TYPE)
63
public @interface URLStreamHandlerRegistration {
64
65
    /**
66
     * URL protocol(s) which are handled.
67
     * {@link URLStreamHandler#openConnection} will be called with a matching {@link URL#getProtocol}.
68
     */
69
    String[] protocol();
70
71
    /**
72
     * An optional position in which to register this handler relative to others.
73
     * The lowest-numbered handler is used in favor of any others, including unnumbered handlers.
74
     */
75
    int position() default Integer.MAX_VALUE;
76
77
    // cannot be a constant: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6857918
78
    /**
79
     * Factory which uses these registrations.
80
     * This factory is active whenever the module system is loaded.
81
     * You may also wish to call {@link URL#setURLStreamHandlerFactory}
82
     * from a unit test or otherwise without the module system active.
83
     */
84
    class ProxyURLStreamHandlerFactory implements URLStreamHandlerFactory {
85
86
        /** prevents GC only */
87
        private final Map<String,Lookup.Result<URLStreamHandler>> results = new HashMap<String,Lookup.Result<URLStreamHandler>>();
88
        private final Map<String,URLStreamHandler> handlers = new HashMap<String,URLStreamHandler>();
89
90
        /** Create a new proxy factory. */
91
        public ProxyURLStreamHandlerFactory() {}
92
93
        public synchronized URLStreamHandler createURLStreamHandler(final String protocol) {
94
            if (!results.containsKey(protocol)) {
95
                final Lookup.Result<URLStreamHandler> result = Lookups.forPath(
96
                        ServiceProviderProcessor.URL_STREAM_HANDLER_REGISTRATION_PREFIX + protocol).lookupResult(URLStreamHandler.class);
97
                LookupListener listener = new LookupListener() {
98
                    public void resultChanged(LookupEvent ev) {
99
                        synchronized (ProxyURLStreamHandlerFactory.this) {
100
                            Collection<? extends URLStreamHandler> instances = result.allInstances();
101
                            handlers.put(protocol, instances.isEmpty() ? null : instances.iterator().next());
102
                        }
103
                    }
104
                };
105
                result.addLookupListener(listener);
106
                listener.resultChanged(null);
107
                results.put(protocol, result);
108
            }
109
            return handlers.get(protocol);
110
        }
111
112
    }
113
114
}
(-)a/openide.util/test/unit/src/org/openide/util/URLStreamHandlerRegistrationTest.java (+69 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of either the GNU
7
 * General Public License Version 2 only ("GPL") or the Common
8
 * Development and Distribution License("CDDL") (collectively, the
9
 * "License"). You may not use this file except in compliance with the
10
 * License. You can obtain a copy of the License at
11
 * http://www.netbeans.org/cddl-gplv2.html
12
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
13
 * specific language governing permissions and limitations under the
14
 * License.  When distributing the software, include this License Header
15
 * Notice in each file and include the License file at
16
 * nbbuild/licenses/CDDL-GPL-2-CP.  Sun designates this
17
 * particular file as subject to the "Classpath" exception as provided
18
 * by Sun in the GPL Version 2 section of the License file that
19
 * accompanied this code. If applicable, add the following below the
20
 * License Header, with the fields enclosed by brackets [] replaced by
21
 * your own identifying information:
22
 * "Portions Copyrighted [year] [name of copyright owner]"
23
 *
24
 * If you wish your version of this file to be governed by only the CDDL
25
 * or only the GPL Version 2, indicate your decision by adding
26
 * "[Contributor] elects to include this software in this distribution
27
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
28
 * single choice of license, a recipient has the option to distribute
29
 * your version of this file under either the CDDL, the GPL Version 2 or
30
 * to extend the choice of license to its licensees as provided above.
31
 * However, if you add GPL Version 2 code and therefore, elected the GPL
32
 * Version 2 license, then the option applies only if the new code is
33
 * made subject to such option by the copyright holder.
34
 *
35
 * Contributor(s):
36
 *
37
 * Portions Copyrighted 2009 Sun Microsystems, Inc.
38
 */
39
40
package org.openide.util;
41
42
import java.io.IOException;
43
import java.net.URL;
44
import java.net.URLConnection;
45
import java.net.URLStreamHandler;
46
import java.net.URLStreamHandlerFactory;
47
import org.netbeans.junit.NbTestCase;
48
49
public class URLStreamHandlerRegistrationTest extends NbTestCase {
50
51
    public URLStreamHandlerRegistrationTest(String n) {
52
        super(n);
53
    }
54
55
    public void testURLStreamHandlerRegistration() throws Exception {
56
        URLStreamHandlerFactory factory = new URLStreamHandlerRegistration.ProxyURLStreamHandlerFactory();
57
        assertEquals(MyHandler.class, factory.createURLStreamHandler("stuff").getClass());
58
        assertEquals(MyHandler.class, factory.createURLStreamHandler("stuff").getClass());
59
        assertNull(factory.createURLStreamHandler("whatever"));
60
    }
61
62
    @URLStreamHandlerRegistration(protocol="stuff")
63
    public static class MyHandler extends URLStreamHandler {
64
        protected URLConnection openConnection(URL u) throws IOException {
65
            throw new IOException("unsupported");
66
        }
67
    }
68
69
}

Return to bug 20838