aboutsummaryrefslogtreecommitdiffstats
path: root/src/java/com/jogamp/common/net/GenericURLStreamHandlerFactory.java
blob: 79d7f71113443492ad8cfb0922971f38148a04e0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.jogamp.common.net;

import java.net.URL;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Map;

public class GenericURLStreamHandlerFactory implements URLStreamHandlerFactory {
    private static GenericURLStreamHandlerFactory factory = null;
    
    private final Map<String, URLStreamHandler> protocolHandlers;

    private GenericURLStreamHandlerFactory() {
        protocolHandlers = new HashMap<String, URLStreamHandler>();
    }
    
    /**
     * Sets the <code>handler</code> for <code>protocol</code>.
     * 
     * @return the previous set <code>handler</code>, or null if none was set.
     */
    public synchronized final URLStreamHandler setHandler(String protocol, URLStreamHandler handler) {
        return protocolHandlers.put(protocol, handler);
    }
    
    /**
     * Returns the <code>protocol</code> handler previously set via {@link #setHandler(String, URLStreamHandler)}, 
     * or null if none was set.
     */
    public synchronized final URLStreamHandler getHandler(String protocol) {
        return protocolHandlers.get(protocol);
    }
    
    @Override
    public synchronized final URLStreamHandler createURLStreamHandler(String protocol) {
        return getHandler(protocol);
    }

    /**
     * Returns the singleton instance of the registered GenericURLStreamHandlerFactory
     * or null if registration was not successful.
     * <p>
     * Registration is only performed once.
     * </p>
     */
    public synchronized static GenericURLStreamHandlerFactory register() {
        if(null == factory) {
            factory = AccessController.doPrivileged(new PrivilegedAction<GenericURLStreamHandlerFactory>() {
                public GenericURLStreamHandlerFactory run() {
                    boolean ok = false;
                    GenericURLStreamHandlerFactory f = new GenericURLStreamHandlerFactory();
                    try {
                        URL.setURLStreamHandlerFactory(f);
                        ok = true;
                    } catch (Throwable e) {
                        System.err.println("GenericURLStreamHandlerFactory: Setting URLStreamHandlerFactory failed: "+e.getMessage());
                    }
                    return ok ? f : null;
                } } );
        }
        return factory;
    }
}