Search in sources :

Example 11 with ManagedService

use of org.osgi.service.cm.ManagedService in project felix by apache.

the class MongoDBStoreTest method canRunTest.

/**
 * Sets up MongoDB and tries to clear the useradmin collection. When this fails, it is assumed that no MongoDB service is available.
 */
private boolean canRunTest() throws BundleException {
    Bundle mongoBundle = getMongoDBBundle();
    mongoBundle.start();
    Bundle mongoStoreBundle = getMongoDBStoreBundle();
    mongoStoreBundle.start();
    // Provision an empty configuration...
    BundleContext context = mongoStoreBundle.getBundleContext();
    ServiceReference serviceRef = context.getServiceReference(ManagedService.class.getName());
    assertNotNull(serviceRef);
    ManagedService service = (ManagedService) context.getService(serviceRef);
    try {
        service.updated(null);
        Mongo mongo = new Mongo();
        DB db = mongo.getDB("ua_repo");
        DBCollection collection = db.getCollection("useradmin");
        // we always get a collection back, regardless if there is an actual MongoDB listening, hence we should do
        // some actual calls that cause a connection to MongoDB to be created...
        collection.remove(new BasicDBObject(), WriteConcern.SAFE);
        CommandResult lastError = db.getLastError();
        return (lastError.getException() == null && collection.getCount() == 0L);
    } catch (Exception e) {
    // Ignore; apparently, we failed to connect to MongoDB...
    }
    return false;
}
Also used : ManagedService(org.osgi.service.cm.ManagedService) DBCollection(com.mongodb.DBCollection) BasicDBObject(com.mongodb.BasicDBObject) Mongo(com.mongodb.Mongo) Bundle(org.osgi.framework.Bundle) DB(com.mongodb.DB) BundleException(org.osgi.framework.BundleException) BundleContext(org.osgi.framework.BundleContext) ServiceReference(org.osgi.framework.ServiceReference) CommandResult(com.mongodb.CommandResult)

Example 12 with ManagedService

use of org.osgi.service.cm.ManagedService in project felix by apache.

the class ConfigAdminSupport method listConfigurations.

final void listConfigurations(JSONWriter jw, String pidFilter, String locale, Locale loc) {
    try {
        // start with ManagedService instances
        Map optionsPlain = getServices(ManagedService.class.getName(), pidFilter, locale, true);
        // next are the MetaType informations without ManagedService
        final MetaTypeServiceSupport mtss = getMetaTypeSupport();
        if (mtss != null) {
            addMetaTypeNames(optionsPlain, mtss.getPidObjectClasses(locale), pidFilter, Constants.SERVICE_PID);
        }
        // add in existing configuration (not duplicating ManagedServices)
        Configuration[] cfgs = this.service.listConfigurations(pidFilter);
        for (int i = 0; cfgs != null && i < cfgs.length; i++) {
            // ignore configuration object if an entry already exists in the map
            // or if it is invalid
            final String pid = cfgs[i].getPid();
            if (optionsPlain.containsKey(pid) || !ConfigManager.isAllowedPid(pid)) {
                continue;
            }
            // insert and entry for the PID
            if (mtss != null) {
                try {
                    ObjectClassDefinition ocd = mtss.getObjectClassDefinition(cfgs[i], locale);
                    if (ocd != null) {
                        optionsPlain.put(pid, ocd.getName());
                        continue;
                    }
                } catch (IllegalArgumentException t) {
                // MetaTypeProvider.getObjectClassDefinition might throw illegal
                // argument exception. So we must catch it here, otherwise the
                // other configurations will not be shown
                // See https://issues.apache.org/jira/browse/FELIX-2390
                }
            }
            // no object class definition, use plain PID
            optionsPlain.put(pid, pid);
        }
        // $NON-NLS-1$
        jw.key("pids");
        jw.array();
        for (Iterator ii = optionsPlain.keySet().iterator(); ii.hasNext(); ) {
            String id = (String) ii.next();
            Object name = optionsPlain.get(id);
            final Configuration config = this.getConfiguration(id);
            jw.object();
            // $NON-NLS-1$
            jw.key("id").value(id);
            // $NON-NLS-1$
            jw.key("name").value(name);
            if (null != config) {
                // FELIX-3848
                // $NON-NLS-1$
                jw.key("has_config").value(true);
                final String fpid = config.getFactoryPid();
                if (null != fpid) {
                    // $NON-NLS-1$
                    jw.key("fpid").value(fpid);
                    final String val = getConfigurationFactoryNameHint(config, mtss);
                    if (val != null) {
                        // $NON-NLS-1$
                        jw.key("nameHint").value(val);
                    }
                }
                final Bundle bundle = getBoundBundle(config);
                if (null != bundle) {
                    // $NON-NLS-1$
                    jw.key("bundle").value(bundle.getBundleId());
                    // $NON-NLS-1$
                    jw.key("bundle_name").value(Util.getName(bundle, loc));
                }
            }
            jw.endObject();
        }
        jw.endArray();
    } catch (Exception e) {
        configManager.log("listConfigurations: Unexpected problem encountered", e);
    }
}
Also used : ManagedService(org.osgi.service.cm.ManagedService) Configuration(org.osgi.service.cm.Configuration) Bundle(org.osgi.framework.Bundle) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) IOException(java.io.IOException) Iterator(java.util.Iterator) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) SortedMap(java.util.SortedMap) ObjectClassDefinition(org.osgi.service.metatype.ObjectClassDefinition)

Example 13 with ManagedService

use of org.osgi.service.cm.ManagedService in project controller by opendaylight.

the class ComponentProcessor method registerManagedService.

private void registerManagedService(final String persistentId) {
    // Register a ManagedService so we get updates from the ConfigAdmin when the cfg file corresponding
    // to the persistentId changes.
    final ManagedService managedService = new ManagedService() {

        private final AtomicBoolean initialUpdate = new AtomicBoolean(true);

        private volatile Dictionary<String, ?> previousProperties;

        @Override
        public void updated(final Dictionary<String, ?> properties) {
            LOG.debug("{}: ManagedService updated for persistentId {}, properties: {}, initialUpdate: {}", logName(), persistentId, properties, initialUpdate);
            // yet exist.
            if (!initialUpdate.compareAndSet(true, false) && !Objects.equals(previousProperties, properties)) {
                blueprintContainerRestartService.restartContainerAndDependents(bundle);
            }
            previousProperties = properties;
        }
    };
    Dictionary<String, Object> props = new Hashtable<>();
    props.put(Constants.SERVICE_PID, persistentId);
    props.put(Constants.BUNDLE_SYMBOLICNAME, bundle.getSymbolicName());
    props.put(Constants.BUNDLE_VERSION, bundle.getHeaders().get(Constants.BUNDLE_VERSION));
    managedServiceRegs.add(bundle.getBundleContext().registerService(ManagedService.class.getName(), managedService, props));
}
Also used : ManagedService(org.osgi.service.cm.ManagedService) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Dictionary(java.util.Dictionary) Hashtable(java.util.Hashtable)

Example 14 with ManagedService

use of org.osgi.service.cm.ManagedService in project felix by apache.

the class BaseIntegrationTest method configureHttpService.

protected void configureHttpService(Dictionary<String, ?> props) throws Exception {
    final String pid = "org.apache.felix.http";
    final Collection<ServiceReference<ManagedService>> serviceRefs = m_context.getServiceReferences(ManagedService.class, String.format("(%s=%s)", Constants.SERVICE_PID, pid));
    assertNotNull("Unable to obtain managed configuration for " + pid, serviceRefs);
    assertFalse("Unable to obtain managed configuration for " + pid, serviceRefs.isEmpty());
    for (final ServiceReference<ManagedService> serviceRef : serviceRefs) {
        ManagedService service = m_context.getService(serviceRef);
        try {
            service.updated(props);
        } catch (ConfigurationException ex) {
            fail("Invalid configuration provisioned: " + ex.getMessage());
        } finally {
            m_context.ungetService(serviceRef);
        }
    }
}
Also used : ManagedService(org.osgi.service.cm.ManagedService) ConfigurationException(org.osgi.service.cm.ConfigurationException) ServiceReference(org.osgi.framework.ServiceReference)

Example 15 with ManagedService

use of org.osgi.service.cm.ManagedService in project felix by apache.

the class RegionConfigurationSupport method getConfigurationInfo.

/**
 * This gets config admin, gets the requested configuration, extracts the info we need from it, and ungets config admin.
 * Some versions of felix config admin do not allow access to configurations after the config admin instance they were obtained from
 * are ungot.  Extracting the info we need into "configInfo" solves this problem.
 *
 * @param pid TargetedPID for the desired configuration
 * @param targetedPid the targeted factory pid for a factory configuration or the pid for a singleton configuration
 * @param componentHolder ComponentHolder that holds the old change count (for r4 fake change counting)
 * @param bundleContext BundleContext to get the CA from
 * @return ConfigurationInfo object containing the info we need from the configuration.
 */
private ConfigurationInfo getConfigurationInfo(final TargetedPID pid, TargetedPID targetedPid, ComponentHolder<?> componentHolder, final BundleContext bundleContext) {
    try {
        final ConfigurationAdmin ca = getConfigAdmin(bundleContext);
        try {
            Configuration[] configs = ca.listConfigurations(filter(pid.getRawPid()));
            if (configs != null && configs.length > 0) {
                Configuration config = configs[0];
                ServiceReference<ManagedService> ref = getManagedServiceReference(bundleContext);
                return new ConfigurationInfo(config.getProcessedProperties(ref), config.getBundleLocation(), config.getChangeCount());
            }
        } catch (IOException e) {
            logger.log(LogService.LOG_WARNING, "Failed reading configuration for pid={0}", e, pid);
        } catch (InvalidSyntaxException e) {
            logger.log(LogService.LOG_WARNING, "Failed reading configuration for pid={0}", e, pid);
        } finally {
            bundleContext.ungetService(caReference);
        }
    } catch (IllegalStateException ise) {
        // If the bundle has been stopped concurrently
        logger.log(LogService.LOG_WARNING, "Bundle in unexpected state", ise);
    }
    return null;
}
Also used : ManagedService(org.osgi.service.cm.ManagedService) Configuration(org.osgi.service.cm.Configuration) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) IOException(java.io.IOException) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin)

Aggregations

ManagedService (org.osgi.service.cm.ManagedService)29 ServiceReference (org.osgi.framework.ServiceReference)23 Hashtable (java.util.Hashtable)22 ConfigurationException (org.osgi.service.cm.ConfigurationException)20 FooService (org.apache.felix.ipojo.runtime.core.services.FooService)19 Test (org.junit.Test)19 Properties (java.util.Properties)10 Dictionary (java.util.Dictionary)7 BundleContext (org.osgi.framework.BundleContext)4 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)3 Configuration (org.osgi.service.cm.Configuration)3 ConfigurationAdmin (org.osgi.service.cm.ConfigurationAdmin)3 Enumeration (java.util.Enumeration)2 Bundle (org.osgi.framework.Bundle)2 Sets (com.google.common.collect.Sets)1 BasicDBObject (com.mongodb.BasicDBObject)1 CommandResult (com.mongodb.CommandResult)1