Search in sources :

Example 1 with Framework

use of org.osgi.framework.launch.Framework in project sling by apache.

the class FrameworkSetup method call.

public Object call() throws Exception {
    final Model model = require(Launcher.MODEL_KEY, Model.class);
    final LauncherListener listener = (LauncherListener) get(Launcher.LISTENER_KEY);
    log.info("Setting OSGi framework properties");
    final Map<String, String> fprops = new FrameworkProperties(model).getProperties(null);
    log.info("Starting the OSGi framework");
    final FrameworkFactory factory = (FrameworkFactory) getClass().getClassLoader().loadClass("org.apache.felix.framework.FrameworkFactory").newInstance();
    final Framework framework = factory.newFramework(fprops);
    framework.start();
    final RunModeFilter rmFilter = new RunModeFilter();
    final Configurations cfg = new Configurations(framework.getBundleContext(), model, rmFilter);
    setShutdownHook(framework, new Closeable[] { cfg });
    log.info("OSGi framework started");
    log.info("Installing bundles from provisioning model");
    final BundlesInstaller bi = new BundlesInstaller(model, rmFilter);
    final BundleContext bc = framework.getBundleContext();
    bi.installBundles(bc, Launcher.NOT_CRANKSTART_FILTER);
    cfg.maybeConfigure();
    // TODO shall we gradually increase start levels like the launchpad does?? Reuse that DefaultStartupHandler code?
    final Bundle[] bundles = bc.getBundles();
    log.info("Starting all bundles ({} bundles installed)", bundles.length);
    int started = 0;
    int failed = 0;
    for (Bundle b : bundles) {
        if (isFragment(b)) {
            started++;
        } else {
            try {
                b.start();
                started++;
            } catch (BundleException be) {
                failed++;
                log.warn("Error starting bundle " + b.getSymbolicName(), be);
            }
        }
        cfg.maybeConfigure();
    }
    if (failed == 0) {
        log.info("All {} bundles started.", started);
    } else {
        log.info("{} bundles started, {} failed to start, total {}", started, failed, bundles.length);
    }
    log.info("OSGi setup done, waiting for framework to stop");
    if (listener != null) {
        listener.onStartup(started, failed, bundles.length);
    }
    framework.waitForStop(0);
    if (listener != null) {
        listener.onShutdown();
    }
    return null;
}
Also used : Bundle(org.osgi.framework.Bundle) FrameworkFactory(org.osgi.framework.launch.FrameworkFactory) Model(org.apache.sling.provisioning.model.Model) BundleException(org.osgi.framework.BundleException) Framework(org.osgi.framework.launch.Framework) BundleContext(org.osgi.framework.BundleContext)

Example 2 with Framework

use of org.osgi.framework.launch.Framework in project webservices-axiom by apache.

the class UsesConstraintsTest method test.

@Test
public void test() throws Exception {
    System.setProperty("java.protocol.handler.pkgs", "org.ops4j.pax.url");
    Map<String, String> p = new HashMap<String, String>();
    p.put(FRAMEWORK_STORAGE, new File("target/felix").getAbsolutePath());
    p.put(FRAMEWORK_STORAGE_CLEAN, FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
    FrameworkFactory frameworkFactory = new org.apache.felix.framework.FrameworkFactory();
    Framework framework = frameworkFactory.newFramework(p);
    framework.init();
    BundleContext context = framework.getBundleContext();
    Listener listener = new Listener();
    context.addFrameworkListener(listener);
    List<Bundle> bundles = new ArrayList<Bundle>();
    bundles.add(context.installBundle("link:classpath:META-INF/links/org.ops4j.pax.logging.api.link"));
    bundles.add(context.installBundle("link:classpath:org.apache.servicemix.specs.stax-api-1.0.link"));
    bundles.add(context.installBundle("link:classpath:stax2-api.link"));
    bundles.add(context.installBundle("link:classpath:woodstox-core-asl.link"));
    bundles.add(context.installBundle("link:classpath:org.apache.james.apache-mime4j-core.link"));
    bundles.add(context.installBundle("link:classpath:org.apache.ws.commons.axiom.axiom-api.link"));
    // This bundle will be wired to the javax.xml.stream package exported by the ServiceMix stax-api bundle.
    bundles.add(context.installBundle(streamBundle(bundle().set(BUNDLE_SYMBOLICNAME, "testbundle1").set(IMPORT_PACKAGE, "org.apache.axiom.om, javax.xml.stream; version=1.0").build()).getURL()));
    // This bundle will be wired to the javax.xml.stream package exported by the framework bundle
    bundles.add(context.installBundle(streamBundle(bundle().set(BUNDLE_SYMBOLICNAME, "testbundle2").set(IMPORT_PACKAGE, "org.apache.axiom.om, javax.xml.stream; version=\"[0.0.0,1.0)\"").build()).getURL()));
    for (Bundle bundle : bundles) {
        bundle.start();
    }
    framework.start();
    try {
        listener.awaitStart();
        assertTrue("Uses constraint violation expected", listener.gotExpectedError());
    } finally {
        framework.stop();
    }
}
Also used : FrameworkListener(org.osgi.framework.FrameworkListener) HashMap(java.util.HashMap) CoreOptions.streamBundle(org.ops4j.pax.exam.CoreOptions.streamBundle) Bundle(org.osgi.framework.Bundle) ArrayList(java.util.ArrayList) FrameworkFactory(org.osgi.framework.launch.FrameworkFactory) File(java.io.File) Framework(org.osgi.framework.launch.Framework) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 3 with Framework

use of org.osgi.framework.launch.Framework in project bnd by bndtools.

the class Launcher method createFramework.

private Framework createFramework() throws Exception {
    Properties p = new Properties();
    p.putAll(properties);
    File workingdir = null;
    if (parms.storageDir != null)
        workingdir = parms.storageDir;
    else if (parms.keep && parms.name != null) {
        workingdir = new File(bnd, parms.name);
    }
    if (workingdir == null) {
        workingdir = File.createTempFile("osgi.", ".fw");
        final File wd = workingdir;
        Runtime.getRuntime().addShutdownHook(new Thread("launcher::delete temp working dir") {

            public void run() {
                deleteFiles(wd);
            }
        });
    }
    trace("using working dir: %s with keeping=%s", workingdir, parms.keep);
    if (!parms.keep && workingdir.exists()) {
        trace("deleting working dir %s because not kept", workingdir);
        delete(workingdir);
        p.setProperty(Constants.FRAMEWORK_STORAGE_CLEAN, "true");
    }
    IO.mkdirs(workingdir);
    if (!workingdir.isDirectory())
        throw new IllegalArgumentException("Cannot create a working dir: " + workingdir);
    if (System.getProperty(Constants.FRAMEWORK_STORAGE) == null)
        p.setProperty(Constants.FRAMEWORK_STORAGE, workingdir.getAbsolutePath());
    else
        p.setProperty(Constants.FRAMEWORK_STORAGE, System.getProperty(Constants.FRAMEWORK_STORAGE));
    if (parms.systemPackages != null) {
        p.setProperty(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, parms.systemPackages);
        trace("system packages used: %s", parms.systemPackages);
    }
    if (parms.systemCapabilities != null) {
        p.setProperty(FRAMEWORK_SYSTEM_CAPABILITIES_EXTRA, parms.systemCapabilities);
        trace("system capabilities used: %s", parms.systemCapabilities);
    }
    Framework systemBundle;
    if (parms.services) {
        trace("using META-INF/services");
        // 3) framework = null, lookup in META-INF/services
        ClassLoader loader = getClass().getClassLoader();
        // 3) Lookup in META-INF/services
        List<String> implementations = getMetaInfServices(loader, FrameworkFactory.class.getName());
        if (implementations.size() == 0)
            error("Found no fw implementation");
        if (implementations.size() > 1)
            error("Found more than one framework implementations: %s", implementations);
        String implementation = implementations.get(0);
        Class<?> clazz = loader.loadClass(implementation);
        FrameworkFactory factory = (FrameworkFactory) clazz.getConstructor().newInstance();
        trace("Framework factory %s", factory);
        @SuppressWarnings({ "unchecked", "rawtypes" }) Map<String, String> configuration = (Map) p;
        systemBundle = factory.newFramework(configuration);
        trace("framework instance %s", systemBundle);
    } else {
        trace("using embedded mini framework because we were told not to use META-INF/services");
        // we have to use our own dummy framework
        systemBundle = new MiniFramework(p);
    }
    systemBundle.init();
    try {
        systemBundle.getBundleContext().addFrameworkListener(new FrameworkListener() {

            public void frameworkEvent(FrameworkEvent event) {
                switch(event.getType()) {
                    case FrameworkEvent.ERROR:
                    case FrameworkEvent.WAIT_TIMEDOUT:
                        trace("Refresh will end due to error or timeout %s", event.toString());
                    case FrameworkEvent.PACKAGES_REFRESHED:
                        inrefresh = false;
                        trace("refresh ended");
                        break;
                }
            }
        });
    } catch (Exception e) {
        trace("could not register a framework listener: %s", e);
    }
    trace("inited system bundle %s", systemBundle);
    return systemBundle;
}
Also used : FrameworkEvent(org.osgi.framework.FrameworkEvent) Properties(java.util.Properties) MiniFramework(aQute.launcher.minifw.MiniFramework) BundleException(org.osgi.framework.BundleException) InvocationTargetException(java.lang.reflect.InvocationTargetException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) FrameworkFactory(org.osgi.framework.launch.FrameworkFactory) FrameworkListener(org.osgi.framework.FrameworkListener) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Framework(org.osgi.framework.launch.Framework) MiniFramework(aQute.launcher.minifw.MiniFramework)

Example 4 with Framework

use of org.osgi.framework.launch.Framework in project bnd by bndtools.

the class RepoIndexTask method execute.

@Override
public void execute() throws BuildException {
    printCopyright(System.err);
    if (repositoryFile == null)
        throw new BuildException("Output file not specified");
    try {
        // Configure PojoSR
        Map<String, Object> pojoSrConfig = new HashMap<String, Object>();
        pojoSrConfig.put(PojoServiceRegistryFactory.BUNDLE_DESCRIPTORS, new ClasspathScanner());
        // Start PojoSR 'framework'
        Framework framework = new PojoServiceRegistryFactoryImpl().newFramework(pojoSrConfig);
        framework.init();
        framework.start();
        if (knownBundles) {
            registerKnownBundles(framework.getBundleContext());
        }
        // Look for indexer and run index generation
        ServiceTracker<ResourceIndexer, ResourceIndexer> tracker = new ServiceTracker<ResourceIndexer, ResourceIndexer>(framework.getBundleContext(), ResourceIndexer.class, null);
        tracker.open();
        ResourceIndexer index = tracker.waitForService(1000);
        if (index == null)
            throw new IllegalStateException("Timed out waiting for ResourceIndexer service.");
        // Flatten the file sets into a single list
        Set<File> fileList = new LinkedHashSet<File>();
        for (FileSet fileSet : fileSets) {
            DirectoryScanner ds = fileSet.getDirectoryScanner(getProject());
            File basedir = ds.getBasedir();
            String[] files = ds.getIncludedFiles();
            for (int i = 0; i < files.length; i++) fileList.add(new File(basedir, files[i]));
        }
        // Run
        try (OutputStream fos = Files.newOutputStream(repositoryFile.toPath())) {
            index.index(fileList, fos, config);
        }
    } catch (Exception e) {
        throw new BuildException(e);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) FileSet(org.apache.tools.ant.types.FileSet) HashMap(java.util.HashMap) ServiceTracker(org.osgi.util.tracker.ServiceTracker) OutputStream(java.io.OutputStream) ResourceIndexer(org.osgi.service.indexer.ResourceIndexer) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException) ClasspathScanner(de.kalpatec.pojosr.framework.launch.ClasspathScanner) PojoServiceRegistryFactoryImpl(de.kalpatec.pojosr.framework.PojoServiceRegistryFactoryImpl) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) BuildException(org.apache.tools.ant.BuildException) File(java.io.File) Framework(org.osgi.framework.launch.Framework)

Example 5 with Framework

use of org.osgi.framework.launch.Framework in project bnd by bndtools.

the class Index method main.

/**
	 * Main entry point. See -help for options.
	 * 
	 * @param args Program arguments
	 */
public static void main(String[] args) {
    try {
        // Configure PojoSR
        Map<String, Object> pojoSrConfig = new HashMap<String, Object>();
        pojoSrConfig.put(PojoServiceRegistryFactory.BUNDLE_DESCRIPTORS, new ClasspathScanner());
        // Start PojoSR 'framework'
        Framework framework = new PojoServiceRegistryFactoryImpl().newFramework(pojoSrConfig);
        framework.init();
        framework.start();
        // Look for indexer and run index generation
        ServiceTracker<ResourceIndexer, ResourceIndexer> tracker = new ServiceTracker<ResourceIndexer, ResourceIndexer>(framework.getBundleContext(), ResourceIndexer.class, null);
        tracker.open();
        ResourceIndexer index = tracker.waitForService(1000);
        if (index == null)
            throw new IllegalStateException("Timed out waiting for ResourceIndexer service.");
        // Process arguments
        Set<File> fileList = new LinkedHashSet<File>();
        Map<String, String> config = new HashMap<String, String>();
        File outputFile = processArgs(args, System.err, config, fileList, framework.getBundleContext());
        if (outputFile == null) {
            System.exit(1);
        }
        boolean verbose = Boolean.parseBoolean(config.get(ResourceIndexer.VERBOSE));
        if (verbose) {
            printCopyright(System.err);
        }
        try (@SuppressWarnings("null") OutputStream fos = Files.newOutputStream(outputFile.toPath())) {
            index.index(fileList, fos, config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println(e.getMessage());
        System.exit(1);
    }
    // We really need to ensure all non-daemon threads -- which may have
    // been started by a bundle -- are terminated.
    System.exit(0);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) HashMap(java.util.HashMap) ServiceTracker(org.osgi.util.tracker.ServiceTracker) OutputStream(java.io.OutputStream) ResourceIndexer(org.osgi.service.indexer.ResourceIndexer) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) CmdLineException(org.kohsuke.args4j.CmdLineException) ClasspathScanner(de.kalpatec.pojosr.framework.launch.ClasspathScanner) PojoServiceRegistryFactoryImpl(de.kalpatec.pojosr.framework.PojoServiceRegistryFactoryImpl) File(java.io.File) Framework(org.osgi.framework.launch.Framework)

Aggregations

Framework (org.osgi.framework.launch.Framework)11 File (java.io.File)6 FrameworkFactory (org.osgi.framework.launch.FrameworkFactory)6 IOException (java.io.IOException)4 HashMap (java.util.HashMap)4 Bundle (org.osgi.framework.Bundle)4 BundleContext (org.osgi.framework.BundleContext)4 BundleException (org.osgi.framework.BundleException)4 Properties (java.util.Properties)3 Test (org.junit.Test)3 FrameworkListener (org.osgi.framework.FrameworkListener)3 PojoServiceRegistryFactoryImpl (de.kalpatec.pojosr.framework.PojoServiceRegistryFactoryImpl)2 ClasspathScanner (de.kalpatec.pojosr.framework.launch.ClasspathScanner)2 OutputStream (java.io.OutputStream)2 LinkedHashSet (java.util.LinkedHashSet)2 FrameworkEvent (org.osgi.framework.FrameworkEvent)2 ResourceIndexer (org.osgi.service.indexer.ResourceIndexer)2 ServiceTracker (org.osgi.util.tracker.ServiceTracker)2 MiniFramework (aQute.launcher.minifw.MiniFramework)1 FileNotFoundException (java.io.FileNotFoundException)1