Search in sources :

Example 56 with ConfigurationAdmin

use of org.osgi.service.cm.ConfigurationAdmin in project opennms by OpenNMS.

the class KarafExtender method init.

public void init() throws InterruptedException {
    Objects.requireNonNull(m_configurationAdmin, "configurationAdmin");
    Objects.requireNonNull(m_mavenResolver, "mavenResolver");
    Objects.requireNonNull(m_featuresService, "featuresService");
    List<Repository> repositories;
    try {
        repositories = getRepositories();
    } catch (IOException e) {
        LOG.error("Failed to retrieve the list of repositories. Aborting.", e);
        return;
    }
    // Prepend the featuresBoot from the repository definitions
    List<Feature> featuresBoot = repositories.stream().flatMap(r -> r.getFeaturesBoot().stream()).collect(Collectors.toList());
    try {
        featuresBoot.addAll(getFeaturesBoot());
    } catch (IOException e) {
        LOG.error("Failed to retrieve the list of features to boot. Aborting.", e);
        return;
    }
    // Filter the list of features
    filterFeatures(featuresBoot);
    // Build a comma separated list of our Maven repositories
    StringBuilder mavenReposSb = new StringBuilder();
    for (Repository repository : repositories) {
        if (mavenReposSb.length() != 0) {
            mavenReposSb.append(",");
        }
        mavenReposSb.append(repository.toMavenUri());
    }
    LOG.info("Updating Maven repositories to include: {}", mavenReposSb);
    try {
        final Configuration config = m_configurationAdmin.getConfiguration(PAX_MVN_PID);
        if (config == null) {
            throw new IOException("The OSGi configuration (admin) registry was found for pid " + PAX_MVN_PID + ", but a configuration could not be located/generated.  This shouldn't happen.");
        }
        final Dictionary<String, Object> props = config.getProperties();
        props.put(PAX_MVN_REPOSITORIES, mavenReposSb.toString());
        config.update(props);
    } catch (IOException e) {
        LOG.error("Failed to update the list of Maven repositories to '{}'. Aborting.", mavenReposSb, e);
        return;
    }
    // The configuration update is async, we need to wait for the feature URLs to be resolvable before we use them
    LOG.info("Waiting up-to 30 seconds for the Maven repositories to be updated...");
    // Attempting to resolve a missing features writes an exception to the log
    // We sleep fix a fixed amount of time before our first try in order to help minimize the logged
    // exceptions, even if we catch them
    Thread.sleep(2000);
    for (int i = 28; i > 0 && !canResolveAllFeatureUris(repositories); i--) {
        Thread.sleep(1000);
    }
    for (Repository repository : repositories) {
        for (URI featureUri : repository.getFeatureUris()) {
            try {
                LOG.info("Adding feature repository: {}", featureUri);
                m_featuresService.addRepository(featureUri);
                m_featuresService.refreshRepository(featureUri);
            } catch (Exception e) {
                LOG.error("Failed to add feature repository '{}'. Skipping.", featureUri, e);
            }
        }
    }
    final Set<String> featuresToInstall = featuresBoot.stream().map(f -> f.getVersion() != null ? f.getName() + "/" + f.getVersion() : f.getName()).collect(Collectors.toCollection(LinkedHashSet::new));
    try {
        LOG.info("Installing features: {}", featuresToInstall);
        m_featuresService.installFeatures(featuresToInstall, EnumSet.noneOf(Option.class));
    } catch (Exception e) {
        LOG.error("Failed to install one or more features.", e);
    }
}
Also used : Option(org.apache.karaf.features.FeaturesService.Option) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) FeaturesService(org.apache.karaf.features.FeaturesService) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) DirectoryStream(java.nio.file.DirectoryStream) Matcher(java.util.regex.Matcher) Lists(com.google.common.collect.Lists) Configuration(org.osgi.service.cm.Configuration) URI(java.net.URI) Path(java.nio.file.Path) EnumSet(java.util.EnumSet) LinkedHashSet(java.util.LinkedHashSet) MavenResolver(org.ops4j.pax.url.mvn.MavenResolver) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Files(java.nio.file.Files) Set(java.util.Set) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) Paths(java.nio.file.Paths) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) Dictionary(java.util.Dictionary) Configuration(org.osgi.service.cm.Configuration) IOException(java.io.IOException) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) Option(org.apache.karaf.features.FeaturesService.Option)

Example 57 with ConfigurationAdmin

use of org.osgi.service.cm.ConfigurationAdmin in project aries by apache.

the class IsolatedCfgAdminRuntimeTest method assertExpectedServices.

/**
     * Assert that the following services are present in the service registry:
     * <p/>
     * - ConfigurationAdmin
     * - ManagedService
     * - HelloWorld
     *
     * @param ctx the bundle context
     * @param pid the service pid used to register the underlying ManagedService
     * @throws Exception
     */
private void assertExpectedServices(RichBundleContext ctx, String pid) throws Exception {
    //assert the CfgAdmin service was registered
    Assert.assertNotNull("Missing the ConfigurationAdmin service", ctx.getService(ConfigurationAdmin.class));
    //assert we have the ManagedService exposed
    Assert.assertNotNull("Missing the Managed service", ctx.getService(ManagedService.class, "(" + Constants.SERVICE_PID + "=" + pid + ")"));
    //now just make sure we can see it through the context of our config admin bundle context (should be in the same scope)
    ServiceReference ref = ctx.getServiceReference(ConfigurationAdmin.class.getName());
    Assert.assertNotNull("Couldn't find the ManagedService using the ConfigAdmin bundle context", new RichBundleContext(ref.getBundle().getBundleContext()).getService(ManagedService.class, "(" + Constants.SERVICE_PID + "=" + pid + ")"));
    //make sure we have the helloworld service registered
    HelloWorld helloWorldBluePrint = IsolationTestUtils.findHelloWorldService(ctx);
    Assert.assertNotNull("Missing the HelloWorld service", helloWorldBluePrint);
}
Also used : ManagedService(org.osgi.service.cm.ManagedService) RichBundleContext(org.apache.aries.itest.RichBundleContext) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) ServiceReference(org.osgi.framework.ServiceReference) HelloWorld(org.apache.aries.isolated.sample.HelloWorld)

Example 58 with ConfigurationAdmin

use of org.osgi.service.cm.ConfigurationAdmin in project aries by apache.

the class CmUtils method getProperties.

public static Dictionary<String, Object> getProperties(ServiceReference service, String persistentId) throws IOException {
    BundleContext bc = service.getBundle().getBundleContext();
    ServiceReference<ConfigurationAdmin> caRef = bc.getServiceReference(ConfigurationAdmin.class);
    try {
        ConfigurationAdmin ca = bc.getService(caRef);
        Configuration config = getConfiguration(ca, persistentId);
        if (config != null) {
            Dictionary<String, Object> props = new CaseInsensitiveDictionary(config.getProperties());
            Bundle bundle = caRef.getBundle();
            if (bundle != null) {
                BundleContext caBc = bundle.getBundleContext();
                if (caBc != null) {
                    try {
                        callPlugins(caBc, props, service, persistentId, null);
                    } catch (IllegalStateException ise) {
                    // we don't care it doesn't exist so, shrug.
                    }
                }
            }
            return props;
        } else {
            return null;
        }
    } finally {
        bc.ungetService(caRef);
    }
}
Also used : Configuration(org.osgi.service.cm.Configuration) Bundle(org.osgi.framework.Bundle) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) BundleContext(org.osgi.framework.BundleContext)

Example 59 with ConfigurationAdmin

use of org.osgi.service.cm.ConfigurationAdmin in project aries by apache.

the class AbstractBlueprintIntegrationTest method applyCommonConfiguration.

protected void applyCommonConfiguration(BundleContext ctx) throws Exception {
    ConfigurationAdmin ca = (new RichBundleContext(ctx)).getService(ConfigurationAdmin.class);
    Configuration cf = ca.getConfiguration("blueprint-sample-placeholder", null);
    Hashtable<String, String> props = new Hashtable<String, String>();
    props.put("key.b", "10");
    cf.update(props);
}
Also used : RichBundleContext(org.apache.aries.itest.RichBundleContext) Configuration(org.osgi.service.cm.Configuration) Hashtable(java.util.Hashtable) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin)

Example 60 with ConfigurationAdmin

use of org.osgi.service.cm.ConfigurationAdmin in project aries by apache.

the class ConnectionLifecycleTest method testUpdateOfConfig.

@Test
public void testUpdateOfConfig() throws Exception {
    Assume.assumeTrue("Not a configuration test", isConfigured());
    txControl.required(() -> connection.createStatement().execute("Insert into TEST_TABLE values ( 'Hello World!' )"));
    assertEquals("Hello World!", txControl.notSupported(() -> {
        ResultSet rs = connection.createStatement().executeQuery("Select * from TEST_TABLE");
        rs.next();
        return rs.getString(1);
    }));
    ConfigurationAdmin cm = getService(ConfigurationAdmin.class, 5000);
    Configuration[] configurations = cm.listConfigurations("(service.factoryPid=org.apache.aries.tx.control.jdbc.*)");
    assertNotNull(configurations);
    assertEquals(1, configurations.length);
    configurations[0].update();
    Thread.sleep(2000);
    try {
        assertEquals("Hello World!", txControl.notSupported(() -> {
            ResultSet rs = connection.createStatement().executeQuery("Select * from TEST_TABLE");
            rs.next();
            return rs.getString(1);
        }));
        fail("Should not be accessible");
    } catch (ScopedWorkException swe) {
        assertTrue(swe.getCause().toString(), swe.getCause() instanceof TransactionException);
        assertEquals("There was a problem getting hold of a database connection", swe.getCause().getMessage());
    }
}
Also used : ScopedWorkException(org.osgi.service.transaction.control.ScopedWorkException) TransactionException(org.osgi.service.transaction.control.TransactionException) Configuration(org.osgi.service.cm.Configuration) ResultSet(java.sql.ResultSet) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) Test(org.junit.Test)

Aggregations

ConfigurationAdmin (org.osgi.service.cm.ConfigurationAdmin)108 Configuration (org.osgi.service.cm.Configuration)42 Subject (javax.security.auth.Subject)24 Test (org.junit.Test)19 Hashtable (java.util.Hashtable)14 BundleContext (org.osgi.framework.BundleContext)14 ServiceReference (org.osgi.framework.ServiceReference)13 IOException (java.io.IOException)9 Dictionary (java.util.Dictionary)8 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)7 Method (java.lang.reflect.Method)6 Bundle (org.osgi.framework.Bundle)6 File (java.io.File)4 Properties (java.util.Properties)4 MBeanServer (javax.management.MBeanServer)4 ObjectName (javax.management.ObjectName)4 KarafMBeanServerGuard (org.apache.karaf.management.KarafMBeanServerGuard)4 CountDownLatch (java.util.concurrent.CountDownLatch)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 CompositeData (javax.management.openmbean.CompositeData)3