org.osgi.framework.BundleException Java Examples

The following examples show how to use org.osgi.framework.BundleException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Bundles.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Install a new bundle.
 *
 * @param location The location to be installed
 */
BundleImpl install(final String location, final InputStream in, final Bundle caller)
  throws BundleException
{
  checkIllegalState();
  BundleImpl b;
  synchronized (this) {
    b = bundles.get(location);
    if (b != null) {
      if (fwCtx.bundleHooks.filterBundle(b.bundleContext, b) == null &&
          caller != fwCtx.systemBundle) {
        throw new BundleException("Rejected by a bundle hook",
                                  BundleException.REJECTED_BY_HOOK);
      } else {
        return b;
      }
    }
    b = fwCtx.perm.callInstall0(this, location, in, caller);
  }
  return b;
}
 
Example #2
Source File: SecurePermissionOps.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
BundleImpl callInstall0(final Bundles bs,
                        final String location,
                        final InputStream in,
                        final Bundle caller)
    throws BundleException
{
  try {
    final AccessControlContext acc = AccessController.getContext();
    return  AccessController
        .doPrivileged(new PrivilegedExceptionAction<BundleImpl>() {
          public BundleImpl run()
              throws BundleException
          {
            return bs.install0(location, in, acc, caller);
          }
        });
  } catch (final PrivilegedActionException e) {
    throw (BundleException) e.getException();
  }
}
 
Example #3
Source File: DeployedCMData.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void uninstall()
    throws BundleException
{
  final ConfigurationAdmin ca = DirDeployerImpl.caTracker.getService();
  if (pids != null && ca != null) {
    for (final String pid : pids) {
      try {
        final Configuration cfg = ca.getConfiguration(pid, null);
        cfg.delete();
        installedCfgs.remove(pid);
        deleteFilePidToCmPidEntry(pid);
      } catch (final IOException e) {
        DirDeployerImpl.log("Failed to uninstall configuration with pid '"
                            + pid + "': " + e.getMessage(), e);
      }
    }
    saveState();
    pids = null;
  }
}
 
Example #4
Source File: BundleImpl.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
protected boolean resolve(final boolean critical)
		throws BundleException {
	if (!resolveMetadata(critical)) {
		return false;
	}

	if (!framework.resolve(
			Collections.<BundleRevision> singletonList(this),
			critical)) {
		return false;
	}
	
	markResolved();
	
	return true;
}
 
Example #5
Source File: ClasspathJar.java    From takari-lifecycle with Eclipse Public License 1.0 6 votes vote down vote up
public static ClasspathJar create(Path file) throws IOException {
  ZipFile zipFile = new ZipFile(file.toFile());
  Set<String> packageNames = getPackageNames(zipFile);
  Collection<String> exportedPackages = null;
  // TODO do not look for exported packages in java standard library
  ZipEntry entry = zipFile.getEntry(PATH_EXPORT_PACKAGE);
  if (entry != null) {
    try (InputStream is = zipFile.getInputStream(entry)) {
      exportedPackages = parseExportPackage(is);
    }
  }
  if (exportedPackages == null) {
    entry = zipFile.getEntry(PATH_MANIFESTMF);
    if (entry != null) {
      try (InputStream is = zipFile.getInputStream(entry)) {
        exportedPackages = parseBundleManifest(is);
      } catch (BundleException e) {
        // silently ignore bundle manifest parsing problems
      }
    }
  }
  return new ClasspathJar(file, zipFile, packageNames, exportedPackages);
}
 
Example #6
Source File: Concierge.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * install a new bundle from input stream.
 * 
 * @param location
 *            the location.
 * @param in
 *            the input stream.
 * @return the bundle object.
 * @throws BundleException
 *             if something goes wrong.
 * @see org.osgi.framework.BundleContext#installBundle(java.lang.String,
 *      java.io.InputStream)
 * 
 */
public Bundle installBundle(final String location, final InputStream in)
		throws BundleException {
	if (location == null) {
		throw new IllegalArgumentException("Location must not be null");
	}
	checkValid();

	// TODO: check AdminPermission(new bundle, LIFECYCLE)

	if (in == null) {
		return installNewBundle(this, location);	 
	} else {
		return installNewBundle(this, location, in);
	}
}
 
Example #7
Source File: RequireBundleTestSuite.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void runTest() throws Throwable {
  // Start buA to resolve it
  try {
    buA.start();
  }
  catch (BundleException bexcR) {
    fail("framework test bundle "+ bexcR
         +"(" + bexcR.getNestedException() + ") :FRAME400A:FAIL");
  }
  catch (SecurityException secR) {
    fail("framework test bundle "+ secR +" :FRAME400A:FAIL");
  }

  String ceStr = checkExports(bc, buA, new String[]{"test_rb.B"});
  if ( ceStr != null ) {
      fail(ceStr +  ":FRAME400A:FAIL");
  }
  out.println("### framework test bundle :FRAME400A:PASS");
}
 
Example #8
Source File: Util.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Install a bundle from a resource file.
 *
 * @param bc context owning both resources and to install bundle from
 * @param resource resource name of bundle jar file
 * @return the installed bundle
 * @throws BundleException if no such resource is found or if
 *                         installation fails.
 */
public static Bundle installBundle(BundleContext bc, String resource) throws BundleException {
  try {
    URL url = bc.getBundle().getResource(resource);
    if(url == null) {
      throw new BundleException("No resource " + resource);
    }
    InputStream in = url.openStream();
    if(in == null) {
      throw new BundleException("No resource " + resource);
    }
    return bc.installBundle("internal:" + resource, in);
  } catch (IOException e) {
    throw new BundleException("Failed to get input stream for " + resource + ": " + e);
  }
}
 
Example #9
Source File: KarmaIntegrationTestMojo.java    From wisdom with Apache License 2.0 6 votes vote down vote up
private void startChameleon() throws IOException, BundleException {
    if (ChameleonInstanceHolder.get() != null) {
        getLog().info("Reusing running Chameleon");
    } else {
        ChameleonConfiguration configuration = new ChameleonConfiguration(getWisdomRootDirectory());
        // Use a different cache for testing.
        configuration.put("org.osgi.framework.storage",
                getWisdomRootDirectory().getAbsolutePath() + "/chameleon-test-cache");

        // Set the httpPort to 0 to use the random port feature.
        // Except if already set explicitly
        String port = System.getProperty("http.port");
        if (port == null) {
            System.setProperty("http.port", "0");
        }

        System.setProperty("application.configuration",
                new File(getWisdomRootDirectory(), "/conf/application.conf").getAbsolutePath());

        Chameleon chameleon = new Chameleon(configuration);
        ChameleonInstanceHolder.fixLoggingSystem(getWisdomRootDirectory());
        chameleon.start().waitForStability();
        ChameleonInstanceHolder.set(chameleon);
    }
}
 
Example #10
Source File: BundleImpl.java    From ACDD with MIT License 6 votes vote down vote up
public synchronized void startBundle() throws BundleException {
    if (this.state == BundleEvent.INSTALLED) {
        throw new IllegalStateException("Cannot start uninstalled bundle "
                + toString());
    } else if (this.state != BundleEvent.RESOLVED) {
        if (this.state == BundleEvent.STARTED) {
            resolveBundle(true);
        }
        this.state = BundleEvent.UPDATED;
        try {

            isValid = true;
            this.state = BundleEvent.RESOLVED;
            Framework.notifyBundleListeners(BundleEvent.STARTED, this);
            if (Framework.DEBUG_BUNDLES && log.isInfoEnabled()) {
                log.info("Framework: Bundle " + toString() + " started.");
            }
        } catch (Throwable th) {

            Framework.clearBundleTrace(this);
            this.state = BundleEvent.STOPPED;
            String msg = "Error starting bundle " + toString();
            log.error(msg,th);
        }
    }
}
 
Example #11
Source File: BundleClassLoader.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Create class loader for specified bundle.
 */
BundleClassLoader(final BundleGeneration gen) throws BundleException {
  // otherwise getResource will bypass OUR parent
  super(gen.bundle.fwCtx.parentClassLoader);

  fwCtx = gen.bundle.fwCtx;
  debug = fwCtx.debug;
  secure = fwCtx.perm;
  protectionDomain = gen.getProtectionDomain();
  bpkgs = gen.bpkgs;
  archive = gen.archive;
  classPath = new BundleClassPath(archive, gen);
  if (debug.classLoader) {
    debug.println(this + " Created new classloader");
  }
}
 
Example #12
Source File: BundleUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static BundleInfo getBundleInfo(String bundleLocation) throws IOException, BundleException {
	try (JarFile jarFile = new JarFile(bundleLocation)) {
		Manifest manifest = jarFile.getManifest();
		if (manifest != null) {
			Attributes mainAttributes = manifest.getMainAttributes();
			if (mainAttributes != null) {
				String bundleVersion = mainAttributes.getValue(Constants.BUNDLE_VERSION);
				if (StringUtils.isBlank(bundleVersion)) {
					return null;
				}
				String symbolicName = mainAttributes.getValue(Constants.BUNDLE_SYMBOLICNAME);
				boolean isSingleton = false;
				if (StringUtils.isNotBlank(symbolicName)) {
					ManifestElement[] symbolicNameElements = ManifestElement.parseHeader(Constants.BUNDLE_SYMBOLICNAME, symbolicName);
					if (symbolicNameElements.length > 0) {
						symbolicName = symbolicNameElements[0].getValue();
						String singleton = symbolicNameElements[0].getDirective(Constants.SINGLETON_DIRECTIVE);
						isSingleton = "true".equals(singleton);
					}
				}
				return new BundleInfo(bundleVersion, symbolicName, isSingleton);
			}
		}
	}
	return null;
}
 
Example #13
Source File: BundleExtensionHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void uninstall(MarketplaceExtension ext) throws MarketplaceHandlerException {
    Long id = installedBundles.get(ext.getId());
    if (id != null) {
        Bundle bundle = bundleContext.getBundle(id);
        if (bundle != null) {
            try {
                bundle.stop();
                bundle.uninstall();
                installedBundles.remove(ext.getId());
                persistInstalledBundlesMap(installedBundles);
            } catch (BundleException e) {
                throw new MarketplaceHandlerException("Failed deinstalling bundle: " + e.getMessage());
            }
        } else {
            // we do not have such a bundle, so let's remove it from our internal map
            installedBundles.remove(ext.getId());
            persistInstalledBundlesMap(installedBundles);
            throw new MarketplaceHandlerException("Id not known.");
        }
    } else {
        throw new MarketplaceHandlerException("Id not known.");
    }
}
 
Example #14
Source File: BundleImpl.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
private MultiMap<String, BundleCapability> parseCapabilities(
		final String str) throws BundleException {
	final MultiMap<String, BundleCapability> result = new MultiMap<String, BundleCapability>();

	if (str == null) {
		return result;
	}

	final String[] reqStrs = Utils.splitString(str, ',');
	for (int i = 0; i < reqStrs.length; i++) {
		final BundleCapabilityImpl cap = new BundleCapabilityImpl(this,
				reqStrs[i]);
		final String namespace = cap.getNamespace();
		if(namespace.equals(NativeNamespace.NATIVE_NAMESPACE)){
			throw new BundleException("Only the system bundle can provide a native capability", BundleException.MANIFEST_ERROR);
		}
		result.insert(namespace, cap);
	}
	return result;
}
 
Example #15
Source File: ExportPackagesIntegrationTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Ignore // jdisc_core.jar cannot be installed as a bundle since Felix 6.0, due to exporting java.* packages.
@Test
public void requireThatManifestContainsExportPackage() throws BundleException {
    FelixFramework felix = TestDriver.newOsgiFramework();
    felix.start();
    List<Bundle> bundles = felix.installBundle("jdisc_core.jar");
    assertEquals(1, bundles.size());
    Object obj = bundles.get(0).getHeaders().get("Export-Package");
    assertTrue(obj instanceof String);
    String str = (String)obj;
    assertTrue(str.contains(ExportPackages.getSystemPackages()));
    assertTrue(str.contains("com.yahoo.jdisc"));
    assertTrue(str.contains("com.yahoo.jdisc.application"));
    assertTrue(str.contains("com.yahoo.jdisc.handler"));
    assertTrue(str.contains("com.yahoo.jdisc.service"));
    felix.stop();
}
 
Example #16
Source File: BundleImpl.java    From AtlasForAndroid with MIT License 5 votes vote down vote up
BundleImpl(File file, String str, BundleContextImpl bundleContextImpl, InputStream inputStream, File file2, boolean z) throws BundleException {
    this.persistently = false;
    this.domain = null;
    this.registeredServices = null;
    this.registeredFrameworkListeners = null;
    this.registeredBundleListeners = null;
    this.registeredServiceListeners = null;
    this.staleExportedPackages = null;
    long currentTimeMillis = System.currentTimeMillis();
    this.location = str;
    bundleContextImpl.bundle = this;
    this.context = bundleContextImpl;
    this.currentStartlevel = Framework.initStartlevel;
    this.bundleDir = file;
    if (inputStream != null) {
        try {
            this.archive = new BundleArchive(str, file, inputStream);
        } catch (Throwable e) {
            Framework.deleteDirectory(file);
            throw new BundleException("Could not install bundle " + str, e);
        }
    } else if (file2 != null) {
        this.archive = new BundleArchive(str, file, file2);
    }
    this.state = 2;
    Framework.notifyBundleListeners(1, this);
    updateMetadata();
    if (z) {
        Framework.bundles.put(str, this);
        resolveBundle(false);
    }
    if (Framework.DEBUG_BUNDLES && log.isInfoEnabled()) {
        log.info("Framework: Bundle " + toString() + " created. " + (System.currentTimeMillis() - currentTimeMillis) + " ms");
    }
}
 
Example #17
Source File: BundleImpl.java    From AtlasForAndroid with MIT License 5 votes vote down vote up
public synchronized void start() throws BundleException {
    this.persistently = true;
    updateMetadata();
    if (this.currentStartlevel <= Framework.startlevel) {
        startBundle();
    }
}
 
Example #18
Source File: BundleImpl.java    From ACDD with MIT License 5 votes vote down vote up
@Override
public synchronized void start() throws BundleException {
    this.persistently = true;
    updateMetadata();
    if (this.currentStartlevel <= Framework.startlevel) {
        startBundle();
    }
}
 
Example #19
Source File: InstrumentationHook.java    From ACDD with MIT License 5 votes vote down vote up
/**
 * Perform calling of an activity's {@link Activity#onCreate}
 * method.  The default implementation simply calls through to that method.
 *
 * @param activity The activity being created.
 * @param icicle The previously frozen state (or null) to pass through to
 *               onCreate().
 */
@Override
public void callActivityOnCreate(Activity activity, Bundle icicle) {
    if (RuntimeVariables.androidApplication.getPackageName().equals(activity.getPackageName())) {
        ContextImplHook contextImplHook = new ContextImplHook(activity.getBaseContext(), activity.getClass()
                .getClassLoader());
        if (!(OpenAtlasHacks.ContextThemeWrapper_mBase == null || OpenAtlasHacks.ContextThemeWrapper_mBase.getField() == null)) {
            OpenAtlasHacks.ContextThemeWrapper_mBase.set(activity, contextImplHook);
        }
        OpenAtlasHacks.ContextWrapper_mBase.set(activity, contextImplHook);
        if (activity.getClass().getClassLoader() instanceof BundleClassLoader) {
            try {
                ((BundleClassLoader) activity.getClass().getClassLoader()).getBundle().startBundle();
            } catch (BundleException e) {
                log.error(e.getMessage() + " Caused by: ", e.getNestedException());
            }
        }
        String property = Framework.getProperty(OpenAtlasInternalConstant.BOOT_ACTIVITY, OpenAtlasInternalConstant.BOOT_ACTIVITY);
        if (TextUtils.isEmpty(property)) {
            property = OpenAtlasInternalConstant.BOOT_ACTIVITY;
        }
        try {
            ensureResourcesInjected(activity);
            this.mBase.callActivityOnCreate(activity, icicle);
            return;
        } catch (Exception e2) {
            if (!e2.toString().contains("android.content.res.Resources")
                    || e2.toString().contains("OutOfMemoryError")) {
                e2.printStackTrace();
            }
            HandleResourceNotFound(activity, icicle, e2);
            return;
        }
    }
    this.mBase.callActivityOnCreate(activity, icicle);
}
 
Example #20
Source File: OSGiTestSupport.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void assertBundleStarted(String name) {
    Bundle bundle = findBundleByName(name);
    Assert.assertNotNull("Bundle " + name + " should be deployed", bundle);
    if (bundle.getState() != Bundle.ACTIVE) {
        try {
            bundle.start();
        } catch (BundleException e) {
            throw new RuntimeException("Bundle " + name + " should be started but we get this error", e);
        }
    }
}
 
Example #21
Source File: OsgiLogManagerTestCase.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void requireThatRootLoggerModificationCanBeDisabled() throws BundleException {
    Logger logger = Logger.getLogger("");
    logger.setLevel(Level.WARNING);

    new OsgiLogManager(false).install(Mockito.mock(BundleContext.class));
    assertEquals(Level.WARNING, logger.getLevel());

    new OsgiLogManager(true).install(Mockito.mock(BundleContext.class));
    assertEquals(Level.ALL, logger.getLevel());
}
 
Example #22
Source File: BundleClassLoader.java    From ACDD with MIT License 5 votes vote down vote up
private static String[] readProperty(Attributes attributes, String name)
        throws BundleException {
    String value = attributes.getValue(name);
    if (value == null || !value.equals("")) {
        return splitString(value);
    }
    return new String[0];
}
 
Example #23
Source File: BundleContextImpl.java    From AtlasForAndroid with MIT License 5 votes vote down vote up
public Bundle installBundle(String str, InputStream inputStream) throws BundleException {
    if (str == null) {
        throw new IllegalArgumentException("Location must not be null");
    }
    checkValid();
    return Framework.installNewBundle(str, inputStream);
}
 
Example #24
Source File: Test8.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void cleanup() {
   tracker1.close();
   tracker2.close();
   
   try {
    b1.uninstall();
    b2.uninstall();
    tracker.getServiceReference().getBundle().uninstall();
     
  } catch (BundleException e) {
    e.printStackTrace();
  }
  tracker.close();
}
 
Example #25
Source File: NonWorkingOsgiFrameworkTestCase.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void requireThatFrameworkThrowsOnInstallBundle() throws BundleException {
    OsgiFramework osgi = new NonWorkingOsgiFramework();
    try {
        osgi.installBundle("file:bundle.jar");
        fail();
    } catch (UnsupportedOperationException e) {
        // expected
    }
}
 
Example #26
Source File: OpenAtlas.java    From ACDD with MIT License 5 votes vote down vote up
public void updateBundle(String pkgName, InputStream inputStream)
        throws BundleException {
    Bundle bundle = Framework.getBundle(pkgName);
    if (bundle != null) {
        bundle.update(inputStream);
        return;
    }
    throw new BundleException("Could not update bundle " + pkgName
            + ", because could not find it");
}
 
Example #27
Source File: Framework.java    From ACDD with MIT License 5 votes vote down vote up
static void installOrUpdate(String[] locations, File[] archiveFiles) throws BundleException {
    if (locations == null || archiveFiles == null || locations.length != archiveFiles.length) {
        throw new IllegalArgumentException("locations and files must not be null and must be same length");
    }
    String valueOf = String.valueOf(System.currentTimeMillis());
    File file = new File(new File(STORAGE_LOCATION, "wal"), valueOf);
    file.mkdirs();
    int i = 0;
    while (i < locations.length) {
        if (!(locations[i] == null || archiveFiles[i] == null)) {
            try {
                BundleLock.WriteLock(locations[i]);
                Bundle bundle = getBundle(locations[i]);
                if (bundle != null) {
                    bundle.update(archiveFiles[i]);
                } else {
                    BundleImpl bundleImpl = new BundleImpl(new File(file, locations[i]), locations[i],  null, archiveFiles[i], false);
                }
                BundleLock.WriteUnLock(locations[i]);
            } catch (Throwable th) {
                BundleLock.WriteUnLock(locations[i]);
            }
        }
        i++;
    }
    writeAheads.add(valueOf);
    storeMetadata();
}
 
Example #28
Source File: FelixFramework.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public List<Bundle> installBundle(String bundleLocation) throws BundleException {
    List<Bundle> bundles = new LinkedList<>();
    try {
        installBundle(bundleLocation, new HashSet<>(), bundles);
    } catch (Exception e) {
        throw new BundleInstallationException(bundles, e);
    }
    return bundles;
}
 
Example #29
Source File: FrameworkCommandGroup.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public int cmdStop(Dictionary<String,?> opts, Reader in, PrintWriter out,
                   Session session) {
  int stopOptions = 0;
  if (opts.get("-t") != null) {
    stopOptions |= Bundle.STOP_TRANSIENT;
  }

  final Bundle[] b = getBundles((String[]) opts.get("bundle"), true);
  boolean found = false;
  for (int i = b.length - 1; i >= 0; i--) {
    if (b[i] != null) {
      try {
        b[i].stop(stopOptions);
        out.println("Stopped: " + showBundle(b[i]));
      } catch (final BundleException e) {
        Throwable t = e;
        while (t instanceof BundleException
               && ((BundleException) t).getNestedException() != null) {
          t = ((BundleException) t).getNestedException();
        }
        out.println("Couldn't stop bundle: " + showBundle(b[i])
                    + " (due to: " + t + ")");
      }
      found = true;
    }
  }
  if (!found) {
    out.println("ERROR! No matching bundle");
    return 1;
  }
  return 0;
}
 
Example #30
Source File: AbstractOSGiResource.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
protected Representation ERROR(final Throwable t,
		final Variant variant) {
	t.printStackTrace();
	if (t instanceof BundleException) {
		try {
			final Representation rep;
			final MediaType mt;

			if (MediaType.APPLICATION_ALL_XML.includes(variant.getMediaType())) {
				mt = MT_BE_XML;

				rep = getRepresentation(new BundleExceptionPojo(
						(BundleException) t), new Variant(MediaType.TEXT_XML));
			} else {
				mt = MT_BE_JSON;
				rep = getRepresentation(new BundleExceptionPojo(
						(BundleException) t), new Variant(MediaType.APPLICATION_JSON));
			}

			setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
			rep.setMediaType(mt);

			return rep;
		} catch (final Exception ioe) {
			// fallback
		}
	} else if (t instanceof IllegalArgumentException) {
		setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
		return ERROR;
	} else if (t instanceof InvalidSyntaxException) {
		setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
		return ERROR;
	}

	setStatus(Status.SERVER_ERROR_INTERNAL, t);
	return ERROR;
}