Search in sources :

Example 71 with BundleException

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

the class SubsystemResource method getRegion.

public synchronized Region getRegion() throws BundleException, IOException, InvalidSyntaxException, URISyntaxException {
    if (region == null) {
        region = createRegion(getId());
        Coordination coordination = Activator.getInstance().getCoordinator().peek();
        coordination.addParticipant(new Participant() {

            @Override
            public void ended(Coordination arg0) throws Exception {
            // Nothing.
            }

            @Override
            public void failed(Coordination arg0) throws Exception {
                if (isScoped())
                    region.getRegionDigraph().removeRegion(region);
            }
        });
        if (!isApplication()) {
            setImportIsolationPolicy();
        }
    }
    return region;
}
Also used : Coordination(org.osgi.service.coordinator.Coordination) Participant(org.osgi.service.coordinator.Participant) URISyntaxException(java.net.URISyntaxException) BundleException(org.osgi.framework.BundleException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) ResolutionException(org.osgi.service.resolver.ResolutionException) SubsystemException(org.osgi.service.subsystem.SubsystemException) IOException(java.io.IOException)

Example 72 with BundleException

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

the class BundleEventHookTest method testIgnoreUninstalledOriginBundleInAsyncInstalledEvent.

/*
     * Because bundle events are queued for later asynchronous processing while
     * the root subsystem is initializing, it is possible to see an installed
     * event whose origin bundle has been uninstalled (i.e. the origin bundle's
     * revision will be null). These events should result in the installed
     * bundle being associated with the root subsystem.
     */
@Test
public void testIgnoreUninstalledOriginBundleInAsyncInstalledEvent() throws Exception {
    final Bundle core = getSubsystemCoreBundle();
    core.stop();
    final Bundle b = bundleContext.installBundle(BUNDLE_B, new FileInputStream(BUNDLE_B));
    // Ensure bundle B has a context.
    b.start();
    final AtomicReference<Bundle> a = new AtomicReference<Bundle>();
    bundleContext.addServiceListener(new ServiceListener() {

        @SuppressWarnings("unchecked")
        @Override
        public void serviceChanged(ServiceEvent event) {
            if ((event.getType() & (ServiceEvent.REGISTERED | ServiceEvent.MODIFIED)) == 0)
                return;
            if (a.get() != null)
                // We've been here before and already done what needs doing.
                return;
            ServiceReference sr = (ServiceReference) event.getServiceReference();
            bundleContext.getService(sr);
            try {
                // Queue up the installed event for bundle A using B's context.
                a.set(b.getBundleContext().installBundle(BUNDLE_A, new FileInputStream(BUNDLE_A)));
                // Ensure the origin bundle will be uninstalled before the event is processed.
                b.uninstall();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, "(&(objectClass=org.osgi.service.subsystem.Subsystem)(subsystem.id=0)(subsystem.state=RESOLVED))");
    try {
        // Before the fix, this would fail due to an NPE resulting from a
        // null bundle revision.
        core.start();
    } catch (BundleException e) {
        e.printStackTrace();
        fail("Subsystems failed to handle an asynchronous bundle installed event after the origin bundle was uninstalled");
    }
    assertBundleState(a.get(), Bundle.INSTALLED);
    assertBundleState(b, Bundle.UNINSTALLED);
    Subsystem root = getRootSubsystem();
    assertState(Subsystem.State.ACTIVE, root);
    assertConstituent(root, a.get().getSymbolicName());
}
Also used : ServiceListener(org.osgi.framework.ServiceListener) Bundle(org.osgi.framework.Bundle) ServiceEvent(org.osgi.framework.ServiceEvent) Subsystem(org.osgi.service.subsystem.Subsystem) AtomicReference(java.util.concurrent.atomic.AtomicReference) BundleException(org.osgi.framework.BundleException) FileInputStream(java.io.FileInputStream) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) BundleException(org.osgi.framework.BundleException) ServiceReference(org.osgi.framework.ServiceReference) Test(org.junit.Test)

Example 73 with BundleException

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

the class JPALifecycleTest method doBundleStoppingTest.

private void doBundleStoppingTest(Predicate<Bundle> p, String exceptionMessage) {
    Message m = new Message();
    m.message = "Hello World";
    txControl.required(() -> {
        em.persist(m);
        return null;
    });
    assertEquals(m.message, txControl.notSupported(() -> em.find(Message.class, m.id).message));
    List<Bundle> toStop = Arrays.stream(context.getBundles()).filter(p).collect(toList());
    System.out.println(toStop);
    try {
        toStop.stream().forEach(b -> {
            System.out.println("Stopping " + b.getSymbolicName());
            try {
                b.stop();
            } catch (BundleException e) {
            }
        });
        try {
            assertEquals(m.message, txControl.notSupported(() -> em.find(Message.class, m.id).message));
            fail("Should not be accessible " + (Boolean.getBoolean(IS_XA) ? "xa" : "local"));
        } catch (ScopedWorkException swe) {
            assertTrue(swe.getCause().toString(), swe.getCause() instanceof TransactionException);
            assertEquals(exceptionMessage, swe.getCause().getMessage());
        } catch (TransactionException te) {
            assertEquals(exceptionMessage, te.getMessage());
        }
    } finally {
        toStop.stream().forEach(b -> {
            System.out.println("Restarting " + b.getSymbolicName());
            try {
                b.start();
            } catch (BundleException e) {
            }
        });
        getService(JPAEntityManagerProvider.class, 5000);
    }
}
Also used : ScopedWorkException(org.osgi.service.transaction.control.ScopedWorkException) TransactionException(org.osgi.service.transaction.control.TransactionException) Message(org.apache.aries.tx.control.itests.entity.Message) Bundle(org.osgi.framework.Bundle) CoreOptions.mavenBundle(org.ops4j.pax.exam.CoreOptions.mavenBundle) BundleException(org.osgi.framework.BundleException)

Example 74 with BundleException

use of org.osgi.framework.BundleException in project logging-log4j2 by apache.

the class AbstractLoadBundleTest method testClassNotFoundErrorLogger.

/**
     * Tests LOG4J2-1637.
     */
@Test
public void testClassNotFoundErrorLogger() throws BundleException {
    final Bundle api = getApiBundle();
    final Bundle core = getCoreBundle();
    api.start();
    // fails if LOG4J2-1637 is not fixed
    try {
        core.start();
    } catch (final BundleException ex) {
        boolean shouldRethrow = true;
        final Throwable t = ex.getCause();
        if (t != null) {
            final Throwable t2 = t.getCause();
            if (t2 != null) {
                final String cause = t2.toString();
                final boolean result = // Equinox
                cause.equals("java.lang.ClassNotFoundException: org.apache.logging.log4j.Logger") || // Felix
                cause.equals("java.lang.ClassNotFoundException: org.apache.logging.log4j.Logger not found by org.apache.logging.log4j.core [2]");
                Assert.assertFalse("org.apache.logging.log4j package is not properly imported in org.apache.logging.log4j.core bundle, check that the package is exported from api and is not split between api and core", result);
                shouldRethrow = !result;
            }
        }
        if (shouldRethrow) {
            // rethrow if the cause of the exception is something else
            throw ex;
        }
    }
    core.stop();
    api.stop();
    core.uninstall();
    api.uninstall();
}
Also used : Bundle(org.osgi.framework.Bundle) BundleException(org.osgi.framework.BundleException) Test(org.junit.Test)

Example 75 with BundleException

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

the class ResourceBuilder method doBuild.

private static ResourceImpl doBuild(ResourceImpl resource, String uri, Map<String, String> headerMap, boolean removeServiceRequirements) throws BundleException {
    // Verify that only manifest version 2 is specified.
    String manifestVersion = getManifestVersion(headerMap);
    if (manifestVersion == null || !manifestVersion.equals("2")) {
        throw new BundleException("Unsupported 'Bundle-ManifestVersion' value: " + manifestVersion);
    }
    //
    // Parse bundle version.
    //
    Version bundleVersion = Version.emptyVersion;
    if (headerMap.get(Constants.BUNDLE_VERSION) != null) {
        bundleVersion = VersionTable.getVersion(headerMap.get(Constants.BUNDLE_VERSION));
    }
    //
    // Parse bundle symbolic name.
    //
    String bundleSymbolicName;
    ParsedHeaderClause bundleCap = parseBundleSymbolicName(headerMap);
    if (bundleCap == null) {
        throw new BundleException("Bundle manifest must include bundle symbolic name");
    }
    bundleSymbolicName = (String) bundleCap.attrs.get(BundleRevision.BUNDLE_NAMESPACE);
    // Now that we have symbolic name and version, create the resource
    String type = headerMap.get(Constants.FRAGMENT_HOST) == null ? IdentityNamespace.TYPE_BUNDLE : IdentityNamespace.TYPE_FRAGMENT;
    {
        Map<String, String> dirs = new HashMap<>();
        Map<String, Object> attrs = new HashMap<>();
        attrs.put(IdentityNamespace.IDENTITY_NAMESPACE, bundleSymbolicName);
        attrs.put(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE, type);
        attrs.put(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE, bundleVersion);
        CapabilityImpl identity = new CapabilityImpl(resource, IdentityNamespace.IDENTITY_NAMESPACE, dirs, attrs);
        resource.addCapability(identity);
    }
    if (uri != null) {
        Map<String, Object> attrs = new HashMap<>();
        attrs.put(ContentNamespace.CAPABILITY_URL_ATTRIBUTE, uri);
        resource.addCapability(new CapabilityImpl(resource, ContentNamespace.CONTENT_NAMESPACE, Collections.emptyMap(), attrs));
    }
    // dependencies.
    if (headerMap.get(Constants.FRAGMENT_HOST) == null) {
        // All non-fragment bundles have bundle capability.
        resource.addCapability(new CapabilityImpl(resource, BundleRevision.BUNDLE_NAMESPACE, bundleCap.dirs, bundleCap.attrs));
        // A non-fragment bundle can choose to not have a host capability.
        String attachment = bundleCap.dirs.get(Constants.FRAGMENT_ATTACHMENT_DIRECTIVE);
        attachment = (attachment == null) ? Constants.FRAGMENT_ATTACHMENT_RESOLVETIME : attachment;
        if (!attachment.equalsIgnoreCase(Constants.FRAGMENT_ATTACHMENT_NEVER)) {
            Map<String, Object> hostAttrs = new HashMap<>(bundleCap.attrs);
            Object value = hostAttrs.remove(BundleRevision.BUNDLE_NAMESPACE);
            hostAttrs.put(BundleRevision.HOST_NAMESPACE, value);
            resource.addCapability(new CapabilityImpl(resource, BundleRevision.HOST_NAMESPACE, bundleCap.dirs, hostAttrs));
        }
    }
    //
    // Parse Fragment-Host.
    //
    List<RequirementImpl> hostReqs = parseFragmentHost(resource, headerMap);
    //
    // Parse Require-Bundle
    //
    List<ParsedHeaderClause> rbClauses = parseStandardHeader(headerMap.get(Constants.REQUIRE_BUNDLE));
    rbClauses = normalizeRequireClauses(rbClauses);
    List<Requirement> rbReqs = convertRequires(rbClauses, resource);
    //
    // Parse Import-Package.
    //
    List<ParsedHeaderClause> importClauses = parseStandardHeader(headerMap.get(Constants.IMPORT_PACKAGE));
    importClauses = normalizeImportClauses(importClauses);
    List<Requirement> importReqs = convertImports(importClauses, resource);
    //
    // Parse DynamicImport-Package.
    //
    List<ParsedHeaderClause> dynamicClauses = parseStandardHeader(headerMap.get(Constants.DYNAMICIMPORT_PACKAGE));
    dynamicClauses = normalizeDynamicImportClauses(dynamicClauses);
    List<Requirement> dynamicReqs = convertImports(dynamicClauses, resource);
    //
    // Parse Require-Capability.
    //
    List<ParsedHeaderClause> requireClauses = parseStandardHeader(headerMap.get(Constants.REQUIRE_CAPABILITY));
    requireClauses = normalizeRequireCapabilityClauses(requireClauses);
    List<Requirement> requireReqs = convertRequireCapabilities(requireClauses, resource);
    //
    // Parse Bundle-RequiredExecutionEnvironment.
    //
    List<Requirement> breeReqs = parseBreeHeader(headerMap.get(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT), resource);
    //
    // Parse Export-Package.
    //
    List<ParsedHeaderClause> exportClauses = parseStandardHeader(headerMap.get(Constants.EXPORT_PACKAGE));
    exportClauses = normalizeExportClauses(exportClauses, bundleSymbolicName, bundleVersion);
    List<Capability> exportCaps = convertExports(exportClauses, resource);
    //
    // Parse Provide-Capability.
    //
    List<ParsedHeaderClause> provideClauses = parseStandardHeader(headerMap.get(Constants.PROVIDE_CAPABILITY));
    provideClauses = normalizeProvideCapabilityClauses(provideClauses);
    List<Capability> provideCaps = convertProvideCapabilities(provideClauses, resource);
    //
    // Parse Import-Service and Export-Service
    // if Require-Capability and Provide-Capability are not set for services
    //
    boolean hasServiceReferenceCapability = false;
    for (Capability cap : exportCaps) {
        hasServiceReferenceCapability |= ServiceNamespace.SERVICE_NAMESPACE.equals(cap.getNamespace());
    }
    if (!hasServiceReferenceCapability) {
        List<ParsedHeaderClause> exportServices = parseStandardHeader(headerMap.get(Constants.EXPORT_SERVICE));
        List<Capability> caps = convertExportService(exportServices, resource);
        provideCaps.addAll(caps);
    }
    boolean hasServiceReferenceRequirement = false;
    for (Requirement req : requireReqs) {
        hasServiceReferenceRequirement |= ServiceNamespace.SERVICE_NAMESPACE.equals(req.getNamespace());
    }
    if (!hasServiceReferenceRequirement) {
        List<ParsedHeaderClause> importServices = parseStandardHeader(headerMap.get(Constants.IMPORT_SERVICE));
        List<Requirement> reqs = convertImportService(importServices, resource);
        if (!reqs.isEmpty()) {
            requireReqs.addAll(reqs);
            hasServiceReferenceRequirement = true;
        }
    }
    if (hasServiceReferenceRequirement && removeServiceRequirements) {
        for (Iterator<Requirement> iterator = requireReqs.iterator(); iterator.hasNext(); ) {
            Requirement req = iterator.next();
            if (ServiceNamespace.SERVICE_NAMESPACE.equals(req.getNamespace())) {
                iterator.remove();
            }
        }
    }
    // Combine all capabilities.
    resource.addCapabilities(exportCaps);
    resource.addCapabilities(provideCaps);
    // Combine all requirements.
    resource.addRequirements(hostReqs);
    resource.addRequirements(importReqs);
    resource.addRequirements(rbReqs);
    resource.addRequirements(requireReqs);
    resource.addRequirements(dynamicReqs);
    return resource;
}
Also used : Capability(org.osgi.resource.Capability) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Requirement(org.osgi.resource.Requirement) Version(org.osgi.framework.Version) BundleException(org.osgi.framework.BundleException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

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