Search in sources :

Example 11 with ServiceRegistration

use of org.osgi.framework.ServiceRegistration in project aries by apache.

the class ServiceRecipe method unregister.

public void unregister() {
    ServiceRegistration reg = registration.get();
    if (reg != null) {
        LOGGER.debug("Unregistering service {}", name);
        // set to null before actually unregistering the service
        if (listeners != null) {
            LOGGER.debug("Calling listeners for service unregistration");
            for (ServiceListener listener : listeners) {
                listener.unregister(service, registrationProperties);
            }
        }
        ServiceUtil.safeUnregisterService(reg);
        registration.compareAndSet(reg, null);
    }
}
Also used : ServiceListener(org.apache.aries.blueprint.utils.ServiceListener) ServiceRegistration(org.osgi.framework.ServiceRegistration)

Example 12 with ServiceRegistration

use of org.osgi.framework.ServiceRegistration in project aries by apache.

the class Activator method unregister.

private void unregister(ServiceReference reference, ConcurrentMap<Long, ServiceRegistration> mbeans) {
    Long id = (Long) reference.getProperty(Constants.SERVICE_ID);
    ServiceRegistration reg = mbeans.remove(id);
    if (reg != null)
        reg.unregister();
}
Also used : ServiceRegistration(org.osgi.framework.ServiceRegistration)

Example 13 with ServiceRegistration

use of org.osgi.framework.ServiceRegistration in project aries by apache.

the class ProviderBundleTrackerCustomizer method removedBundle.

@SuppressWarnings("unchecked")
public void removedBundle(Bundle bundle, BundleEvent event, Object registrations) {
    activator.unregisterProviderBundle(bundle);
    if (registrations == null)
        return;
    for (ServiceRegistration reg : (List<ServiceRegistration>) registrations) {
        reg.unregister();
        log(LogService.LOG_INFO, "Unregistered: " + reg);
    }
}
Also used : ArrayList(java.util.ArrayList) List(java.util.List) ServiceRegistration(org.osgi.framework.ServiceRegistration)

Example 14 with ServiceRegistration

use of org.osgi.framework.ServiceRegistration in project aries by apache.

the class ProviderBundleTrackerCustomizer method addingBundle.

public List<ServiceRegistration> addingBundle(final Bundle bundle, BundleEvent event) {
    log(LogService.LOG_DEBUG, "Bundle Considered for SPI providers: " + bundle.getSymbolicName());
    if (bundle.equals(spiBundle))
        // don't process the SPI bundle itself
        return null;
    List<String> providedServices = null;
    Map<String, Object> customAttributes = new HashMap<String, Object>();
    if (bundle.getHeaders().get(SpiFlyConstants.REQUIRE_CAPABILITY) != null) {
        try {
            providedServices = readServiceLoaderMediatorCapabilityMetadata(bundle, customAttributes);
        } catch (InvalidSyntaxException e) {
            log(LogService.LOG_ERROR, "Unable to read capabilities from bundle " + bundle, e);
        }
    }
    boolean fromSPIProviderHeader = false;
    String spiProviderHeader = getHeaderFromBundleOrFragment(bundle, SpiFlyConstants.SPI_PROVIDER_HEADER);
    if (providedServices == null && spiProviderHeader != null) {
        String header = spiProviderHeader.trim();
        if ("*".equals(header)) {
            providedServices = new ArrayList<String>();
        } else {
            providedServices = Arrays.asList(header.split(","));
        }
        fromSPIProviderHeader = true;
    }
    if (providedServices == null) {
        log(LogService.LOG_DEBUG, "No '" + SpiFlyConstants.SPI_PROVIDER_HEADER + "' Manifest header. Skipping bundle: " + bundle.getSymbolicName());
        return null;
    } else {
        log(LogService.LOG_INFO, "Examining bundle for SPI provider: " + bundle.getSymbolicName());
    }
    for (String svc : providedServices) {
        // Eagerly register any services that are explicitly listed, as they may not be found in META-INF/services
        activator.registerProviderBundle(svc, bundle, customAttributes);
    }
    List<URL> serviceFileURLs = new ArrayList<URL>();
    @SuppressWarnings("unchecked") Enumeration<URL> entries = bundle.findEntries(METAINF_SERVICES, "*", false);
    if (entries != null) {
        serviceFileURLs.addAll(Collections.list(entries));
    }
    Object bcp = bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH);
    if (bcp instanceof String) {
        for (String entry : ((String) bcp).split(",")) {
            entry = entry.trim();
            if (entry.equals("."))
                continue;
            URL url = bundle.getResource(entry);
            if (url != null) {
                serviceFileURLs.addAll(getMetaInfServiceURLsFromJar(url));
            }
        }
    }
    final List<ServiceRegistration> registrations = new ArrayList<ServiceRegistration>();
    for (URL serviceFileURL : serviceFileURLs) {
        log(LogService.LOG_INFO, "Found SPI resource: " + serviceFileURL);
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(serviceFileURL.openStream()));
            String className = null;
            while ((className = reader.readLine()) != null) {
                try {
                    className = className.trim();
                    if (className.length() == 0)
                        // empty line
                        continue;
                    if (className.startsWith("#"))
                        // a comment
                        continue;
                    String serviceFile = serviceFileURL.toExternalForm();
                    int idx = serviceFile.lastIndexOf('/');
                    String registrationClassName = className;
                    if (serviceFile.length() > idx) {
                        registrationClassName = serviceFile.substring(idx + 1);
                    }
                    if (providedServices.size() > 0 && !providedServices.contains(registrationClassName))
                        continue;
                    final Class<?> cls = bundle.loadClass(className);
                    log(LogService.LOG_INFO, "Loaded SPI provider: " + cls);
                    final Hashtable<String, Object> properties;
                    if (fromSPIProviderHeader)
                        properties = new Hashtable<String, Object>();
                    else
                        properties = findServiceRegistrationProperties(bundle.getHeaders(), registrationClassName, className);
                    if (properties != null) {
                        properties.put(SpiFlyConstants.SERVICELOADER_MEDIATOR_PROPERTY, spiBundle.getBundleId());
                        properties.put(SpiFlyConstants.PROVIDER_IMPLCLASS_PROPERTY, cls.getName());
                        ServiceRegistration reg = null;
                        SecurityManager sm = System.getSecurityManager();
                        if (sm != null) {
                            if (bundle.hasPermission(new ServicePermission(registrationClassName, ServicePermission.REGISTER))) {
                                reg = bundle.getBundleContext().registerService(registrationClassName, new ProviderServiceFactory(cls), properties);
                            } else {
                                log(LogService.LOG_INFO, "Bundle " + bundle + " does not have the permission to register services of type: " + registrationClassName);
                            }
                        } else {
                            reg = bundle.getBundleContext().registerService(registrationClassName, new ProviderServiceFactory(cls), properties);
                        }
                        if (reg != null) {
                            registrations.add(reg);
                            log(LogService.LOG_INFO, "Registered service: " + reg);
                        }
                    }
                    activator.registerProviderBundle(registrationClassName, bundle, customAttributes);
                    log(LogService.LOG_INFO, "Registered provider: " + registrationClassName + " in bundle " + bundle.getSymbolicName());
                } catch (Exception e) {
                    log(LogService.LOG_WARNING, "Could not load SPI implementation referred from " + serviceFileURL, e);
                }
            }
        } catch (IOException e) {
            log(LogService.LOG_WARNING, "Could not read SPI metadata from " + serviceFileURL, e);
        }
    }
    return registrations;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) URL(java.net.URL) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) ServiceRegistration(org.osgi.framework.ServiceRegistration) InputStreamReader(java.io.InputStreamReader) Hashtable(java.util.Hashtable) IOException(java.io.IOException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) IOException(java.io.IOException) ServicePermission(org.osgi.framework.ServicePermission) BufferedReader(java.io.BufferedReader)

Example 15 with ServiceRegistration

use of org.osgi.framework.ServiceRegistration in project aries by apache.

the class ServiceInterceptor method registerServiceEnhancer.

@SuppressWarnings({ "rawtypes", "unchecked" })
private void registerServiceEnhancer(ServiceReference reference) {
    Object actualService = ctx.getService(reference);
    if (actualService instanceof ModelInfoService) {
        ModelInfoService infoService = (ModelInfoService) actualService;
        Object serviceId = reference.getProperty(SERVICE_ID);
        Object enhancer = new ModelInfoEnhancerService(infoService);
        Dictionary properties = new Hashtable();
        Object originalDisplayName = reference.getProperty(DISPLAY_NAME);
        properties.put(DISPLAY_NAME, originalDisplayName + " [enhanced]");
        ServiceRegistration registration = ctx.registerService(ModelInfoService.class.getName(), enhancer, properties);
        registrations.put(serviceId + "", registration);
    } else {
        System.out.println("Oh dear - unexpected service " + actualService.getClass());
    }
}
Also used : Dictionary(java.util.Dictionary) Hashtable(java.util.Hashtable) ModelInfoService(org.apache.aries.samples.goat.api.ModelInfoService) ServiceRegistration(org.osgi.framework.ServiceRegistration)

Aggregations

ServiceRegistration (org.osgi.framework.ServiceRegistration)188 Test (org.junit.Test)80 Hashtable (java.util.Hashtable)61 BundleContext (org.osgi.framework.BundleContext)35 Bundle (org.osgi.framework.Bundle)26 Dictionary (java.util.Dictionary)23 Properties (java.util.Properties)22 HashMap (java.util.HashMap)21 ServiceReference (org.osgi.framework.ServiceReference)21 ArrayList (java.util.ArrayList)18 Map (java.util.Map)13 IOException (java.io.IOException)8 ServiceFactory (org.osgi.framework.ServiceFactory)8 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7 URL (java.net.URL)6 HashSet (java.util.HashSet)6 List (java.util.List)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 ObjectName (javax.management.ObjectName)5 InitialContext (javax.naming.InitialContext)5