下面列出了org.osgi.framework.ServiceListener#org.osgi.framework.BundleException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
}
/**
* 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);
}
}
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);
}
}
}
/**
* 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");
}
}
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;
}
/**
* 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;
}
@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.");
}
}
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);
}
}
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;
}
/**
* 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);
}
}
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");
}
@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();
}
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);
}
@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();
}
}
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;
}
@Override
public synchronized void start() throws BundleException {
this.persistently = true;
updateMetadata();
if (this.currentStartlevel <= Framework.startlevel) {
startBundle();
}
}
public int cmdUninstall(Dictionary<String,?> opts, Reader in, PrintWriter out,
Session session) {
final Bundle[] b = getBundles((String[]) opts.get("bundle"), true);
boolean found = false;
for (final Bundle element : b) {
if (element != null) {
try {
element.uninstall();
out.println("Uninstalled: " + showBundle(element));
} catch (final BundleException e) {
Throwable t = e;
while (t instanceof BundleException
&& ((BundleException) t).getNestedException() != null) {
t = ((BundleException) t).getNestedException();
}
out.println("Couldn't uninstall: " + showBundle(element)
+ " (due to: " + t + ")");
}
found = true;
}
}
if (!found) {
out.println("ERROR! No matching bundle");
return 1;
}
return 0;
}
BundleRevisionImpl(
Bundle bundle, String id, Map headerMap, Content content)
throws BundleException
{
m_bundle = bundle;
m_id = id;
m_headerMap = headerMap;
m_content = content;
ManifestParser mp = new ManifestParser(
((BundleImpl) bundle).getFramework().getLogger(),
((BundleImpl) bundle).getFramework().getConfig(),
this,
m_headerMap);
// Record some of the parsed metadata. Note, if this is an extension
// bundle it's exports are removed, since they will be added to the
// system bundle directly later on.
m_manifestVersion = mp.getManifestVersion();
m_version = mp.getBundleVersion();
m_declaredCaps = mp.getCapabilities();
m_declaredReqs = mp.getRequirements();
m_declaredNativeLibs = mp.getLibraries();
m_declaredActivationPolicy = mp.getActivationPolicy();
m_activationExcludes = (mp.getActivationExcludeDirective() == null)
? null
: ManifestParser.parseDelimitedString(mp.getActivationExcludeDirective(), ",");
m_activationIncludes = (mp.getActivationIncludeDirective() == null)
? null
: ManifestParser.parseDelimitedString(mp.getActivationIncludeDirective(), ",");
m_symbolicName = mp.getSymbolicName();
m_isExtension = mp.isExtension();
m_isFragment = m_headerMap.containsKey(Constants.FRAGMENT_HOST);
}
/**
* the actual starting happens here. This method does not modify the
* persistent metadata.
*
* @throws BundleException
* if the bundle cannot be resolved or the Activator throws an
* exception.
*/
synchronized void activate(final int options) throws BundleException {
if (state == ACTIVE) {
return;
}
if (currentRevision.isFragment()) {
return;
}
// step4
if (state == INSTALLED) {
// this time, it is critical to get the bundle resolved
// so if we need exports from other unresolved bundles,
// we will try to resolve them (recursively) to get the bundle
// started
currentRevision.resolve(true);
}
// step5
this.context = framework.createBundleContext(this);
if ((options & Bundle.START_ACTIVATION_POLICY) > 0 && lazyActivation) {
if (state != STARTING) {
beingLazy = true;
state = STARTING;
framework.notifyBundleListeners(BundleEvent.LAZY_ACTIVATION,
this);
}
synchronized (this) {
notify();
}
return;
} else {
beingLazy = false;
}
activate0();
}
@After
public void tearDown() throws IOException, BundleException {
testBundle.uninstall();
managedThingProvider.remove(thing.getUID());
new DefaultLocaleSetter(getService(ConfigurationAdmin.class)).setDefaultLocale(defaultLocale);
waitForAssert(() -> assertThat(getService(LocaleProvider.class).getLocale(), is(defaultLocale)));
}
static BundleImpl installNewBundle(String str) throws BundleException {
try {
String str2 = str.indexOf(":") > -1 ? str : BUNDLE_LOCATION + File.separatorChar + str;
return installNewBundle(str2, new URL(str2).openConnection().getInputStream());
} catch (Throwable e) {
throw new BundleException("Cannot retrieve bundle from " + str, e);
}
}
@Test
public void requireThatAllLogMethodsAreImplemented() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.start();
BundleContext ctx = felix.bundleContext();
OsgiLogManager manager = new OsgiLogManager(true);
manager.install(ctx);
MyLogService service = new MyLogService();
ctx.registerService(LogService.class.getName(), service, null);
manager.log(2, "a");
assertLast(service, null, 2, "a", null);
Throwable t1 = new Throwable();
manager.log(4, "b", t1);
assertLast(service, null, 4, "b", t1);
ServiceReference<?> ref1 = Mockito.mock(ServiceReference.class);
manager.log(ref1, 8, "c");
assertLast(service, ref1, 8, "c", null);
ServiceReference<?> ref2 = Mockito.mock(ServiceReference.class);
Throwable t2 = new Throwable();
manager.log(ref2, 16, "d", t2);
assertLast(service, ref2, 16, "d", t2);
manager.uninstall();
felix.stop();
}
/**
* Installs a bundle with an import to a package in an library in lib/ext
* (here: sunjce_provider.jar).
*/
private void setupSunJceBundle() throws BundleException {
SyntheticBundleBuilder builder = new SyntheticBundleBuilder();
builder.bundleSymbolicName("bundle").addManifestHeader(
"Import-Package", "com.sun.crypto.provider");
bundleUnderTest = installBundle(builder);
bundleUnderTest.start();
assertBundleActive(bundleUnderTest);
}
@Test
public void requireThatInstallCanThrowException() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.start();
try {
felix.installBundle("file:notfound.jar");
fail();
} catch (BundleException e) {
}
felix.stop();
}
@Test
public void testOSGIBundle () throws BundleException
{
LSInput aRes;
// Initializing Apache Felix as OSGI container is required to get the
// "bundle" URL protocol installed correctly
// Otherwise the first call would end up as a "file" resource ;-)
final Framework aOSGI = new FrameworkFactory ().newFramework (new HashMap <String, String> ());
aOSGI.start ();
try
{
// Bundle 0 is the org.apache.felix.framework bundle
final Bundle b = aOSGI.getBundleContext ().getBundle (0);
assertNotNull (b);
assertEquals (Bundle.ACTIVE, b.getState ());
// No leading slash is important as the ClassLoader is used!
assertNotNull (b.getResource ("org/apache/felix/framework/util/Util.class"));
final LSResourceResolver aRR = new SimpleLSResourceResolver ();
// No class loader
aRes = aRR.resolveResource (XMLConstants.W3C_XML_SCHEMA_NS_URI,
null,
null,
"../Felix.class",
"bundle://0.0:1/org/apache/felix/framework/util/Util.class");
assertTrue (aRes instanceof ResourceLSInput);
final IHasInputStream aISP = ((ResourceLSInput) aRes).getInputStreamProvider ();
assertTrue (aISP instanceof URLResource);
// Path maybe a "jar:file:" resource
assertTrue (((URLResource) aISP).getPath ().endsWith ("org/apache/felix/framework/Felix.class"));
}
finally
{
aOSGI.stop ();
}
}
@Test
public void requireThatFrameworkThrowsOnStartBundles() throws BundleException {
OsgiFramework osgi = new NonWorkingOsgiFramework();
try {
osgi.startBundles(Collections.<Bundle>emptyList(), false);
fail();
} catch (UnsupportedOperationException e) {
// expected
}
}
/**
* Starts the underlying Chameleon instance.
*
* @param root the base directory of the Chameleon.
* @throws java.io.IOException if the chameleon configuration cannot be read.
* @throws org.osgi.framework.BundleException if the chameleon cannot be started.
*/
private void start(File root) throws BundleException, IOException {
ChameleonConfiguration configuration = new ChameleonConfiguration(root);
// Use a different cache for testing.
configuration.put("org.osgi.framework.storage", root.getAbsolutePath() + "/chameleon-test-cache");
StringBuilder packages = new StringBuilder();
Packages.junit(packages);
Packages.wisdomtest(packages);
Packages.javaxinject(packages);
Packages.assertj(packages);
configuration.put("org.osgi.framework.system.packages.extra", packages.toString());
// 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");
}
Chameleon chameleon = new Chameleon(configuration);
ChameleonInstanceHolder.fixLoggingSystem(root);
chameleon.start();
// Set the TIME_FACTOR
String factor = System.getProperty("time.factor");
if (factor != null) {
int factorAsInteger = getFactorAsAnInteger(factor);
if (factorAsInteger == 1) {
LoggerFactory.getLogger(this.getClass()).info("Setting time.factor to " + factorAsInteger + " (given " +
"as '" + factor + "')");
} else {
LoggerFactory.getLogger(this.getClass()).info("Setting time.factor to " + factorAsInteger);
}
setTimeFactory(factorAsInteger);
}
chameleon.waitForStability();
ChameleonInstanceHolder.set(chameleon);
}
/**
* Uninstall this bundle.
*
* @see org.osgi.framework.Bundle#uninstall
*/
public void uninstall() throws BundleException {
secure.checkLifecycleAdminPerm(this);
if (current().isExtension()) {
secure.checkExtensionLifecycleAdminPerm(this);
}
secure.callUninstall0(this);
}
private void ensureBundleStarted(String symbolicName) throws BundleException {
Bundle bundle = Activator.getBundle(symbolicName);
if (bundle != null) {
if (bundle.getState() == Bundle.RESOLVED || bundle.getState() == Bundle.STARTING) {
bundle.start(Bundle.START_TRANSIENT);
}
}
}
/**
* Tests LOG4J2-920.
*/
@Test
public void testLoadingOfConfigurableCoreClasses() throws BundleException, ReflectiveOperationException {
final Bundle api = getApiBundle();
final Bundle plugins = getPluginsBundle();
final Bundle core = getCoreBundle();
final Bundle dummy = getDummyBundle();
start(api, plugins, core, dummy);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream logStream = new PrintStream(baos);
final PrintStream bakStream = setupStream(api, logStream);
log(dummy);
setupStream(api, bakStream);
// org.apache.logging.log4j.core.osgi.BundleContextSelector cannot be found by org.apache.logging.log4j.api
final boolean result = baos.toString().contains("BundleContextSelector cannot be found");
Assert.assertFalse("Core class BundleContextSelector cannot be loaded in OSGI setup", result);
stop(api, plugins, core, dummy);
uninstall(api, plugins, core, dummy);
}