@SuppressWarnings({"unchecked", "rawtypes"}) private void getServices() { try { BundleContext bundleContext = FrameworkUtil.getBundle(VehicleViewForm.class).getBundleContext(); ServiceReference vehicleServiceReference = bundleContext.getServiceReference(VehicleService.class.getName()); vehicleService = VehicleService.class.cast(bundleContext.getService(vehicleServiceReference)); ServiceReference supplierServiceReference = bundleContext.getServiceReference(SupplierService.class.getName()); supplierService = SupplierService.class.cast(bundleContext.getService(supplierServiceReference)); ServiceReference tireTypeServiceReference = bundleContext.getServiceReference(TireTypeService.class.getName()); tireTypeService = TireTypeService.class.cast(bundleContext.getService(tireTypeServiceReference)); ServiceReference tireStatusServiceReference = bundleContext.getServiceReference(TireStatusService.class.getName()); tireStatusService = TireStatusService.class.cast(bundleContext.getService(tireStatusServiceReference)); } catch (Exception e) { e.getMessage(); } }
public void start(BundleContext context) throws Exception { // simplistic way of achieving the WebContainer as service ServiceReference<WebContainer> serviceReference = context.getServiceReference(WebContainer.class); while (serviceReference == null) { serviceReference = context.getServiceReference(WebContainer.class); } WebContainer service = (WebContainer) context.getService(serviceReference); Collection<ServiceReference<HttpContext>> serviceReferences = context.getServiceReferences(HttpContext.class, "(httpContext.id=shared)"); if (serviceReferences.size() > 1) { throw new RuntimeException("should only be one http shared context"); } HttpContext httpContext = context.getService(serviceReferences.iterator().next()); Dictionary<String, String> props; props = new Hashtable<String, String>(); props.put("pattern", ".*"); props.put(ExtenderConstants.PROPERTY_HTTP_CONTEXT_ID, "shared"); service.registerFilter(new ServletFilter(), new String[] {"/*"}, null, props, httpContext); }
/* (non-Javadoc) * @see org.osgi.framework.ServiceFactory#getService(org.osgi.framework.Bundle, org.osgi.framework.ServiceRegistration) */ @Override public Object getService(Bundle bundle, ServiceRegistration registration) { if (serviceInstance == null) { IRepositoryService repositoryService = null; IMarketService marketService = null; try { BundleContext context = CoreActivator.getDefault().getBundle().getBundleContext(); ServiceReference serviceReference = context.getServiceReference(IRepositoryService.class.getName()); if (serviceReference != null) { repositoryService = (IRepositoryService) context.getService(serviceReference); context.ungetService(serviceReference); } serviceReference = context.getServiceReference(IMarketService.class.getName()); if (serviceReference != null) { marketService = (IMarketService) context.getService(serviceReference); context.ungetService(serviceReference); } serviceInstance = new CurrencyService(repositoryService, marketService); serviceInstance.startUp(null); } catch (Exception e) { CoreActivator.log("Error starting currency service", e); } } return serviceInstance; }
public void start(BundleContext context) throws Exception { ServiceReference messageManager = context.getServiceReference(MessageManager.class.getName()); mgr = (MessageManager) context.getService(messageManager); ServiceReference azureuCore = context.getServiceReference(AzureusCore.class.getName()); core = (AzureusCore) context.getService(azureuCore); // ServiceReference gmRef = context.getServiceReference(GlobalManager.class.getName()); // gm = (GlobalManager) context.getService(gmRef); ServiceReference dlmgrRef = context.getServiceReference(DownloadManager.class.getName()); dlmgr = (DownloadManager) context.getService(dlmgrRef); initialize(); }
public synchronized MavenResolver getMavenResolver() throws RuntimeException { if (mavenResolver == null) { BundleContext context = CoreRuntimePlugin.getInstance().getBundle().getBundleContext(); ServiceReference<ManagedService> managedServiceRef = context.getServiceReference(ManagedService.class); if (managedServiceRef != null) { String repositories = ""; NexusServerBean customServer = getCustomNexusServer(); if (customServer != null) { // custom nexus server should use snapshot repository repositories = customServer.getRepositoryUrl() + NexusConstants.SNAPSHOTS + ","; } final NexusServerBean officailServer = getLibrariesNexusServer(); repositories = repositories + officailServer.getRepositoryUrl(); ManagedService managedService = context.getService(managedServiceRef); Dictionary<String, String> props = new Hashtable<String, String>(); props.put( ServiceConstants.PID + '.' + ServiceConstants.PROPERTY_REPOSITORIES, repositories); // get the setting file same as M2E preference in M2eUserSettingForTalendLoginTask. String settingsFile = MavenPlugin.getMavenConfiguration().getUserSettingsFile(); if (settingsFile != null && new File(settingsFile).exists()) { props.put( ServiceConstants.PID + '.' + ServiceConstants.PROPERTY_SETTINGS_FILE, settingsFile); } try { managedService.updated(props); } catch (ConfigurationException e) { throw new RuntimeException("Failed to modifiy the service properties"); // $NON-NLS-1$ } } else { throw new RuntimeException( "Failed to load the service :" + ManagedService.class.getCanonicalName()); // $NON-NLS-1$ } ServiceReference<org.ops4j.pax.url.mvn.MavenResolver> mavenResolverService = context.getServiceReference(org.ops4j.pax.url.mvn.MavenResolver.class); if (mavenResolverService != null) { mavenResolver = context.getService(mavenResolverService); } else { throw new RuntimeException("Unable to acquire org.ops4j.pax.url.mvn.MavenResolver"); } } return mavenResolver; }
static Object getService(String name) { ServiceReference reference = context.getServiceReference(name); if (reference == null) return null; Object result = context.getService(reference); context.ungetService(reference); return result; }
// //@Override public ServiceDescriptor lookupServiceDescriptor(String type, String name, Properties overrides) throws ServiceException { try { // Get all services which match the interface. ServiceReference[] services; if (context != null) { services = context.getServiceReferences(TransportServiceDescriptor.class.getName(), null); } else { throw new InitialisationException( Message.createStaticMessage("BundleContext has not been set for Manager."), this); } // Match the service by name. String servicePid; for (int i = 0; i < services.length; ++i) { servicePid = (String) services[i].getProperty(Constants.SERVICE_PID); if (servicePid != null && servicePid.endsWith(name)) { return (ServiceDescriptor) context.getService(services[i]); } } return null; } catch (Exception e) { throw new ServiceException( Message.createStaticMessage("Exception while looking up the service descriptor."), e); } }
@Before public void areWeReady() { assertNotNull(bc); boolean debugit = false; Bundle b[] = bc.getBundles(); for (int i = 0; i < b.length; i++) { int state = b[i].getState(); if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) { System.out.println(">>> " + b[i].getSymbolicName() + " " + stateToString(state)); log.debug("Bundle:" + b[i].getSymbolicName() + " state:" + stateToString(state)); debugit = true; } } if (debugit) { log.debug("Do some debugging because some bundle is unresolved"); } // Assert if true, if false we are good to go! assertFalse(debugit); ServiceReference r = bc.getServiceReference(IAffinityManager.class.getName()); if (r != null) { this.manager = (IAffinityManager) bc.getService(r); } // If AffinityManager is null, cannot run tests. assertNotNull(this.manager); }
@Override public void start(BundleContext context) throws Exception { LOG.info("Starting Bundle"); // Get our name. String myName = context.getBundle().getSymbolicName(); // Find reference. ServiceReference<HelloService> ref = context.getServiceReference(HelloService.class); if (ref != null) { try { // Print service properties. String props = getServiceProperties(ref); LOG.info( "Calling HelloService#sayHello('{}') Published by {}. Props:\n{}", myName, ref.getBundle().getSymbolicName(), props); // Get the service HelloService service = context.getService(ref); if (service != null) { service.sayHello(myName); } } finally { // Release reference context.ungetService(ref); } } }
@Override public List<CamelContext> getLocalCamelContexts() { List<CamelContext> camelContexts = new ArrayList<CamelContext>(); try { ServiceReference<?>[] references = bundleContext.getServiceReferences(CamelContext.class.getName(), null); if (references != null) { for (ServiceReference<?> reference : references) { if (reference != null) { CamelContext camelContext = (CamelContext) bundleContext.getService(reference); if (camelContext != null) { camelContexts.add(camelContext); } } } } } catch (Exception e) { LOG.warn("Cannot retrieve the list of Camel contexts.", e); } // sort the list Collections.sort( camelContexts, new Comparator<CamelContext>() { @Override public int compare(CamelContext o1, CamelContext o2) { return o1.getName().compareTo(o2.getName()); } }); return camelContexts; }
/** * This will try and find a resource of the given name using the bundle from which was originally * loaded the given class so as to try and detect if it is jarred. If <code>clazz</code> hasn't * been loaded from a bundle class loader, we'll resort to the default class loader mechanism. * This will only return <code>null</code> in the case where the resource at <code>resourcePath * </code> cannot be located at all. * * @param clazz Class which class loader will be used to try and locate the resource. * @param resourcePath Path of the resource we seek, relative to the class. * @return The URL of the resource as we could locate it. * @throws IOException This will be thrown if we fail to convert bundle-scheme URIs into * file-scheme URIs. */ public static URL getResourceURL(Class<?> clazz, String resourcePath) throws IOException { BundleContext context = AcceleoCommonPlugin.getDefault().getContext(); ServiceReference packageAdminReference = context.getServiceReference(PackageAdmin.class.getName()); PackageAdmin packageAdmin = null; if (packageAdminReference != null) { packageAdmin = (PackageAdmin) context.getService(packageAdminReference); } URL resourceURL = null; if (packageAdmin != null) { Bundle bundle = packageAdmin.getBundle(clazz); if (bundle != null) { final String pathSeparator = "/"; // $NON-NLS-1$ // We found the appropriate bundle. We'll now try and determine whether the emtl is jarred resourceURL = getBundleResourceURL(bundle, pathSeparator, resourcePath); } } /* * We couldn't locate either the bundle which loaded the class or the resource. Resort to the class * loader and return null if it cannot locate the resource either. */ if (resourceURL == null) { resourceURL = clazz.getResource(resourcePath); } if (packageAdminReference != null) { context.ungetService(packageAdminReference); } return resourceURL; }
public MdsRestFacade getRestFacade(String entityName, String moduleName, String namespace) { String restId = ClassName.restId(entityName, moduleName, namespace); MdsRestFacade restFacade = null; try { String filter = String.format("(org.eclipse.gemini.blueprint.bean.name=%s)", restId); Collection<ServiceReference<MdsRestFacade>> refs = bundleContext.getServiceReferences(MdsRestFacade.class, filter); if (refs != null && refs.size() > 1 && LOGGER.isWarnEnabled()) { LOGGER.warn( "More then one Rest Facade matching for entityName={}, module={}, namespace={}. " + "Using first one available.", entityName, moduleName, namespace); } if (refs != null && refs.size() > 0) { ServiceReference<MdsRestFacade> ref = refs.iterator().next(); restFacade = bundleContext.getService(ref); } } catch (InvalidSyntaxException e) { throw new IllegalArgumentException("Invalid Syntax for Rest Facade retrieval", e); } if (restFacade == null) { throw new RestNotSupportedException(entityName, moduleName, namespace); } return restFacade; }
@Override public void start(BundleContext context) throws Exception { bundleContext = context; this.tracker = new ServiceTracker(context, HttpService.class.getName(), null) { @Override public Object addingService(ServiceReference ref) { Object service = super.addingService(ref); serviceAdded((HttpService) service); return service; } @Override public void removedService(ServiceReference ref, Object service) { serviceRemoved((HttpService) service); super.removedService(ref, service); } }; this.tracker.open(); httpService = context.getServiceReference(HttpService.class.getName()); if (httpService != null) { HttpService service = (HttpService) context.getService(httpService); serviceAdded(service); } }
public static SlingRepository getSlingRepositoryFromServiceList(BundleContext bundleContext) { ServiceReference slingRepositoryServiceReference = bundleContext.getServiceReference(SlingRepository.class.getName()); SlingRepository slingRepository = (SlingRepository) bundleContext.getService(slingRepositoryServiceReference); return slingRepository; }
public static ConfigurationAdmin getConfigurationAdminService(BundleContext bundleContext) { ServiceReference configurationAdminServiceReference = bundleContext.getServiceReference(ConfigurationAdmin.class.getName()); ConfigurationAdmin configurationAdminService = (ConfigurationAdmin) bundleContext.getService(configurationAdminServiceReference); return configurationAdminService; }
protected <T> T requiredService(Class<T> serviceType) { ServiceReference reference = bundleContext.getServiceReference(serviceType); if (reference == null) { throw new IllegalStateException("Cannot find service: " + serviceType.getName()); } return (T) bundleContext.getService(reference); }
@Test public void testServiceContributorDiscovery() throws Exception { final ServiceReference sr = bundleContext.getServiceReference(SessionFactory.class.getName()); final SessionFactoryImplementor sfi = (SessionFactoryImplementor) bundleContext.getService(sr); assertNotNull(sfi.getServiceRegistry().getService(SomeService.class)); }
@SuppressWarnings({"rawtypes", "unchecked", "unused"}) private void logServiceProperties(final Class<?> klaz, final Object instance) throws Exception { final BundleContext context = bundleContext(); final ServiceReference[] referenceArray = context.getAllServiceReferences(klaz.getName(), null); for (final ServiceReference reference : referenceArray) { final Object service = context.getService(reference); if (service == instance) { log.info("instance=" + instance); final String[] propKeyArray = reference.getPropertyKeys(); for (final String propKey : propKeyArray) { final Object propValue = reference.getProperty(propKey); log.info(propKey + "=" + propValue); } // final String[] nameArray = (String[]) reference // .getProperty("objectClass"); // for (final String name : nameArray) { // log.info("name=" + name); // } } } }
private static final IBundleScanService lookupBundleScanner(BundleContext ctx) { ServiceReference svcRef = ctx.getServiceReference(IBundleScanService.class); if (svcRef == null) { throw new ServiceException("Unable to lookup IBundleScanService"); } return IBundleScanService.class.cast(ctx.getService(svcRef)); }
// TODO - we should really make this a bundle and inject this. private FeaturesService getFeaturesService() throws InterruptedException { FeaturesService featuresService = null; boolean ready = false; long timeoutLimit = System.currentTimeMillis() + REQUIRED_BUNDLES_TIMEOUT; while (!ready) { ServiceReference<FeaturesService> featuresServiceRef = bundleCtx.getServiceReference(FeaturesService.class); try { if (featuresServiceRef != null) { featuresService = bundleCtx.getService(featuresServiceRef); if (featuresService != null) { ready = true; } } } catch (NullPointerException e) { // ignore } if (!ready) { if (System.currentTimeMillis() > timeoutLimit) { fail( String.format( "Feature service could not be resolved within %d minutes.", TimeUnit.MILLISECONDS.toMinutes(REQUIRED_BUNDLES_TIMEOUT))); } Thread.sleep(1000); } } return featuresService; }
protected Component getContent(MPart mPart) { BundleContext context = getBundleContext(); String id = getServiceID(mPart); try { String filter = String.format("(%s=%s)", IOutlineViewProvider.PROPERTY, id); Collection<ServiceReference<IOutlineViewProvider>> services = context.getServiceReferences(IOutlineViewProvider.class, filter); if (!services.isEmpty()) { ServiceReference<IOutlineViewProvider> ref = services.iterator().next(); IOutlineViewProvider service = context.getService(ref); if (service != null) { try { return service.getOutlineContent(mPart); } finally { getBundleContext().ungetService(ref); } } } } catch (InvalidSyntaxException e) { e.printStackTrace(); } return null; }
/** * Returns the prefix for all persistently stored properties of the account with the specified id. * * @param bundleContext a currently valid bundle context. * @param accountID the AccountID of the account whose properties we're looking for. * @param sourcePackageName a String containing the package name of the concrete factory class * that extends us. * @return a String indicating the ConfigurationService property name prefix under which all * account properties are stored or null if no account corresponding to the specified id was * found. */ public static String findAccountPrefix( BundleContext bundleContext, AccountID accountID, String sourcePackageName) { ServiceReference confReference = bundleContext.getServiceReference(ConfigurationService.class.getName()); ConfigurationService configurationService = (ConfigurationService) bundleContext.getService(confReference); // first retrieve all accounts that we've registered List<String> storedAccounts = configurationService.getPropertyNamesByPrefix(sourcePackageName, true); // find an account with the corresponding id. for (String accountRootPropertyName : storedAccounts) { // unregister the account in the configuration service. // all the properties must have been registered in the following // hierarchy: // net.java.sip.communicator.impl.protocol.PROTO_NAME.ACC_ID.PROP_NAME String accountUID = configurationService.getString( accountRootPropertyName // node id + "." + ACCOUNT_UID); // propname if (accountID.getAccountUniqueID().equals(accountUID)) { return accountRootPropertyName; } } return null; }
public void stop(BundleContext context) throws Exception { this.tracker.close(); if (httpService != null) { HttpService service = (HttpService) context.getService(httpService); serviceRemoved(service); } }
/* * (non-Javadoc) * * @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext) */ public void stop(final BundleContext context) throws Exception { // TODO-mkuppe here we should do something like a deregisterAll(), but see ungetService(...); if (serviceRegistration != null && serviceFactory.isActive()) { ServiceReference reference = serviceRegistration.getReference(); IDiscoveryLocator aLocator = (IDiscoveryLocator) context.getService(reference); serviceRegistration.unregister(); IContainer container = (IContainer) aLocator.getAdapter(IContainer.class); container.disconnect(); container.dispose(); serviceRegistration = null; } plugin = null; bundleContext = null; if (advertiserSt != null) { advertiserSt.close(); advertiserSt = null; } if (locatorSt != null) { locatorSt.close(); locatorSt = null; } }
public void start() throws IOException { if (httpService != null || httpServiceReference != null) throw new IllegalStateException("Server has already been started."); httpServiceReference = context.getServiceReference(HttpService.class.getName()); if (httpServiceReference != null) { httpService = (HttpService) context.getService(httpServiceReference); if (httpService == null) throw new IOException("Unable to access Http Service"); } else { throw new IOException("Unable to access Http Service"); } for (Iterator i = registrations.keySet().iterator(); i.hasNext(); ) { String prefix = (String) i.next(); IHandler handler = (IHandler) registrations.get(prefix); try { httpService.registerServlet( globalPrefix + "/" + prefix, new HandlerServletAdapter(handler), null, null); } catch (Exception e) { throw new IOException(e.getMessage()); } } }
/** * Implements the <tt>SimpleShape</tt> interface method. When acting as a proxy, this method gets * the shape service and then uses it to draw the shape. When acting as a placeholder shape, this * method draws the default icon. * * @param g2 The graphics object used for painting. * @param p The position to paint the triangle. */ public void draw(Graphics2D g2, Point p) { // If this is a proxy shape, instantiate the shape class // and use it to draw the shape. if (m_context != null) { try { if (m_shape == null) { // Get the shape service. m_shape = (SimpleShape) m_context.getService(m_ref); } // Draw the shape. m_shape.draw(g2, p); // If everything was successful, then simply return. return; } catch (Exception ex) { // This generally should not happen, but if it does then // we can just fall through and paint the default icon. } } // If the proxied shape could not be drawn for any reason or if // this shape is simply a placeholder, then draw the default icon. if (m_icon == null) { try { m_icon = new ImageIcon(this.getClass().getResource("underc.png")); } catch (Exception ex) { ex.printStackTrace(); g2.setColor(Color.red); g2.fillRect(0, 0, 60, 60); return; } } g2.drawImage(m_icon.getImage(), 0, 0, null); }
protected void removingWebContainerCallback(ServiceReference serviceReference) { WebContainer service = (WebContainer) bundleContext.getService(serviceReference); if (service != null) { service.unregisterLoginConfig(httpContext); service.unregisterConstraintMapping(httpContext); } }
@Override public void start(BundleContext bundleContext) throws Exception { context = bundleContext; // URL x = context.getBundle().getEntry("config.xml"); // InputStream is = x.openStream(); ServiceReference reference = context.getServiceReference(IAqua.class.getName()); aqua = (IAqua) context.getService(reference); FileInputStream is = new FileInputStream(new File(getBaseDir(), "config.xml")); config = new XmlConfig(MXml.loadXml(is).getDocumentElement()); config.setString("_path", getBaseDir().getAbsolutePath()); is.close(); // init directories to publish IConfig cp = aqua.getConfig().getConfig("deploy"); contentDir = cp.getExtracted("content") + "/" + getId(); templateDir = cp.getExtracted("templates") + "/" + getId(); getConfiguration().setProperty("_contentdir", contentDir); getConfiguration().setProperty("_templatedir", templateDir); // publish publish(); // load resources loadResources(); jmx = new JmxAquaModule(this); Activator.getAqua().getJmxManager().register(jmx); }
/** * Get the <tt>AccountManager</tt> of the protocol. * * @return <tt>AccountManager</tt> of the protocol */ private AccountManager getAccountManager() { BundleContext bundleContext = getBundleContext(); ServiceReference serviceReference = bundleContext.getServiceReference(AccountManager.class.getName()); return (AccountManager) bundleContext.getService(serviceReference); }
@Before public void areWeReady() { assertNotNull(bc); boolean debugit = false; Bundle b[] = bc.getBundles(); for (Bundle element : b) { int state = element.getState(); if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) { log.debug("Bundle:" + element.getSymbolicName() + " state:" + stateToString(state)); debugit = true; } } if (debugit) { log.debug("Do some debugging because some bundle is " + "unresolved"); } // Assert if true, if false we are good to go! assertFalse(debugit); ServiceReference r = bc.getServiceReference(IForwardingRulesManager.class.getName()); if (r != null) { this.manager = (IForwardingRulesManager) bc.getService(r); } // If StatisticsManager is null, cannot run tests. assertNotNull(this.manager); }