Search in sources :

Example 36 with BundleException

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

the class SlingServletDelegate method init.

/**
     * Initializes this servlet by loading the framework configuration
     * properties, starting the OSGi framework (Apache Felix) and exposing the
     * system bundle context and the <code>Felix</code> instance as servlet
     * context attributes.
     *
     * @throws ServletException if the framework cannot be initialized.
     */
@Override
public final void init() throws ServletException {
    // temporary holders control final setup and ensure proper
    // disposal in case of setup errors
    Sling tmpSling = null;
    Servlet tmpDelegatee = null;
    try {
        log("Starting Apache Sling in " + slingHome);
        // read the default parameters
        Map<String, String> props = loadConfigProperties(slingHome);
        Logger logger = new ServletContextLogger(getServletContext());
        LaunchpadContentProvider rp = new ServletContextResourceProvider(getServletContext());
        tmpSling = SlingBridge.getSlingBridge(notifiable, logger, rp, props, getServletContext());
        // set up the OSGi HttpService proxy servlet
        tmpDelegatee = new ProxyServlet();
        tmpDelegatee.init(getServletConfig());
        // them destroyed in the finally clause.
        if (servletDestroyed) {
            log("SlingServletDelegate destroyed while starting Apache Sling, shutting Apache Sling down");
        } else {
            // set the fields now
            sling = tmpSling;
            delegatee = tmpDelegatee;
            // reset temporary holders to prevent destroyal
            tmpSling = null;
            tmpDelegatee = null;
            log("Apache Sling successfully started in " + slingHome);
        }
    } catch (BundleException be) {
        throw new ServletException("Failed to start Apache Sling in " + slingHome, be);
    } catch (ServletException se) {
        throw new ServletException("Failed to start bridge servlet for Apache Sling", se);
    } catch (Throwable t) {
        throw new ServletException("Uncaught Failure starting Apache Sling", t);
    } finally {
        // clean up temporary fields
        if (tmpDelegatee != null) {
            tmpDelegatee.destroy();
        }
        if (tmpSling != null) {
            tmpSling.destroy();
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) LaunchpadContentProvider(org.apache.sling.launchpad.api.LaunchpadContentProvider) ProxyServlet(org.apache.felix.http.proxy.ProxyServlet) ProxyServlet(org.apache.felix.http.proxy.ProxyServlet) Servlet(javax.servlet.Servlet) GenericServlet(javax.servlet.GenericServlet) BundleException(org.osgi.framework.BundleException) Logger(org.apache.felix.framework.Logger) Sling(org.apache.sling.launchpad.base.impl.Sling)

Example 37 with BundleException

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

the class Sling method loadConfigProperties.

// ---------- Configuration Loading
/**
     * Loads the configuration properties in the configuration property file
     * associated with the framework installation; these properties are
     * accessible to the framework and to bundles and are intended for
     * configuration purposes. By default, the configuration property file is
     * located in the <tt>conf/</tt> directory of the Felix installation
     * directory and is called "<tt>config.properties</tt>". The
     * installation directory of Felix is assumed to be the parent directory of
     * the <tt>framework.jar</tt> file as found on the system class path property.
     * The precise file from which to load configuration properties can be set
     * by initializing the "<tt>framework.config.properties</tt>" system
     * property to an arbitrary URL.
     *
     * @return A <tt>Properties</tt> instance or <tt>null</tt> if there was
     *         an error.
     */
private Map<String, String> loadConfigProperties(final Map<String, String> propOverwrite) throws BundleException {
    // The config properties file is either specified by a system
    // property or it is in the same directory as the Felix JAR file.
    // Try to load it from one of these places.
    final Map<String, String> staticProps = new HashMap<String, String>();
    // Read the embedded (default) properties file.
    this.load(staticProps, CONFIG_PROPERTIES);
    // resolve inclusions (and remove property)
    this.loadIncludes(staticProps, null);
    // overwrite default properties with initial overwrites
    if (propOverwrite != null) {
        staticProps.putAll(propOverwrite);
    }
    // check whether sling.home is overwritten by system property
    String slingHome = staticProps.get(SharedConstants.SLING_HOME);
    if (slingHome == null || slingHome.length() == 0) {
        throw new BundleException("sling.home property is missing, cannot start");
    }
    // resolve variables and ensure sling.home is an absolute path
    slingHome = Util.substVars(slingHome, SharedConstants.SLING_HOME, null, staticProps);
    File slingHomeFile = new File(slingHome).getAbsoluteFile();
    slingHome = slingHomeFile.getAbsolutePath();
    // overlay with ${sling.home}/sling.properties
    this.logger.log(Logger.LOG_INFO, "Starting Apache Sling in " + slingHome);
    File propFile = getSlingProperties(slingHome, staticProps);
    this.load(staticProps, propFile);
    // migrate old properties to new properties
    migrateProp(staticProps, "framework.cache.profiledir", Constants.FRAMEWORK_STORAGE);
    migrateProp(staticProps, "sling.osgi-core-packages", "osgi-core-packages");
    migrateProp(staticProps, "sling.osgi-compendium-services", "osgi-compendium-services");
    // migrate initial start level property: Felix used to have
    // framework.startlevel.framework, later moved to org.osgi.framework.startlevel
    // and finally now uses org.osgi.framework.startlevel.beginning as
    // speced in the latest R 4.2 draft (2009/03/10). We first check the
    // intermediate Felix property, then the initial property, thus allowing
    // the older (and more probable value) to win
    migrateProp(staticProps, "org.osgi.framework.startlevel", Constants.FRAMEWORK_BEGINNING_STARTLEVEL);
    migrateProp(staticProps, "framework.startlevel.framework", Constants.FRAMEWORK_BEGINNING_STARTLEVEL);
    // create a copy of the properties to perform variable substitution
    final Map<String, String> runtimeProps = new HashMap<String, String>();
    runtimeProps.putAll(staticProps);
    // check system properties for any overrides (except sling.home !)
    String ignoreSystemProperties = runtimeProps.get(SLING_IGNORE_SYSTEM_PROPERTIES);
    if (!"true".equalsIgnoreCase(ignoreSystemProperties)) {
        for (String name : runtimeProps.keySet()) {
            String sysProp = System.getProperty(name);
            if (sysProp != null) {
                runtimeProps.put(name, sysProp);
            }
        }
    }
    // resolve inclusions again
    this.loadIncludes(runtimeProps, slingHome);
    // overwrite properties, this is not persisted as such
    this.loadPropertiesOverride(runtimeProps);
    // resolve boot delegation and system packages
    this.resolve(runtimeProps, "org.osgi.framework.bootdelegation", "sling.bootdelegation.");
    this.resolve(runtimeProps, "org.osgi.framework.system.packages", "sling.system.packages.");
    // reset back the sling home property
    // might have been overwritten by system properties, included
    // files or the sling.properties file
    staticProps.put(SharedConstants.SLING_HOME, slingHome);
    runtimeProps.put(SharedConstants.SLING_HOME, slingHome);
    runtimeProps.put(SLING_HOME_URL, slingHomeFile.toURI().toString());
    // add property file locations
    runtimeProps.put(SharedConstants.SLING_PROPERTIES, propFile.getAbsolutePath());
    runtimeProps.put(SharedConstants.SLING_PROPERTIES_URL, propFile.toURI().toString());
    // Perform variable substitution for system properties.
    for (Entry<String, String> entry : runtimeProps.entrySet()) {
        entry.setValue(Util.substVars(entry.getValue(), entry.getKey(), null, runtimeProps));
    }
    // look for context:/ URLs to substitute
    for (Entry<String, String> entry : runtimeProps.entrySet()) {
        String name = entry.getKey();
        String value = entry.getValue();
        if (value != null && value.startsWith("context:/")) {
            String path = value.substring("context:/".length() - 1);
            InputStream src = this.resourceProvider.getResourceAsStream(path);
            if (src != null) {
                File target = new File(slingHome, path);
                OutputStream dest = null;
                try {
                    // only copy file if not existing
                    if (!target.exists()) {
                        target.getParentFile().mkdirs();
                        dest = new FileOutputStream(target);
                        byte[] buf = new byte[2048];
                        int rd;
                        while ((rd = src.read(buf)) >= 0) {
                            dest.write(buf, 0, rd);
                        }
                    }
                    // after copying replace property and add url property
                    entry.setValue(target.getAbsolutePath());
                    // also set the new property on the unsubstituted props
                    staticProps.put(name, "${sling.home}" + path);
                } catch (IOException ioe) {
                    this.logger.log(Logger.LOG_ERROR, "Cannot copy file " + value + " to " + target, ioe);
                } finally {
                    if (dest != null) {
                        try {
                            dest.close();
                        } catch (IOException ignore) {
                        }
                    }
                    try {
                        src.close();
                    } catch (IOException ignore) {
                    }
                }
            }
        }
    }
    // write the unsubstituted properties back to the overlay file
    OutputStream os = null;
    try {
        // ensure parent folder(s)
        propFile.getParentFile().mkdirs();
        os = new FileOutputStream(propFile);
        // copy the values into a temporary properties structure to store
        Properties tmp = new Properties();
        tmp.putAll(staticProps);
        // remove properties where overlay makes no sense
        tmp.remove(SharedConstants.SLING_HOME);
        tmp.remove(SharedConstants.SLING_LAUNCHPAD);
        tmp.remove(SharedConstants.SLING_PROPERTIES);
        tmp.store(os, "Overlay properties for configuration");
    } catch (Exception ex) {
        this.logger.log(Logger.LOG_ERROR, "Error loading overlay properties from " + propFile, ex);
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException ex2) {
            // Nothing we can do.
            }
        }
    }
    return runtimeProps;
}
Also used : HashMap(java.util.HashMap) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) Properties(java.util.Properties) BundleException(org.osgi.framework.BundleException) IOException(java.io.IOException) FileOutputStream(java.io.FileOutputStream) BundleException(org.osgi.framework.BundleException) File(java.io.File)

Example 38 with BundleException

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

the class MainDelegate method start.

@Override
public boolean start() {
    Map<String, String> props = new HashMap<String, String>();
    // parse the command line (exit in case of failure)
    if (commandLine == null) {
        setCommandLine(new HashMap<String, String>());
    }
    // if sling.home was set on the command line, set it in the properties
    if (slingHome != null) {
        props.put(SharedConstants.SLING_HOME, slingHome);
    } else if (commandLine.containsKey(SharedConstants.SLING_HOME)) {
        props.put(SharedConstants.SLING_HOME, commandLine.get(SharedConstants.SLING_HOME));
    }
    // ensure sling.launchpad is set
    if (!commandLine.containsKey(SharedConstants.SLING_LAUNCHPAD)) {
        commandLine.put(SharedConstants.SLING_LAUNCHPAD, slingHome);
    }
    // check sling.properties in the command line
    final String slingPropertiesProp = commandLine.remove(SharedConstants.SLING_PROPERTIES);
    if (slingPropertiesProp != null) {
        props.put(SharedConstants.SLING_PROPERTIES, slingPropertiesProp);
    }
    // set up and configure Felix Logger
    int logLevel;
    if (!commandLine.containsKey(PROP_LOG_LEVEL)) {
        logLevel = DEFAULT_LOG_LEVEL;
    } else {
        logLevel = toLogLevelInt(commandLine.get(PROP_LOG_LEVEL), DEFAULT_LOG_LEVEL);
        commandLine.put(LOG_LEVEL_PROP, String.valueOf(logLevel));
    }
    final Logger logger = new SlingLogger();
    // default log level: prevent tons of needless WARN from the framework
    logger.setLogLevel(Logger.LOG_ERROR);
    if (System.getProperty(PROP_BOOT_LOG_LEVEL) != null) {
        try {
            logger.setLogLevel(Integer.parseInt(System.getProperty(PROP_BOOT_LOG_LEVEL)));
        } catch (final NumberFormatException ex) {
        // just ignore
        }
    }
    try {
        LaunchpadContentProvider resProvider = new ClassLoaderResourceProvider(getClass().getClassLoader());
        // creating the instance launches the framework and we are done here
        // ..
        sling = new Sling(notifiable, logger, resProvider, props) {

            // overwrite the loadPropertiesOverride method to inject the
            // command line arguments unconditionally. These will not be
            // persisted in any properties file, though
            @Override
            protected void loadPropertiesOverride(Map<String, String> properties) {
                if (commandLine != null) {
                    properties.putAll(commandLine);
                }
                // Display port number on console, in case HttpService doesn't. This is logged as late as
                // possible in order to pick up defaults from the Sling property files, although system
                // property substitutions will be missed.
                info("HTTP server port: " + properties.get(PROP_PORT), null);
            }
        };
        // we successfully started it
        return true;
    } catch (BundleException be) {
        error("Failed to Start OSGi framework", be);
    }
    // we failed to start
    return false;
}
Also used : HashMap(java.util.HashMap) Logger(org.apache.felix.framework.Logger) Sling(org.apache.sling.launchpad.base.impl.Sling) LaunchpadContentProvider(org.apache.sling.launchpad.api.LaunchpadContentProvider) ClassLoaderResourceProvider(org.apache.sling.launchpad.base.impl.ClassLoaderResourceProvider) BundleException(org.osgi.framework.BundleException)

Example 39 with BundleException

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

the class BootstrapInstaller method installBundle.

/**
     * @param bundleJar the jar file for the bundle to install
     * @param startLevel the start level to use for this bundle
     * @param context The <code>BundleContext</code> used to install the new Bundles.
     * @param currentBundles The currently installed Bundles indexed by their
     *            Bundle location.
     * @param installed The list of Bundles installed by this method. Each
     *            Bundle successfully installed is added to this list.
     * @param startLevelService the service which sets the start level
     *
     * @return <code>true</code> if a system bundle fragment was updated which
     *      requires the framework to restart.
     */
private boolean installBundle(final File bundleJar, final int startLevel, final Map<String, Bundle> currentBundles, final List<Bundle> installed) {
    // get the manifest for the bundle information
    Manifest manifest = getManifest(bundleJar);
    if (manifest == null) {
        logger.log(Logger.LOG_ERROR, "Ignoring " + bundleJar + ": Cannot read manifest");
        // SHORT CIRCUIT
        return false;
    }
    // ensure a symbolic name in the jar file
    String symbolicName = getBundleSymbolicName(manifest);
    if (symbolicName == null) {
        logger.log(Logger.LOG_ERROR, "Ignoring " + bundleJar + ": Missing " + Constants.BUNDLE_SYMBOLICNAME + " in manifest");
        // SHORT CIRCUIT
        return false;
    }
    // check for an installed Bundle with the symbolic name
    Bundle installedBundle = currentBundles.get(symbolicName);
    if (ignore(installedBundle, manifest)) {
        logger.log(Logger.LOG_INFO, "Ignoring " + bundleJar + ": More recent version already installed");
        // SHORT CIRCUIT
        return false;
    }
    // try to access the JAR file, ignore if not possible
    InputStream ins;
    try {
        ins = new FileInputStream(bundleJar);
    } catch (FileNotFoundException e) {
        // SHORT CIRCUIT
        return false;
    }
    final boolean requireRestart;
    if (installedBundle != null) {
        // if the installed bundle is an extension fragment we have to
        // restart the framework after completing the installation
        // or upgrade of all new bundles
        requireRestart = isSystemBundleFragment(installedBundle);
        try {
            installedBundle.update(ins);
            logger.log(Logger.LOG_INFO, "Bundle " + installedBundle.getSymbolicName() + " updated from " + bundleJar);
            // optionally set the start level
            if (startLevel > 0) {
                installedBundle.adapt(BundleStartLevel.class).setStartLevel(startLevel);
            }
        } catch (BundleException be) {
            logger.log(Logger.LOG_ERROR, "Bundle update from " + bundleJar + " failed", be);
        }
    } else {
        // restart is not required for any bundle installation at this
        // stage
        requireRestart = false;
        // install the JAR file as a bundle
        String path = bundleJar.getPath();
        String location = SCHEME + path.substring(path.lastIndexOf('/') + 1);
        try {
            Bundle theBundle = bundleContext.installBundle(location, ins);
            logger.log(Logger.LOG_INFO, "Bundle " + theBundle.getSymbolicName() + " installed from " + location);
            // finally add the bundle to the list for later start
            installed.add(theBundle);
            // optionally set the start level
            if (startLevel > 0) {
                theBundle.adapt(BundleStartLevel.class).setStartLevel(startLevel);
            }
        } catch (BundleException be) {
            logger.log(Logger.LOG_ERROR, "Bundle installation from " + location + " failed", be);
        }
    }
    return requireRestart;
}
Also used : BundleStartLevel(org.osgi.framework.startlevel.BundleStartLevel) Bundle(org.osgi.framework.Bundle) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) BundleException(org.osgi.framework.BundleException) Manifest(java.util.jar.Manifest) FileInputStream(java.io.FileInputStream)

Example 40 with BundleException

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

the class BundleInstallUpgradeExceptionRetryTest method testUpdateSuccedsWithLessThanMaxRetrys.

@Test
public void testUpdateSuccedsWithLessThanMaxRetrys() throws Exception {
    // install version 1.1 and fail activation with exception all attempts
    final Object listener = this.startObservingBundleEvents();
    final AtomicReference<ServiceRegistration<AtomicInteger>> ref = new AtomicReference<ServiceRegistration<AtomicInteger>>(null);
    final AtomicInteger counter = new AtomicInteger(3);
    bundleContext.addBundleListener(new SynchronousBundleListener() {

        @Override
        public void bundleChanged(org.osgi.framework.BundleEvent event) {
            if (event.getType() == org.osgi.framework.BundleEvent.STOPPED && event.getBundle().getSymbolicName().equals(symbolicName) && event.getBundle().getVersion().equals(new Version("1.0.0"))) {
                if (ref.get() == null) {
                    try {
                        event.getBundle().start();
                        ref.set(bundleContext.registerService(AtomicInteger.class, counter, null));
                    } catch (BundleException e) {
                    }
                } else {
                    ref.getAndSet(null).unregister();
                    if (counter.get() == 0) {
                        bundleContext.removeBundleListener(this);
                    }
                }
            }
        }
    });
    installer.updateResources(URL_SCHEME, getInstallableResource(createTestBundle(new Version("2.0.0"))), null);
    try {
        long time = 0;
        while (counter.get() >= 0 && time < 1000) {
            sleep(100);
            time += 100;
        }
        assertBundle("After installing", symbolicName, "2.0.0", Bundle.ACTIVE);
    } finally {
        if (ref.get() != null) {
            ref.get().unregister();
        }
    }
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Version(org.osgi.framework.Version) BundleException(org.osgi.framework.BundleException) SynchronousBundleListener(org.osgi.framework.SynchronousBundleListener) ServiceRegistration(org.osgi.framework.ServiceRegistration) Test(org.junit.Test)

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