Java Examples for org.osgi.framework.FrameworkUtil
The following java examples will help you to understand the usage of org.osgi.framework.FrameworkUtil. These source code samples are taken from different open source projects.
Example 1
Project: konekti-master File: PermissionViewForm.java View source code |
@SuppressWarnings({ "unchecked", "rawtypes" })
private void getServices() {
try {
BundleContext bundleContext = FrameworkUtil.getBundle(PermissionViewForm.class).getBundleContext();
ServiceReference menuCommandResourceServiceReference = bundleContext.getServiceReference(MenuCommandResourceService.class.getName());
menuCommandResourceService = MenuCommandResourceService.class.cast(bundleContext.getService(menuCommandResourceServiceReference));
} catch (Exception e) {
e.getMessage();
}
}
Example 2
Project: BETaaS_Platform-Tools-master File: HibernateSupport.java View source code |
private static EntityManagerFactory getEntityManagerFactory() {
if (emf == null) {
Bundle thisBundle = FrameworkUtil.getBundle(HibernateSupport.class);
// Could get this by wiring up OsgiTestBundleActivator as well.
BundleContext context = thisBundle.getBundleContext();
ServiceReference serviceReference = context.getServiceReference(PersistenceProvider.class.getName());
PersistenceProvider persistenceProvider = (PersistenceProvider) context.getService(serviceReference);
emf = persistenceProvider.createEntityManagerFactory(CONFIG_PROP, null);
}
return emf;
}
Example 3
Project: arduino-eclipse-plugin-master File: PleaseHelp.java View source code |
@Override
protected Control createContents(Composite parent) {
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
parent.setLayout(gridLayout);
try {
this.browser = new Browser(parent, SWT.NONE);
} catch (SWTError e) {
System.out.println("Could not instantiate Browser: " + e.getMessage());
}
GridData data = new GridData();
data.horizontalAlignment = GridData.FILL;
data.verticalAlignment = GridData.FILL;
data.horizontalSpan = 3;
data.grabExcessHorizontalSpace = true;
data.grabExcessVerticalSpace = true;
this.browser.setLayoutData(data);
this.browser.addProgressListener(new ProgressListener() {
@Override
public void changed(ProgressEvent event) {
// I'm not interested in change
}
@Override
public void completed(ProgressEvent event) {
PleaseHelp.this.ph.setBlockOnOpen(false);
PleaseHelp.this.ph.open();
}
});
this.buttonBar = createButtonBar(parent);
org.osgi.framework.Version version = FrameworkUtil.getBundle(getClass()).getVersion();
//$NON-NLS-1$
String url = myhelpLocation + "?os=" + Platform.getOS();
//$NON-NLS-1$
url += "&arch=" + Platform.getOSArch();
//$NON-NLS-1$
url += "&majorVersion=" + version.getMajor();
//$NON-NLS-1$
url += "&minorVersion=" + version.getMinor();
//$NON-NLS-1$
url += "µVersion=" + version.getMicro();
//$NON-NLS-1$
url += "&qualifierVersion=" + version.getQualifier();
this.browser.setUrl(url);
return parent;
}
Example 4
Project: CopyTo-master File: HistoryViewPart.java View source code |
@Override
public void createPartControl(Composite parent) {
final Composite client = new Composite(parent, SWT.NULL);
viewer = new TreeViewer(client, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.FULL_SELECTION);
final TreeColumnLayout tableLayout = new TreeColumnLayout();
client.setLayout(tableLayout);
final Tree table = viewer.getTree();
table.setLinesVisible(true);
table.setHeaderVisible(true);
table.setFont(parent.getFont());
final DataBindingContext ctx = new DataBindingContext();
table.addDisposeListener(new DisposeListener() {
public void widgetDisposed(final DisposeEvent e) {
ctx.dispose();
viewer = null;
}
});
final String[] columnNames = new String[] { "target.name" };
final String[] columnLables = new String[] { "Target" };
for (int i = 0; i < columnNames.length; ++i) {
final TreeViewerColumn viewerColumn = new TreeViewerColumn(viewer, SWT.LEFT);
viewerColumn.getColumn().setText(columnLables[i]);
tableLayout.setColumnData(viewerColumn.getColumn(), new ColumnWeightData(i == columnNames.length - 1 ? 100 : 30));
}
items = new WritableList();
MultiListProperty childrenProp = new MultiListProperty(new IListProperty[] { PojoProperties.list("successes"), PojoProperties.list("failures") });
/*ViewerSupport.bind(viewer, items, childrenProp, BeanProperties
.values(columnNames));*/
ObservableListTreeContentProvider contentProvider = new ObservableListTreeContentProvider(childrenProp.listFactory(), null);
viewer.setContentProvider(contentProvider);
ObservableMapLabelProvider labelProvider = new ObservableMapLabelProvider(BeanProperties.value("target.name").observeDetail(contentProvider.getKnownElements())) {
public String getText(Object element) {
if (element instanceof Result) {
}
return super.getText(element);
}
};
viewer.setLabelProvider(labelProvider);
viewer.setInput(items);
serviceRegistration = FrameworkUtil.getBundle(getClass()).getBundleContext().registerService(UIResultHandler.class.getName(), this, null);
}
Example 5
Project: dynamic-extensions-testrunner-master File: TestRunner.java View source code |
@Override
protected Object createTest() throws Exception {
final Bundle testBundle = FrameworkUtil.getBundle(testClazz);
// check if test is defined as Spring component
final ApplicationContext testContext = ContextUtils.findApplicationContext(testBundle.getSymbolicName());
if (testContext != null) {
try {
return testContext.getBean(testClazz);
} catch (NoSuchBeanDefinitionException ignore) {
}
}
return testClazz.newInstance();
}
Example 6
Project: e-fx-clipse-master File: AbstractThemeProcessor.java View source code |
@Execute
public void process() {
if (!check()) {
return;
}
// FIXME Remove once bug 314091 is resolved
Bundle bundle = FrameworkUtil.getBundle(getClass());
BundleContext context = bundle.getBundleContext();
ServiceReference reference = context.getServiceReference(ThemeManager.class.getName());
ThemeManager themeManager = (ThemeManager) context.getService(reference);
List<Theme> themes = themeManager.getAvailableThemes();
if (themes.size() > 0) {
MApplication application = getApplication();
MCommand switchThemeCommand = null;
for (MCommand cmd : application.getCommands()) {
if (//$NON-NLS-1$
"contacts.switchTheme".equals(cmd.getElementId())) {
switchThemeCommand = cmd;
break;
}
}
if (switchThemeCommand != null) {
preprocess();
for (Theme theme : themes) {
MParameter parameter = MCommandsFactory.INSTANCE.createParameter();
parameter.setName("contacts.commands.switchtheme.themeid");
parameter.setValue(theme.getId());
String iconURI = getCSSUri(theme.getId());
if (iconURI != null) {
iconURI = iconURI.replace(".css", ".png");
}
processTheme(theme.getName(), switchThemeCommand, parameter, iconURI);
}
postprocess();
}
}
}
Example 7
Project: emap-master File: EMapRuntimeModule.java View source code |
@Override
public IEClassLookupService get() {
BundleContext bundleContext = FrameworkUtil.getBundle(EMapRuntimeModule.class).getBundleContext();
ServiceReference<IEClassLookupService> lookupServiceReference = bundleContext.getServiceReference(IEClassLookupService.class);
if (lookupServiceReference != null) {
return bundleContext.getService(lookupServiceReference);
} else {
return null;
}
}
Example 8
Project: liferay-ide-master File: AutoCorrectAllAction.java View source code |
public void run() {
final BundleContext context = FrameworkUtil.getBundle(AutoCorrectAction.class).getBundleContext();
WorkspaceJob job = new WorkspaceJob("Auto correcting all of migration problem.") {
@Override
public IStatus runInWorkspace(IProgressMonitor monitor) {
IStatus retval = Status.OK_STATUS;
try {
if (_problemsContainerList != null) {
for (ProblemsContainer problemsContainer : _problemsContainerList) {
for (UpgradeProblems upgradeProblems : problemsContainer.getProblemsArray()) {
FileProblems[] FileProblemsArray = upgradeProblems.getProblems();
for (FileProblems fileProblems : FileProblemsArray) {
List<Problem> problems = fileProblems.getProblems();
for (Problem problem : problems) {
if (problem.autoCorrectContext != null) {
String autoCorrectKey = null;
final int filterKeyIndex = problem.autoCorrectContext.indexOf(":");
if (filterKeyIndex > -1) {
autoCorrectKey = problem.autoCorrectContext.substring(0, filterKeyIndex);
} else {
autoCorrectKey = problem.autoCorrectContext;
}
final Collection<ServiceReference<AutoMigrator>> refs = context.getServiceReferences(AutoMigrator.class, "(auto.correct=" + autoCorrectKey + ")");
final IResource file = MigrationUtil.getIResourceFromProblem(problem);
for (ServiceReference<AutoMigrator> ref : refs) {
final AutoMigrator autoMigrator = context.getService(ref);
int problemsCorrected = autoMigrator.correctProblems(problem.file, problems);
if (problemsCorrected > 0 && file != null) {
IMarker problemMarker = file.findMarker(problem.markerId);
if (problemMarker != null && problemMarker.exists()) {
problemMarker.delete();
}
}
}
file.refreshLocal(IResource.DEPTH_ONE, monitor);
}
}
}
}
}
}
UIUtil.sync(new Runnable() {
@Override
public void run() {
IViewPart view = UIUtil.findView(UpgradeView.ID);
new RunMigrationToolAction("Run Migration Tool", view.getViewSite().getShell()).run();
}
});
} catch (InvalidSyntaxException e) {
} catch (AutoMigrateExceptionCoreException | e) {
return retval = ProjectUI.createErrorStatus("Unable to auto correct problem", e);
}
return retval;
}
};
job.schedule();
}
Example 9
Project: recommenders-master File: IndexProvider.java View source code |
@VisibleForTesting
static File computeIndexDir(IJavaProject project) {
Bundle bundle = FrameworkUtil.getBundle(IndexProvider.class);
File location = Platform.getStateLocation(bundle).toFile();
//$NON-NLS-1$ //$NON-NLS-2$
String mangledProjectName = project.getElementName().replaceAll("\\W", "_");
File indexDir = new File(new File(location, INDEX_DIR), mangledProjectName);
return indexDir;
}
Example 10
Project: sapphire-master File: ExtensionsLocatorFactory.java View source code |
@Override
public synchronized List<Handle> find() {
if (this.handles == null) {
final BundleContext context = FrameworkUtil.getBundle(ExtensionsLocatorFactory.class).getBundleContext();
final ListFactory<Handle> handlesListFactory = ListFactory.start();
for (final Bundle bundle : context.getBundles()) {
final int state = bundle.getState();
if (state == Bundle.RESOLVED || state == Bundle.STARTING || state == Bundle.ACTIVE) {
final URL url = bundle.getEntry(DEFAULT_PATH);
if (url != null) {
boolean ok = false;
try {
// Verify that the bundle is using this version of Sapphire before trying to
// load its extensions.
ok = (bundle.loadClass(Sapphire.class.getName()) == Sapphire.class);
} catch (Exception e) {
}
if (ok) {
handlesListFactory.add(new Handle(url, BundleBasedContext.adapt(bundle)));
}
}
}
}
this.handles = handlesListFactory.result();
}
return this.handles;
}
Example 11
Project: tapiji-master File: ResourceLoader.java View source code |
@Override
public Image loadImage(final String path) {
Image img = IMAGES.get(path);
if (null == img) {
final Bundle bundle = FrameworkUtil.getBundle(ResourceLoader.class);
final URL url = FileLocator.find(bundle, new Path(path), null);
final ImageDescriptor imageDescr = ImageDescriptor.createFromURL(url);
img = imageDescr.createImage();
IMAGES.put(path, img);
}
return img;
}
Example 12
Project: cxf-master File: SpringOsgiUtil.java View source code |
public static ResourcePatternResolver getResolver(ClassLoader loader) {
Bundle bundle = null;
if (loader == null) {
loader = Thread.currentThread().getContextClassLoader();
}
if (loader instanceof BundleDelegatingClassLoader) {
bundle = ((BundleDelegatingClassLoader) loader).getBundle();
} else {
bundle = FrameworkUtil.getBundle(SpringClasspathScanner.class);
}
return bundle != null ? new OsgiBundleResourcePatternResolver(bundle) : null;
}
Example 13
Project: accesscontroltool-master File: GlobalConfigurationValidator.java View source code |
private static void checkForValidVersion(String configuredMinRequiredVersion) {
String bundleVersion = FrameworkUtil.getBundle(GlobalConfigurationValidator.class).getVersion().toString();
boolean isVersionValid = versionCompare(bundleVersion, configuredMinRequiredVersion) >= 0;
if (!isVersionValid) {
throw new IllegalArgumentException("AC Tool Version " + bundleVersion + " is too old for configuration (MinRequiredVersion=" + configuredMinRequiredVersion + ")");
}
}
Example 14
Project: aries-master File: ResourceHelper.java View source code |
public static boolean matches(Requirement requirement, Capability capability) {
// if (logger.isDebugEnabled())
// logger.debug(LOG_ENTRY, "matches", new Object[]{requirement, capability});
boolean result = false;
if (requirement == null && capability == null)
result = true;
else if (requirement == null || capability == null)
result = false;
else if (!capability.getNamespace().equals(requirement.getNamespace()))
result = false;
else {
String filterStr = requirement.getDirectives().get(Constants.FILTER_DIRECTIVE);
if (filterStr == null)
result = true;
else {
try {
if (FrameworkUtil.createFilter(filterStr).matches(capability.getAttributes()))
result = true;
} catch (InvalidSyntaxException e) {
logger.debug("Requirement had invalid filter string: " + requirement, e);
result = false;
}
}
}
// logger.debug(LOG_EXIT, "matches", result);
return result;
}
Example 15
Project: arquillian-extension-liferay-master File: LiferayWaitForServiceObserver.java View source code |
public void execute(@Observes(precedence = Integer.MAX_VALUE) EventContext<BeforeSuite> event) throws InvalidSyntaxException { Bundle bundle = FrameworkUtil.getBundle(getClass()); BundleContext bundleContext = bundle.getBundleContext(); Filter filter = FrameworkUtil.createFilter("(&(objectClass=org.springframework.context.ApplicationContext)" + "(org.springframework.context.service.name=" + bundleContext.getBundle().getSymbolicName() + "))"); ServiceTracker<ApplicationContext, ApplicationContext> serviceTracker = new ServiceTracker<>(bundleContext, filter, null); serviceTracker.open(); try { serviceTracker.waitForService(30 * 1000L); } catch (InterruptedException e) { throw new RuntimeException(e); } serviceTracker.close(); event.proceed(); }
Example 16
Project: blade.tools-master File: MigrateCommand.java View source code |
private void execute() throws Exception {
File projectDir = new File(options._arguments().get(0));
if (!projectDir.exists()) {
addError("migrate", "projectDir does not exist");
return;
}
final BundleContext context = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
Format format = options.format();
FileOutputStream fos = null;
if (options._arguments().size() > 1) {
File file = new File(options._arguments().get(1));
if (!file.exists()) {
file.createNewFile();
}
fos = new FileOutputStream(file);
}
ServiceReference<Migration> migrationSR = context.getServiceReference(Migration.class);
Migration migrationService = context.getService(migrationSR);
List<Problem> problems = migrationService.findProblems(projectDir, new ConsoleProgressMonitor());
String formatValue = format != null ? format.toString() : "";
if (options.detailed()) {
migrationService.reportProblems(problems, Migration.DETAIL_LONG, formatValue, fos);
} else {
migrationService.reportProblems(problems, Migration.DETAIL_SHORT, formatValue, fos);
}
}
Example 17
Project: bnd-master File: BasicTestReport.java View source code |
public void startTest(Test test) {
activator.trace(" >> %s", test);
check();
Bundle b = targetBundle;
if (b == null)
b = FrameworkUtil.getBundle(test.getClass());
if (b != null) {
BundleContext context = b.getBundleContext();
activator.trace("got bundle context %s from %s in state %s", context, b, b.getState());
assert context != null;
try {
Method m = test.getClass().getMethod("setBundleContext", new Class[] { BundleContext.class });
m.setAccessible(true);
m.invoke(test, new Object[] { context });
activator.trace("set context through setter");
} catch (Exception e) {
Field f;
try {
f = test.getClass().getField("context");
f.setAccessible(true);
f.set(test, context);
activator.trace("set context in field");
} catch (Exception e1) {
}
}
}
fails = result.failureCount();
errors = result.errorCount();
systemOut.clear().capture(true).echo(true);
systemErr.clear().capture(true).echo(true);
}
Example 18
Project: central-icon-management-master File: IconURLStreamHandlerService.java View source code |
@SuppressWarnings("unchecked")
public void register() {
Bundle bundle = FrameworkUtil.getBundle(IconURLStreamHandlerService.class);
BundleContext bundleContext = bundle.getBundleContext();
try {
@SuppressWarnings("rawtypes") Hashtable properties = new Hashtable();
properties.put(URLConstants.URL_HANDLER_PROTOCOL, new String[] { "icon" });
iconUrlHandler = bundleContext.registerService(URLStreamHandlerService.class, this, properties);
} catch (Exception e) {
LogHelper.logError("Could not register icon URL handler.", e);
}
LogHelper.logInfo("Icon URL handler registered.");
}
Example 19
Project: ch.hsr.ifs.cdttesting-master File: ShowInPASTAHandler.java View source code |
private void sendEvent(final Object data) {
final Event selectionEvent = new Event(PastaEventConstants.SHOW_SELECTION, createMap(data));
final BundleContext ctx = FrameworkUtil.getBundle(ASTView.class).getBundleContext();
final ServiceReference<?> ref = ctx.getServiceReference(EventAdmin.class.getName());
if (ref != null) {
final EventAdmin admin = (EventAdmin) ctx.getService(ref);
admin.sendEvent(selectionEvent);
ctx.ungetService(ref);
}
}
Example 20
Project: eclipse-team-etceteras-master File: PluginImages.java View source code |
/**
* Initialize the image register.
*
* @param registry the {@link ImageRegistry} to initialize
*/
public static void initializeImageRegistry(ImageRegistry registry) {
String imagePath = null;
ImageDescriptor descriptor = null;
// load images to image register
for (int i = 0; i < IMAGE_IDS.length; i++) {
imagePath = IMAGE_IDS[i];
descriptor = AbstractUIPlugin.imageDescriptorFromPlugin(FrameworkUtil.getBundle(PluginImages.class).getSymbolicName(), imagePath);
registry.put(IMAGE_IDS[i], descriptor);
}
}
Example 21
Project: elexis-3-core-master File: FindingsDataAccessor.java View source code |
private Object getService(Class<?> clazz) {
// use osgi service reference to get the service
BundleContext context = FrameworkUtil.getBundle(FindingsDataAccessor.class).getBundleContext();
if (context != null) {
ServiceReference<?> serviceReference = context.getServiceReference(clazz.getName());
if (serviceReference != null) {
return context.getService(serviceReference);
}
}
return null;
}
Example 22
Project: EmfStore-e4-master File: JavaAttribute.java View source code |
public String getContextKey() {
if (isInjected()) {
Named named = field.getAnnotation(Named.class);
if (named != null) {
//$NON-NLS-1$ //$NON-NLS-2$
return "@Named(" + named.value() + ")";
}
Preference preference = field.getAnnotation(Preference.class);
if (preference != null) {
String path = preference.nodePath();
if (path == null || path.trim().length() == 0) {
path = FrameworkUtil.getBundle(getFieldValue().getClass()).getSymbolicName();
}
//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return "@Preference(" + preference.nodePath() + "/" + preference.value() + ")";
}
EventTopic topic = field.getAnnotation(EventTopic.class);
if (topic != null) {
//$NON-NLS-1$//$NON-NLS-2$
return "@Topic(" + topic.value() + ")";
}
UIEventTopic uiTopic = field.getAnnotation(UIEventTopic.class);
if (uiTopic != null) {
//$NON-NLS-1$ //$NON-NLS-2$
return "@UITopic(" + uiTopic.value() + ")";
}
Translation translation = field.getAnnotation(Translation.class);
if (translation != null) {
//$NON-NLS-1$//$NON-NLS-2$
return "@Translation(" + field.getType().getName() + ")";
}
return field.getType().getName();
}
//$NON-NLS-1$
return "";
}
Example 23
Project: felix-master File: MemoryRoleRepositoryStore.java View source code |
public Role[] getRoles(String filterValue) throws Exception {
Collection roles = m_entries.values();
Filter filter = null;
if (filterValue != null) {
filter = FrameworkUtil.createFilter(filterValue);
}
List matchingRoles = new ArrayList();
Iterator rolesIter = roles.iterator();
while (rolesIter.hasNext()) {
Role role = (Role) rolesIter.next();
if ((filter == null) || filter.match(role.getProperties())) {
matchingRoles.add(role);
}
}
Role[] result = new Role[matchingRoles.size()];
return (Role[]) matchingRoles.toArray(result);
}
Example 24
Project: genModelAddon-master File: Util.java View source code |
public static void saveGenModel(GenModel gm, Shell parentShell) {
final Map<Object, Object> opt = new HashMap<Object, Object>();
opt.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
opt.put(Resource.OPTION_LINE_DELIMITER, Resource.OPTION_LINE_DELIMITER_UNSPECIFIED);
try {
gm.eResource().save(opt);
} catch (IOException e) {
MessageDialog.openInformation(parentShell, "genModel could not be saved", "The genmodel could not be saved.\nReason is : " + e.getMessage());
Bundle bundle = FrameworkUtil.getBundle(Util.class);
ILog logger = Platform.getLog(bundle);
logger.log(new Status(IStatus.WARNING, bundle.getSymbolicName(), "Unable to save the genModel in : " + gm.eResource(), e));
}
}
Example 25
Project: hibernate-demos-master File: HibernateUtil.java View source code |
private SessionFactory getSessionFactory() {
if (sf == null) {
Bundle thisBundle = FrameworkUtil.getBundle(HibernateUtil.class);
// Could get this by wiring up OsgiTestBundleActivator as well.
BundleContext context = thisBundle.getBundleContext();
ServiceReference sr = context.getServiceReference(SessionFactory.class.getName());
sf = (SessionFactory) context.getService(sr);
}
return sf;
}
Example 26
Project: hibernate-orm-master File: OsgiPersistenceProviderService.java View source code |
@Override public Object getService(Bundle requestingBundle, ServiceRegistration registration) { final OsgiClassLoader osgiClassLoader = new OsgiClassLoader(); // First, add the client bundle that's requesting the OSGi services. osgiClassLoader.addBundle(requestingBundle); // Then, automatically add hibernate-core and hibernate-entitymanager. These are needed to load resources // contained in those jars, such as em's persistence.xml schemas. osgiClassLoader.addBundle(FrameworkUtil.getBundle(SessionFactory.class)); osgiClassLoader.addBundle(FrameworkUtil.getBundle(HibernateEntityManagerFactory.class)); // Some "boot time" code does still rely on TCCL. "run time" code should all be using // ClassLoaderService now. final ClassLoader originalTccl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(osgiClassLoader); try { return new OsgiPersistenceProvider(osgiClassLoader, osgiJtaPlatform, osgiServiceUtil, requestingBundle); } finally { Thread.currentThread().setContextClassLoader(originalTccl); } }
Example 27
Project: infinispan-master File: ServiceLocator.java View source code |
public static <T> T getOsgiService(Class<T> type, String filter, long timeout) {
BundleContext bundleContext = getBundleContext();
ServiceTracker tracker = null;
try {
String flt;
if (filter != null) {
if (filter.startsWith("(")) {
flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")" + filter + ")";
} else {
flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")(" + filter + "))";
}
} else {
flt = "(" + Constants.OBJECTCLASS + "=" + type.getName() + ")";
}
Filter osgiFilter = FrameworkUtil.createFilter(flt);
tracker = new ServiceTracker(bundleContext, osgiFilter, null);
tracker.open(true);
// Note that the tracker is not closed to keep the reference
// This is buggy, as the service reference may change i think
Object svc = type.cast(tracker.waitForService(timeout));
if (svc == null) {
Dictionary<String, String> dic = bundleContext.getBundle().getHeaders();
System.err.println("Test bundle headers: " + explode(dic));
for (ServiceReference ref : asCollection(bundleContext.getAllServiceReferences(null, null))) {
System.err.println("ServiceReference: " + ref);
}
for (ServiceReference ref : asCollection(bundleContext.getAllServiceReferences(null, flt))) {
System.err.println("Filtered ServiceReference: " + ref);
}
throw new RuntimeException("Gave up waiting for service " + flt);
}
return type.cast(svc);
} catch (InvalidSyntaxException e) {
throw new IllegalArgumentException("Invalid filter", e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
Example 28
Project: jabylon-master File: TeamProviderUtil.java View source code |
public static List<String> getAvailableTeamProviders() {
Bundle bundle = FrameworkUtil.getBundle(TeamProviderUtil.class);
BundleContext context = bundle.getBundleContext();
List<String> providers = new ArrayList<String>();
try {
Collection<ServiceReference<TeamProvider>> references = context.getServiceReferences(TeamProvider.class, null);
for (ServiceReference<TeamProvider> reference : references) {
Object property = reference.getProperty(TeamProvider.KEY_KIND);
if (property == null) {
LOGGER.error("Team provider service has no 'kind' property. Ignoring team provider from " + reference.getBundle());
} else {
providers.add(property.toString());
}
}
} catch (InvalidSyntaxException e) {
LOGGER.error("Failed to retrieve service references", e);
}
return providers;
}
Example 29
Project: jbosgi-master File: SimpleAnnotatedServlet.java View source code |
@PostConstruct
public void messageSetup() {
echo = new Echo() {
@Override
public String echo(String msg) {
String bundle = null;
try {
bundle = FrameworkUtil.getBundle(SimpleAnnotatedServlet.class).getSymbolicName();
} catch (Throwable th) {
}
return bundle + " called with: " + msg;
}
};
}
Example 30
Project: karaf-cave-master File: Activator.java View source code |
@Override
protected void doStart() throws Exception {
CaveRepositoryServiceImpl service = new CaveRepositoryServiceImpl();
service.setBundleContext(FrameworkUtil.getBundle(Activator.class).getBundleContext());
service.setStorageLocation(new File(getString("cave.storage.location", System.getProperty("karaf.data") + File.separator + "cave")));
service.init();
register(CaveRepositoryService.class, service);
}
Example 31
Project: lb-karaf-examples-jpa-master File: EclipseLinkOSGiTransactionController.java View source code |
@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 32
Project: liferay-portal-master File: ServiceTrackerTest.java View source code |
@Test
public void testUnregisterServiceDuringServiceTrackerClosing() {
Bundle bundle = FrameworkUtil.getBundle(ServiceTrackerTest.class);
BundleContext bundleContext = bundle.getBundleContext();
TestService testService1 = new TestService();
ServiceRegistration<TestService> serviceRegistration1 = bundleContext.registerService(TestService.class, testService1, null);
ServiceReference<TestService> serviceReference1 = serviceRegistration1.getReference();
TestService testService2 = new TestService();
ServiceRegistration<TestService> serviceRegistration2 = bundleContext.registerService(TestService.class, testService2, null);
ServiceReference<TestService> serviceReference2 = serviceRegistration2.getReference();
testService1._serviceRegistration = serviceRegistration2;
testService2._serviceRegistration = serviceRegistration1;
List<ObjectValuePair<ServiceReference<TestService>, Bundle>> objectValuePairs = new ArrayList<>();
ServiceTracker<TestService, TestService> serviceTracker = new ServiceTracker<TestService, TestService>(bundleContext, TestService.class, null) {
@Override
public void removedService(ServiceReference<TestService> serviceReference, TestService testService) {
objectValuePairs.add(new ObjectValuePair<>(serviceReference, serviceReference.getBundle()));
ServiceRegistration<TestService> serviceRegistration = testService._serviceRegistration;
serviceRegistration.unregister();
super.removedService(serviceReference, testService);
}
};
serviceTracker.open();
serviceTracker.close();
Assert.assertEquals(objectValuePairs.toString(), 2, objectValuePairs.size());
ObjectValuePair<ServiceReference<TestService>, Bundle> objectValuePair = objectValuePairs.get(0);
if (serviceReference1 == objectValuePair.getKey()) {
Assert.assertSame(bundle, objectValuePair.getValue());
objectValuePair = objectValuePairs.get(1);
Assert.assertSame(serviceReference2, objectValuePair.getKey());
Assert.assertNull(objectValuePair.getValue());
} else {
Assert.assertSame(serviceReference2, objectValuePair.getKey());
Assert.assertSame(bundle, objectValuePair.getValue());
objectValuePair = objectValuePairs.get(1);
Assert.assertSame(serviceReference1, objectValuePair.getKey());
Assert.assertNull(objectValuePair.getValue());
}
}
Example 33
Project: linuxtools-master File: RPMExportOperation.java View source code |
@Override public IStatus run(IProgressMonitor monitor) { IStatus result = null; if (rpmProject.getSpecFile() == null) { return new Status(IStatus.ERROR, FrameworkUtil.getBundle(this.getClass()).getSymbolicName(), Messages.getString("RPMExportOperation.No_Spec_File")); } IOConsoleOutputStream out = RpmConsole.findConsole(rpmProject).linkJob(this); if (out == null) { return Status.CANCEL_STATUS; } switch(exportType) { case ALL: try { monitor.beginTask(Messages.getString("RPMExportOperation.Executing_All_Export"), //$NON-NLS-1$ IProgressMonitor.UNKNOWN); result = rpmProject.buildAll(out); } catch (CoreException e) { result = new Status(IStatus.ERROR, FrameworkUtil.getBundle(this.getClass()).getSymbolicName(), e.getMessage(), e); } break; case BINARY: monitor.beginTask(Messages.getString("RPMExportOperation.Executing_RPM_Export"), //$NON-NLS-1$ IProgressMonitor.UNKNOWN); try { result = rpmProject.buildBinaryRPM(out); } catch (CoreException e) { result = new Status(IStatus.ERROR, FrameworkUtil.getBundle(this.getClass()).getSymbolicName(), e.getMessage(), e); } break; case SOURCE: monitor.beginTask(Messages.getString("RPMExportOperation.Executing_SRPM_Export"), //$NON-NLS-1$ IProgressMonitor.UNKNOWN); try { result = rpmProject.buildSourceRPM(out); } catch (CoreException e) { result = new Status(IStatus.ERROR, FrameworkUtil.getBundle(this.getClass()).getSymbolicName(), e.getMessage(), e); } break; } return result; }
Example 34
Project: lunifera-dsl-master File: MapperAccess.java View source code |
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public <D, E> IMapper<D, E> getToDtoMapper(Class<D> dto, Class<E> entity) {
TimeLogger logger = TimeLogger.start(MapperAccess.class);
Bundle bundle = FrameworkUtil.getBundle(getClass());
String filterString = String.format("(&(&(objectClass=%s)(fordto.to.dto=%s))(fordto.from.entity=%s))", IMapper.class.getCanonicalName(), dto.getCanonicalName(), entity.getCanonicalName());
try {
BundleContext context = bundle.getBundleContext();
Collection<ServiceReference<IMapper>> references = context.getServiceReferences(IMapper.class, filterString);
if (!references.isEmpty()) {
ServiceReference<IMapper> reference = references.iterator().next();
IMapper<D, E> mapper = context.getService(reference);
return mapper;
}
} catch (InvalidSyntaxException e) {
LOGGER.error("{}", e);
} finally {
logger.stop("Accessing mapper took: ");
}
LOGGER.error("No To-Dto-Mapper available for dto: {} and entity: {}", dto, entity);
return null;
}
Example 35
Project: Newsreader-master File: ServiceUtils.java View source code |
/**
* Returns an instance of the requested service or null if none could be
* found.
*
* @param requester
* the class of the requester of the service
* @param serviceClass
* the service class to look for
* @param filter
* OSGi filter
* @return an instance of the serviceClass or null if none was found or the
* filter syntax is invalid.
*/
public static <T extends Object> T getOSGiService(Class<?> requester, Class<T> serviceClass, String filter) {
BundleContext context = FrameworkUtil.getBundle(requester).getBundleContext();
Collection<ServiceReference<T>> serviceReferences;
try {
serviceReferences = context.getServiceReferences(serviceClass, filter);
} catch (InvalidSyntaxException e) {
e.printStackTrace();
return null;
}
if (serviceReferences.isEmpty()) {
return null;
}
return context.getService(serviceReferences.iterator().next());
}
Example 36
Project: nic-master File: ListenerProviderModule.java View source code |
@Override
public java.lang.AutoCloseable createInstance() {
// Retrieve reference for OFRenderer service
BundleContext context = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
ServiceReference<?> ofServiceReference = context.getServiceReference(OFRendererFlowService.class);
OFRendererFlowService flowService = (OFRendererFlowService) context.getService(ofServiceReference);
ServiceReference<?> graphServiceReference = context.getServiceReference(OFRendererGraphService.class);
ServiceReference<?> intentCommonReference = context.getServiceReference(IntentCommonProviderService.class);
ServiceReference<?> stateMachineExecutorServiceReference = context.getServiceReference(IntentStateMachineExecutorService.class);
OFRendererGraphService graphService = (OFRendererGraphService) context.getService(graphServiceReference);
IntentCommonProviderService intentCommonProviderService = (IntentCommonProviderService) context.getService(intentCommonReference);
IntentStateMachineExecutorService stateMachineExecutorService = (IntentStateMachineExecutorService) context.getService(stateMachineExecutorServiceReference);
final ListenerProviderImpl provider = new ListenerProviderImpl(getDataBrokerDependency(), getNotificationAdapterDependency(), flowService, graphService, intentCommonProviderService.retrieveCommonServiceInstance(), stateMachineExecutorService);
provider.start();
LOG.info("\nNIC Listeners started successfully.");
return provider;
}
Example 37
Project: onos-master File: DefaultServiceDirectory.java View source code |
/**
* Returns the reference to the implementation of the specified service.
*
* @param serviceClass service class
* @param <T> type of service
* @return service implementation
*/
public static <T> T getService(Class<T> serviceClass) {
BundleContext bc = FrameworkUtil.getBundle(serviceClass).getBundleContext();
if (bc != null) {
ServiceReference<T> reference = bc.getServiceReference(serviceClass);
if (reference != null) {
T impl = bc.getService(reference);
if (impl != null) {
return impl;
}
}
}
throw new ServiceNotFoundException("Service " + serviceClass.getName() + " not found");
}
Example 38
Project: org.ops4j.pax.logging-master File: JdkHandler.java View source code |
private Bundle getCallerBundle() {
Bundle ret = null;
Class[] classCtx = securityManager.getClassContext();
for (int i = 0; i < classCtx.length; i++) {
if (!classCtx[i].getName().startsWith("org.ops4j.pax.logging") && !classCtx[i].getName().startsWith("java.util.logging")) {
ret = FrameworkUtil.getBundle(classCtx[i]);
break;
}
}
return ret;
}
Example 39
Project: ovsdb-master File: ServiceHelper.java View source code |
/**
* Retrieve all the Instances of a Service, optionally
* filtered via serviceFilter if non-null else all the results are
* returned if null
*
* @param clazz The target class
* @param bundle The caller
* @param serviceFilter LDAP filter to be applied in the search
*/
private static Object[] getGlobalInstances(Class<?> clazz, Object bundle, String serviceFilter) {
Object instances[] = null;
try {
Bundle ourBundle = FrameworkUtil.getBundle(bundle.getClass());
if (ourBundle != null) {
BundleContext bCtx = ourBundle.getBundleContext();
ServiceReference<?>[] services = bCtx.getServiceReferences(clazz.getName(), serviceFilter);
if (services != null) {
instances = new Object[services.length];
for (int i = 0; i < services.length; i++) {
instances[i] = bCtx.getService(services[i]);
}
}
}
} catch (Exception e) {
LOG.error("Error retrieving global instances of {} from caller {} with filter {}", clazz, bundle, serviceFilter, e);
}
return instances;
}
Example 40
Project: rap-osgi-tutorial-ece2011-master File: ConfiguratorTracker.java View source code |
public static boolean matchesType(String value, ServiceReference<UIContributorFactory> contributorReference) {
try {
String expression = createFilterExpression("type", value);
Filter filter = FrameworkUtil.createFilter(expression);
return filter.match(contributorReference);
} catch (InvalidSyntaxException shouldNotHappen) {
throw new IllegalStateException(shouldNotHappen);
}
}
Example 41
Project: release-master File: BPELEngineFactory.java View source code |
private File getDeploymentsDirectory() {
final Bundle bundle = FrameworkUtil.getBundle(getClass());
final File dataDirectory = bundle.getDataFile("");
final File deploymentsDirectory = new File(dataDirectory, "deployments");
if (!deploymentsDirectory.exists()) {
deploymentsDirectory.mkdir();
deploymentsDirectory.deleteOnExit();
}
return deploymentsDirectory;
}
Example 42
Project: riena-master File: LnfManagerTest.java View source code |
/**
* Test of the method <code>getLnfClassName()</code>.
*/
public void testGetLnfClassNameAndGetLnfUnderDifferentConfigurations() {
// check for riena default L&F
assertEquals(RienaDefaultLnf.class.getName(), LnfManager.getLnf().getClass().getName());
assertEquals(RienaDefaultLnf.class, LnfManager.getLnf().getClass());
// check for some other default L&F
final RienaDefaultLnf otherDefaultLnf = new OtherDefaultTestLnf();
LnfManager.setDefaultLnf(otherDefaultLnf);
assertEquals(otherDefaultLnf.getClass().getName(), LnfManager.getLnf().getClass().getName());
assertEquals(otherDefaultLnf.getClass(), LnfManager.getLnf().getClass());
// check for non-default L&F set
LnfManager.setLnf(FrameworkUtil.getBundle(LnfManagerTest.class).getSymbolicName() + ":" + TestLnf1.class.getName());
assertEquals(TestLnf1.class.getName(), LnfManager.getLnf().getClass().getName());
assertEquals(TestLnf1.class, LnfManager.getLnf().getClass());
// check for clearing non-default L&F
LnfManager.setLnf((String) null);
assertEquals(otherDefaultLnf.getClass().getName(), LnfManager.getLnf().getClass().getName());
assertEquals(otherDefaultLnf.getClass(), LnfManager.getLnf().getClass());
}
Example 43
Project: RWT_CONFIG_ADMIN_EXAMPLE-master File: ConfiguratorTracker.java View source code |
public static boolean matchesType(String value, ServiceReference<UIContributorFactory> contributorReference) {
try {
String expression = createFilterExpression("type", value);
Filter filter = FrameworkUtil.createFilter(expression);
return filter.match(contributorReference);
} catch (InvalidSyntaxException shouldNotHappen) {
throw new IllegalStateException(shouldNotHappen);
}
}
Example 44
Project: skalli-master File: ViewBundleUtil.java View source code |
/**
* Scans the Vaadin bundle, the o.e.s.view bundle (including its fragments)
* all extensions providing a {@link InfoBox}, all extensions providing
* a {@link ExtensionServic} and finally all bundles for theme resources
* matching the given <code>path</code> and <code>pattern</code>.
*
* @param path the path name in which to look.
* @param pattern the pattern for selecting entries in the
* specified path.
* @param recursive if <code>true</code>, recurse into subdirectories.
* @param mode determines whether the method should collect all resources from
* all bundles, or whether it should stop when at least one matching
* resource has been found.
* @see Services#findResources(String, String, boolean, FilterMode, BundleFilter...)
*/
public static List<URL> findThemeResources(String path, String pattern, boolean recursive, FilterMode mode) {
if (FilterMode.ALL.equals(mode)) {
return Services.findResources(path, pattern, recursive, mode, new BundleFilter.AcceptAll());
}
return Services.findResources(path, pattern, recursive, mode, // try Vaadin bundle
new BundleFilter.AcceptMatching(BUNDLE_VAADIN), // try the o.e.s.view bundle
new BundleFilter.AcceptMatching(FrameworkUtil.getBundle(ViewBundleUtil.class).getLocation()), // try view extension bundle
new BundleFilter.AcceptService(InfoBox.class), // try extension bundles
new BundleFilter.AcceptService(ExtensionService.class), // and finally all bundles
new BundleFilter.AcceptAll());
}
Example 45
Project: stocks-master File: ProxyAddon.java View source code |
@Inject
public void setupProxyService(@Preference(value = UIConstants.Preferences.PROXY_HOST) String proxyHost, @Preference(value = UIConstants.Preferences.PROXY_PORT) int proxyPort) {
BundleContext bc = FrameworkUtil.getBundle(ProxyAddon.class).getBundleContext();
ServiceReference<IProxyService> serviceReference = bc.getServiceReference(IProxyService.class);
IProxyService proxyService = bc.getService(serviceReference);
setupProxy(proxyService, proxyHost, proxyPort);
bc.ungetService(serviceReference);
}
Example 46
Project: Virgo-kernel-sandbox-master File: CoreBundleActivatorTests.java View source code |
@Test(expected = IllegalStateException.class)
public void noConfigService() throws Exception {
StubBundleContext bundleContext = new StubBundleContext();
bundleContext.addFilter(StartupTracker.APPLICATION_CONTEXT_FILTER, FrameworkUtil.createFilter(StartupTracker.APPLICATION_CONTEXT_FILTER));
CoreBundleActivator activator = new TestCoreBundleActivator();
activator.start(bundleContext);
}
Example 47
Project: virgo.kernel-master File: DeployerFailureListener.java View source code |
private boolean inThisRegion(Bundle bundle) {
if (regionDigraph == null) {
Bundle agentBundle = FrameworkUtil.getBundle(getClass());
BundleContext bundleContext = agentBundle.getBundleContext();
ServiceReference<RegionDigraph> regionMembershipServiceReference = bundleContext.getServiceReference(RegionDigraph.class);
if (regionMembershipServiceReference != null) {
this.regionDigraph = bundleContext.getService(regionMembershipServiceReference);
this.agentRegion = getRegion(agentBundle);
}
}
return this.regionDigraph != null ? getRegion(bundle).equals(this.agentRegion) : true;
}
Example 48
Project: virgo.snaps-master File: BundleWebXmlLoader.java View source code |
public static WebXml loadWebXml(Bundle bundle) {
MutableWebXml webXml = new MutableWebXml();
URL entry = bundle.getEntry(ENTRY_WEB_XML);
doParse(entry, webXml);
entry = FrameworkUtil.getBundle(BundleWebXmlLoader.class).getEntry(ENTRY_DEFAULT_WEB_XML);
doParse(entry, webXml);
validateWebXml(webXml);
return webXml;
}
Example 49
Project: camel-master File: OSGiCacheManager.java View source code |
private ClassLoader getClassLoader(String providerName) throws Exception {
if (providerName == null || !getConfiguration().isLookupProviders()) {
return null;
}
final BundleContext bc = FrameworkUtil.getBundle(JCacheHelper.class).getBundleContext();
final ClassLoader bcl = bc.getBundle().adapt(BundleWiring.class).getClassLoader();
final ClassLoader acl = getConfiguration().getApplicationContextClassLoader();
for (final Bundle bundle : bc.getBundles()) {
URL spi = bundle.getResource("META-INF/services/javax.cache.spi.CachingProvider");
if (spi != null) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(spi.openStream()))) {
if (ObjectHelper.equal(providerName, in.readLine())) {
return new ClassLoader(bcl) {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
try {
return acl.loadClass(name);
} catch (ClassNotFoundException e) {
return bundle.loadClass(name);
}
}
@Override
protected URL findResource(String name) {
URL resource = acl.getResource(name);
if (resource == null) {
resource = bundle.getResource(name);
}
return resource;
}
@Override
protected Enumeration findResources(String name) throws IOException {
try {
return acl.getResources(name);
} catch (IOException e) {
return bundle.getResources(name);
}
}
};
}
}
}
}
return null;
}
Example 50
Project: CDI-OSGi-master File: OSGiServiceBean.java View source code |
@Override
public Object create(CreationalContext ctx) {
try {
Type serviceType = injectionPoint.getType();
Class serviceClass = ((Class) (serviceType));
String serviceName = serviceClass.getName();
Bundle bundle = FrameworkUtil.getBundle(injectionPoint.getMember().getDeclaringClass());
return Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { (Class) serviceClass }, new DynamicServiceHandler(bundle, serviceName, filter));
} catch (Exception e) {
throw new CreationException(e);
}
}
Example 51
Project: dtgov-master File: FuseTransactionManagerLookup.java View source code |
/**
* @see org.hibernate.transaction.TransactionManagerLookup#getTransactionManager(java.util.Properties)
*/
@Override
public TransactionManager getTransactionManager(Properties props) throws HibernateException {
if (tm == null) {
try {
Bundle bundle = FrameworkUtil.getBundle(getClass());
BundleContext context = bundle.getBundleContext();
ServiceReference[] serviceReferences = context.getServiceReferences(TransactionManager.class.getName(), null);
if (serviceReferences != null) {
if (serviceReferences.length == 1) {
tm = (TransactionManager) context.getService(serviceReferences[0]);
} else if (serviceReferences.length == 0) {
//$NON-NLS-1$
throw new IllegalStateException("No Tx manager found!");
} else {
//$NON-NLS-1$
throw new IllegalStateException("Too many Tx managers found!");
}
}
} catch (InvalidSyntaxException e) {
throw new IllegalStateException("No Tx manager found!");
}
}
return tm;
}
Example 52
Project: flyway-master File: OsgiClassPathLocationScanner.java View source code |
public Set<String> findResourceNames(String location, URL locationUrl) throws IOException {
Set<String> resourceNames = new TreeSet<String>();
Bundle bundle = getTargetBundleOrCurrent(FrameworkUtil.getBundle(getClass()), locationUrl);
@SuppressWarnings({ "unchecked" }) Enumeration<URL> entries = bundle.findEntries(locationUrl.getPath(), "*", true);
if (entries != null) {
while (entries.hasMoreElements()) {
URL entry = entries.nextElement();
String resourceName = getPathWithoutLeadingSlash(entry);
resourceNames.add(resourceName);
}
}
return resourceNames;
}
Example 53
Project: gemini.managment-master File: PackageStateTest.java View source code |
@Test
public void listTest() throws Exception {
TabularData table = jmxFetchData("listPackages", new Object[] {}, new String[] {}, TabularData.class);
Set<?> keys = table.keySet();
Iterator<?> iter = keys.iterator();
BundleContext bundleContext = FrameworkUtil.getBundle(ServiceState.class).getBundleContext();
PackageAdmin admin = (PackageAdmin) bundleContext.getService(bundleContext.getServiceReference(PackageAdmin.class));
ExportedPackage[] exportedPackages = admin.getExportedPackages((Bundle) null);
Map<String, ExportedPackage> packages = new HashMap<String, ExportedPackage>();
for (ExportedPackage exportedPackage : exportedPackages) {
packages.put(getPackageIdentifier(exportedPackage.getExportingBundle().getBundleId(), exportedPackage.getName(), exportedPackage.getVersion().toString()), exportedPackage);
}
while (iter.hasNext()) {
key = iter.next();
keysArray = ((Collection<?>) key).toArray();
packageInfo = table.get(keysArray);
this.exportingBundles = (Long[]) packageInfo.get(PackageStateMBean.EXPORTING_BUNDLES);
this.importingBundles = (Long[]) packageInfo.get(PackageStateMBean.IMPORTING_BUNDLES);
this.name = (String) packageInfo.get(PackageStateMBean.NAME);
this.removalPending = (Boolean) packageInfo.get(PackageStateMBean.REMOVAL_PENDING);
this.version = (String) packageInfo.get(PackageStateMBean.VERSION);
ExportedPackage exportedPackage = packages.get(getPackageIdentifier(this.exportingBundles[0], this.name, this.version));
assertEquals(exportedPackage.getExportingBundle().getBundleId(), this.exportingBundles[0].longValue());
ArrayList<Long> idsAL = new ArrayList<Long>();
Bundle[] bundles = exportedPackage.getImportingBundles();
for (Bundle bundle : bundles) {
idsAL.add(bundle.getBundleId());
}
Long[] ids = idsAL.toArray(new Long[idsAL.size()]);
Arrays.sort(this.importingBundles);
Arrays.sort(ids);
//assertArrayEquals(ids, this.importingBundles);
assertEquals(exportedPackage.getName(), this.name);
assertEquals(exportedPackage.isRemovalPending(), this.removalPending.booleanValue());
assertEquals(exportedPackage.getVersion().toString(), this.version);
}
}
Example 54
Project: HibernateOSGi-master File: HibernateUtil.java View source code |
private static SessionFactory getSessionFactory() {
if (sf == null) {
Bundle thisBundle = FrameworkUtil.getBundle(HibernateUtil.class);
// Could get this by wiring up OsgiTestBundleActivator as well.
BundleContext context = thisBundle.getBundleContext();
ServiceReference sr = context.getServiceReference(SessionFactory.class.getName());
sf = (SessionFactory) context.getService(sr);
}
return sf;
}
Example 55
Project: jbosgi-resolver-master File: XResourceMatchingTestCase.java View source code |
@Test
public void testAttributOnSymbolicNameNoMatch() throws Exception {
XResourceBuilder<XResource> cbuilder = XResourceBuilderFactory.create();
cbuilder.addCapability(IdentityNamespace.IDENTITY_NAMESPACE, "res1");
XCapability cap = cbuilder.addCapability(BundleNamespace.BUNDLE_NAMESPACE, "org.jboss.test.cases.repository.tb1");
cbuilder.getResource();
XResourceBuilder<XResource> rbuilder = XResourceBuilderFactory.create();
rbuilder.addCapability(IdentityNamespace.IDENTITY_NAMESPACE, "res2");
Filter filter = FrameworkUtil.createFilter("(&(osgi.wiring.bundle=org.jboss.test.cases.repository.tb1)(foo=bar))");
XRequirement req = rbuilder.addRequirement("osgi.wiring.bundle", filter);
rbuilder.getResource();
Assert.assertFalse("No match", req.matches(cap));
}
Example 56
Project: jbosstools-openshift-master File: Trace.java View source code |
private DebugOptions createDebugOptions() {
Bundle bundle = FrameworkUtil.getBundle(getClass());
if (bundle == null) {
return null;
}
BundleContext context = bundle.getBundleContext();
if (context == null)
return null;
this.tracker = new ServiceTracker<>(context, DebugOptions.class.getName(), null);
tracker.open();
return tracker.getService();
}
Example 57
Project: kura-master File: NetworkTest.java View source code |
// private static final String PLATFORM_UNKNOWN = "unknown"; /** * This is the profile that runs on cloudbees. Most tests are skipped */ // private static final String PLATFORM_EMULATED = "emulated"; /** * This is for an Ubuntu laptop with Network Manager. The hardware profile assumes: * LAN1 - onboard ethernet controller intiially disabled * WIFI1 - onboard Wifi device initially acting as the WAN interface via DHCP * LAN2 - USB/Ethernet controller initially disabled * WIFI2 - USB/Wifi devices initially disabled * * Ethernet cable connects LAN1 to LAN2 */ // private static String platform; @Override @BeforeClass public void setUp() { // Wait for OSGi dependencies try { dependencyLatch.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) { fail("OSGi dependencies unfulfilled"); } FrameworkUtil.getBundle(this.getClass()).getBundleContext(); // install event listener for network events Dictionary<String, String[]> eventProps = new Hashtable<String, String[]>(); String[] topic = { UsbDeviceAddedEvent.USB_EVENT_DEVICE_ADDED_TOPIC, UsbDeviceRemovedEvent.USB_EVENT_DEVICE_REMOVED_TOPIC }; eventProps.put(EventConstants.EVENT_TOPIC, topic); BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); bundleContext.registerService(EventHandler.class.getName(), this, eventProps); }
Example 58
Project: liferay-apps-content-targeting-master File: CampaignQueryRule.java View source code |
protected void initCampaign() {
try {
Bundle bundle = FrameworkUtil.getBundle(getClass());
CampaignLocalService campaignLocalService = ServiceTrackerUtil.getService(CampaignLocalService.class, bundle.getBundleContext());
_campaign = campaignLocalService.getCampaign(_campaignId);
} catch (Exception e) {
}
}
Example 59
Project: OpenIDM-master File: Config.java View source code |
/**
* Updates the Jetty configuration with new values for the supplied Dictionary of properties. Any existing
* properties not contained in the supplied Dictionary will remain the same.
*
* @param propsToUpdate the properties to update
* @throws Exception
*/
public static void updateConfig(Dictionary propsToUpdate) throws Exception {
BundleContext context = FrameworkUtil.getBundle(Param.class).getBundleContext();
if (context != null) {
ServiceReference configAdminRef = context.getServiceReference(ConfigurationAdmin.class.getName());
if (configAdminRef != null) {
ConfigurationAdmin confAdmin = (ConfigurationAdmin) context.getService(configAdminRef);
Configuration configuration = confAdmin.getConfiguration("org.ops4j.pax.web");
if (propsToUpdate != null) {
Dictionary props = configuration.getProperties();
Enumeration keys = propsToUpdate.keys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
props.put(key, propsToUpdate.get(key));
}
configuration.update(props);
} else {
configuration.update();
}
}
}
}
Example 60
Project: opennaas-routing-nfv-master File: GenericOSGiJpaRepository.java View source code |
private Filter createServiceFilter(String clazz, Properties properties) throws InvalidSyntaxException {
StringBuilder query = new StringBuilder();
query.append("(&");
query.append("(").append(Constants.OBJECTCLASS).append("=").append(clazz).append(")");
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
query.append("(").append(key).append("=").append(value).append(")");
}
query.append(")");
return FrameworkUtil.createFilter(query.toString());
}
Example 61
Project: opennlp-master File: OSGiExtensionLoader.java View source code |
/**
* Retrieves the
*
* @param clazz
* @param id
* @return
*/
<T> T getExtension(Class<T> clazz, String id) {
if (context == null) {
throw new IllegalStateException("OpenNLP Tools Bundle is not active!");
}
Filter filter;
try {
filter = FrameworkUtil.createFilter("(&(objectclass=" + clazz.getName() + ")(" + "opennlp" + "=" + id + "))");
} catch (InvalidSyntaxException e) {
throw new ExtensionNotLoadedException(e);
}
// NOTE: In 4.3 the parameters are <T, T>
ServiceTracker extensionTracker = new ServiceTracker(context, filter, null);
T extension = null;
try {
extensionTracker.open();
try {
extension = (T) extensionTracker.waitForService(30000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} finally {
extensionTracker.close();
}
if (extension == null) {
throw new ExtensionNotLoadedException("No suitable extension found. Extension name: " + id);
}
return extension;
}
Example 62
Project: osgi-hibernate-master File: HibernateUtil.java View source code |
private static SessionFactory getSessionFactory() {
if (sf == null) {
Bundle thisBundle = FrameworkUtil.getBundle(HibernateUtil.class);
// Could get this by wiring up OsgiTestBundleActivator as well.
BundleContext context = thisBundle.getBundleContext();
ServiceReference sr = context.getServiceReference(SessionFactory.class.getName());
sf = (SessionFactory) context.getService(sr);
}
return sf;
}
Example 63
Project: p2abcengine-master File: IssueWizardPageTwo.java View source code |
@Override
public void createControl(Composite parent) {
container = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
container.setLayout(layout);
layout.numColumns = 2;
Bundle bundle = FrameworkUtil.getBundle(this.getClass());
URL url = FileLocator.find(bundle, new Path("icons/load.gif"), null);
Image image = ImageDescriptor.createFromURL(url).createImage();
label1 = new Label(container, SWT.NONE);
label1.setImage(image);
label2 = new Label(container, SWT.NONE);
label2.setText("Getting crendential, please wait...");
setControl(container);
setPageComplete(false);
}
Example 64
Project: rce-master File: AbstractDeserializationClasspathCheck.java View source code |
/**
* Checks the current classpath for classes known or suspected to be unsafe for deserialization of external data.
*
* @return
*
* @return true if problems were detected; false if all tests passed successfully
*/
public boolean checkForKnownUnsafeClassesInClasspath() {
// as this test checks for the ABSENCE of certain things, make sure the test patterns don't contain unintended characters
final Pattern typoGuard = Pattern.compile("^[a-zA-Z][a-zA-Z0-9\\.]+[a-zA-Z]$");
final Bundle bundle = FrameworkUtil.getBundle(getClass());
log.debug("Running in context of bundle " + bundle + " (may be 'null' when not running in an OSGi context)");
boolean unsafeClassFound = false;
for (String className : assembleListOfSuspiciousOrKnownUnsafeClassesForDeserialization()) {
if (!typoGuard.matcher(className).matches()) {
throw new IllegalArgumentException("The class name seems to be malformed: " + className);
}
try {
Class.forName(className);
log.error("Known unsafe class found in classpath: " + className);
unsafeClassFound = true;
} catch (ClassNotFoundException e) {
try {
Thread.currentThread().getContextClassLoader().loadClass(className);
log.error("Known unsafe class found via context classloader: " + className);
unsafeClassFound = true;
} catch (ClassNotFoundException e2) {
try {
if (bundle != null) {
bundle.loadClass(className);
log.error("Known unsafe class found via bundle classloader: " + className);
unsafeClassFound = true;
}
} catch (ClassNotFoundException e3) {
log.debug("Not found in classpath (good): " + className);
}
}
}
}
return unsafeClassFound;
}
Example 65
Project: repoindex-master File: TestStandaloneLibrary.java View source code |
public void testKnownBundleRecognition() throws Exception {
RepoIndex indexer = new RepoIndex();
indexer.addAnalyzer(new KnownBundleAnalyzer(), FrameworkUtil.createFilter("(name=*)"));
StringWriter writer = new StringWriter();
File tempDir = createTempDir();
File tempFile = copyToTempFile(tempDir, "testdata/org.eclipse.equinox.ds-1.4.0.jar");
Map<String, String> config = new HashMap<String, String>();
config.put(ResourceIndexer.ROOT_URL, tempDir.getAbsoluteFile().toURL().toString());
indexer.indexFragment(Collections.singleton(tempFile), writer, config);
assertEquals(readStream(TestStandaloneLibrary.class.getResourceAsStream("/testdata/org.eclipse.equinox.ds-1.4.0.fragment.txt")), writer.toString().trim());
deleteWithException(tempDir);
}
Example 66
Project: sling-master File: MetricsServiceFactory.java View source code |
/** Provide a MetricsService mapped to the Bundle that loaded class c
* @param c a Class loaded by an OSGi bundle
* @return a MetricsService
*/
public static MetricsService getMetricsService(Class<?> c) {
if (c == null) {
throw new IllegalArgumentException("Class parameter is required");
}
final Bundle b = FrameworkUtil.getBundle(c);
if (b == null) {
throw new IllegalArgumentException("No BundleContext, Class was not loaded from a Bundle?: " + c.getClass().getName());
}
final BundleContext ctx = b.getBundleContext();
// In theory we should unget this reference, but the OSGi framework
// ungets all references held by a bundle when it stops and we cannot
// do much better than that anyway.
final ServiceReference ref = ctx.getServiceReference(MetricsService.class.getName());
if (ref == null) {
throw new IllegalStateException("MetricsService not found for Bundle " + b.getSymbolicName());
}
return (MetricsService) ctx.getService(ref);
}
Example 67
Project: solarnetwork-external-master File: OsgiDataSourceRealm.java View source code |
@Override
protected Connection open() {
BundleContext context = FrameworkUtil.getBundle(getClass()).getBundleContext();
try {
ServiceReference<?>[] service = context.getServiceReferences(DataSource.class.getName(), getDataSourceName());
if (service == null || service.length < 1) {
throw new RuntimeException("No " + DataSource.class.getName() + " available");
}
DataSource dataSource = (DataSource) context.getService(service[0]);
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("Error creating DataSource", e);
} catch (InvalidSyntaxException e) {
throw new RuntimeException("Error creating DataSource", e);
}
}
Example 68
Project: spring-ide-master File: DefaultProjectContributorState.java View source code |
public <T> T get(Class<T> clazz, String filterText) {
if (!StringUtils.hasLength(filterText)) {
return null;
}
try {
Filter filter = FrameworkUtil.createFilter(filterText);
for (Map.Entry<Dictionary<String, String>, Object> entry : managedObjectsWithFilters.entrySet()) {
if (filter.match(entry.getKey())) {
return (T) entry.getValue();
}
}
} catch (InvalidSyntaxException e) {
SpringCore.log(e);
}
return null;
}
Example 69
Project: alto-master File: ServiceHelper.java View source code |
/**
* Register a Global Service in the OSGi service registry
*
* @param clazz
* The target class
* @param instance
* of the object exporting the service, be careful the object must
* implement/extend clazz else the registration will fail unless a
* ServiceFactory is passed as parameter
* @param properties
* The properties to be attached to the service registration
* @return the ServiceRegistration if registration happened, null otherwise
*/
public static ServiceRegistration registerGlobalServiceWReg(Class<?> clazz, Object instance, Dictionary<String, Object> properties) {
try {
BundleContext bCtx = FrameworkUtil.getBundle(instance.getClass()).getBundleContext();
if (bCtx == null) {
logger.error("Could not retrieve the BundleContext");
return null;
}
ServiceRegistration registration = bCtx.registerService(clazz.getName(), instance, properties);
return registration;
} catch (Exception e) {
logger.error("Exception {} while registering the service {}", e.getMessage(), instance.toString());
}
return null;
}
Example 70
Project: bioclipse.balloon-master File: AbstractBalloonManagerPluginTest.java View source code |
@Test
public void generate3DconformationsStringString() throws CoreException, BioclipseException, IOException {
Bundle b = FrameworkUtil.getBundle(this.getClass());
Enumeration<URL> urls = b.findEntries("", "*.cml", true);
if (!urls.hasMoreElements())
System.out.println("Nothing found!");
else
System.out.println("Found: ");
while (urls.hasMoreElements()) {
System.out.println(urls.nextElement().toString());
}
URL cml = b.getEntry("bin/testFiles/0037.cml");
String project = ui.newProject("Test Project");
String fileName = cml.getFile();
System.out.println(fileName);
System.out.println(new Path("/" + project).append(new Path(fileName).removeFirstSegments(2)).toString());
IFile cmlFile = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path("/" + project).append(new Path(fileName).removeFirstSegments(2)));
if (!cmlFile.exists()) {
cmlFile.create(cml.openStream(), true, null);
}
String input = cmlFile.getLocation().toOSString();
String output = balloon.generate3Dconformations(input, null, 1);
List<ICDKMolecule> molecules = cdk.loadMolecules(output);
Assert.assertEquals(1, molecules.size());
}
Example 71
Project: buildship-master File: EditorUtils.java View source code |
private static void showWithMarker(IEditorPart editor, IFile file, int offset, int length) {
IMarker marker = null;
try {
Bundle bundle = FrameworkUtil.getBundle(EditorUtils.class);
//$NON-NLS-1$
marker = file.createMarker(bundle.getSymbolicName() + "navigationmarker");
Map<String, Integer> attributes = new HashMap<String, Integer>(4);
attributes.put(IMarker.CHAR_START, offset);
attributes.put(IMarker.CHAR_END, offset + length);
marker.setAttributes(attributes);
IDE.gotoMarker(editor, marker);
} catch (CoreException e) {
String message = String.format("Cannot set marker in file %s.", file.getFullPath());
UiPlugin.logger().error(message, e);
throw new GradlePluginsRuntimeException(message, e);
} finally {
if (marker != null) {
try {
marker.delete();
} catch (CoreException e) {
}
}
}
}
Example 72
Project: Conferences-master File: EngineControlPart.java View source code |
@PostConstruct
public void postConstruct(Composite parent, final ImageRegistry reg) {
parent.setLayout(new GridLayout(1, true));
Canvas canvas = new Canvas(parent, SWT.BORDER);
canvas.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
final LightweightSystem lws = new LightweightSystem(canvas);
// Create Scaled Slider
final ScaledSliderFigure slider = new ScaledSliderFigure();
slider.setHorizontal(true);
// Init Scaled Slider
// can brake or accelerate from -10 to 10 m/s2
slider.setRange(-10, 10);
slider.setValue(0);
slider.setLoLevel(-5);
slider.setLoloLevel(-8);
slider.setHiLevel(6);
slider.setHihiLevel(8);
slider.setThumbColor(ColorConstants.gray);
slider.setEffect3D(true);
slider.setShowMinorTicks(false);
slider.addManualValueChangeListener(new IManualValueChangeListener() {
public void manualValueChanged(double newValue) {
if (engineSimu != null)
engineSimu.accelerate((int) newValue);
}
});
lws.setContents(slider);
// Initialize needed images
Bundle b = FrameworkUtil.getBundle(getClass());
reg.put(IMG_START, ImageDescriptor.createFromURL(b.getEntry(IMG_START)));
reg.put(IMG_STOP, ImageDescriptor.createFromURL(b.getEntry(IMG_STOP)));
// reg.put(IMG_FUNCTION,
// ImageDescriptor.createFromURL(b.getEntry(IMG_FUNCTION)));
// Create only 1 button for start and stop.
Composite buttonComposite = new Composite(parent, SWT.NONE);
buttonComposite.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
buttonComposite.setLayout(new GridLayout(1, true));
final Label startButton = new Label(buttonComposite, SWT.NONE);
startButton.setImage(reg.get(IMG_START));
startButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
if (engineSimu != null) {
if (engineSimu.isStarted()) {
engineSimu.stop();
startButton.setImage(reg.get(IMG_START));
} else {
engineSimu.start();
startButton.setImage(reg.get(IMG_STOP));
}
}
}
});
}
Example 73
Project: ConSea-master File: ConseaMenuButton.java View source code |
private void sendActionToView(ArrayList<ConseaSearchResonse> conseaEntries) {
// The Service was registered in this bundles activator, so we don't
// need a service listener,
// but we should use a service listener, because this feels (and
// actually is) dirty
BundleContext ctx = FrameworkUtil.getBundle(Activator.class).getBundleContext();
ServiceReference<ResultViewContent> sr = ctx.getServiceReference(ResultViewContent.class);
ResultViewContent content = ctx.getService(sr);
content.clear();
if (conseaEntries == null) {
return;
}
for (ConseaSearchResonse entry : conseaEntries) {
content.addEntry(entry);
}
}
Example 74
Project: ddf-master File: ErrorServlet.java View source code |
private void setErrorHandler() {
if (errorHandler == null) {
Bundle bundle = FrameworkUtil.getBundle(ErrorServlet.class);
if (bundle != null) {
BundleContext bundleContext = bundle.getBundleContext();
if (bundleContext != null) {
ServiceReference<ErrorHandler> serviceReference = bundleContext.getServiceReference(ErrorHandler.class);
if (serviceReference != null) {
errorHandler = bundleContext.getService(serviceReference);
}
}
}
}
}
Example 75
Project: ddf-platform-master File: ErrorServlet.java View source code |
public void setErrorHandler() {
if (errorHandler == null) {
Bundle bundle = FrameworkUtil.getBundle(ErrorServlet.class);
if (bundle != null) {
BundleContext bundleContext = bundle.getBundleContext();
if (bundleContext != null) {
ServiceReference<ErrorHandler> serviceReference = bundleContext.getServiceReference(ErrorHandler.class);
if (serviceReference != null) {
errorHandler = bundleContext.getService(serviceReference);
}
}
}
}
}
Example 76
Project: drc-master File: ApplicationWorkbenchAdvisor.java View source code |
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void initialize(IWorkbenchConfigurer configurer) {
super.initialize(configurer);
Bundle b = FrameworkUtil.getBundle(getClass());
BundleContext context = b.getBundleContext();
ServiceReference serviceRef = context.getServiceReference(IThemeManager.class.getName());
IThemeManager themeManager = (IThemeManager) context.getService(serviceRef);
final IThemeEngine engine = themeManager.getEngineForDisplay(Display.getCurrent());
//$NON-NLS-1$
engine.setTheme("de.uni_koeln.ub.drc.ui.rcp.theme", true);
if (serviceRef != null) {
serviceRef = null;
}
if (themeManager != null) {
themeManager = null;
}
}
Example 77
Project: E34MigrationTooling-master File: Migration34Activator.java View source code |
private void initializeImageRegistry(ImageRegistry reg) {
Bundle b = FrameworkUtil.getBundle(this.getClass());
reg.put(IMG_DEPRECATED, ImageDescriptor.createFromURL(b.getEntry(IMG_DEPRECATED)));
reg.put(IMG_FILTER, ImageDescriptor.createFromURL(b.getEntry(IMG_FILTER)));
reg.put(IMG_COLLAPSE, ImageDescriptor.createFromURL(b.getEntry(IMG_COLLAPSE)));
reg.put(IMG_EXPAND, ImageDescriptor.createFromURL(b.getEntry(IMG_EXPAND)));
reg.put(IMG_EXTENSION, ImageDescriptor.createFromURL(b.getEntry(IMG_EXTENSION)));
reg.put(IMG_PREFIX_COLUMNTITLE, ImageDescriptor.createFromURL(b.getEntry(IMG_PREFIX_COLUMNTITLE)));
reg.put(IMG_HELP, ImageDescriptor.createFromURL(b.getEntry(IMG_HELP)));
reg.put(IMG_EXPORT, ImageDescriptor.createFromURL(b.getEntry(IMG_EXPORT)));
reg.put(IMG_OPCOACH, ImageDescriptor.createFromURL(b.getEntry(IMG_OPCOACH)));
}
Example 78
Project: e4-rendering-master File: AbstractThemeProcessor.java View source code |
@Execute
public void process() {
if (!check()) {
return;
}
// FIXME Remove once bug 314091 is resolved
Bundle bundle = FrameworkUtil.getBundle(getClass());
BundleContext context = bundle.getBundleContext();
ServiceReference reference = context.getServiceReference(IThemeManager.class.getName());
IThemeManager mgr = (IThemeManager) context.getService(reference);
IThemeEngine engine = mgr.getEngineForDisplay(Display.getCurrent());
List<ITheme> themes = engine.getThemes();
if (themes.size() > 0) {
MApplication application = getApplication();
MCommand switchThemeCommand = null;
for (MCommand cmd : application.getCommands()) {
if (//$NON-NLS-1$
"contacts.switchTheme".equals(cmd.getElementId())) {
switchThemeCommand = cmd;
break;
}
}
if (switchThemeCommand != null) {
preprocess();
for (ITheme theme : themes) {
MParameter parameter = MCommandsFactory.INSTANCE.createParameter();
parameter.setName("contacts.commands.switchtheme.themeid");
parameter.setValue(theme.getId());
String iconURI = getCSSUri(theme.getId());
if (iconURI != null) {
iconURI = iconURI.replace(".css", ".png");
}
processTheme(theme.getLabel(), switchThemeCommand, parameter, iconURI);
}
postprocess();
}
}
}
Example 79
Project: eclipse.platform.ui-master File: ExtensionsSortTests.java View source code |
@Before
public void setUp() throws Exception {
BundleContext context = FrameworkUtil.getBundle(getClass()).getBundleContext();
// root has no dependencies on other test bundles
// intermediate depends on root, plus it re-exports
// leaf depends on intermediate, and should also then
// depend on root via the re-export
root = context.installBundle(toFileURL("platform:/plugin/" + context.getBundle().getSymbolicName() + "/data/org.eclipse.extensionsSortTests/tests.extensions.root/"));
intermediate = context.installBundle(toFileURL("platform:/plugin/" + context.getBundle().getSymbolicName() + "/data/org.eclipse.extensionsSortTests/tests.extensions.intermediate/"));
leaf = context.installBundle(toFileURL("platform:/plugin/" + context.getBundle().getSymbolicName() + "/data/org.eclipse.extensionsSortTests/tests.extensions.leaf/"));
root.start(Bundle.START_TRANSIENT);
intermediate.start(Bundle.START_TRANSIENT);
leaf.start(Bundle.START_TRANSIENT);
}
Example 80
Project: eip-designer-master File: RouteTreeLabelProvider.java View source code |
@Override
public Image getImage(Object element) {
if (element instanceof IProject) {
return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_PROJECT);
}
if (element instanceof IResource) {
return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE);
}
if (element instanceof Route) {
Bundle bundle = FrameworkUtil.getBundle(RouteTreeLabelProvider.class);
URL url = FileLocator.find(bundle, new Path("icons/obj16/Route.gif"), null);
ImageDescriptor imageDcr = ImageDescriptor.createFromURL(url);
return imageDcr.createImage();
}
return null;
}
Example 81
Project: emf-compare-master File: SubversiveFileRevision.java View source code |
@Override
public URI getURI() {
URI uri;
try {
uri = new URI(repositoryResource.getUrl());
return uri;
} catch (URISyntaxException e) {
Bundle bundle = FrameworkUtil.getBundle(SubversiveFileRevision.class);
ILog log = Platform.getLog(bundle);
IStatus status = new Status(IStatus.ERROR, bundle.getSymbolicName(), e.getMessage(), e);
log.log(status);
}
return null;
}
Example 82
Project: emf.compare-master File: SubversiveFileRevision.java View source code |
@Override
public URI getURI() {
URI uri;
try {
uri = new URI(repositoryResource.getUrl());
return uri;
} catch (URISyntaxException e) {
Bundle bundle = FrameworkUtil.getBundle(SubversiveFileRevision.class);
ILog log = Platform.getLog(bundle);
IStatus status = new Status(IStatus.ERROR, bundle.getSymbolicName(), e.getMessage(), e);
log.log(status);
}
return null;
}
Example 83
Project: epp.mpc-master File: WinClientBuilderCustomizer.java View source code |
private String getServicePrincipalName(Map<?, ?> properties) {
Object servicePrincipalValue = properties.get(SERVICE_PRINCIPAL_NAME_ATTRIBUTE);
if (servicePrincipalValue != null) {
return servicePrincipalValue.toString();
}
Bundle bundle = FrameworkUtil.getBundle(this.getClass());
if (bundle != null) {
return bundle.getBundleContext().getProperty(SERVICE_PRINCIPAL_NAME_PROPERTY);
}
return System.getProperty(SERVICE_PRINCIPAL_NAME_PROPERTY);
}
Example 84
Project: extended-objects-master File: XOSGi.java View source code |
/**
* Create a {@link com.buschmais.xo.api.XOManagerFactory} for the XO unit
* identified by name.
* <p>
* Internally it performs a lookup in the OSGi service registry to retrieve the
* XOManagerFactory service that is bound to the given XO unit name. The bundle
* providing this XO unit must be processed by the OSGi bundle listener.
* </p>
*
* @param name
* The name of the XO unit.
* @return The {@link com.buschmais.xo.api.XOManagerFactory}.
* @see com.buschmais.xo.impl.bootstrap.osgi.XOUnitBundleListener
*/
public static XOManagerFactory createXOManagerFactory(String name) {
if (OSGiUtil.isXOLoadedAsOSGiBundle()) {
try {
BundleContext bundleContext = FrameworkUtil.getBundle(XOSGi.class).getBundleContext();
String filterString = "(name=" + name + ")";
Collection<ServiceReference<XOManagerFactory>> xoManagerFactoryServices = bundleContext.getServiceReferences(XOManagerFactory.class, filterString);
for (ServiceReference<XOManagerFactory> xoManagerFactoryService : xoManagerFactoryServices) {
XOManagerFactory xoManagerFactory = bundleContext.getService(xoManagerFactoryService);
if (xoManagerFactory != null) {
xoManagerFactory.addCloseListener(new CloseAdapter() {
@Override
public void onAfterClose() {
bundleContext.ungetService(xoManagerFactoryService);
}
});
return xoManagerFactory;
}
}
} catch (InvalidSyntaxException e) {
throw new XOException("Cannot bootstrap XO implementation.", e);
}
}
throw new XOException("Cannot bootstrap XO implementation.");
}
Example 85
Project: fuchsia-master File: FuchsiaUtilsTest.java View source code |
@Test
public void testGetFilterFromFilter() {
Filter myFilter = null;
Filter f = null;
try {
myFilter = FrameworkUtil.createFilter("(!(key=value))");
} catch (InvalidSyntaxException e) {
fail("Can't create a filter with org.apache.felix.framework.FilterImpl", e);
}
try {
f = FuchsiaUtils.getFilter(myFilter);
} catch (InvalidFilterException e) {
fail("GetFilter thrown an exception on a valid String filter", e);
}
assertThat(f).isNotNull().isInstanceOf(Filter.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("key", "value");
assertThat(f.matches(map)).isFalse();
map.clear();
map.put("key", "not-value");
assertThat(f.matches(map)).isTrue();
map.clear();
map.put("not-key", "value");
assertThat(f.matches(map)).isTrue();
}
Example 86
Project: jbosstools-base-master File: DescriptiveDialogPasswordProvider.java View source code |
/*
* Taken from org.eclipse.equinox.internal.security.storage.friends.InternalExchangeUtils
*/
private boolean isJUnitApp() {
BundleContext context = FrameworkUtil.getBundle(getClass()).getBundleContext();
if (context == null)
return false;
//$NON-NLS-1$
String app = context.getProperty("eclipse.application");
if (app == null)
return false;
if (app.startsWith(JUNIT_APPS1))
return true;
if (app.startsWith(JUNIT_APPS2))
return true;
return false;
}
Example 87
Project: jclouds-karaf-master File: CacheUtils.java View source code |
/**
* Creates a {@link ServiceTracker} which binds {@link org.jclouds.karaf.cache.Cacheable} to {@link CacheManager}.
* @param context
* @param cacheManager
* @return
*/
public static <T> ServiceTracker createCacheableTracker(final BundleContext context, final String type, final CacheManager<T> cacheManager) throws InvalidSyntaxException {
return new ServiceTracker(context, FrameworkUtil.createFilter("(&(cache-type=" + type + ")(objectClass=org.jclouds.karaf.cache.Cacheable))"), null) {
@Override
public Object addingService(ServiceReference reference) {
Object service = super.addingService(reference);
if (Cacheable.class.isAssignableFrom(service.getClass())) {
cacheManager.bindCacheable((Cacheable) service);
}
return service;
}
@Override
public void removedService(ServiceReference reference, Object service) {
if (Cacheable.class.isAssignableFrom(service.getClass())) {
cacheManager.unbindCacheable((Cacheable) service);
}
super.removedService(reference, service);
}
};
}
Example 88
Project: karaf-cellar-master File: EndpointDescription.java View source code |
/**
* Tests the properties of this <code>EndpointDescription</code> against
* the given filter using a case insensitive match.
*
* @param filter The filter to test.
* @return <code>true</code> If the properties of this
* <code>EndpointDescription</code> match the filter,
* <code>false</code> otherwise.
* @throws IllegalArgumentException If <code>filter</code> contains an
* invalid filter string that cannot be parsed.
*/
public boolean matches(String filter) {
Filter f;
try {
f = FrameworkUtil.createFilter(filter);
} catch (InvalidSyntaxException e) {
IllegalArgumentException iae = new IllegalArgumentException(e.getMessage());
iae.initCause(e);
throw iae;
}
Dictionary dictionary = new Properties();
for (Map.Entry<String, Object> entry : properties.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
dictionary.put(key, value);
}
/*
* we can use matchCase here since properties already supports case
* insensitive key lookup.
*/
return f.matchCase(dictionary);
}
Example 89
Project: karaf-master File: BundleHelpProvider.java View source code |
@Override
public String getHelp(Session session, String path) {
if (path.indexOf('|') > 0) {
if (path.startsWith("bundle|")) {
path = path.substring("bundle|".length());
} else {
return null;
}
}
if (path.matches("[0-9]*")) {
long id = Long.parseLong(path);
BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
Bundle bundle = bundleContext.getBundle(id);
if (bundle != null) {
String title = ShellUtil.getBundleName(bundle);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
ps.println("\n" + title);
ps.println(ShellUtil.getUnderlineString(title));
URL bundleInfo = bundle.getEntry("OSGI-INF/bundle.info");
if (bundleInfo != null) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(bundleInfo.openStream()))) {
int maxSize = 80;
Terminal terminal = session.getTerminal();
if (terminal != null) {
maxSize = terminal.getWidth();
}
WikiVisitor visitor = new AnsiPrintingWikiVisitor(ps, maxSize);
WikiParser parser = new WikiParser(visitor);
parser.parse(reader);
} catch (Exception e) {
}
}
ps.close();
return baos.toString();
}
}
return null;
}
Example 90
Project: legacy-jclouds-karaf-master File: CacheUtils.java View source code |
/**
* Creates a {@link ServiceTracker} which binds {@link org.jclouds.karaf.cache.Cacheable} to {@link CacheManager}.
* @param context
* @param cacheManager
* @return
*/
public static <T> ServiceTracker createCacheableTracker(final BundleContext context, final String type, final CacheManager<T> cacheManager) throws InvalidSyntaxException {
return new ServiceTracker(context, FrameworkUtil.createFilter("(&(cache-type=" + type + ")(objectClass=org.jclouds.karaf.cache.Cacheable))"), null) {
@Override
public Object addingService(ServiceReference reference) {
Object service = super.addingService(reference);
if (Cacheable.class.isAssignableFrom(service.getClass())) {
cacheManager.bindCacheable((Cacheable) service);
}
return service;
}
@Override
public void removedService(ServiceReference reference, Object service) {
if (Cacheable.class.isAssignableFrom(service.getClass())) {
cacheManager.unbindCacheable((Cacheable) service);
}
super.removedService(reference, service);
}
};
}
Example 91
Project: logging-log4j2-master File: BundleContextSelector.java View source code |
@Override
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext, final URI configLocation) {
if (currentContext) {
final LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get();
if (ctx != null) {
return ctx;
}
return getDefault();
}
// it's quite possible that the provided ClassLoader may implement BundleReference which gives us a nice shortcut
if (loader instanceof BundleReference) {
return locateContext(((BundleReference) loader).getBundle(), configLocation);
}
final Class<?> callerClass = StackLocatorUtil.getCallerClass(fqcn);
if (callerClass != null) {
return locateContext(FrameworkUtil.getBundle(callerClass), configLocation);
}
final LoggerContext lc = ContextAnchor.THREAD_CONTEXT.get();
return lc == null ? getDefault() : lc;
}
Example 92
Project: mylyn.commons-master File: NotificationEnvironment.java View source code |
@SuppressWarnings({ "unchecked", "rawtypes" })
public boolean matches(IAdaptable item, IProgressMonitor monitor) {
IFilterable entry = (IFilterable) item.getAdapter(IFilterable.class);
if (entry == null) {
return true;
}
if (//$NON-NLS-1$
!matchesVersion(entry.getFilter("frameworkVersion"), getFrameworkVersion())) {
return false;
}
if (//$NON-NLS-1$
!matchesVersion(entry.getFilter("platformVersion"), getPlatformVersion())) {
return false;
}
if (//$NON-NLS-1$
!matchesVersion(entry.getFilter("runtimeVersion"), getRuntimeVersion())) {
return false;
}
//$NON-NLS-1$
List<String> filterExpressions = entry.getFilters("filter");
for (String filterExpression : filterExpressions) {
try {
Filter filter = FrameworkUtil.createFilter(filterExpression);
if (!filter.match((Dictionary) environment)) {
return false;
}
} catch (InvalidSyntaxException e) {
}
}
//$NON-NLS-1$
List<String> requiredFeatures = entry.getFilters("requires");
for (String requiredFeature : requiredFeatures) {
if (!getInstalledFeatures(monitor).contains(parseFeature(requiredFeature))) {
return false;
}
}
//$NON-NLS-1$
List<String> conflictedFeatures = entry.getFilters("conflicts");
for (String conflictedFeature : conflictedFeatures) {
if (getInstalledFeatures(monitor).contains(parseFeature(conflictedFeature))) {
return false;
}
}
return true;
}
Example 93
Project: openengsb-master File: Activator.java View source code |
// FIXME ARIES-875
//
// This is a workaround for ARIES-875. It must wait for the blueprint-extender to finish the initialization,
// so that it does not interfere with the ServiceReference to the ConfigurationAdmin
private void waitForBlueprintToFinish(final BundleContext context) throws InvalidSyntaxException, InterruptedException {
ServiceTracker blueprintTracker = new ServiceTracker(context, FrameworkUtil.createFilter(String.format("(&(%s=%s)(%s=%s)(%s=%s))", Constants.OBJECTCLASS, BlueprintContainer.class.getName(), "osgi.blueprint.container.symbolicname", context.getBundle().getSymbolicName(), "osgi.blueprint.container.version", context.getBundle().getVersion().toString())), null);
blueprintTracker.open();
blueprintTracker.waitForService(30000);
blueprintTracker.close();
}
Example 94
Project: openhab1-addons-master File: ItemStateRequestProcessor.java View source code |
private ItemRegistry getItemRegistry() throws ServiceException {
BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
if (bundleContext != null) {
ServiceReference<?> serviceReference = bundleContext.getServiceReference(ItemRegistry.class.getName());
if (serviceReference != null) {
ItemRegistry itemregistry = (ItemRegistry) bundleContext.getService(serviceReference);
return itemregistry;
}
}
throw new ServiceException("Cannot get ItemRegistry");
}
Example 95
Project: opennaas-master File: AbstractActivator.java View source code |
/**
* Create a Filter to give to the service tracker based on the information about the service to lookup in the properties
*
* @throws InvalidSyntaxException
*/
protected static Filter createServiceFilter(String clazz, Properties properties) throws InvalidSyntaxException {
StringBuilder query = new StringBuilder();
query.append("(&");
query.append("(").append(Constants.OBJECTCLASS).append("=").append(clazz).append(")");
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
query.append("(").append(key).append("=").append(value).append(")");
}
query.append(")");
return FrameworkUtil.createFilter(query.toString());
}
Example 96
Project: org.ops4j.pax.wicket-master File: MountTest.java View source code |
@Before
public void setup() throws Exception {
wicketTester = new WicketTester();
bundleContext = mock(BundleContext.class);
when(bundleContext.createFilter(anyString())).thenAnswer(new Answer<Filter>() {
public Filter answer(InvocationOnMock invocation) throws Throwable {
return FrameworkUtil.createFilter((String) invocation.getArguments()[0]);
}
});
when(bundleContext.getProperty(Constants.FRAMEWORK_VERSION)).thenReturn("1.5.0");
}
Example 97
Project: package-drone-master File: DispatcherServletInitializer.java View source code |
public void start() throws ServletException, NamespaceException {
final BundleContext bundleContext = FrameworkUtil.getBundle(DispatcherServletInitializer.class).getBundleContext();
this.context = Dispatcher.createContext(bundleContext);
Dictionary<String, String> initparams = new Hashtable<>();
final MultipartConfigElement multipart = JspServletInitializer.createMultiPartConfiguration(PROP_PREFIX_MP);
this.webContainer.registerServlet(new DispatcherServlet(), "dispatcher", new String[] { "/" }, initparams, 1, false, multipart, this.context);
this.proxyFilter = new FilterTracker(bundleContext);
this.webContainer.registerFilter(this.proxyFilter, new String[] { "/*" }, null, null, this.context);
initparams = new Hashtable<>();
initparams.put("filter-mapping-dispatcher", "request");
this.webContainer.registerFilter(new BundleFilter(), new String[] { "/bundle/*" }, null, initparams, this.context);
this.jspTracker = new BundleTracker<>(bundleContext, Bundle.INSTALLED | Bundle.ACTIVE, new JspBundleCustomizer(this.webContainer, this.context));
this.jspTracker.open();
}
Example 98
Project: rabbitosgi-master File: ExchangeWireEndpointTracker.java View source code |
private static Filter createFilter(String exchange, String connection) {
String filterStr;
if (connection != null) {
filterStr = String.format("(&(%s=%s)(%s=%s))", ServiceProperties.EXCHANGE_NAME, exchange, ServiceProperties.CONNECTION_NAME, connection);
} else {
filterStr = String.format("(%s=%s)", ServiceProperties.EXCHANGE_NAME, exchange);
}
try {
return FrameworkUtil.createFilter(filterStr);
} catch (InvalidSyntaxException e) {
throw new RuntimeException(e);
}
}
Example 99
Project: rap-master File: PluginContributionAdapterFactory.java View source code |
public Object getAdapter(Object adaptableObject, Class adapterType) {
if (adapterType != ContributionInfo.class) {
return null;
}
if (adaptableObject instanceof IPluginContribution) {
IPluginContribution contribution = (IPluginContribution) adaptableObject;
String elementType;
// RAP [if]: need session aware messages
if (contribution instanceof EditorDescriptor) {
// elementType = ContributionInfoMessages.ContributionInfo_Editor;
elementType = ContributionInfoMessages.get().ContributionInfo_Editor;
} else if (contribution instanceof ViewDescriptor) {
// elementType = ContributionInfoMessages.ContributionInfo_View;
elementType = ContributionInfoMessages.get().ContributionInfo_View;
} else if (contribution instanceof ActionSetDescriptor) {
// elementType = ContributionInfoMessages.ContributionInfo_ActionSet;
elementType = ContributionInfoMessages.get().ContributionInfo_ActionSet;
} else if (contribution instanceof Category) {
// elementType = ContributionInfoMessages.ContributionInfo_Category;
elementType = ContributionInfoMessages.get().ContributionInfo_Category;
} else if (contribution instanceof IViewCategory) {
// elementType = ContributionInfoMessages.ContributionInfo_Category;
elementType = ContributionInfoMessages.get().ContributionInfo_Category;
} else if (contribution instanceof ThemeElementCategory) {
// elementType = ContributionInfoMessages.ContributionInfo_Category;
elementType = ContributionInfoMessages.get().ContributionInfo_Category;
} else if (contribution instanceof WizardCollectionElement) {
// elementType = ContributionInfoMessages.ContributionInfo_Category;
elementType = ContributionInfoMessages.get().ContributionInfo_Category;
} else if (contribution instanceof ColorDefinition) {
// elementType = ContributionInfoMessages.ContributionInfo_ColorDefinition;
elementType = ContributionInfoMessages.get().ContributionInfo_ColorDefinition;
} else if (contribution instanceof WorkbenchWizardElement) {
// elementType = ContributionInfoMessages.ContributionInfo_Wizard;
elementType = ContributionInfoMessages.get().ContributionInfo_Wizard;
} else if (contribution instanceof PerspectiveDescriptor) {
// elementType = ContributionInfoMessages.ContributionInfo_Perspective;
elementType = ContributionInfoMessages.get().ContributionInfo_Perspective;
} else if (contribution instanceof WorkbenchPreferenceExpressionNode) {
// elementType = ContributionInfoMessages.ContributionInfo_Page;
elementType = ContributionInfoMessages.get().ContributionInfo_Page;
} else if (contribution instanceof DecoratorDefinition) {
// elementType = ContributionInfoMessages.ContributionInfo_LabelDecoration;
elementType = ContributionInfoMessages.get().ContributionInfo_LabelDecoration;
} else {
// elementType = ContributionInfoMessages.ContributionInfo_Unknown;
elementType = ContributionInfoMessages.get().ContributionInfo_Unknown;
}
return new ContributionInfo(contribution.getPluginId(), elementType, null);
}
if (adaptableObject instanceof JobInfo) {
JobInfo jobInfo = (JobInfo) adaptableObject;
Job job = jobInfo.getJob();
if (job != null) {
Bundle bundle = FrameworkUtil.getBundle(job.getClass());
if (bundle != null) {
// ContributionInfoMessages.ContributionInfo_Job, null);
return new ContributionInfo(bundle.getSymbolicName(), ContributionInfoMessages.get().ContributionInfo_Job, null);
}
}
}
return null;
}
Example 100
Project: riftsaw-master File: SchedulerDAOConnectionFactoryImpl.java View source code |
@Override
public void init(Properties odeConfig, TransactionManager txm, Object env) {
_txm = txm;
_ds = (DataSource) env;
Bundle thisBundle = FrameworkUtil.getBundle(getClass());
BundleContext context = thisBundle.getBundleContext();
ServiceReference serviceReference = context.getServiceReference(PersistenceProvider.class.getName());
PersistenceProvider persistenceProvider = (PersistenceProvider) context.getService(serviceReference);
Map<?, ?> emfProperties = HibernateUtil.buildConfig(OdeConfigProperties.PROP_DAOCF_SCHEDULER + ".", odeConfig, _txm, _ds);
_emf = persistenceProvider.createEntityManagerFactory("ode-scheduler", emfProperties);
}
Example 101
Project: sensormix-master File: MaintenanceCommand.java View source code |
/**
* Retrieve a specific implementation of SensormixAdminInterface by its bean
* name.
*
* @param id the name of the bean implementation
* @return the instance of implementation if exists
*/
private SensormixAdminInterface getSensormixAdminServiceById(String id) {
SensormixAdminInterface service = null;
ServiceReference[] refs = null;
final Bundle b = FrameworkUtil.getBundle(this.getClass());
final BundleContext bc = b.getBundleContext();
try {
refs = bc.getAllServiceReferences(SensormixAdminInterface.class.getName(), "(org.springframework.osgi.bean.name=" + id + ")");
if (refs == null || refs.length == 0) {
logger.log(Level.SEVERE, "Unable to retrieve service reference for SensormixAdminInterface");
} else if (refs.length > 1) {
logger.log(Level.SEVERE, "More than one service registered for SensormixAdminInterface");
} else {
service = (SensormixAdminInterface) bc.getService(refs[0]);
}
} catch (InvalidSyntaxException e) {
logger.log(Level.SEVERE, "Unable to retrieve service reference for SensormixAdminInterface", e);
}
return service;
}