public void start(BundleContext context) throws Exception { final Map<String, Object> props = new HashMap<String, Object>(); props.put(Constants.SERVICE_PID, "net.michaelpigg.xbeelib.xbeeservice"); serviceFactory = new XbeeServiceFactory(context); serviceFactoryRegistration = context.registerService( ManagedServiceFactory.class.getName(), serviceFactory, new Hashtable(props)); logger.debug("Registering ToXbeeCommand"); context.registerService( ToXbeeCommand.class.getName(), new ToXbeeCommand(context), commandRegistrationProperties("xbee", "xb", "xbr")); context.registerService( XbeeMonitorCommand.class.getName(), new XbeeMonitorCommand(context), commandRegistrationProperties("xbee", "xmon")); context.registerService( ConfigureXbeeServiceCommand.class.getName(), new ConfigureXbeeServiceCommand(context), commandRegistrationProperties("xbee", "xbconfig", "listports")); configAdminTracker = new ServiceTracker( context, ConfigurationAdmin.class.getName(), new ConfigAdminTrackerCustomizer(context)); configAdminTracker.open(); }
@Test public void testSynchronousBundleListener() throws Exception { final List<BundleEvent> events = new ArrayList<BundleEvent>(); BundleListener listener = new SynchronousBundleListener() { @Override public void bundleChanged(BundleEvent event) { events.add(event); } }; BundleContext context = getSystemContext(); context.addBundleListener(listener); Bundle bundle = installBundle(getBundleArchiveA()); try { bundle.start(); bundle.stop(); bundle.update(); } finally { bundle.uninstall(); } assertEquals("Event count in: " + events, 10, events.size()); assertEquals(BundleEvent.INSTALLED, events.get(0).getType()); assertEquals(BundleEvent.RESOLVED, events.get(1).getType()); assertEquals(BundleEvent.STARTING, events.get(2).getType()); assertEquals(BundleEvent.STARTED, events.get(3).getType()); assertEquals(BundleEvent.STOPPING, events.get(4).getType()); assertEquals(BundleEvent.STOPPED, events.get(5).getType()); assertEquals(BundleEvent.UNRESOLVED, events.get(6).getType()); assertEquals(BundleEvent.UPDATED, events.get(7).getType()); assertEquals(BundleEvent.UNRESOLVED, events.get(8).getType()); assertEquals(BundleEvent.UNINSTALLED, events.get(9).getType()); }
@Test public void testStopedBundleContext() throws Exception { Bundle bundle = installBundle(getBundleArchiveA()); try { bundle.start(); BundleContext bundleContext = bundle.getBundleContext(); assertNotNull(bundleContext); // The context should be illegal to use. bundle.stop(); try { bundleContext.getProperty(getClass().getName()); fail("Should not be here!"); } catch (IllegalStateException t) { // expected } // The context should not become reusable after we restart the bundle bundle.start(); try { bundleContext.getProperty(getClass().getName()); fail("Should not be here!"); } catch (IllegalStateException t) { // expected } } finally { bundle.uninstall(); } }
public OSGiRuntimeService(OSGiRuntimeContext runtimeContext, BundleContext context) { super(runtimeContext); bundleContext = context; bundles = new ConcurrentHashMap<String, Bundle>(); contexts = new ConcurrentHashMap<String, RuntimeContext>(); String bindAddress = context.getProperty(PROP_NUXEO_BIND_ADDRESS); if (bindAddress != null) { properties.put(PROP_NUXEO_BIND_ADDRESS, bindAddress); } String homeDir = getProperty(PROP_HOME_DIR); log.debug("Home directory: " + homeDir); if (homeDir != null) { workingDir = new File(homeDir); } else { workingDir = bundleContext.getDataFile("/"); } // environment may not be set by some bootstrappers (like tests) - we // create it now if not yet created Environment env = Environment.getDefault(); if (env == null) { Environment.setDefault(new Environment(workingDir)); } workingDir.mkdirs(); persistence = new ComponentPersistence(this); log.debug("Working directory: " + workingDir); }
/** * 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); }
@Test public void testOwnerCannotSeeServiceClass() throws Exception { final Bundle bundleA = installBundle(getBundleArchiveA()); final Bundle bundleB = installBundle(getBundleArchiveB()); try { bundleA.start(); bundleB.start(); BundleContext contextA = bundleA.getBundleContext(); BundleContext contextB = bundleB.getBundleContext(); final CountDownLatch latch = new CountDownLatch(1); ServiceListener listener = new ServiceListener() { public void serviceChanged(ServiceEvent event) { latch.countDown(); } }; contextB.addServiceListener(listener); Object service = bundleB.loadClass(B.class.getName()).newInstance(); ServiceRegistration reg = contextA.registerService(B.class.getName(), service, null); ServiceReference ref = reg.getReference(); assertTrue(ref.isAssignableTo(bundleA, B.class.getName())); assertTrue(ref.isAssignableTo(bundleB, B.class.getName())); if (latch.await(5, TimeUnit.SECONDS) == false) throw new TimeoutException(); } finally { bundleA.uninstall(); bundleB.uninstall(); } }
// 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; }
// //@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); } }
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)); }
@Override public synchronized void start(BundleContext bundleContext) throws Exception { // This is how we replace the default FactoryFinder strategy // with one that is more compatible in an OSGi env. FactoryFinder.setObjectFactory(this); debug("activating"); this.bundleContext = bundleContext; cachePackageCapabilities( Service.class, Transport.class, DiscoveryAgent.class, PersistenceAdapter.class); debug("checking existing bundles"); bundleContext.addBundleListener(this); for (Bundle bundle : bundleContext.getBundles()) { if (bundle.getState() == Bundle.RESOLVED || bundle.getState() == Bundle.STARTING || bundle.getState() == Bundle.ACTIVE || bundle.getState() == Bundle.STOPPING) { register(bundle); } } debug("activated"); }
@Override public void start(BundleContext context) throws Exception { this.logger = LoggerActivator.getLogger(); this.logger.info("Starting the " + context.getBundle().getSymbolicName() + " bundle..."); PermissionActivator.configTracker = new ServiceTracker<Config, Config>(context, Config.class, null); PermissionActivator.configTracker.open(); PermissionActivator.messengerTracker = new ServiceTracker<MessengerService, MessengerService>( context, MessengerService.class, null); PermissionActivator.messengerTracker.open(); /* Register the Permissions service. */ this.logger.debug("Registering the Permissions SOAP interface service."); ServletContainerService soapService = new ServletContainerService(); soapService.addServlet(new ServletContainer(new AxisServlet(), true)); this.soapRegistration = context.registerService(ServletContainerService.class, soapService, null); this.pageRegistrations = new ArrayList<ServiceRegistration<HostedPage>>(3); this.pageRegistrations.add( context.registerService(HostedPage.class, UsersPage.getHostedPage(), null)); this.pageRegistrations.add( context.registerService(HostedPage.class, UserClassesPage.getHostedPage(), null)); this.pageRegistrations.add( context.registerService(HostedPage.class, KeysPage.getHostedPage(), null)); }
@Override protected String customResolveManagementName(String pattern, String answer) { String bundleId = "" + bundleContext.getBundle().getBundleId(); String symbolicName = bundleContext.getBundle().getSymbolicName(); if (symbolicName != null) { symbolicName = Matcher.quoteReplacement(symbolicName); } else { symbolicName = ""; } String version = Matcher.quoteReplacement(bundleContext.getBundle().getVersion().toString()); answer = answer.replaceFirst("#bundleId#", bundleId); answer = answer.replaceFirst("#symbolicName#", symbolicName); answer = answer.replaceFirst("#version#", version); // we got a candidate then find a free name // true = check fist if the candidate as-is is free, if not then use the counter answer = OsgiNamingHelper.findFreeCamelContextName( bundleContext, answer, OsgiCamelContextPublisher.CONTEXT_MANAGEMENT_NAME_PROPERTY, CONTEXT_COUNTER, true); return answer; }
@Override public int complete(String buffer, int cursor, List<CharSequence> candidates) { Bundle[] bundles = bundleContext.getBundles(); List<Long> bundleIds = new ArrayList<Long>(); for (Bundle b : bundles) { if (matcher.bundleMatches(b)) { bundleIds.add(b.getBundleId()); } } SortedSet<String> variants = new TreeSet<String>(); if (buffer.matches("^[0-9]+$")) { for (Long l : bundleIds) { variants.add(String.valueOf(l)); } } else { for (Long l : bundleIds) { variants.add(bundleContext.getBundle(l).getSymbolicName()); } } if (buffer.isEmpty()) { candidates.addAll(variants); } else { for (String match : variants.tailSet(buffer)) { if (!match.startsWith(buffer)) { break; } candidates.add(match.substring(buffer.length())); } } return candidates.isEmpty() ? -1 : buffer.length(); }
private void initServices() { BundleContext context = Activator.getContext(); if (context == null) { RuntimeLog.log( new Status( IStatus.ERROR, RegistryMessages.OWNER_NAME, 0, RegistryMessages.bundle_not_activated, null)); return; } debugTracker = new ServiceTracker(context, DebugOptions.class.getName(), null); debugTracker.open(); bundleTracker = new ServiceTracker(context, PackageAdmin.class.getName(), null); bundleTracker.open(); // locations final String FILTER_PREFIX = "(&(objectClass=org.eclipse.osgi.service.datalocation.Location)(type="; //$NON-NLS-1$ Filter filter = null; try { filter = context.createFilter(FILTER_PREFIX + PROP_CONFIG_AREA + "))"); // $NON-NLS-1$ } catch (InvalidSyntaxException e) { // ignore this. It should never happen as we have tested the above format. } configurationLocationTracker = new ServiceTracker(context, filter, null); configurationLocationTracker.open(); }
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()); } } }
public static void activateBundlesFromFile(BundleContext context, String bundleStartupFileName) throws IOException, BundleException { Map<String, Version> bundleMap = readBundleActivationFile(context.getBundle(), bundleStartupFileName); Map<String, Bundle> startupBundleMap = new HashMap<String, Bundle>(); for (Bundle b : context.getBundles()) { String symbolicName = b.getSymbolicName(); if (bundleMap.containsKey(symbolicName)) { Version version = b.getVersion(); Version reqVersion = bundleMap.get(symbolicName); if (version.getMajor() == reqVersion.getMajor() && version.getMinor() >= reqVersion.getMinor()) { if (startupBundleMap.containsKey(symbolicName)) { Bundle previousBundle = startupBundleMap.get(symbolicName); if (version.compareTo(previousBundle.getVersion()) <= 0) { break; } } startupBundleMap.put(symbolicName, b); } } } for (Bundle startupBundle : startupBundleMap.values()) { logger.log(Level.INFO, "Starting bundle: " + startupBundle); startupBundle.start(); } }
@Test public void testRegBundleIsRefBundle() throws Exception { Bundle bundle = installBundle(getBundleArchiveA()); try { bundle.start(); final CountDownLatch latch = new CountDownLatch(1); ServiceListener listener = new ServiceListener() { public void serviceChanged(ServiceEvent event) { latch.countDown(); } }; BundleContext context = bundle.getBundleContext(); context.addServiceListener(listener); Object service = bundle.loadClass(A.class.getName()).newInstance(); ServiceRegistration reg = context.registerService(A.class.getName(), service, null); ServiceReference ref = reg.getReference(); assertTrue(ref.isAssignableTo(bundle, A.class.getName())); if (latch.await(5, TimeUnit.SECONDS) == false) throw new TimeoutException(); } finally { bundle.uninstall(); } }
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; }
@Test public void testObjectClassFilter() throws Exception { Bundle bundle = installBundle(getBundleArchiveA()); try { bundle.start(); BundleContext context = bundle.getBundleContext(); assertNotNull(context); assertNoServiceEvent(); String filter = "(" + Constants.OBJECTCLASS + "=" + BundleContext.class.getName() + ")"; context.addServiceListener(this, filter); ServiceRegistration sreg = context.registerService(BundleContext.class.getName(), context, null); ServiceReference sref = sreg.getReference(); assertServiceEvent(ServiceEvent.REGISTERED, sref); sreg.unregister(); assertServiceEvent(ServiceEvent.UNREGISTERING, sref); filter = "(objectClass=dummy)"; context.addServiceListener(this, filter); sreg = context.registerService(BundleContext.class.getName(), context, null); assertNoServiceEvent(); sreg.unregister(); assertNoServiceEvent(); } finally { bundle.uninstall(); } }
public void start(BundleContext context) throws Exception { backendEndpointsCommand = context.registerService( Command.class.getName(), new BackendEndpointsCommand(context), null); backendTracesCommand = context.registerService(Command.class.getName(), new BackendTracesCommand(), null); }
/** @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext bundleContext) { // shut down the trackers. m_eventAdmin.destroy(); // Clean up the listeners. bundleContext.removeBundleListener(m_frameworkHandler); bundleContext.removeFrameworkListener(m_frameworkHandler); bundleContext.removeServiceListener(m_frameworkHandler); // Remove the global handler for all JDK Logging (java.util.logging). if (m_JdkHandler != null) { Logger rootLogger = LogManager.getLogManager().getLogger(""); rootLogger.removeHandler(m_JdkHandler); m_JdkHandler.flush(); m_JdkHandler.close(); m_JdkHandler = null; } m_RegistrationPaxLogging.unregister(); m_RegistrationPaxLogging = null; m_registrationLogReaderService.unregister(); m_registrationLogReaderService = null; m_paxLogging.stop(); m_paxLogging = null; }
void removeInitListeners() { BundleContext context = createBundleContext(false); for (FrameworkListener initListener : initListeners) { context.removeFrameworkListener(initListener); } initListeners.clear(); }
/** * 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; }
@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 void indexTargetPlatform( OutputStream outputStream, List<File> additionalJarFiles, long stopWaitTimeout, String... dirNames) throws Exception { Framework framework = null; Path tempPath = Files.createTempDirectory(null); ClassLoader classLoader = TargetPlatformIndexerUtil.class.getClassLoader(); try (InputStream inputStream = classLoader.getResourceAsStream("META-INF/system.packages.extra.mf")) { Map<String, String> properties = new HashMap<>(); properties.put(Constants.FRAMEWORK_STORAGE, tempPath.toString()); Manifest extraPackagesManifest = new Manifest(inputStream); Attributes attributes = extraPackagesManifest.getMainAttributes(); properties.put( Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, attributes.getValue("Export-Package")); ServiceLoader<FrameworkFactory> serviceLoader = ServiceLoader.load(FrameworkFactory.class); FrameworkFactory frameworkFactory = serviceLoader.iterator().next(); framework = frameworkFactory.newFramework(properties); framework.init(); BundleContext bundleContext = framework.getBundleContext(); Bundle systemBundle = bundleContext.getBundle(0); TargetPlatformIndexer targetPlatformIndexer = new TargetPlatformIndexer(systemBundle, additionalJarFiles, dirNames); targetPlatformIndexer.index(outputStream); } finally { framework.stop(); FrameworkEvent frameworkEvent = framework.waitForStop(stopWaitTimeout); if (frameworkEvent.getType() == FrameworkEvent.WAIT_TIMEDOUT) { throw new Exception( "OSGi framework event " + frameworkEvent + " triggered after a " + stopWaitTimeout + "ms timeout"); } PathUtil.deltree(tempPath); } }
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; }
@Test public void testFrameworkListener() throws Exception { Bundle bundle = installBundle(getBundleArchiveA()); try { bundle.start(); BundleContext bundleContext = bundle.getBundleContext(); assertNotNull(bundleContext); try { bundleContext.addFrameworkListener(null); fail("Should not be here!"); } catch (IllegalArgumentException t) { // expected } try { bundleContext.removeFrameworkListener(null); fail("Should not be here!"); } catch (IllegalArgumentException t) { // expected } // todo test events } finally { bundle.uninstall(); } }
public void activate() { try { // we need to call the activator ourselves as this bundle is included in the lib folder com.sun.jersey.core.osgi.Activator jerseyActivator = new com.sun.jersey.core.osgi.Activator(); BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); try { jerseyActivator.start(bundleContext); } catch (Exception e) { logger.error("Could not start Jersey framework", e); } httpPort = Integer.parseInt(bundleContext.getProperty("jetty.port")); httpSSLPort = Integer.parseInt(bundleContext.getProperty("jetty.port.ssl")); httpService.registerServlet( CV_SERVLET_ALIAS, new AtmosphereServlet(), getJerseyServletParams(), createHttpContext()); logger.info("Started Cometvisu API at " + CV_SERVLET_ALIAS); if (discoveryService != null) { discoveryService.registerService(getDefaultServiceDescription()); discoveryService.registerService(getSSLServiceDescription()); } } catch (ServletException se) { throw new RuntimeException(se); } catch (NamespaceException se) { throw new RuntimeException(se); } }
public void execute(@Observes(precedence = Integer.MAX_VALUE) EventContext<BeforeSuite> event) throws Exception { 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(); }
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; }