Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * #%L
   * JBossOSGi Framework
   * %%
   * Copyright (C) 2010 - 2012 JBoss by Red Hat
   * %%
   * This program is free software: you can redistribute it and/or modify
   * it under the terms of the GNU Lesser General Public License as
   * published by the Free Software Foundation, either version 2.1 of the
  * License, or (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Lesser Public License for more details.
  *
  * You should have received a copy of the GNU General Lesser Public
  * License along with this program.  If not, see
  * <http://www.gnu.org/licenses/lgpl-2.1.html>.
  * #L%
  */
 package org.jboss.osgi.framework.internal;
 
 import static org.jboss.osgi.framework.FrameworkLogger.LOGGER;
 import static org.jboss.osgi.framework.FrameworkMessages.MESSAGES;
 
 import java.net.Proxy;
 import java.net.URL;
 import java.util.List;
 
This plugin provides OSGi URL handler support as per the specification. The interface is through the java.net.URL class and the OSGi Service Registry.

Author(s):
David Bosschaert
Thomas.Diesler@jboss.com
Since:
10-Jan-2011
 
 final class URLHandlerSupportImpl implements URLHandlerSupport {
 
     private final BundleManagerPlugin bundleManager;
     private ServiceRegistration registration;
 
 
     static void initURLHandlerSupport() {
     	if ( == null) {
              = new OSGiStreamHandlerFactoryDelegate();
             AccessController.doPrivileged(new PrivilegedAction<Void>() {
                 @Override
                 public Void run() {
                     try {
                         URL.setURLStreamHandlerFactory();
                     } catch (Throwable th) {
                         // [MODULES-44] Provide an API that allows adding of URLStreamHandlerFactories
                         .debugf("Unable to set the URLStreamHandlerFactory");
                     }
                     return null;
                 }
             });
     	}
     	if ( == null) {
              = new OSGiContentHandlerFactoryDelegate();
             AccessController.doPrivileged(new PrivilegedAction<Void>() {
                 @Override
                 public Void run() {
                     try {
                         URLConnection.setContentHandlerFactory();
                     } catch (Throwable th) {
                         // [MODULES-44] Provide an API that allows adding of URLStreamHandlerFactories
                         .debugf("Unable to set the ContentHandlerFactory");
                     }
                     return null;
                 }
             });
    	}
    }
    public URLHandlerSupportImpl(BundleManagerPlugin bundleManager) {
        this. = bundleManager;
    }
    @Override
    public void start(BundleContext systemContext) {
        OSGiStreamHandlerFactoryService.setDelegateFactory(this);
        setupStreamHandlerTracker(systemContext);
        setupContentHandlerTracker(systemContext);
    }
    @Override
    public void stop() {
        .unregister();
        OSGiStreamHandlerFactoryService.setDelegateFactory(null);
    }
    private void registerStreamHandlerService() {
        // Register the 'bundle' protocol
        Dictionary<StringObjectprops = new Hashtable<StringObject>();
        BundleContext systemContext = .getSystemBundle().getBundleContext();
         = systemContext.registerService(URLStreamHandlerService.class.getName(), serviceprops);
    }
    private void setupContentHandlerTracker(BundleContext systemContext) {
         = new ServiceTracker(systemContextContentHandler.class.getName(), null) {
            @Override
            public Object addingService(ServiceReference reference) {
                Object service = super.addingService(reference);
                String[] mimeTypes = parseServiceProperty(reference.getProperty(.));
                if (mimeTypes != null && service instanceof ContentHandler) {
                    .debugf("Adding content handler '%s' for: %s"service, Arrays.asList(mimeTypes));
                    for (String mimeType : mimeTypes) {
                        .addHandler(mimeTypereference);
                    }
                }
                return service;
            }
            @Override
            public void modifiedService(ServiceReference referenceObject service) {
                removedService(referenceservice);
                addingService(reference);
            }
            @Override
            public void removedService(ServiceReference referenceObject service) {
                super.removedService(referenceservice);
                .removeHandler(reference);
            }
        };
        .open();
    }
    private void setupStreamHandlerTracker(BundleContext systemContext) {
         = new ServiceTracker(systemContextURLStreamHandlerService.class.getName(), null) {
            @Override
            public Object addingService(ServiceReference reference) {
                Object service = super.addingService(reference);
                String[] protocols = parseServiceProperty(reference.getProperty(.));
                if (protocols != null && service instanceof URLStreamHandlerService) {
                    .tracef("Adding stream handler '%s' for: %s"service, Arrays.asList(protocols));
                    for (String protocol : protocols) {
                        .addHandler(protocolreference);
                    }
                }
                return service;
            }
            @Override
            public void modifiedService(ServiceReference referenceObject service) {
                removedService(referenceservice);
                addingService(reference);
            }
            @Override
            public void removedService(ServiceReference referenceObject service) {
                super.removedService(referenceservice);
                .removeHandler(reference);
            }
        };
        .open();
    }

    
Creates a new URLStreamHandler instance with the specified protocol.

    @Override
    public URLStreamHandler createURLStreamHandler(String protocol) {
        List<ServiceReferencerefList = .getStreamHandlers(protocol);
        if (refList == null || refList.isEmpty())
            return null;
        return new URLStreamHandlerProxy(protocolrefList);
    }

    
Creates a new ContentHandler to read an object from a URLStreamHandler.

    @Override
    public ContentHandler createContentHandler(String mimetype) {
        List<ServiceReferencerefList = .getContentHandlers(mimetype);
        if (refList == null || refList.isEmpty())
            return null;
        ServiceReference ref = refList.get(0);
        Object service = ref.getBundle().getBundleContext().getService(ref);
        if (service instanceof ContentHandler)
            return (ContentHandlerservice;
        return null;
    }

    
Parses a service registration property with a value which can be of type String or String [].

Parameters:
prop The property value.
Returns:
All the values found in a String [] or null of the property doesn't comply.
    private String[] parseServiceProperty(Object prop) {
        if (prop == null)
            return null;
        if (prop instanceof String)
            return new String[] { (Stringprop };
        if (prop instanceof String[])
            return (String[]) prop;
        return null;
    }
    private static final class URLStreamHandlerProxy extends URLStreamHandler implements URLStreamHandlerSetter {
        // This list is maintained in the ServiceTracker that tracks the URLStreamHandlerService
        // This proxy should always use to top element (if it contains any elements).
        private final List<ServiceReferenceserviceReferences;
        private final String protocol;
        public URLStreamHandlerProxy(String protocolList<ServiceReferencerefList) {
            this. = protocol;
            this. = refList;
        }
        @Override
        public void setURL(URL uString protocolString hostint portString authorityString userInfoString pathString queryString ref) {
            // Made public to implement URLStreamHandlerSetter
            super.setURL(uprotocolhostportauthorityuserInfopathqueryref);
        }
        @Override
        @SuppressWarnings("deprecation")
        public void setURL(URL uString protocolString hostint portString fileString ref) {
            // Made public to implement URLStreamHandlerSetter
            super.setURL(uprotocolhostportfileref);
        }
        @Override
        protected void parseURL(URL uString specint startint limit) {
            getHandlerService().parseURL(thisuspecstartlimit);
        }
        @Override
        protected URLConnection openConnection(URL uthrows IOException {
            return getHandlerService().openConnection(u);
        }
        @Override
        protected String toExternalForm(URL u) {
            return getHandlerService().toExternalForm(u);
        }
        @Override
        protected URLConnection openConnection(URL uProxy pthrows IOException {
            URLStreamHandlerService handler = getHandlerService();
            try {
                Method method = handler.getClass().getDeclaredMethod("openConnection"URL.classProxy.class);
                return (URLConnectionmethod.invoke(handlerup);
            } catch (Throwable th) {
                if (th instanceof InvocationTargetException)
                    th = ((InvocationTargetException)th).getTargetException();
                throw .cannotOpenConnectionOnHandler(thhandler);
            }
        }
        @Override
        protected int getDefaultPort() {
            return getHandlerService().getDefaultPort();
        }
        @Override
        protected boolean equals(URL u1URL u2) {
            return getHandlerService().equals(u1u2);
        }
        @Override
        protected int hashCode(URL u) {
            return getHandlerService().hashCode(u);
        }
        @Override
        protected boolean sameFile(URL u1URL u2) {
            return getHandlerService().sameFile(u1u2);
        }
        @Override
        protected synchronized InetAddress getHostAddress(URL u) {
            return getHandlerService().getHostAddress(u);
        }
        @Override
        protected boolean hostsEqual(URL u1URL u2) {
            return getHandlerService().hostsEqual(u1u2);
        }
        private URLStreamHandlerService getHandlerService() {
            if (.isEmpty())
                throw .illegalStateNoStreamHandlersForProtocol();
            ServiceReference ref = .get(0);
            Object service = ref.getBundle().getBundleContext().getService(ref);
            return (URLStreamHandlerServiceservice;
        }
    }
New to GrepCode? Check out our FAQ X