Search in sources :

Example 71 with BundleRevision

use of org.osgi.framework.wiring.BundleRevision in project ddf by codice.

the class ApplicationServiceImplTest method createMockFeaturesService.

/**
     * Creates a mock {@code FeaturesService} object consisting of all of the
     * features contained in a {@code Set} of {@code Repository} objects. Each
     * {@code Feature} will be in the <i>installed</i> state unless it is
     * contained in the received set of features that are not to be installed.
     * Each {@code Bundle} will be in the {@code Bundle#ACTIVE} state and the
     * {@code BundleState#Active} extended bundle state (as reported by a
     * dependency injection framework) unless it is contained in the received
     * set of {@code Bundle}s that are not to be active, in which case the
     * {@code Bundle} will be in the {@code Bundle#INSTALLED} state and the
     * {@code BundleState#Installed} extended bundle state.
     * <p>
     * Note that not all of the state and {@code Bundle} information is
     * contained in the {@code FeaturesService}. As such, this method stores
     * some of the required information in the class's {@code #bundleContext}
     * and {@code bundleStateServices}. As such, these objects must be
     * re-instantiated for each test (i.e., they must be instantiated in the
     * {@link #setUp()} method).
     *
     * @param repos                A {@code Set} of {@link Repository} objects from which to
     *                             obtain the {@link Feature}s that are to be included in the
     *                             mock {@code FeaturesService}
     * @param notInstalledFeatures A {@code Set} of {@code Feature}s that the
     *                             {@code FeaturesService} should report as not installed
     * @param inactiveBundles      A {@code Set} of {@link BundleInfo}s containing the locations
     *                             of {@code Bundle}s that should be set to inactive and for
     *                             which the {@link BundleStateService} contained in index 0 of
     *                             {@link #bundleStateServices} should report a
     *                             {@link BundleState#Installed} state.
     * @return A mock {@link FeaturesService} with {@link Feature}s and
     * {@link Bundle}s in the requested states.
     * @throws Exception
     */
private FeaturesService createMockFeaturesService(Set<Repository> repos, Set<Feature> notInstalledFeatures, Set<BundleInfo> inactiveBundles) throws Exception {
    if (LOGGER.isTraceEnabled()) {
        for (Repository repo : repos) {
            for (Feature feature : repo.getFeatures()) {
                LOGGER.trace("Repo Feature: {}", feature);
                LOGGER.trace("Repo Feature name/version: {}/{}", feature.getName(), feature.getVersion());
                LOGGER.trace("Dependencies: ");
                for (Dependency depFeature : feature.getDependencies()) {
                    LOGGER.trace("Dependency Feature: {}", depFeature);
                    LOGGER.trace("Dependency Feature name/version: {}/{}", depFeature.getName(), depFeature.getVersion());
                }
            }
        }
    }
    if (null == notInstalledFeatures) {
        notInstalledFeatures = new HashSet<Feature>();
    }
    if (null == inactiveBundles) {
        inactiveBundles = new HashSet<BundleInfo>();
    }
    Set<String> installedBundleLocations = new HashSet<String>();
    for (BundleInfo bundleInfo : inactiveBundles) {
        installedBundleLocations.add(bundleInfo.getLocation());
    }
    FeaturesService featuresService = mock(FeaturesService.class);
    Set<Feature> featuresSet = new HashSet<Feature>();
    BundleRevision mockBundleRevision = mock(BundleRevision.class);
    when(mockBundleRevision.getTypes()).thenReturn(0);
    for (Repository curRepo : repos) {
        for (Feature curFeature : curRepo.getFeatures()) {
            featuresSet.add(curFeature);
            when(featuresService.getFeature(curFeature.getName())).thenReturn(curFeature);
            when(featuresService.getFeature(curFeature.getName(), curFeature.getVersion())).thenReturn(curFeature);
            // TODO: File Karaf bug that necessitates this, then reference
            // it here.
            when(featuresService.getFeature(curFeature.getName(), "0.0.0")).thenReturn(curFeature);
            when(featuresService.isInstalled(curFeature)).thenReturn(!notInstalledFeatures.contains(curFeature));
            // of that bundle, this logic will need to be modified.
            for (BundleInfo bundleInfo : curFeature.getBundles()) {
                if (installedBundleLocations.contains(bundleInfo.getLocation())) {
                    Bundle mockInstalledBundle = mock(Bundle.class);
                    when(mockInstalledBundle.getState()).thenReturn(Bundle.INSTALLED);
                    when(mockInstalledBundle.adapt(BundleRevision.class)).thenReturn(mockBundleRevision);
                    when(bundleContext.getBundle(bundleInfo.getLocation())).thenReturn(mockInstalledBundle);
                    when(bundleStateServices.get(0).getState(mockInstalledBundle)).thenReturn(BundleState.Installed);
                } else {
                    Bundle mockActiveBundle = mock(Bundle.class);
                    when(mockActiveBundle.getState()).thenReturn(Bundle.ACTIVE);
                    when(mockActiveBundle.adapt(BundleRevision.class)).thenReturn(mockBundleRevision);
                    when(bundleContext.getBundle(bundleInfo.getLocation())).thenReturn(mockActiveBundle);
                    when(bundleStateServices.get(0).getState(mockActiveBundle)).thenReturn(BundleState.Active);
                }
            }
        }
    }
    when(featuresService.listRepositories()).thenReturn(repos.toArray(new Repository[repos.size()]));
    when(featuresService.listFeatures()).thenReturn(featuresSet.toArray(new Feature[] {}));
    return featuresService;
}
Also used : Bundle(org.osgi.framework.Bundle) Dependency(org.apache.karaf.features.Dependency) Mockito.anyString(org.mockito.Mockito.anyString) Feature(org.apache.karaf.features.Feature) Repository(org.apache.karaf.features.Repository) BundleInfo(org.apache.karaf.features.BundleInfo) BundleRevision(org.osgi.framework.wiring.BundleRevision) FeaturesService(org.apache.karaf.features.FeaturesService) HashSet(java.util.HashSet)

Example 72 with BundleRevision

use of org.osgi.framework.wiring.BundleRevision in project bnd by bndtools.

the class AgentServer method getBundleRevisons.

/**
	 * Return the bundle revisions
	 */
@Override
public List<BundleRevisionDTO> getBundleRevisons(long... bundleId) throws Exception {
    Bundle[] bundles;
    if (bundleId.length == 0) {
        bundles = context.getBundles();
    } else {
        bundles = new Bundle[bundleId.length];
        for (int i = 0; i < bundleId.length; i++) {
            bundles[i] = context.getBundle(bundleId[i]);
        }
    }
    List<BundleRevisionDTO> revisions = new ArrayList<BundleRevisionDTO>(bundles.length);
    for (Bundle b : bundles) {
        BundleRevision resource = b.adapt(BundleRevision.class);
        BundleRevisionDTO bwd = toDTO(resource);
        revisions.add(bwd);
    }
    return revisions;
}
Also used : BundleRevisionDTO(org.osgi.framework.wiring.dto.BundleRevisionDTO) Bundle(org.osgi.framework.Bundle) ArrayList(java.util.ArrayList) BundleRevision(org.osgi.framework.wiring.BundleRevision)

Example 73 with BundleRevision

use of org.osgi.framework.wiring.BundleRevision in project rt.equinox.framework by eclipse.

the class StateImpl method resolve.

private StateDelta resolve(boolean incremental, BundleDescription[] reResolve, BundleDescription[] triggers) {
    fullyLoad();
    synchronized (this.monitor) {
        if (resolver == null)
            // $NON-NLS-1$
            throw new IllegalStateException("no resolver set");
        if (resolving == true)
            // $NON-NLS-1$
            throw new IllegalStateException("An attempt to start a nested resolve process has been detected.");
        try {
            resolving = true;
            if (!incremental) {
                resolved = false;
                reResolve = getBundles();
                // need to get any removal pendings before flushing
                if (removalPendings.size() > 0) {
                    BundleDescription[] removed = internalGetRemovalPending();
                    reResolve = mergeBundles(reResolve, removed);
                }
                flush(reResolve);
            } else {
                if (resolved && reResolve == null)
                    return new StateDeltaImpl(this);
                if (developmentMode) {
                    // in dev mode we need to aggressively flush removal pendings
                    if (removalPendings.size() > 0) {
                        BundleDescription[] removed = internalGetRemovalPending();
                        reResolve = mergeBundles(reResolve, removed);
                    }
                }
                if (reResolve == null)
                    reResolve = internalGetRemovalPending();
                if (triggers == null) {
                    Set<BundleDescription> triggerSet = new HashSet<>();
                    Collection<BundleDescription> closure = getDependencyClosure(Arrays.asList(reResolve));
                    for (BundleDescription toRefresh : closure) {
                        Bundle bundle = toRefresh.getBundle();
                        if (bundle != null && (bundle.getState() & (Bundle.INSTALLED | Bundle.UNINSTALLED | Bundle.RESOLVED)) == 0)
                            triggerSet.add(toRefresh);
                    }
                    triggers = triggerSet.toArray(new BundleDescription[triggerSet.size()]);
                }
            }
            // use the Headers class to handle ignoring case while matching keys (bug 180817)
            @SuppressWarnings("unchecked") CaseInsensitiveDictionaryMap<Object, Object>[] tmpPlatformProperties = new CaseInsensitiveDictionaryMap[platformProperties.length];
            for (int i = 0; i < platformProperties.length; i++) {
                tmpPlatformProperties[i] = new CaseInsensitiveDictionaryMap<>(platformProperties[i].size());
                for (Enumeration<Object> keys = platformProperties[i].keys(); keys.hasMoreElements(); ) {
                    Object key = keys.nextElement();
                    tmpPlatformProperties[i].put(key, platformProperties[i].get(key));
                }
            }
            ResolverHookFactory currentFactory = hookFactory;
            if (currentFactory != null) {
                @SuppressWarnings("unchecked") Collection<BundleRevision> triggerRevisions = Collections.unmodifiableCollection(triggers == null ? Collections.EMPTY_LIST : Arrays.asList((BundleRevision[]) triggers));
                begin(triggerRevisions);
            }
            ResolverHookException error = null;
            try {
                resolver.resolve(reResolve, tmpPlatformProperties);
            } catch (ResolverHookException e) {
                error = e;
                resolverErrors.clear();
            }
            resolved = removalPendings.size() == 0;
            StateDeltaImpl savedChanges = changes == null ? new StateDeltaImpl(this) : changes;
            savedChanges.setResolverHookException(error);
            changes = new StateDeltaImpl(this);
            if (savedChanges.getChanges().length > 0)
                updateTimeStamp();
            return savedChanges;
        } finally {
            resolving = false;
        }
    }
}
Also used : ResolverHookFactory(org.osgi.framework.hooks.resolver.ResolverHookFactory) BundleRevision(org.osgi.framework.wiring.BundleRevision)

Example 74 with BundleRevision

use of org.osgi.framework.wiring.BundleRevision in project rt.equinox.framework by eclipse.

the class SystemBundleTests method testSystemCapabilitiesBug522125.

public void testSystemCapabilitiesBug522125() throws URISyntaxException, FileNotFoundException, IOException, BundleException, InterruptedException {
    String frameworkLocation = OSGiTestsActivator.getContext().getProperty(EquinoxConfiguration.PROP_FRAMEWORK);
    URI uri = new URI(frameworkLocation);
    File f = new File(uri);
    if (!f.isFile()) {
        Assert.fail("Cannot test when framework location is a directory: " + f.getAbsolutePath());
    }
    File testDestination = OSGiTestsActivator.getContext().getDataFile(getName() + ".framework.jar");
    BaseSecurityTest.copy(new FileInputStream(f), testDestination);
    FilePath userDir = new FilePath(System.getProperty("user.dir"));
    FilePath testPath = new FilePath(testDestination);
    String relative = userDir.makeRelative(testPath);
    System.out.println(relative);
    URL relativeURL = new URL("file:" + relative);
    relativeURL.openStream().close();
    final ClassLoader osgiClassLoader = getClass().getClassLoader();
    URLClassLoader cl = new URLClassLoader(new URL[] { relativeURL }) {

        @Override
        protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
            if (name.startsWith("org.osgi.")) {
                return osgiClassLoader.loadClass(name);
            }
            return super.loadClass(name, resolve);
        }
    };
    ServiceLoader<FrameworkFactory> sLoader = ServiceLoader.load(FrameworkFactory.class, cl);
    FrameworkFactory factory = sLoader.iterator().next();
    // $NON-NLS-1$
    File config = OSGiTestsActivator.getContext().getDataFile(getName());
    Map<String, String> configuration = new HashMap<String, String>();
    configuration.put(Constants.FRAMEWORK_STORAGE, config.getAbsolutePath());
    configuration.put(EquinoxConfiguration.PROP_FRAMEWORK, relativeURL.toExternalForm());
    Framework framework = factory.newFramework(configuration);
    framework.init();
    framework.stop();
    framework.waitForStop(5000);
    BundleRevision systemRevision1 = framework.adapt(BundleRevision.class);
    int capCount1 = systemRevision1.getCapabilities(null).size();
    framework = factory.newFramework(configuration);
    framework.init();
    framework.stop();
    framework.waitForStop(5000);
    BundleRevision systemRevision2 = framework.adapt(BundleRevision.class);
    int capCount2 = systemRevision2.getCapabilities(null).size();
    Assert.assertEquals("Wrong number of capabilities", capCount1, capCount2);
}
Also used : FilePath(org.eclipse.osgi.framework.util.FilePath) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) URI(java.net.URI) FileInputStream(java.io.FileInputStream) URL(java.net.URL) FrameworkFactory(org.osgi.framework.launch.FrameworkFactory) URLClassLoader(java.net.URLClassLoader) BundleRevision(org.osgi.framework.wiring.BundleRevision) URLClassLoader(java.net.URLClassLoader) File(java.io.File) Framework(org.osgi.framework.launch.Framework)

Example 75 with BundleRevision

use of org.osgi.framework.wiring.BundleRevision in project rt.equinox.framework by eclipse.

the class SystemBundleTests method testBug405919.

public void testBug405919() throws Exception {
    File config = OSGiTestsActivator.getContext().getDataFile(getName());
    config.mkdirs();
    Map<String, Object> configuration = new HashMap<String, Object>();
    configuration.put(Constants.FRAMEWORK_STORAGE, config.getAbsolutePath());
    configuration.put("osgi.framework", "boo");
    // Initialize and start a framework specifying an invalid osgi.framework configuration value.
    Equinox equinox = null;
    try {
        equinox = new Equinox(configuration);
        equinox.start();
    } catch (NullPointerException e) {
        fail("failed to accept an invalid value for osgi.framework", e);
    }
    try {
        // Make sure the framework can install and start a bundle.
        BundleContext systemContext = equinox.getBundleContext();
        try {
            Bundle tb1 = systemContext.installBundle(installer.getBundleLocation("test.bug375784"));
            tb1.start();
        } catch (BundleException e) {
            fail("failed to install and start test bundle", e);
        }
        // Check the capabilities and requirements of the system bundle.
        BundleRevision inner = systemContext.getBundle().adapt(BundleRevision.class);
        BundleRevision outer = getContext().getBundle(0).adapt(BundleRevision.class);
        // Capabilities.
        List<Capability> innerCaps = inner.getCapabilities(null);
        List<Capability> outerCaps = outer.getCapabilities(null);
        assertEquals("Number of capabilities differ", outerCaps.size(), innerCaps.size());
        for (int i = 0; i < innerCaps.size(); i++) {
            Capability innerCap = innerCaps.get(i);
            Capability outerCap = innerCaps.get(i);
            assertEquals("Capability namespaces differ: " + outerCap.getNamespace(), outerCap.getNamespace(), innerCap.getNamespace());
            String namespace = outerCap.getNamespace();
            if (NativeNamespace.NATIVE_NAMESPACE.equals(namespace) || "eclipse.platform".equals(namespace)) {
                // Ignore these because they are known to differ.
                continue;
            }
            assertEquals("Capability attributes differ: " + outerCap.getNamespace(), outerCap.getAttributes(), innerCap.getAttributes());
            assertEquals("Capability directives differ: " + outerCap.getNamespace(), outerCap.getDirectives(), innerCap.getDirectives());
        }
        // Requirements.
        List<Requirement> innerReqs = inner.getRequirements(null);
        List<Requirement> outerReqs = outer.getRequirements(null);
        assertEquals("Number of requirements differ", outerReqs.size(), innerReqs.size());
        for (int i = 0; i < innerReqs.size(); i++) {
            Requirement innerReq = innerReqs.get(i);
            Requirement outerReq = innerReqs.get(i);
            assertEquals("Requirement namespaces differ: " + outerReq.getNamespace(), outerReq.getNamespace(), innerReq.getNamespace());
            assertEquals("Requirement attributes differ: " + outerReq.getNamespace(), outerReq.getAttributes(), innerReq.getAttributes());
            assertEquals("Requirement directives differ: " + outerReq.getNamespace(), outerReq.getDirectives(), innerReq.getDirectives());
        }
    } finally {
        equinox.stop();
        equinox.waitForStop(5000);
    }
}
Also used : BundleCapability(org.osgi.framework.wiring.BundleCapability) Capability(org.osgi.resource.Capability) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Bundle(org.osgi.framework.Bundle) BundleRequirement(org.osgi.framework.wiring.BundleRequirement) Requirement(org.osgi.resource.Requirement) Equinox(org.eclipse.osgi.launch.Equinox) BundleRevision(org.osgi.framework.wiring.BundleRevision) BundleException(org.osgi.framework.BundleException) File(java.io.File) BundleContext(org.osgi.framework.BundleContext)

Aggregations

BundleRevision (org.osgi.framework.wiring.BundleRevision)79 Bundle (org.osgi.framework.Bundle)42 ArrayList (java.util.ArrayList)24 HashMap (java.util.HashMap)18 BundleWiring (org.osgi.framework.wiring.BundleWiring)14 BundleCapability (org.osgi.framework.wiring.BundleCapability)13 Test (org.junit.Test)12 Map (java.util.Map)11 BundleRequirement (org.osgi.framework.wiring.BundleRequirement)11 Resource (org.osgi.resource.Resource)11 HashSet (java.util.HashSet)9 BundleRevisions (org.osgi.framework.wiring.BundleRevisions)9 BundleContext (org.osgi.framework.BundleContext)8 BundleException (org.osgi.framework.BundleException)8 List (java.util.List)7 BundleConstituent (org.apache.aries.subsystem.core.internal.BundleResourceInstaller.BundleConstituent)7 BundleWire (org.osgi.framework.wiring.BundleWire)7 Requirement (org.osgi.resource.Requirement)7 File (java.io.File)6 Collection (java.util.Collection)6