Search in sources :

Example 6 with Dictionary

use of java.util.Dictionary in project graphdb by neo4j-attic.

the class ExampleActivator method start.

/**
     * Called whenever the OSGi framework starts our bundle
     */
public void start(BundleContext bc) throws Exception {
    System.out.println("STARTING org.neo4j.release.it.poja");
    Dictionary props = new Properties();
    // add specific service properties here...
    System.out.println("REGISTER org.neo4j.release.it.poja.ExampleService");
    // Register our example service implementation in the OSGi service registry
    bc.registerService(ExampleService.class.getName(), new ExampleServiceImpl(), props);
}
Also used : Dictionary(java.util.Dictionary) Properties(java.util.Properties) ExampleService(org.neo4j.release.it.poja.ExampleService)

Example 7 with Dictionary

use of java.util.Dictionary in project graphdb by neo4j-attic.

the class OSGiActivator method start.

/**
     * Called whenever the OSGi framework starts our bundle
     */
public void start(BundleContext bc) throws Exception {
    // register the UdcExtenionImpl
    Dictionary props = new Properties();
    // Register our example service implementation in the OSGi service registry
    bc.registerService(KernelExtension.class.getName(), new UdcExtensionImpl(), props);
}
Also used : Dictionary(java.util.Dictionary) UdcExtensionImpl(org.neo4j.ext.udc.impl.UdcExtensionImpl) Properties(java.util.Properties) KernelExtension(org.neo4j.kernel.KernelExtension)

Example 8 with Dictionary

use of java.util.Dictionary in project camel by apache.

the class Activator method updateAvailableScriptLanguages.

private void updateAvailableScriptLanguages() {
    ServiceReference<LanguageResolver> ref = null;
    try {
        Collection<ServiceReference<LanguageResolver>> references = context.getServiceReferences(LanguageResolver.class, "(resolver=default)");
        if (references.size() == 1) {
            // Unregistry the old language resolver first
            if (registration != null) {
                registration.unregister();
                registration = null;
            }
            ref = references.iterator().next();
            LanguageResolver resolver = context.getService(ref);
            Dictionary props = new Hashtable();
            // Just publish the language resolve with the language we found
            props.put("language", getAvailableScriptNames());
            registration = context.registerService(LanguageResolver.class, resolver, props);
        }
    } catch (InvalidSyntaxException e) {
        LOG.error("Invalid syntax for LanguageResolver service reference filter.");
    } finally {
        if (ref != null) {
            context.ungetService(ref);
        }
    }
}
Also used : Dictionary(java.util.Dictionary) LanguageResolver(org.apache.camel.spi.LanguageResolver) Hashtable(java.util.Hashtable) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) ServiceReference(org.osgi.framework.ServiceReference)

Example 9 with Dictionary

use of java.util.Dictionary in project camel by apache.

the class CamelBlueprintTestSupport method createBundleContext.

@SuppressWarnings({ "rawtypes", "unchecked" })
protected BundleContext createBundleContext() throws Exception {
    System.setProperty("org.apache.aries.blueprint.synchronous", Boolean.toString(!useAsynchronousBlueprintStartup()));
    // load configuration file
    String[] file = loadConfigAdminConfigurationFile();
    String[][] configAdminPidFiles = new String[0][0];
    if (file != null) {
        if (file.length % 2 != 0) {
            // This needs to return pairs of filename and pid
            throw new IllegalArgumentException("The length of the String[] returned from loadConfigAdminConfigurationFile must divisible by 2, was " + file.length);
        }
        configAdminPidFiles = new String[file.length / 2][2];
        int pair = 0;
        for (int i = 0; i < file.length; i += 2) {
            String fileName = file[i];
            String pid = file[i + 1];
            if (!new File(fileName).exists()) {
                throw new IllegalArgumentException("The provided file \"" + fileName + "\" from loadConfigAdminConfigurationFile doesn't exist");
            }
            configAdminPidFiles[pair][0] = fileName;
            configAdminPidFiles[pair][1] = pid;
            pair++;
        }
    }
    // fetch initial configadmin configuration if provided programmatically
    Properties initialConfiguration = new Properties();
    String pid = setConfigAdminInitialConfiguration(initialConfiguration);
    if (pid != null) {
        configAdminPidFiles = new String[][] { { prepareInitialConfigFile(initialConfiguration), pid } };
    }
    final String symbolicName = getClass().getSimpleName();
    final BundleContext answer = CamelBlueprintHelper.createBundleContext(symbolicName, getBlueprintDescriptor(), includeTestBundle(), getBundleFilter(), getBundleVersion(), getBundleDirectives(), configAdminPidFiles);
    boolean expectReload = expectBlueprintContainerReloadOnConfigAdminUpdate();
    // must register override properties early in OSGi containers
    Properties extra = useOverridePropertiesWithPropertiesComponent();
    if (extra != null) {
        answer.registerService(PropertiesComponent.OVERRIDE_PROPERTIES, extra, null);
    }
    Map<String, KeyValueHolder<Object, Dictionary>> map = new LinkedHashMap<String, KeyValueHolder<Object, Dictionary>>();
    addServicesOnStartup(map);
    List<KeyValueHolder<String, KeyValueHolder<Object, Dictionary>>> servicesList = new LinkedList<KeyValueHolder<String, KeyValueHolder<Object, Dictionary>>>();
    for (Map.Entry<String, KeyValueHolder<Object, Dictionary>> entry : map.entrySet()) {
        servicesList.add(asKeyValueService(entry.getKey(), entry.getValue().getKey(), entry.getValue().getValue()));
    }
    addServicesOnStartup(servicesList);
    for (KeyValueHolder<String, KeyValueHolder<Object, Dictionary>> item : servicesList) {
        String clazz = item.getKey();
        Object service = item.getValue().getKey();
        Dictionary dict = item.getValue().getValue();
        log.debug("Registering service {} -> {}", clazz, service);
        ServiceRegistration<?> reg = answer.registerService(clazz, service, dict);
        if (reg != null) {
            services.add(reg);
        }
    }
    // if blueprint XML uses <cm:property-placeholder> (any update-strategy and any default properties)
    // - org.apache.aries.blueprint.compendium.cm.ManagedObjectManager.register() is called
    // - ManagedServiceUpdate is scheduled in felix.cm
    // - org.apache.felix.cm.impl.ConfigurationImpl.setDynamicBundleLocation() is called
    // - CM_LOCATION_CHANGED event is fired
    // - if BP was alredy created, it's <cm:property-placeholder> receives the event and
    // - org.apache.aries.blueprint.compendium.cm.CmPropertyPlaceholder.updated() is called,
    //   but no BP reload occurs
    // we will however wait for BP container of the test bundle to become CREATED for the first time
    // each configadmin update *may* lead to reload of BP container, if it uses <cm:property-placeholder>
    // with update-strategy="reload"
    // we will gather timestamps of BP events. We don't want to be fooled but repeated events related
    // to the same state of BP container
    Set<Long> bpEvents = new HashSet<>();
    CamelBlueprintHelper.waitForBlueprintContainer(bpEvents, answer, symbolicName, BlueprintEvent.CREATED, null);
    // must reuse props as we can do both load from .cfg file and override afterwards
    final Dictionary props = new Properties();
    // allow end user to override properties
    pid = useOverridePropertiesWithConfigAdmin(props);
    if (pid != null) {
        // we will update the configuration again
        ConfigurationAdmin configAdmin = CamelBlueprintHelper.getOsgiService(answer, ConfigurationAdmin.class);
        // passing null as second argument ties the configuration to correct bundle.
        // using single-arg method causes:
        // *ERROR* Cannot use configuration xxx.properties for [org.osgi.service.cm.ManagedService, id=N, bundle=N/jar:file:xyz.jar!/]: No visibility to configuration bound to felix-connect
        final Configuration config = configAdmin.getConfiguration(pid, null);
        if (config == null) {
            throw new IllegalArgumentException("Cannot find configuration with pid " + pid + " in OSGi ConfigurationAdmin service.");
        }
        // lets merge configurations
        Dictionary<String, Object> currentProperties = config.getProperties();
        final Dictionary newProps = new Properties();
        if (currentProperties == null) {
            currentProperties = newProps;
        }
        for (Enumeration<String> ek = currentProperties.keys(); ek.hasMoreElements(); ) {
            String k = ek.nextElement();
            newProps.put(k, currentProperties.get(k));
        }
        for (String p : ((Properties) props).stringPropertyNames()) {
            newProps.put(p, ((Properties) props).getProperty(p));
        }
        log.info("Updating ConfigAdmin {} by overriding properties {}", config, newProps);
        if (expectReload) {
            CamelBlueprintHelper.waitForBlueprintContainer(bpEvents, answer, symbolicName, BlueprintEvent.CREATED, new Runnable() {

                @Override
                public void run() {
                    try {
                        config.update(newProps);
                    } catch (IOException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                }
            });
        } else {
            config.update(newProps);
        }
    }
    return answer;
}
Also used : Dictionary(java.util.Dictionary) Configuration(org.osgi.service.cm.Configuration) Properties(java.util.Properties) LinkedHashMap(java.util.LinkedHashMap) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) KeyValueHolder(org.apache.camel.util.KeyValueHolder) IOException(java.io.IOException) LinkedList(java.util.LinkedList) File(java.io.File) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) BundleContext(org.osgi.framework.BundleContext)

Example 10 with Dictionary

use of java.util.Dictionary in project camel by apache.

the class CamelKarafTestSupport method getOsgiService.

@SuppressWarnings("unchecked")
protected <T> T getOsgiService(Class<T> type, String filter, long timeout) {
    ServiceTracker tracker = null;
    try {
        String flt;
        if (filter != null) {
            if (filter.startsWith("(")) {
                flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")" + filter + ")";
            } else {
                flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")(" + filter + "))";
            }
        } else {
            flt = "(" + Constants.OBJECTCLASS + "=" + type.getName() + ")";
        }
        Filter osgiFilter = FrameworkUtil.createFilter(flt);
        tracker = new ServiceTracker(bundleContext, osgiFilter, null);
        tracker.open(true);
        // Note that the tracker is not closed to keep the reference
        // This is buggy, as the service reference may change i think
        Object svc = type.cast(tracker.waitForService(timeout));
        if (svc == null) {
            Dictionary dic = bundleContext.getBundle().getHeaders();
            System.err.println("Test bundle headers: " + explode(dic));
            for (ServiceReference ref : asCollection(bundleContext.getAllServiceReferences(null, null))) {
                System.err.println("ServiceReference: " + ref);
            }
            for (ServiceReference ref : asCollection(bundleContext.getAllServiceReferences(null, flt))) {
                System.err.println("Filtered ServiceReference: " + ref);
            }
            throw new RuntimeException("Gave up waiting for service " + flt);
        }
        return type.cast(svc);
    } catch (InvalidSyntaxException e) {
        throw new IllegalArgumentException("Invalid filter", e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}
Also used : Dictionary(java.util.Dictionary) ServiceTracker(org.osgi.util.tracker.ServiceTracker) Filter(org.osgi.framework.Filter) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) ServiceReference(org.osgi.framework.ServiceReference)

Aggregations

Dictionary (java.util.Dictionary)161 Hashtable (java.util.Hashtable)61 Test (org.junit.Test)48 Configuration (org.osgi.service.cm.Configuration)33 Enumeration (java.util.Enumeration)27 Properties (java.util.Properties)24 BundleContext (org.osgi.framework.BundleContext)21 ServiceReference (org.osgi.framework.ServiceReference)21 HashMap (java.util.HashMap)19 ServiceRegistration (org.osgi.framework.ServiceRegistration)19 Map (java.util.Map)17 ArrayList (java.util.ArrayList)15 Bundle (org.osgi.framework.Bundle)15 IOException (java.io.IOException)13 LinkedHashMap (java.util.LinkedHashMap)12 Matchers.anyString (org.mockito.Matchers.anyString)11 ConfigurationAdmin (org.osgi.service.cm.ConfigurationAdmin)10 ComponentContext (org.osgi.service.component.ComponentContext)10 TreeMap (java.util.TreeMap)9 MinionIdentity (org.opennms.minion.core.api.MinionIdentity)9