Search in sources :

Example 41 with BundleException

use of org.osgi.framework.BundleException in project sling by apache.

the class InstallServlet method installBasedOnUploadedJar.

private void installBasedOnUploadedJar(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    InstallationResult result = null;
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // try to hold even largish bundles in memory to potentially improve performance
        factory.setSizeThreshold(UPLOAD_IN_MEMORY_SIZE_THRESHOLD);
        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileItemFactory(factory);
        @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(req);
        if (items.size() != 1) {
            logAndWriteError("Found " + items.size() + " items to process, but only updating 1 bundle is supported", resp);
            return;
        }
        FileItem item = items.get(0);
        JarInputStream jar = null;
        InputStream rawInput = null;
        try {
            jar = new JarInputStream(item.getInputStream());
            Manifest manifest = jar.getManifest();
            if (manifest == null) {
                logAndWriteError("Uploaded jar file does not contain a manifest", resp);
                return;
            }
            final String symbolicName = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
            if (symbolicName == null) {
                logAndWriteError("Manifest does not have a " + Constants.BUNDLE_SYMBOLICNAME, resp);
                return;
            }
            final String version = manifest.getMainAttributes().getValue(Constants.BUNDLE_VERSION);
            // the JarInputStream is used only for validation, we need a fresh input stream for updating
            rawInput = item.getInputStream();
            Bundle found = getBundle(symbolicName);
            try {
                installOrUpdateBundle(found, rawInput, "inputstream:" + symbolicName + "-" + version + ".jar");
                result = new InstallationResult(true, null);
                resp.setStatus(200);
                result.render(resp.getWriter());
                return;
            } catch (BundleException e) {
                logAndWriteError("Unable to install/update bundle " + symbolicName, e, resp);
                return;
            }
        } finally {
            IOUtils.closeQuietly(jar);
            IOUtils.closeQuietly(rawInput);
        }
    } catch (FileUploadException e) {
        logAndWriteError("Failed parsing uploaded bundle", e, resp);
        return;
    }
}
Also used : JarInputStream(java.util.jar.JarInputStream) JarInputStream(java.util.jar.JarInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Bundle(org.osgi.framework.Bundle) Manifest(java.util.jar.Manifest) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) BundleException(org.osgi.framework.BundleException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 42 with BundleException

use of org.osgi.framework.BundleException in project sling by apache.

the class InstallServlet method installBasedOnDirectory.

private void installBasedOnDirectory(HttpServletResponse resp, final File dir) throws FileNotFoundException, IOException {
    InstallationResult result = null;
    if (dir.exists() && dir.isDirectory()) {
        logger.info("Checking dir {} for bundle install", dir);
        final File manifestFile = new File(dir, JarFile.MANIFEST_NAME);
        if (manifestFile.exists()) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(manifestFile);
                final Manifest mf = new Manifest(fis);
                final String symbolicName = mf.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
                if (symbolicName != null) {
                    // search bundle
                    Bundle found = getBundle(symbolicName);
                    final File tempFile = File.createTempFile(dir.getName(), "bundle");
                    try {
                        createJar(dir, tempFile, mf);
                        final InputStream in = new FileInputStream(tempFile);
                        try {
                            String location = dir.getAbsolutePath();
                            installOrUpdateBundle(found, in, location);
                            result = new InstallationResult(true, null);
                            resp.setStatus(200);
                            result.render(resp.getWriter());
                            return;
                        } catch (final BundleException be) {
                            logAndWriteError("Unable to install/update bundle from dir " + dir, be, resp);
                        }
                    } finally {
                        tempFile.delete();
                    }
                } else {
                    logAndWriteError("Manifest in " + dir + " does not have a symbolic name", resp);
                }
            } finally {
                IOUtils.closeQuietly(fis);
            }
        } else {
            result = new InstallationResult(false, "Dir " + dir + " does not have a manifest");
            logAndWriteError("Dir " + dir + " does not have a manifest", resp);
        }
    } else {
        result = new InstallationResult(false, "Dir " + dir + " does not exist");
        logAndWriteError("Dir " + dir + " does not exist", resp);
    }
}
Also used : Bundle(org.osgi.framework.Bundle) JarInputStream(java.util.jar.JarInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BundleException(org.osgi.framework.BundleException) Manifest(java.util.jar.Manifest) JarFile(java.util.jar.JarFile) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 43 with BundleException

use of org.osgi.framework.BundleException 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 44 with BundleException

use of org.osgi.framework.BundleException in project sling by apache.

the class RestartActiveBundlesTask method execute.

@Override
public void execute(final InstallationContext ctx) {
    @SuppressWarnings("unchecked") final Set<Long> ids = (Set<Long>) this.getResource().getAttribute(ATTR);
    int started = 0;
    if (ids != null) {
        final Set<Long> remove = new HashSet<Long>();
        for (final Long id : ids) {
            final Bundle bundle = this.getBundleContext().getBundle(id);
            if (bundle != null && bundle.getState() != Bundle.ACTIVE && bundle.getState() != Bundle.STARTING && bundle.getState() != Bundle.STOPPING && bundle.getState() != Bundle.UNINSTALLED) {
                try {
                    bundle.start();
                    started++;
                    ctx.log("Started bundle {}", bundle);
                    remove.add(id);
                } catch (final BundleException e) {
                    getLogger().info("Unable to start bundle {} : {}", bundle, e.getMessage());
                } catch (final IllegalStateException ie) {
                    getLogger().info("Unable to start bundle {} : {}", bundle, ie.getMessage());
                    remove.add(id);
                }
            } else {
                // bundle might be null(!)
                getLogger().debug("Bundle does not need restart: {} (state {})", bundle, (bundle == null ? "uninstalled" : bundle.getState()));
                remove.add(id);
            }
        }
        ids.removeAll(remove);
    }
    getLogger().debug("{} bundles were started", started);
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) Bundle(org.osgi.framework.Bundle) BundleException(org.osgi.framework.BundleException) HashSet(java.util.HashSet)

Example 45 with BundleException

use of org.osgi.framework.BundleException in project sling by apache.

the class BundleRemoveTask method execute.

/**
     * @see org.apache.sling.installer.api.tasks.InstallTask#execute(org.apache.sling.installer.api.tasks.InstallationContext)
     */
public void execute(InstallationContext ctx) {
    final String symbolicName = (String) getResource().getAttribute(Constants.BUNDLE_SYMBOLICNAME);
    final String version = (String) getResource().getAttribute(Constants.BUNDLE_VERSION);
    final Bundle b = BundleInfo.getMatchingBundle(this.getBundleContext(), symbolicName, version);
    if (b == null) {
        // nothing to do, so just stop
        this.setFinishedState(ResourceState.UNINSTALLED);
        return;
    }
    final int state = b.getState();
    try {
        if (state == Bundle.ACTIVE || state == Bundle.STARTING) {
            b.stop();
        }
        b.uninstall();
        ctx.log("Uninstalled bundle {} from resource {}", b, getResource());
        // if the bundle exported packages, we need to refresh
        if (BundleUtil.getFragmentHostHeader(b) == null) {
            RefreshBundlesTask.markBundleForRefresh(ctx, this.getTaskSupport(), b);
        }
        this.setFinishedState(ResourceState.UNINSTALLED);
    } catch (final BundleException be) {
        this.getLogger().info("Exception during removal of bundle " + this.getResource() + " : " + be.getMessage() + ". Retrying later.", be);
    }
}
Also used : Bundle(org.osgi.framework.Bundle) BundleException(org.osgi.framework.BundleException)

Aggregations

BundleException (org.osgi.framework.BundleException)99 Bundle (org.osgi.framework.Bundle)54 IOException (java.io.IOException)31 Test (org.junit.Test)19 File (java.io.File)15 ArrayList (java.util.ArrayList)13 InputStream (java.io.InputStream)10 FileInputStream (java.io.FileInputStream)9 BundleContext (org.osgi.framework.BundleContext)9 HashMap (java.util.HashMap)8 Map (java.util.Map)7 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)7 Hashtable (java.util.Hashtable)5 Manifest (java.util.jar.Manifest)5 ServiceReference (org.osgi.framework.ServiceReference)5 Version (org.osgi.framework.Version)5 BundleStartLevel (org.osgi.framework.startlevel.BundleStartLevel)5 LowDiskException (android.taobao.atlas.runtime.LowDiskException)4 TimeoutException (java.util.concurrent.TimeoutException)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4