Java Code Examples for org.osgi.framework.Bundle#getState()

The following examples show how to use org.osgi.framework.Bundle#getState() . 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: AppContextUtil.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Load class by certain bundle name
 * 
 * @param bundleName
 * @param className
 * @return
 */
private static Class loadClass( String bundleName, String className )
{
	try
	{
		Bundle bundle = Platform.getBundle( bundleName );
		if ( bundle != null )
		{
			if ( bundle.getState( ) == Bundle.RESOLVED )
			{
				bundle.start( Bundle.START_TRANSIENT );
			}
		}

		if ( bundle != null )
			return bundle.loadClass( className );
	}
	catch ( Exception e )
	{
	}
	return null;
}
 
Example 2
Source File: CoreUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates an extension.  If the extension plugin has not
 * been loaded a busy cursor will be activated during the duration of
 * the load.
 *
 * @param element the config element defining the extension
 * @param classAttribute the name of the attribute carrying the class
 * @return the extension object
 * @throws CoreException thrown if the creation failed
 */
public static Object createExtension(final IConfigurationElement element, final String classAttribute) throws CoreException {
	// If plugin has been loaded create extension.
	// Otherwise, show busy cursor then create extension.
	String pluginId = element.getContributor().getName();
	Bundle bundle = Platform.getBundle(pluginId);
	if (bundle != null && bundle.getState() == Bundle.ACTIVE ) {
		return element.createExecutableExtension(classAttribute);
	} else {
		final Object[] ret = new Object[1];
		final CoreException[] exc = new CoreException[1];
		BusyIndicator.showWhile(null, new Runnable() {
			public void run() {
				try {
					ret[0] = element.createExecutableExtension(classAttribute);
				} catch (CoreException e) {
					exc[0] = e;
				}
			}
		});
		if (exc[0] != null)
			throw exc[0];
		else
			return ret[0];
	}
}
 
Example 3
Source File: BrooklynLauncherRebindCatalogOsgiTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@AfterMethod(alwaysRun=true)
@Override
public void tearDown() throws Exception {
    try {
        launcherT1 = null; launcherT2 = null; launcherLast = null;
        startupAssertions = null;
        reuseOsgi = true;
        
        // OSGi reuse system will clear cache on framework no longer being used,
        // but we've installed out of band so need to clean it up ourselves if the test doesn't actually use it!
        for (Bundle bundle : manuallyInsertedBundles) {
            if (bundle != null && bundle.getState() != Bundle.UNINSTALLED) {
                bundle.uninstall();
            }
        }
        manuallyInsertedBundles.clear();
    } finally {
        super.tearDown();
    }
}
 
Example 4
Source File: HybridCore.java    From thym with Eclipse Public License 1.0 6 votes vote down vote up
private boolean startBundle(String bundleId) {
	Bundle[] bundles = context.getBundles();
	for(Bundle bundle: bundles){
		if(bundle.getSymbolicName().equals(bundleId)){
			if ((bundle.getState() & Bundle.INSTALLED) == 0) {
				try {
					bundle.start(Bundle.START_ACTIVATION_POLICY);
					bundle.start(Bundle.START_TRANSIENT);
					return true;
				} catch (BundleException e) {
					return false;
				}
			}
		}
	}
	return false;
}
 
Example 5
Source File: ExplorerPreferencePage.java    From eclipse-explorer with Eclipse Public License 1.0 6 votes vote down vote up
private static String getBundleInfo(Bundle bundle) {
    String name = bundle.getHeaders().get("Bundle-Name");
    String ver = bundle.getVersion().toString();
    // UNINSTALLED,INSTALLED, RESOLVED, STARTING, STOPPING, ACTIVE.
    String stStr = "unknown";
    int st = bundle.getState();
    if (st == Bundle.UNINSTALLED) {
        stStr = "uninstalled";
    }
    else if (st == Bundle.INSTALLED) {
        stStr = "installed";
    }
    else if (st == Bundle.RESOLVED) {
        stStr = "resolved";
    }
    else if (st == Bundle.STARTING) {
        stStr = "starting";
    }
    else if (st == Bundle.STOPPING) {
        stStr = "stopping";
    }
    else if (st == Bundle.ACTIVE) {
        stStr = "active";
    }
    return String.format("%s(%s):%s", name, ver, stStr);
}
 
Example 6
Source File: AbstractConciergeTestCase.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
/** Checks about Bundle ACTIVE state. */
protected void assertBundleActive(final Bundle bundle) {
	if (bundle.getState() == Bundle.ACTIVE) {
		// all fine
	} else {
		if (isFragmentBundle(bundle) && isBundleResolved(bundle)) {
			// all fine
		} else {
			Assert.assertThat(
					"Bundle " + bundle.getSymbolicName()
							+ " needs to be ACTIVE",
					getBundleStateAsString(bundle.getState()),
					is(getBundleStateAsString(Bundle.ACTIVE)));
		}
	}
}
 
Example 7
Source File: AbstractResourceBundleProvider.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method provides common functionality for {@link ModuleTypeProvider} and {@link TemplateProvider} to process
 * the bundles. For {@link RuleResourceBundleImporter} this method is overridden.
 * <p>
 * Checks for availability of the needed {@link Parser}. If it is not available - the bundle is added into
 * {@link #waitingProviders} and the execution of the method ends.
 * <p>
 * If it is available, the execution of the method continues with checking if the version of the bundle is changed.
 * If the version is changed - removes persistence of old variants of the objects, provided by this bundle.
 * <p>
 * Continues with loading the new version of these objects. If this bundle is added for the very first time, only
 * loads the provided objects.
 * <p>
 * The loading can fail because of {@link IOException}.
 *
 * @param bundle it is a {@link Bundle} which has to be processed, because it provides resources for automation
 *            objects.
 */
protected void processAutomationProvider(Bundle bundle) {
    Enumeration<URL> urlEnum = null;
    try {
        if (bundle.getState() != Bundle.UNINSTALLED) {
            urlEnum = bundle.findEntries(path, null, true);
        }
    } catch (IllegalStateException e) {
        logger.debug("Can't read from resource of bundle with ID {}. The bundle is uninstalled.",
                bundle.getBundleId(), e);
        processAutomationProviderUninstalled(bundle);
    }
    Vendor vendor = new Vendor(bundle.getSymbolicName(), bundle.getVersion().toString());
    List<String> previousPortfolio = getPreviousPortfolio(vendor);
    List<String> newPortfolio = new LinkedList<>();
    if (urlEnum != null) {
        while (urlEnum.hasMoreElements()) {
            URL url = urlEnum.nextElement();
            if (url.getPath().endsWith(File.separator)) {
                continue;
            }
            String parserType = getParserType(url);
            Parser<E> parser = parsers.get(parserType);
            updateWaitingProviders(parser, bundle, url);
            if (parser != null) {
                Set<E> parsedObjects = parseData(parser, url, bundle);
                if (!parsedObjects.isEmpty()) {
                    addNewProvidedObjects(newPortfolio, previousPortfolio, parsedObjects);
                }
            }
        }
        putNewPortfolio(vendor, newPortfolio);
    }
    removeUninstalledObjects(previousPortfolio, newPortfolio);
}
 
Example 8
Source File: NetigsoServicesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Bundle findBundle(String bsn) throws Exception {
    Bundle[] arr = findFramework().getBundleContext().getBundles();
    Bundle candidate = null;
    for (Bundle b : arr) {
        if (bsn.equals(b.getSymbolicName())) {
            candidate = b;
            if ((b.getState() & Bundle.ACTIVE) != 0) {
                return b;
            }
        }
    }
    return candidate;
}
 
Example 9
Source File: Activator.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private void ensureBundleStarted(String symbolicName) {
	Bundle bundle = getBundle(symbolicName);
	if (bundle != null) {
		if (bundle.getState() == Bundle.RESOLVED || bundle.getState() == Bundle.STARTING) {
			try {
				bundle.start(Bundle.START_TRANSIENT);
			} catch (BundleException e) {
				Logger logger = LoggerFactory.getLogger("org.eclipse.orion.server.core"); //$NON-NLS-1$
				logger.error("Could not start bundle " + symbolicName, e);

			}
		}
	}
}
 
Example 10
Source File: BundleTracker.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@code BundleListener} method for the {@code BundleTracker} class.
 * This method must NOT be synchronized to avoid deadlock potential.
 * 
 * @param event {@code BundleEvent} object from the framework.
 */
public void bundleChanged(final BundleEvent event) {
	/*
	 * Check if we had a delayed call (which could happen when we
	 * close).
	 */
	if (closed) {
		return;
	}
	final Bundle bundle = event.getBundle();
	final int state = bundle.getState();
	if (DEBUG) {
		System.out.println("BundleTracker.Tracked.bundleChanged[" + state + "]: " + bundle); //$NON-NLS-1$ //$NON-NLS-2$
	}

	if ((state & mask) != 0) {
		track(bundle, event);
		/*
		 * If the customizer throws an unchecked exception, it is safe
		 * to let it propagate
		 */
	} else {
		untrack(bundle, event);
		/*
		 * If the customizer throws an unchecked exception, it is safe
		 * to let it propagate
		 */
	}
}
 
Example 11
Source File: AutomationResourceBundlesTracker.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private BundleEvent initializeEvent(Bundle bundle) {
    switch (bundle.getState()) {
        case Bundle.INSTALLED:
            return new BundleEvent(BundleEvent.INSTALLED, bundle);
        case Bundle.RESOLVED:
            return new BundleEvent(BundleEvent.RESOLVED, bundle);
        default:
            return new BundleEvent(BundleEvent.STARTED, bundle);
    }
}
 
Example 12
Source File: ContributionExtensionManager.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Returns true if the given configuration element is in a bundle that was already loaded.
 */
public static boolean isLoadedBundle(String bundle)
{
	Bundle b = Platform.getBundle(bundle);
	return b != null && b.getState() == Bundle.ACTIVE;
}
 
Example 13
Source File: BundleInstaller.java    From vespa with Apache License 2.0 4 votes vote down vote up
private void stop(Bundle bundle) throws BundleException {
    if (bundle.getState() != Bundle.ACTIVE) {
        throw new BundleException("OSGi bundle " + bundle.getSymbolicName() + " not started.");
    }
    bundle.stop();
}
 
Example 14
Source File: UserMgtDSComponent.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
protected void activate(ComponentContext ctxt) {
    log.debug("User Mgt bundle is activated ");

    // for new cahing, every thread should has its own populated CC. During the deployment time we assume super tenant
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    carbonContext.setTenantDomain(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    carbonContext.setTenantId(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID);

    UserMgtInitializer userMgtInitializer = new UserMgtInitializer();
    try {
        userMgtInitializer.start(ctxt.getBundleContext(), registryService);
        ManagementPermissionsAdder uiPermissionAdder = new ManagementPermissionsAdder();
        ctxt.getBundleContext().addBundleListener(uiPermissionAdder);
        Bundle[] bundles = ctxt.getBundleContext().getBundles();
        for (Bundle bundle : bundles) {
            if (bundle.getState() == Bundle.ACTIVE) {
                uiPermissionAdder.addUIPermissionFromBundle(bundle);
            }
        }
        // register the Authorization listener to restriction tenant!=0 setting super tenant
        // specific permissions
        ServiceRegistration serviceRegistration = ctxt.getBundleContext().registerService
                (AuthorizationManagerListener.class.getName(),
                        new PermissionAuthorizationListener(), null);
        if (serviceRegistration == null) {
            log.error("Error while registering PermissionAuthorizationListener.");
        } else {
            if (log.isDebugEnabled()) {
                log.debug("PermissionAuthorizationListener successfully registered.");
            }
        }
        serviceRegistration = ctxt.getBundleContext().registerService(UserOperationEventListener.class.getName(),
                new UserMgtAuditLogger(), null);
        if (serviceRegistration == null) {
            log.error("Error while registering UserMgtAuditLogger.");
        } else {
            if (log.isDebugEnabled()) {
                log.debug("UserMgtAuditLogger successfully registered.");
            }
        }
    } catch (Throwable e) {
        log.error(e.getMessage(), e);
        // don't throw exception
    }
}
 
Example 15
Source File: FrameworkCommandGroup.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public String showState(Bundle bundle) {
  final StringBuffer sb = new StringBuffer();

  try {
    final StringBuffer s = new StringBuffer
      (String.valueOf(bundle.adapt(BundleStartLevel.class).getStartLevel()));
    while (s.length() < 2) {
      s.insert(0, " ");
    }
    sb.append(s.toString());
  } catch (final Exception ignored) {
    sb.append("--");
  }

  sb.append("/");

  switch (bundle.getState()) {
  case Bundle.INSTALLED:
    sb.append("installed");
    break;
  case Bundle.RESOLVED:
    sb.append("resolved");
    break;
  case Bundle.STARTING:
    sb.append("starting");
    break;
  case Bundle.ACTIVE:
    sb.append("active");
    break;
  case Bundle.STOPPING:
    sb.append("stopping");
    break;
  case Bundle.UNINSTALLED:
    sb.append("uninstalled");
    break;
  default:
    sb.append("ILLEGAL <" + bundle.getState() + "> ");
    break;
  }
  while (sb.length() < 13) {
    sb.append(" ");
  }

  return sb.toString();
}
 
Example 16
Source File: AdminBundlesInstalled.java    From opencps-v2 with GNU Affero General Public License v3.0 4 votes vote down vote up
public static String getBundleState(String symbolicName) {

		String stateName;
		
		if (AdminBundlesInstalled.getBundles().containsKey(symbolicName)) {
			Bundle bundle = AdminBundlesInstalled.getBundles().get(symbolicName);
			int state = bundle.getState();
			switch (state) {
			case 0x00000001:
				stateName = "UNINSTALLED";
				break;

			case 0x00000002:
				stateName = "INSTALLED";
				break;

			case 0x00000004:
				stateName = "RESOLVED";
				break;

			case 0x00000008:
				stateName = "STARTING";
				break;

			case 0x00000010:
				stateName = "STOPPING";
				break;

			case 0x00000020:
				stateName = "ACTIVE";
				break;

			default:
				stateName = "UNINSTALLED";
				break;
			}
		}
		else {
			stateName = "UNINSTALLED";
		}
		
		return stateName;
	}
 
Example 17
Source File: BasicDistroTest.java    From servicemix with Apache License 2.0 4 votes vote down vote up
private boolean isResolved(Bundle bundle) {
    return Bundle.RESOLVED == bundle.getState();
}
 
Example 18
Source File: ActiveBundleHealthCheck.java    From aem-healthcheck with Apache License 2.0 3 votes vote down vote up
/**
 * Checks whether the provided bundle is active. A bundle is considered active if it meets the following criteria:
 * - the bundle is active, or
 * - it is a fragment bundle, or
 * - it has a lazy activation policy
 *
 * @param bundle
 * @return
 */
private static boolean isActiveBundle(Bundle bundle) {
    return (bundle.getState() == Bundle.ACTIVE ||
            bundle.getHeaders().get(BUNDLE_FRAGMENT_HOST) != null) ||
            (bundle.getHeaders().get(BUNDLE_ACTIVATION_POLICY) != null &&
                    bundle.getHeaders().get(BUNDLE_ACTIVATION_POLICY).equals(LAZY_ACTIVATION_POLICY));
}
 
Example 19
Source File: AbstractResourceBundleProvider.java    From smarthome with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * This method is called before the {@link Parser} services to be added to the {@code ServiceTracker} and storing
 * them in the {@link #parsers} into the memory, for fast access on demand. The returned service object is stored in
 * the {@code ServiceTracker} and is available from the {@code getService} and {@code getServices} methods.
 * <p>
 * Also if there are bundles that were stored in {@link #waitingProviders}, to be processed later, because of
 * missing {@link Parser} for particular format,
 * <p>
 * and then the {@link Parser} service appears, they will be processed.
 *
 * @param parser {@link Parser} service
 * @param properties of the service that has been added.
 */
protected void addParser(Parser<E> parser, Map<String, String> properties) {
    String parserType = properties.get(Parser.FORMAT);
    parserType = parserType == null ? Parser.FORMAT_JSON : parserType;
    parsers.put(parserType, parser);
    for (Bundle bundle : waitingProviders.keySet()) {
        if (bundle.getState() != Bundle.UNINSTALLED) {
            processAutomationProvider(bundle);
        }
    }
}
 
Example 20
Source File: Desktop.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Determine if the given bundle can and needs to be resolved.
 *
 * <ol>
 * <li>A bundle in state installed can be resolved.
 * </ol>
 *
 * @param bundle
 *          the bundle to check.
 * @return {@code true} if the bundle needs to be resolved.
 */
boolean resolveBundlePossible(final Bundle bundle)
{
  final int state = bundle.getState();
  return (state & Bundle.INSTALLED) != 0;
}