Java Code Examples for org.osgi.framework.FrameworkUtil#getBundle()

The following examples show how to use org.osgi.framework.FrameworkUtil#getBundle() . 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: LaunchServiceTest.java    From JaxRSProviders with Apache License 2.0 6 votes vote down vote up
static <T> T getService(Class<T> clazz) {
	Bundle bundle = FrameworkUtil.getBundle(LaunchServiceTest.class);
	bundle.getBundleContext().getBundles();
	if (bundle != null) {
		ServiceTracker<T, T> st = new ServiceTracker<T, T>(bundle.getBundleContext(), clazz, null);
		st.open();
		if (st != null) {
			try {
				// give the runtime some time to startup
				return st.waitForService(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	return null;
}
 
Example 2
Source File: AddNodeTreeAction.java    From ice with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * The default constructor.
 */
public AddNodeTreeAction() {

	// Set the text and tool tip.
	setText("Add Child");
	setToolTipText("Add a child to the selected node.");

	// Set the image to be the green plus button.
	Bundle bundle = FrameworkUtil.getBundle(AddNodeTreeAction.class);
	Path imagePath = new Path(
			"icons" + System.getProperty("file.separator") + "add.png");
	URL imageURL = FileLocator.find(bundle, imagePath, null);
	setImageDescriptor(ImageDescriptor.createFromURL(imageURL));

	return;
}
 
Example 3
Source File: CcuGateway.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Load predefined scripts from an XML file.
 */
private Map<String, String> loadTclRegaScripts() throws IOException {
    Bundle bundle = FrameworkUtil.getBundle(getClass());
    try (InputStream stream = bundle.getResource("homematic/tclrega-scripts.xml").openStream()) {
        TclScriptList scriptList = (TclScriptList) xStream.fromXML(stream);
        Map<String, String> result = new HashMap<String, String>();
        if (scriptList.getScripts() != null) {
            for (TclScript script : scriptList.getScripts()) {
                result.put(script.name, StringUtils.trimToNull(script.data));
            }
        }
        return result;
    } catch (IllegalStateException | IOException e) {
        throw new IOException("The resource homematic/tclrega-scripts.xml could not be loaded!", e);
    }
}
 
Example 4
Source File: ImportFileAction.java    From ice with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Constructor
 */
public ImportFileAction(IWorkbenchWindow window) {

	// Set the action ID, Menu Text, and a tool tip.
	workbenchWindow = window;

	// Set the text properties.
	setId(ID);
	setText("&Import a file");
	setToolTipText("Import a file into ICE's "
			+ "project space for use by your items.");

	// Find the client bundle
	Bundle bundle = FrameworkUtil.getBundle(ImportFileAction.class);
	Path imagePath = new Path("icons"
			+ System.getProperty("file.separator") + "importArrow.gif");
	URL imageURL = FileLocator.find(bundle, imagePath, null);
	setImageDescriptor(ImageDescriptor.createFromURL(imageURL));

	return;
}
 
Example 5
Source File: EclipseLinkOSGiTransactionController.java    From lb-karaf-examples-jpa with Apache License 2.0 6 votes vote down vote up
@Override
protected TransactionManager acquireTransactionManager() throws Exception {
    Bundle bundle = FrameworkUtil.getBundle(EclipseLinkOSGiTransactionController.class);
    BundleContext ctx = bundle.getBundleContext();

    if (ctx != null) {
        ServiceReference<?> ref = ctx.getServiceReference(TransactionManager.class.getName());

        if (ref != null) {
            TransactionManager manager = (TransactionManager) ctx.getService(ref);
            return manager;
        }
    }

    return super.acquireTransactionManager();
}
 
Example 6
Source File: PlayAction.java    From ice with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * <p>
 * The function called whenever the button is clicked.
 * </p>
 */
@Override
public void run() {

	// Check that the button is in a clickable state
	if (viewer.isPlayable()) {
		// If the timer is not running, set up the play behavior
		if (!timer.isRunning()) {
			// Set the play rate
			timer.setDelay(delay);
			// Start the play loop
			timer.start();
			// Turn the play button into a pause button by changing its
			// "hover" text and image
			this.setText("Pause");
			Bundle bundle = FrameworkUtil.getBundle(getClass());
			Path imagePath = new Path("icons"
					+ System.getProperty("file.separator") + "pause.gif");
			URL imageURL = FileLocator.find(bundle, imagePath, null);
			ImageDescriptor imageDescriptor = ImageDescriptor
					.createFromURL(imageURL);
			this.setImageDescriptor(imageDescriptor);
		} else {
			// If the button is clicked while the timer is running, pause
			// instead
			stop();
		}
	}

	return;
}
 
Example 7
Source File: AbstractDiscoveryService.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Notifies the registered {@link DiscoveryListener}s about a discovered device.
 *
 * @param discoveryResult Holds the information needed to identify the discovered device.
 */
protected void thingDiscovered(final DiscoveryResult discoveryResult) {
    final DiscoveryResult discoveryResultNew;
    if (this.i18nProvider != null && this.localeProvider != null) {
        Bundle bundle = FrameworkUtil.getBundle(this.getClass());

        String defaultLabel = discoveryResult.getLabel();

        String key = I18nUtil.stripConstantOr(defaultLabel, () -> inferKey(discoveryResult, "label"));

        String label = this.i18nProvider.getText(bundle, key, defaultLabel, this.localeProvider.getLocale());

        discoveryResultNew = new DiscoveryResultImpl(discoveryResult.getThingTypeUID(),
                discoveryResult.getThingUID(), discoveryResult.getBridgeUID(), discoveryResult.getProperties(),
                discoveryResult.getRepresentationProperty(), label, discoveryResult.getTimeToLive());
    } else {
        discoveryResultNew = discoveryResult;
    }
    for (DiscoveryListener discoveryListener : discoveryListeners) {
        try {
            discoveryListener.thingDiscovered(this, discoveryResultNew);
        } catch (Exception e) {
            logger.error("An error occurred while calling the discovery listener {}.",
                    discoveryListener.getClass().getName(), e);
        }
    }
    synchronized (cachedResults) {
        cachedResults.put(discoveryResultNew.getThingUID(), discoveryResultNew);
    }
}
 
Example 8
Source File: SectionDescriptor.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Handle the section error when an issue is found loading from the
 * configuration element.
 *
 * @param exception
 *            an optional CoreException
 */
private void handleSectionError(CoreException exception) {
	String pluginId = getConfigurationElement().getDeclaringExtension()
			.getContributor().getName();
	String message = TabbedPropertyMessages.SectionDescriptor_Section_error;
	if (exception == null) {
		message = MessageFormat.format(TabbedPropertyMessages.SectionDescriptor_Section_error, pluginId);
	} else {
		message = MessageFormat.format(TabbedPropertyMessages.SectionDescriptor_class_not_found_error, pluginId);
	}
	IStatus status = new Status(IStatus.ERROR, pluginId,
			TabbedPropertyViewStatusCodes.SECTION_ERROR, message, exception);
	Bundle bundle = FrameworkUtil.getBundle(SectionDescriptor.class);
	Platform.getLog(bundle).log(status);
}
 
Example 9
Source File: ApplicationStatusHandler.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static BundleInfo bundleInfo(Object component) {
    try {
        Bundle bundle = FrameworkUtil.getBundle(component.getClass());

        String bundleName = bundle != null ?
                bundle.getSymbolicName() + ":" + bundle.getVersion() :
                "From classpath";
        return new BundleInfo(component.getClass().getName(), bundleName);
    } catch (Exception | NoClassDefFoundError e) {
        return new BundleInfo("Unavailable, reconfiguration in progress.", "");
    }
}
 
Example 10
Source File: TemplatesTest.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
private static InputStream getDataFile(String fileName) throws IOException {
  Bundle bundle = FrameworkUtil.getBundle(TemplatesTest.class);
  URL expectedFileUrl = bundle.getResource("/testData/templates/appengine/" + fileName);
  if (expectedFileUrl == null) {
    throw new IOException("Could not find comparison file " + fileName);
  }
  return expectedFileUrl.openStream();
}
 
Example 11
Source File: JavaOSGiTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Initialize the {@link BundleContext}, which is used for registration and unregistration of OSGi services.
 *
 * <p>
 * This uses the bundle context of the test class itself.
 *
 * @return bundle context
 */
private @Nullable BundleContext initBundleContext() {
    final Bundle bundle = FrameworkUtil.getBundle(this.getClass());
    if (bundle != null) {
        return bundle.getBundleContext();
    } else {
        return null;
    }
}
 
Example 12
Source File: ChannelStateDescriptionProviderOSGiTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Bundle resolveBundle(@Nullable Class<?> clazz) {
    if (clazz != null && clazz.equals(AbstractThingHandler.class)) {
        return testBundle;
    } else {
        return FrameworkUtil.getBundle(clazz);
    }
}
 
Example 13
Source File: Compat.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private Compat() {
    Bundle bundle = FrameworkUtil.getBundle(Compat.class);
    if (bundle != null) {
        BundleContext bundleContext = bundle.getBundleContext();
        managementContextTracker = new ServiceTracker(bundleContext, ManagementContext.class, null);
        managementContextTracker.open();
    } else {
        managementContextTracker = null;
    }
}
 
Example 14
Source File: ProductVersion.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private static String manifestVersion() {
    Bundle bundle = FrameworkUtil.getBundle(ProductVersion.class);
    if (bundle == null) {
        String implementationVersion = ProductVersion.class.getPackage().getImplementationVersion();
        if (implementationVersion == null) {
            return "7.6.0";//fake version used in unit test
        }
        return stripSnaphot(implementationVersion);
    }
    Version version = bundle.getVersion();
    return String.format("%s.%s.%s", version.getMajor(), version.getMinor(), version.getMicro());
}
 
Example 15
Source File: AnnotatedThingActionModuleTypeProvider.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private @Nullable ModuleType localizeModuleType(String uid, @Nullable Locale locale) {
    Set<ModuleInformation> mis = moduleInformation.get(uid);
    if (mis != null && !mis.isEmpty()) {
        ModuleInformation mi = mis.iterator().next();

        Bundle bundle = FrameworkUtil.getBundle(mi.getActionProvider().getClass());
        ModuleType mt = helper.buildModuleType(uid, moduleInformation);

        ModuleType localizedModuleType = moduleTypeI18nService.getModuleTypePerLocale(mt, locale, bundle);
        return localizedModuleType;
    }
    return null;
}
 
Example 16
Source File: WorkingSetExtrasPluginPDETest.java    From eclipse-extras with Eclipse Public License 1.0 4 votes vote down vote up
@Before
public void setUp() {
  bundle = FrameworkUtil.getBundle( WorkingSetExtrasPlugin.class );
}
 
Example 17
Source File: JDTExtrasPluginPDETest.java    From eclipse-extras with Eclipse Public License 1.0 4 votes vote down vote up
@Before
public void setUp() {
  bundle = FrameworkUtil.getBundle( JDTExtrasPlugin.class );
}
 
Example 18
Source File: TargetPlatformUtil.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Sets the target platform for tests (to be used in tycho mainly)
 * @param context any class of the test bundle to be able to determine the test bundle
 * @since 2.14
 */
public static void setTargetPlatform(Class<?> context) throws Exception {
	if (isPdeLaunch()) {
		return;
	}
	Bundle currentBundle = FrameworkUtil.getBundle(context);
	ITargetPlatformService tpService = TargetPlatformService.getDefault();
	ITargetDefinition targetDef = tpService.newTarget();
	targetDef.setName("Tycho platform");
	Bundle[] bundles = Platform.getBundle("org.eclipse.core.runtime").getBundleContext().getBundles();
	List<ITargetLocation> bundleContainers = new ArrayList<ITargetLocation>();
	Set<File> dirs = new HashSet<File>();
	for (Bundle bundle : bundles) {
		if (bundle.equals(currentBundle)) {
			// we skip the current bundle, otherwise the folder for the target platform
			// will include the absolute directory of the maven parent project
			// since the projects are nested in the parent project the result
			// would be that Java packages of our project will be available twice
			// and Java won't be able to find our classes leading in compilation
			// errors during our tests.
			continue;
		}
		EquinoxBundle bundleImpl = (EquinoxBundle) bundle;
		Generation generation = (Generation) bundleImpl.getModule().getCurrentRevision().getRevisionInfo();
		File file = generation.getBundleFile().getBaseFile();
		File folder = file.getParentFile();
		if ((file.isFile() || Platform.inDevelopmentMode()) && !dirs.contains(folder)) {
			dirs.add(folder);
			bundleContainers.add(tpService.newDirectoryLocation(folder.getAbsolutePath()));
		}
	}
	targetDef.setTargetLocations(bundleContainers.toArray(new ITargetLocation[bundleContainers.size()]));
	targetDef.setArch(Platform.getOSArch());
	targetDef.setOS(Platform.getOS());
	targetDef.setWS(Platform.getWS());
	targetDef.setNL(Platform.getNL());
	// targetDef.setJREContainer()
	tpService.saveTargetDefinition(targetDef);

	Job job = new LoadTargetDefinitionJob(targetDef);
	job.schedule();
	job.join();
}
 
Example 19
Source File: BundleResolverImpl.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Bundle resolveBundle(Class<?> clazz) {
    return FrameworkUtil.getBundle(clazz);
}
 
Example 20
Source File: DataRepositoryServerManager.java    From bonita-studio with GNU General Public License v2.0 4 votes vote down vote up
private Path extractLocation() {
    Bundle bundle = FrameworkUtil.getBundle(UIDesignerServerManager.class);
    IPath stateLoc = Platform.getStateLocation(bundle);
    return stateLoc.toFile().toPath();
}