@Override protected void setUp() throws Exception { tmp = IO.getFile("generated/tmp"); tmp.mkdirs(); configuration = new HashMap<String, Object>(); configuration.put( Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); configuration.put(Constants.FRAMEWORK_STORAGE, new File(tmp, "fwstorage").getAbsolutePath()); configuration.put( Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.framework.launch;version=1.4"); framework = new org.apache.felix.framework.FrameworkFactory().newFramework(configuration); framework.init(); framework.start(); BundleContext context = framework.getBundleContext(); String[] bundles = { "../cnf/repo/osgi.cmpn/osgi.cmpn-4.3.1.jar", "testdata/slf4j-simple-1.7.12.jar", "testdata/slf4j-api-1.7.12.jar", "testdata/org.apache.aries.util-1.1.0.jar", "testdata/org.apache.aries.jmx-1.1.1.jar", "generated/biz.aQute.remote.test.jmx.jar" }; for (String bundle : bundles) { String location = "reference:" + IO.getFile(bundle).toURI().toString(); Bundle b = context.installBundle(location); if (!bundle.contains("slf4j-simple")) { b.start(); } } super.setUp(); }
public static FrameworkDTO newFrameworkDTO( BundleContext systemBundleContext, Map<String, String> configuration) { FrameworkDTO dto = new FrameworkDTO(); dto.properties = asProperties(configuration); if (systemBundleContext == null) { dto.bundles = newList(0); dto.services = newList(0); return dto; } Bundle[] bundles = systemBundleContext.getBundles(); int size = bundles == null ? 0 : bundles.length; List<BundleDTO> bundleDTOs = newList(size); for (int i = 0; i < size; i++) { bundleDTOs.add(newBundleDTO(bundles[i])); } dto.bundles = bundleDTOs; try { ServiceReference<?>[] references = systemBundleContext.getAllServiceReferences(null, null); size = references == null ? 0 : references.length; List<ServiceReferenceDTO> refDTOs = newList(size); for (int i = 0; i < size; i++) { ServiceReferenceDTO serviceRefDTO = getServiceReferenceDTO(references[i]); if (serviceRefDTO != null) { refDTOs.add(serviceRefDTO); } } dto.services = refDTOs; } catch (InvalidSyntaxException e) { dto.services = newList(0); } return dto; }
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; }
/** * Called when this bundle is started so the Framework can perform the bundle-specific activities * necessary to start this bundle. This method can be used to register services or to allocate any * resources that this bundle needs. * * <p>This method must complete and return to its caller in a timely manner. * * @param context The execution context of the bundle being started. * @throws Exception If this method throws an exception, this bundle is marked as stopped and the * Framework will remove this bundle's listeners, unregister all services registered by this * bundle, and release all services used by this bundle. */ @Override public void start(BundleContext context) throws Exception { this.context = context; initMembers(); this.activatorLogger.info( "Starting APSActivator for bundle '" + context.getBundle().getSymbolicName() + "' with activatorMode: " + this.activatorMode); Bundle bundle = context.getBundle(); List<Class> classEntries = new LinkedList<>(); if (!this.activatorMode) { classEntries.addAll(this.managedInstances.keySet()); } collectClassEntries(bundle, classEntries, "/"); for (Class entryClass : classEntries) { OSGiServiceProvider serviceProvider = (OSGiServiceProvider) entryClass.getAnnotation(OSGiServiceProvider.class); if (serviceProvider != null && serviceProvider.threadStart()) { new StartThread(entryClass, context).start(); } else { handleServiceInstances(entryClass, context); handleFieldInjections(entryClass, context); handleServiceRegistrations(entryClass, context); handleMethods(entryClass, context); } } }
/** * 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); }
@Override protected void tearDown() throws Exception { BundleContext context = HistoryServiceLick.bc; context.ungetService(this.historyServiceRef); this.history = null; this.historyService = null; this.historyServiceRef = null; }
@Override protected void setUp() throws Exception { BundleContext context = HistoryServiceLick.bc; historyServiceRef = context.getServiceReference(HistoryService.class.getName()); this.historyService = (HistoryService) context.getService(historyServiceRef); HistoryID testID = HistoryID.createFromRawID(new String[] {"test", "alltests"}); this.history = this.historyService.createHistory(testID, recordStructure); }
public static boolean matchesCurrentEnvironment(IMonitorModelBase model) { BundleContext context = MDECore.getDefault().getBundleContext(); Dictionary environment = getTargetEnvironment(); BundleDescription bundle = model.getBundleDescription(); String filterSpec = bundle != null ? bundle.getPlatformFilter() : null; try { return filterSpec == null || context.createFilter(filterSpec).match(environment); } catch (InvalidSyntaxException e) { return false; } }
/* * Launches against the agent */ public void testSimpleLauncher() throws Exception { Project project = workspace.getProject("p1"); Run bndrun = new Run(workspace, project.getBase(), project.getFile("one.bndrun")); bndrun.setProperty("-runpath", "biz.aQute.remote.launcher"); bndrun.setProperty("-runbundles", "bsn-1,bsn-2"); bndrun.setProperty("-runremote", "test"); final RemoteProjectLauncherPlugin pl = (RemoteProjectLauncherPlugin) bndrun.getProjectLauncher(); pl.prepare(); final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger exitCode = new AtomicInteger(-1); List<? extends RunSession> sessions = pl.getRunSessions(); assertEquals(1, sessions.size()); final RunSession session = sessions.get(0); Thread t = new Thread("test-launch") { public void run() { try { exitCode.set(session.launch()); } catch (Exception e) { e.printStackTrace(); } finally { latch.countDown(); } } }; t.start(); Thread.sleep(500); for (Bundle b : context.getBundles()) { System.out.println(b.getLocation()); } assertEquals(4, context.getBundles().length); String p1 = t1.getAbsolutePath(); System.out.println(p1); assertNotNull(context.getBundle(p1)); assertNotNull(context.getBundle(t2.getAbsolutePath())); pl.cancel(); latch.await(); assertEquals(-3, exitCode.get()); bndrun.close(); }
/** * The dependent service is available and the bundle will start. * * @param dependentService the UIService this activator is waiting. */ @Override public void start(Object dependentService) { if (logger.isDebugEnabled()) logger.debug("Update checker [STARTED]"); ConfigurationService cfg = getConfiguration(); if (OSUtils.IS_WINDOWS) { updateService = new Update(); bundleContext.registerService(UpdateService.class.getName(), updateService, null); // Register the "Check for Updates" menu item if // the "Check for Updates" property isn't disabled. if (!cfg.getBoolean(CHECK_FOR_UPDATES_MENU_DISABLED_PROP, false)) { // Register the "Check for Updates" menu item. CheckForUpdatesMenuItemComponent checkForUpdatesMenuItemComponent = new CheckForUpdatesMenuItemComponent(Container.CONTAINER_HELP_MENU); Hashtable<String, String> toolsMenuFilter = new Hashtable<String, String>(); toolsMenuFilter.put(Container.CONTAINER_ID, Container.CONTAINER_HELP_MENU.getID()); bundleContext.registerService( PluginComponent.class.getName(), checkForUpdatesMenuItemComponent, toolsMenuFilter); } // Check for software update upon startup if enabled. if (cfg.getBoolean(UPDATE_ENABLED, true)) updateService.checkForUpdates(false); } if (cfg.getBoolean(CHECK_FOR_UPDATES_DAILY_ENABLED_PROP, false)) { logger.info("Scheduled update checking enabled"); // Schedule a "check for updates" task that will run once a day int hoursToWait = calcHoursToWait(); Runnable updateRunnable = new Runnable() { public void run() { logger.debug("Performing scheduled update check"); getUpdateService().checkForUpdates(false); } }; mUpdateExecutor = Executors.newSingleThreadScheduledExecutor(); mUpdateExecutor.scheduleAtFixedRate( updateRunnable, hoursToWait, 24 * 60 * 60, TimeUnit.SECONDS); } if (logger.isDebugEnabled()) logger.debug("Update checker [REGISTERED]"); }
/** * Initializes and creates an account corresponding to the specified accountProperties and * registers the resulting ProtocolProvider in the <tt>context</tt> BundleContext parameter. * * @param accountProperties a set of protocol (or implementation) specific properties defining the * new account. * @return the AccountID of the newly created account */ protected AccountID loadAccount(Map accountProperties) { BundleContext context = SipActivator.getBundleContext(); if (context == null) throw new NullPointerException("The specified BundleContext was null"); String userIDStr = (String) accountProperties.get(USER_ID); if (userIDStr == null) throw new NullPointerException("The account properties contained no user id."); if (accountProperties == null) throw new NullPointerException("The specified property map was null"); String serverAddress = (String) accountProperties.get(SERVER_ADDRESS); if (serverAddress == null) throw new NullPointerException(serverAddress + " is not a valid ServerAddress"); if (!accountProperties.containsKey(PROTOCOL)) accountProperties.put(PROTOCOL, ProtocolNames.SIP); SipAccountID accountID = new SipAccountID(userIDStr, accountProperties, serverAddress); // get a reference to the configuration service and register whatever // properties we have in it. Hashtable properties = new Hashtable(); properties.put(PROTOCOL, ProtocolNames.SIP); properties.put(USER_ID, userIDStr); ProtocolProviderServiceSipImpl sipProtocolProvider = new ProtocolProviderServiceSipImpl(); try { sipProtocolProvider.initialize(userIDStr, accountID); // We store again the account in order to store all properties added // during the protocol provider initialization. this.storeAccount(SipActivator.getBundleContext(), accountID); } catch (OperationFailedException ex) { logger.error("Failed to initialize account", ex); throw new IllegalArgumentException("Failed to initialize account" + ex.getMessage()); } ServiceRegistration registration = context.registerService( ProtocolProviderService.class.getName(), sipProtocolProvider, properties); registeredAccounts.put(accountID, registration); return accountID; }
/** * Starts the configuration service * * @param bundleContext the <tt>BundleContext</tt> as provided by the OSGi framework. * @throws Exception if anything goes wrong */ public void start(BundleContext bundleContext) throws Exception { FileAccessService fas = ServiceUtils.getService(bundleContext, FileAccessService.class); if (fas != null) { File usePropFileConfig; try { usePropFileConfig = fas.getPrivatePersistentFile(".usepropfileconfig", FileCategory.PROFILE); } catch (Exception ise) { // There is somewhat of a chicken-and-egg dependency between // FileConfigurationServiceImpl and ConfigurationServiceImpl: // FileConfigurationServiceImpl throws IllegalStateException if // certain System properties are not set, // ConfigurationServiceImpl will make sure that these properties // are set but it will do that later. // A SecurityException is thrown when the destination // is not writable or we do not have access to that folder usePropFileConfig = null; } if (usePropFileConfig != null && usePropFileConfig.exists()) { logger.info("Using properties file configuration store."); this.cs = LibJitsi.getConfigurationService(); } } if (this.cs == null) { this.cs = new JdbcConfigService(fas); } bundleContext.registerService(ConfigurationService.class.getName(), this.cs, null); fixPermissions(this.cs); }
@Override protected void setUp() throws Exception { tmp = IO.getFile("generated/tmp"); tmp.mkdirs(); IO.copy(IO.getFile("testdata/ws"), tmp); workspace = Workspace.getWorkspace(tmp); workspace.refresh(); InfoRepository repo = workspace.getPlugin(InfoRepository.class); t1 = create("bsn-1", new Version(1, 0, 0)); t2 = create("bsn-2", new Version(1, 0, 0)); repo.put(new FileInputStream(t1), null); repo.put(new FileInputStream(t2), null); t1 = repo.get("bsn-1", new Version(1, 0, 0), null); t2 = repo.get("bsn-2", new Version(1, 0, 0), null); repo.put(new FileInputStream(IO.getFile("generated/biz.aQute.remote.launcher.jar")), null); workspace.getPlugins().add(repo); File storage = IO.getFile("generated/storage-1"); storage.mkdirs(); configuration = new HashMap<String, Object>(); configuration.put( Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); configuration.put(Constants.FRAMEWORK_STORAGE, storage.getAbsolutePath()); configuration.put( Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.framework.launch;version=1.2"); framework = new org.apache.felix.framework.FrameworkFactory().newFramework(configuration); framework.init(); framework.start(); context = framework.getBundleContext(); location = "reference:" + IO.getFile("generated/biz.aQute.remote.agent.jar").toURI().toString(); agent = context.installBundle(location); agent.start(); thread = new Thread() { @Override public void run() { try { Main.main( new String[] { "-s", "generated/storage", "-c", "generated/cache", "-p", "1090", "-et" }); } catch (Exception e) { e.printStackTrace(); } } }; thread.setDaemon(true); thread.start(); super.setUp(); }
public AuthServiceTracker(BundleContext context) throws InvalidSyntaxException { super(context, getAuthFilter(), null); // TODO: Filters are case sensitive, we should be too if (NoneAuthenticationService.AUTH_TYPE.equalsIgnoreCase(getAuthName())) { Dictionary<String, String> properties = new Hashtable<String, String>(); properties.put(ServerConstants.CONFIG_AUTH_NAME, getAuthName()); // TODO: shouldn't we always register the none-auth service? context.registerService( IAuthenticationService.class, new NoneAuthenticationService(), properties); } }
/** * Starts the Metacafe replacement source bundle * * @param context the <tt>BundleContext</tt> as provided from the OSGi framework * @throws Exception if anything goes wrong */ public void start(BundleContext context) throws Exception { Hashtable<String, String> hashtable = new Hashtable<String, String>(); hashtable.put( ReplacementService.SOURCE_NAME, ReplacementServiceMetacafeImpl.METACAFE_CONFIG_LABEL); metacafeSource = new ReplacementServiceMetacafeImpl(); metacafeServReg = context.registerService(ReplacementService.class.getName(), metacafeSource, hashtable); logger.info("Metacafe source implementation [STARTED]."); }
/** * Removes the specified account from the list of accounts that this provider factory is handling. * If the specified accountID is unknown to the ProtocolProviderFactory, the call has no effect * and false is returned. This method is persistent in nature and once called the account * corresponding to the specified ID will not be loaded during future runs of the project. * * @param accountID the ID of the account to remove. * @return true if an account with the specified ID existed and was removed and false otherwise. */ public boolean uninstallAccount(AccountID accountID) { // Unregister the protocol provider. ServiceReference serRef = getProviderForAccount(accountID); boolean wasAccountExisting = false; // If the protocol provider service is registered, first unregister the // service. if (serRef != null) { BundleContext bundleContext = getBundleContext(); ProtocolProviderService protocolProvider = (ProtocolProviderService) bundleContext.getService(serRef); try { protocolProvider.unregister(); } catch (OperationFailedException ex) { logger.error( "Failed to unregister protocol provider for account: " + accountID + " caused by: " + ex); } } ServiceRegistration registration; synchronized (registeredAccounts) { registration = registeredAccounts.remove(accountID); } // first remove the stored account so when PP is unregistered we can // distinguish between deleted or just disabled account wasAccountExisting = removeStoredAccount(accountID); if (registration != null) { // Kill the service. registration.unregister(); } return wasAccountExisting; }
/** * Returns the <tt>NotificationService</tt> obtained from the bundle context. * * @return The <tt>NotificationService</tt> obtained from the bundle context. */ public static NotificationService getNotificationService() { if (notificationService == null) { // Get the notification service implementation ServiceReference notifReference = bundleContext.getServiceReference(NotificationService.class.getName()); notificationService = (NotificationService) bundleContext.getService(notifReference); if (notificationService != null) { // Register a popup message for a device configuration changed // notification. notificationService.registerDefaultNotificationForEvent( DEVICE_CONFIGURATION_HAS_CHANGED, net.java.sip.communicator.service.notification.NotificationAction.ACTION_POPUP_MESSAGE, "Device onfiguration has changed", null); } } return notificationService; }
/** * Tracks and injects APSServiceTracker directly or as wrapped service instance using the tracker * to call the service depending on the field type. * * @param field The field to inject. * @param managedClass Used to lookup or create an instance of this class to inject into. * @param context The bundle context. */ protected void handleServiceInjections(Field field, Class managedClass, BundleContext context) { OSGiService service = field.getAnnotation(OSGiService.class); if (service != null) { String trackerKey = field.getType().getName() + service.additionalSearchCriteria(); APSServiceTracker tracker = this.trackers.get(trackerKey); if (tracker == null) { tracker = new APSServiceTracker<>( context, field.getType(), service.additionalSearchCriteria(), service.timeout()); this.trackers.put(trackerKey, tracker); } tracker.start(); List<Object> managedInstances = getManagedInstances(managedClass); for (Object managedInstance : managedInstances) { if (field.getType().equals(APSServiceTracker.class)) { injectObject(managedInstance, tracker, field); } else { injectObject(managedInstance, tracker.getWrappedService(), field); } } if (service.required() && this.supportsRequired) { Tuple4<APSServiceTracker, Class, Boolean, List<ServiceRegistration>> requiredService = new Tuple4<>( tracker, managedClass, false, (List<ServiceRegistration>) new LinkedList<ServiceRegistration>()); this.requiredServices.add(requiredService); } this.activatorLogger.info( "Injected tracked service '" + field.getType().getName() + (service.additionalSearchCriteria().length() > 0 ? " " + service.additionalSearchCriteria() : "") + "' " + "into '" + managedClass.getName() + "." + field.getName() + "' for bundle: " + context.getBundle().getSymbolicName() + " for " + managedInstances.size() + " instance(s)!"); } }
/** Returns the platform instance location. */ public Location getInstanceLocation() { if (instanceLocationTracker == null) { Filter filter; try { filter = bundleContext.createFilter(Location.INSTANCE_FILTER); } catch (InvalidSyntaxException e) { LogHelper.log(e); return null; } instanceLocationTracker = new ServiceTracker<Location, Location>(bundleContext, filter, null); instanceLocationTracker.open(); } return instanceLocationTracker.getService(); }
/** * Unloads the account corresponding to the given <tt>accountID</tt>. Unregisters the * corresponding protocol provider, but keeps the account in contrast to the uninstallAccount * method. * * @param accountID the account identifier * @return true if an account with the specified ID existed and was unloaded and false otherwise. */ public boolean unloadAccount(AccountID accountID) { // Unregister the protocol provider. ServiceReference serRef = getProviderForAccount(accountID); if (serRef == null) { return false; } BundleContext bundleContext = getBundleContext(); ProtocolProviderService protocolProvider = (ProtocolProviderService) bundleContext.getService(serRef); try { protocolProvider.unregister(); } catch (OperationFailedException ex) { logger.error( "Failed to unregister protocol provider for account : " + accountID + " caused by: " + ex); } ServiceRegistration registration; synchronized (registeredAccounts) { registration = registeredAccounts.remove(accountID); } if (registration == null) { return false; } // Kill the service. registration.unregister(); return true; }
public void testBasic() throws BundleException, InvalidSyntaxException, InterruptedException { // get the system region Region systemRegion = digraph.getRegion(0); // create a disconnected test region Region testRegion = digraph.createRegion(getName()); List<Bundle> bundles = new ArrayList<Bundle>(); // Install all test bundles Bundle pp1, cp2, sc1; bundles.add(pp1 = bundleInstaller.installBundle(PP1, testRegion)); // should be able to start pp1 because it depends on nothing pp1.start(); // do a sanity check that we have no services available in the isolated region assertNull("Found some services.", pp1.getBundleContext().getAllServiceReferences(null, null)); assertEquals("Found extra bundles in region", 1, pp1.getBundleContext().getBundles().length); pp1.stop(); bundles.add(bundleInstaller.installBundle(SP1, testRegion)); bundles.add(bundleInstaller.installBundle(CP1, testRegion)); bundles.add(bundleInstaller.installBundle(PP2, testRegion)); bundles.add(bundleInstaller.installBundle(SP2, testRegion)); bundles.add(cp2 = bundleInstaller.installBundle(CP2, testRegion)); bundles.add(bundleInstaller.installBundle(PC1, testRegion)); bundles.add(bundleInstaller.installBundle(BC1, testRegion)); bundles.add(sc1 = bundleInstaller.installBundle(SC1, testRegion)); bundles.add(bundleInstaller.installBundle(CC1, testRegion)); // Import the system bundle from the systemRegion digraph.connect(testRegion, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_BUNDLE_NAMESPACE, "(id=0)").build(), systemRegion); // must import Boolean services into systemRegion to test digraph.connect(systemRegion, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(objectClass=java.lang.Boolean)").build(), testRegion); bundleInstaller.resolveBundles(bundles.toArray(new Bundle[bundles.size()])); for (Bundle bundle : bundles) { assertEquals("Bundle did not resolve: " + bundle.getSymbolicName(), Bundle.RESOLVED, bundle.getState()); bundle.start(); } BundleContext context = getContext(); ServiceTracker<Boolean, Boolean> cp2Tracker = new ServiceTracker<Boolean, Boolean>(context, context.createFilter("(&(objectClass=java.lang.Boolean)(bundle.id=" + cp2.getBundleId() + "))"), null); ServiceTracker<Boolean, Boolean> sc1Tracker = new ServiceTracker<Boolean, Boolean>(context, context.createFilter("(&(objectClass=java.lang.Boolean)(bundle.id=" + sc1.getBundleId() + "))"), null); cp2Tracker.open(); sc1Tracker.open(); assertNotNull("The cp2 bundle never found the service.", cp2Tracker.waitForService(2000)); assertNotNull("The sc1 bundle never found the service.", sc1Tracker.waitForService(2000)); cp2Tracker.close(); sc1Tracker.close(); }
/** * Handles injections of APSLogger, BundleContext, or other class types with default constructor. * * @param field The field to inject into. * @param managedClass Used to lookup or create an instance of this class to inject into. * @param context The bundle context. */ protected void handleInstanceInjections(Field field, Class managedClass, BundleContext context) { Managed managed = field.getAnnotation(Managed.class); if (managed != null) { String namedInstanceKey = managed.name() + field.getType().getName(); Object namedInstance = this.namedInstances.get(namedInstanceKey); if (namedInstance == null) { if (field.getType().equals(APSLogger.class)) { namedInstance = new APSLogger(System.out); if (managed.loggingFor().length() > 0) { ((APSLogger) namedInstance).setLoggingFor(managed.loggingFor()); } ((APSLogger) namedInstance).start(context); } else if (field.getType().equals(BundleContext.class)) { namedInstance = context; } else { namedInstance = getManagedInstance(field.getType()); } this.namedInstances.put(namedInstanceKey, namedInstance); } else { this.activatorLogger.info( "Got named instance for key '" + namedInstanceKey + "': " + namedInstance.getClass().getName()); } List<Object> managedInstances = getManagedInstances(managedClass); for (Object managedInstance : managedInstances) { injectObject(managedInstance, namedInstance, field); } this.activatorLogger.info( "Injected '" + namedInstance.getClass().getName() + "' instance for name '" + managed.name() + "' " + "into '" + managedClass.getName() + "." + field.getName() + "' for bundle: " + context.getBundle().getSymbolicName() + "!"); } }
/** * Initializes and registers all tests that we'll run as a part of this slick. * * @param context a currently valid bundle context. */ public void start(BundleContext context) { setName("JabberProtocolProviderSlick"); Hashtable<String, String> properties = new Hashtable<String, String>(); properties.put("service.pid", getName()); JabberSlickFixture.bc = context; // verify whether the user wants to avoid online testing String offlineMode = System.getProperty(DISABLE_ONLINE_TESTS_PROPERTY_NAME, null); if (offlineMode != null && offlineMode.equalsIgnoreCase("true")) JabberSlickFixture.onlineTestingDisabled = true; addTestSuite(TestAccountInstallation.class); addTestSuite(TestProtocolProviderServiceJabberImpl.class); addTest(TestOperationSetPresence.suite()); // the following should only be run when we want online testing. if (!JabberSlickFixture.onlineTestingDisabled) { addTest(TestOperationSetPersistentPresence.suite()); addTest(TestOperationSetBasicInstantMessaging.suite()); addTest(TestOperationSetInstantMessageTransformJabberImpl.suite()); addTest(TestOperationSetTypingNotifications.suite()); // tests currently fails due to jingle lib bugs. // will be activated as soon as bugs get fixed // addTestSuite(TestOperationSetBasicTelephonyJabberImpl.class); /** @todo UNCOMMENT */ // addTest(TestOperationSetMultiUserChat.suite()); addTest(TestOperationSetMultiUserChat2.suite()); addTestSuite(TestOperationSetFileTransferImpl.class); } addTest(TestAccountUninstallation.suite()); addTestSuite(TestAccountUninstallationPersistence.class); context.registerService(getClass().getName(), this, properties); }
/** implements BundleActivator.start() */ public void start(BundleContext bc) throws Exception { logger.info("starting popup message test "); bundleContext = bc; setName("PopupMessageHandlerSLick"); Hashtable<String, String> properties = new Hashtable<String, String>(); properties.put("service.pid", getName()); // we maybe are running on machine without WM and systray // (test server machine), skip tests if (ServiceUtils.getService(bc, SystrayService.class) != null) { addTest(TestPopupMessageHandler.suite()); } bundleContext.registerService(getClass().getName(), this, properties); }
/** * Creates a protocol provider for the given <tt>accountID</tt> and registers it in the bundle * context. This method has a persistent effect. Once created the resulting account will remain * installed until removed through the uninstallAccount method. * * @param accountID the account identifier * @return <tt>true</tt> if the account with the given <tt>accountID</tt> is successfully loaded, * otherwise returns <tt>false</tt> */ public boolean loadAccount(AccountID accountID) { // Need to obtain the original user id property, instead of calling // accountID.getUserID(), because this method could return a modified // version of the user id property. String userID = accountID.getAccountPropertyString(ProtocolProviderFactory.USER_ID); ProtocolProviderService service = createService(userID, accountID); Dictionary<String, String> properties = new Hashtable<String, String>(); properties.put(PROTOCOL, protocolName); properties.put(USER_ID, userID); ServiceRegistration serviceRegistration = bundleContext.registerService(ProtocolProviderService.class.getName(), service, properties); if (serviceRegistration == null) return false; else { synchronized (registeredAccounts) { registeredAccounts.put(accountID, serviceRegistration); } return true; } }
void addInitFrameworkListeners() { BundleContext context = createBundleContext(false); for (FrameworkListener initListener : initListeners) { context.addFrameworkListener(initListener); } }
private void doCyclicRegions(int numLevels) throws BundleException, InvalidSyntaxException, InterruptedException { String regionName1 = getName() + "_1"; String regionName2 = getName() + "_2"; // get the system region Region systemRegion = digraph.getRegion(0); // create two regions to hold the bundles Region testRegion1 = digraph.createRegion(regionName1); Region testRegion2 = digraph.createRegion(regionName2); // connect to the system bundle testRegion1.connectRegion(systemRegion, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_BUNDLE_NAMESPACE, "(id=0)").build()); testRegion2.connectRegion(systemRegion, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_BUNDLE_NAMESPACE, "(id=0)").build()); // must import Boolean services into systemRegion to test systemRegion.connectRegion(testRegion1, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(objectClass=java.lang.Boolean)").build()); systemRegion.connectRegion(testRegion2, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(objectClass=java.lang.Boolean)").build()); Map<String, Bundle> bundles = new HashMap<String, Bundle>(); // add bundles to region1 bundles.put(PP1, bundleInstaller.installBundle(PP1, testRegion1)); bundles.put(SP2, bundleInstaller.installBundle(SP2, testRegion1)); bundles.put(CP2, bundleInstaller.installBundle(CP2, testRegion1)); bundles.put(PC1, bundleInstaller.installBundle(PC1, testRegion1)); bundles.put(BC1, bundleInstaller.installBundle(BC1, testRegion1)); // add bundles to region2 bundles.put(SP1, bundleInstaller.installBundle(SP1, testRegion2)); bundles.put(CP1, bundleInstaller.installBundle(CP1, testRegion2)); bundles.put(PP2, bundleInstaller.installBundle(PP2, testRegion2)); bundles.put(SC1, bundleInstaller.installBundle(SC1, testRegion2)); bundles.put(CC1, bundleInstaller.installBundle(CC1, testRegion2)); RegionFilterBuilder testRegionFilter1 = digraph.createRegionFilterBuilder(); // SP2 -> PP2 testRegionFilter1.allow(RegionFilter.VISIBLE_PACKAGE_NAMESPACE, "(" + RegionFilter.VISIBLE_PACKAGE_NAMESPACE + "=pkg2.*)"); // CP2 -> SP1 testRegionFilter1.allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(" + Constants.OBJECTCLASS + "=pkg1.*)"); // PC1 -> PP2 // this is not needed because we already import pkg2.* above //testRegionFilter1.allow(RegionFilter.VISIBLE_PACKAGE_NAMESPACE, "(" + RegionFilter.VISIBLE_PACKAGE_NAMESPACE + "=pkg2.*)"); // BC1 -> PP2 testRegionFilter1.allow(RegionFilter.VISIBLE_REQUIRE_NAMESPACE, "(" + RegionFilter.VISIBLE_REQUIRE_NAMESPACE + "=" + PP2 + ")"); RegionFilterBuilder testRegionFilter2 = digraph.createRegionFilterBuilder(); //SP1 -> PP1 testRegionFilter2.allow(RegionFilter.VISIBLE_PACKAGE_NAMESPACE, "(" + RegionFilter.VISIBLE_PACKAGE_NAMESPACE + "=pkg1.*)"); //SC1 -> SP2 testRegionFilter2.allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(" + Constants.OBJECTCLASS + "=pkg2.*)"); //CC1 -> CP2 testRegionFilter2.allow(CP2, "(name=" + CP2 + ")"); Region r1, r2 = null; for (int i = 0; i <= numLevels; i++) { r1 = (i > 0) ? r2 : testRegion1; r2 = (i < numLevels) ? digraph.createRegion(getName() + "_level_" + i) : testRegion2; r1.connectRegion(r2, testRegionFilter1.build()); r2.connectRegion(r1, testRegionFilter2.build()); } bundleInstaller.resolveBundles(bundles.values().toArray(new Bundle[bundles.size()])); for (Bundle bundle : bundles.values()) { assertEquals("Bundle did not resolve: " + bundle.getSymbolicName(), Bundle.RESOLVED, bundle.getState()); bundle.start(); } BundleContext context = getContext(); ServiceTracker<Boolean, Boolean> cp2Tracker = new ServiceTracker<Boolean, Boolean>(context, context.createFilter("(&(objectClass=java.lang.Boolean)(bundle.id=" + bundles.get(CP2).getBundleId() + "))"), null); ServiceTracker<Boolean, Boolean> sc1Tracker = new ServiceTracker<Boolean, Boolean>(context, context.createFilter("(&(objectClass=java.lang.Boolean)(bundle.id=" + bundles.get(SC1).getBundleId() + "))"), null); cp2Tracker.open(); sc1Tracker.open(); assertNotNull("The cp2 bundle never found the service.", cp2Tracker.waitForService(2000)); assertNotNull("The sc1 bundle never found the service.", sc1Tracker.waitForService(2000)); cp2Tracker.close(); sc1Tracker.close(); }
public void testSingleBundleRegions() throws BundleException, InvalidSyntaxException, InterruptedException { // get the system region Region systemRegion = digraph.getRegion(0); Map<String, Bundle> bundles = new HashMap<String, Bundle>(); // create a disconnected test region for each test bundle for (String location : ALL) { Region testRegion = digraph.createRegion(location); bundles.put(location, bundleInstaller.installBundle(location, testRegion)); // Import the system bundle from the systemRegion digraph.connect(testRegion, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_BUNDLE_NAMESPACE, "(id=0)").build(), systemRegion); // must import Boolean services into systemRegion to test digraph.connect(systemRegion, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(objectClass=java.lang.Boolean)").build(), testRegion); } bundleInstaller.resolveBundles(bundles.values().toArray(new Bundle[bundles.size()])); assertEquals(PP1, Bundle.RESOLVED, bundles.get(PP1).getState()); assertEquals(SP1, Bundle.INSTALLED, bundles.get(SP1).getState()); assertEquals(CP1, Bundle.RESOLVED, bundles.get(CP1).getState()); assertEquals(PP2, Bundle.INSTALLED, bundles.get(PP2).getState()); assertEquals(SP2, Bundle.INSTALLED, bundles.get(SP2).getState()); assertEquals(CP2, Bundle.INSTALLED, bundles.get(CP2).getState()); assertEquals(BC1, Bundle.INSTALLED, bundles.get(BC1).getState()); assertEquals(SC1, Bundle.INSTALLED, bundles.get(SC1).getState()); assertEquals(CC1, Bundle.INSTALLED, bundles.get(CC1).getState()); // now make the necessary connections // SP1 digraph.connect(digraph.getRegion(SP1), digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_PACKAGE_NAMESPACE, "(" + RegionFilter.VISIBLE_PACKAGE_NAMESPACE + "=pkg1.*)").build(), digraph.getRegion(PP1)); // PP2 digraph.connect(digraph.getRegion(PP2), digraph.createRegionFilterBuilder().allow(CP1, "(name=" + CP1 + ")").build(), digraph.getRegion(CP1)); // SP2 digraph.connect(digraph.getRegion(SP2), digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_PACKAGE_NAMESPACE, "(" + RegionFilter.VISIBLE_PACKAGE_NAMESPACE + "=pkg2.*)").build(), digraph.getRegion(PP2)); // CP2 digraph.connect(digraph.getRegion(CP2), digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_PACKAGE_NAMESPACE, "(" + RegionFilter.VISIBLE_PACKAGE_NAMESPACE + "=pkg1.*)").build(), digraph.getRegion(PP1)); digraph.connect(digraph.getRegion(CP2), digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(" + Constants.OBJECTCLASS + "=pkg1.*)").build(), digraph.getRegion(SP1)); // PC1 digraph.connect(digraph.getRegion(PC1), digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_PACKAGE_NAMESPACE, "(" + RegionFilter.VISIBLE_PACKAGE_NAMESPACE + "=pkg2.*)").build(), digraph.getRegion(PP2)); // BC1 digraph.connect(digraph.getRegion(BC1), digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_REQUIRE_NAMESPACE, "(" + RegionFilter.VISIBLE_REQUIRE_NAMESPACE + "=" + PP2 + ")").build(), digraph.getRegion(PP2)); // SC1 digraph.connect(digraph.getRegion(SC1), digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_PACKAGE_NAMESPACE, "(" + RegionFilter.VISIBLE_PACKAGE_NAMESPACE + "=pkg2.*)").build(), digraph.getRegion(PP2)); digraph.connect(digraph.getRegion(SC1), digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(" + Constants.OBJECTCLASS + "=pkg2.*)").build(), digraph.getRegion(SP2)); // CC1 digraph.connect(digraph.getRegion(CC1), digraph.createRegionFilterBuilder().allow(CP2, "(name=" + CP2 + ")").build(), digraph.getRegion(CP2)); bundleInstaller.resolveBundles(bundles.values().toArray(new Bundle[bundles.size()])); for (Bundle bundle : bundles.values()) { assertEquals("Bundle did not resolve: " + bundle.getSymbolicName(), Bundle.RESOLVED, bundle.getState()); bundle.start(); } BundleContext context = getContext(); ServiceTracker<Boolean, Boolean> cp2Tracker = new ServiceTracker<Boolean, Boolean>(context, context.createFilter("(&(objectClass=java.lang.Boolean)(bundle.id=" + bundles.get(CP2).getBundleId() + "))"), null); ServiceTracker<Boolean, Boolean> sc1Tracker = new ServiceTracker<Boolean, Boolean>(context, context.createFilter("(&(objectClass=java.lang.Boolean)(bundle.id=" + bundles.get(SC1).getBundleId() + "))"), null); cp2Tracker.open(); sc1Tracker.open(); assertNotNull("The cp2 bundle never found the service.", cp2Tracker.waitForService(2000)); assertNotNull("The sc1 bundle never found the service.", sc1Tracker.waitForService(2000)); cp2Tracker.close(); sc1Tracker.close(); }
/** * Handles methods annotated with @APSBundleStartup. * * @param method The annotated method to call. * @param managedClass Used to lookup or create an instance of this class containing the method to * call. * @param context The bundle context. */ protected void handleStartupMethods( final Method method, final Class managedClass, final BundleContext context) { BundleStart bundleStart = method.getAnnotation(BundleStart.class); if (bundleStart != null) { if (method.getParameterTypes().length > 0) { throw new APSActivatorException( "An @BundleStart method must take no parameters! [" + managedClass.getName() + "." + method.getName() + "(?)]"); } if (bundleStart.thread()) { new Thread( new Runnable() { @Override public void run() { try { Object managedInstance = null; if (!Modifier.isStatic(method.getModifiers())) { managedInstance = getManagedInstance(managedClass); } method.invoke(managedInstance, null); APSActivator.this.activatorLogger.info( "Called bundle start method '" + managedClass.getName() + "." + method.getName() + "()' for bundle: " + context.getBundle().getSymbolicName() + "!"); } catch (IllegalAccessException iae) { APSActivator.this.activatorLogger.error( "Failed to call start method! [" + managedClass.getName() + "." + method.getName() + "()]", iae); } catch (InvocationTargetException ite) { APSActivator.this.activatorLogger.error( "Failed to call start method! [" + managedClass.getName() + "." + method.getName() + "()]", ite.getCause()); } catch (Exception e) { APSActivator.this.activatorLogger.error( "Failed to call start method! [" + managedClass.getName() + "." + method.getName() + "()]", e); } } }) .start(); } else { try { Object managedInstance = null; if (!Modifier.isStatic(method.getModifiers())) { managedInstance = getManagedInstance(managedClass); } method.invoke(managedInstance, null); this.activatorLogger.info( "Called bundle start method '" + managedClass.getName() + "." + method.getName() + "()' for bundle: " + context.getBundle().getSymbolicName() + "!"); } catch (IllegalAccessException iae) { throw new APSActivatorException( "Failed to call start method! [" + managedClass.getName() + "." + method.getName() + "()]", iae); } catch (InvocationTargetException ite) { throw new APSActivatorException( "Failed to call start method! [" + managedClass.getName() + "." + method.getName() + "()]", ite.getCause()); } } } }