use of org.osgi.util.tracker.ServiceTrackerCustomizer in project jackrabbit-oak by apache.
the class OsgiWhiteboard method track.
/**
* Returns a tracker for services of the given type. The returned tracker
* is optimized for frequent {@link Tracker#getServices()} calls through
* the use of a pre-compiled list of services that's atomically updated
* whenever services are added, modified or removed.
*/
@Override
public <T> Tracker<T> track(final Class<T> type) {
checkNotNull(type);
final AtomicReference<List<T>> list = new AtomicReference<List<T>>(Collections.<T>emptyList());
final ServiceTrackerCustomizer customizer = new ServiceTrackerCustomizer() {
private final Map<ServiceReference, T> services = newHashMap();
@Override
@SuppressWarnings("unchecked")
public synchronized Object addingService(ServiceReference reference) {
Object service = context.getService(reference);
if (type.isInstance(service)) {
services.put(reference, (T) service);
list.set(getServiceList(services));
return service;
} else {
context.ungetService(reference);
return null;
}
}
@Override
@SuppressWarnings("unchecked")
public synchronized void modifiedService(ServiceReference reference, Object service) {
// TODO: Figure out if the old reference instance
// would automatically reflect the updated properties.
// For now we play it safe by replacing the old key
// with the new reference instance passed as argument.
services.remove(reference);
services.put(reference, (T) service);
list.set(getServiceList(services));
}
@Override
public synchronized void removedService(ServiceReference reference, Object service) {
services.remove(reference);
list.set(getServiceList(services));
// TODO: Note that the service might still be in use
// by some client that called getServices() before
// this method was invoked.
context.ungetService(reference);
}
};
final ServiceTracker tracker = new ServiceTracker(context, type.getName(), customizer);
tracker.open();
return new Tracker<T>() {
@Override
public List<T> getServices() {
return list.get();
}
@Override
public void stop() {
tracker.close();
}
};
}
use of org.osgi.util.tracker.ServiceTrackerCustomizer in project karaf by apache.
the class Activator method start.
@Override
public void start(final BundleContext context) throws Exception {
ProxyLoginModule.init(context.getBundle(0).getBundleContext());
final OsgiKeystoreManager keystoreManager = new OsgiKeystoreManager();
keystoreInstanceServiceTracker = new ServiceTracker<>(context, KeystoreInstance.class, new ServiceTrackerCustomizer<KeystoreInstance, KeystoreInstance>() {
@Override
public KeystoreInstance addingService(ServiceReference<KeystoreInstance> reference) {
KeystoreInstance service = context.getService(reference);
keystoreManager.register(service, null);
return service;
}
@Override
public void modifiedService(ServiceReference<KeystoreInstance> reference, KeystoreInstance service) {
}
@Override
public void removedService(ServiceReference<KeystoreInstance> reference, KeystoreInstance service) {
keystoreManager.unregister(service, null);
context.ungetService(reference);
}
});
keystoreInstanceServiceTracker.open();
osgiConfiguration = new OsgiConfiguration();
osgiConfiguration.init();
jaasRealmServiceTracker = new ServiceTracker<>(context, JaasRealm.class, new ServiceTrackerCustomizer<JaasRealm, JaasRealm>() {
@Override
public JaasRealm addingService(ServiceReference<JaasRealm> reference) {
JaasRealm service = context.getService(reference);
osgiConfiguration.register(service, null);
return service;
}
@Override
public void modifiedService(ServiceReference<JaasRealm> reference, JaasRealm service) {
}
@Override
public void removedService(ServiceReference<JaasRealm> reference, JaasRealm service) {
osgiConfiguration.unregister(service, null);
}
});
jaasRealmServiceTracker.open();
registration = context.registerService(KeystoreManager.class, keystoreManager, null);
}
use of org.osgi.util.tracker.ServiceTrackerCustomizer in project karaf by apache.
the class Activator method doStart.
protected void doStart() throws Exception {
// Verify dependencies
ConfigurationAdmin configurationAdmin = getTrackedService(ConfigurationAdmin.class);
KeystoreManager keystoreManager = getTrackedService(KeystoreManager.class);
if (configurationAdmin == null || keystoreManager == null) {
return;
}
String rmiRegistryHost = getString("rmiRegistryHost", "");
int rmiRegistryPort = getInt("rmiRegistryPort", 1099);
String rmiServerHost = getString("rmiServerHost", "0.0.0.0");
int rmiServerPort = getInt("rmiServerPort", 44444);
String jmxRealm = getString("jmxRealm", "karaf");
String serviceUrl = getString("serviceUrl", "service:jmx:rmi://" + rmiServerHost + ":" + rmiServerPort + "/jndi/rmi://" + rmiRegistryHost + ":" + rmiRegistryPort + "/karaf-" + System.getProperty("karaf.name"));
boolean daemon = getBoolean("daemon", true);
boolean threaded = getBoolean("threaded", true);
ObjectName objectName = new ObjectName(getString("objectName", "connector:name=rmi"));
long keyStoreAvailabilityTimeout = getLong("keyStoreAvailabilityTimeout", 5000);
String authenticatorType = getString("authenticatorType", "password");
final boolean secured = getBoolean("secured", false);
String secureAlgorithm = getString("secureAlgorithm", "default");
String secureProtocol = getString("secureProtocol", "TLS");
String keyStore = getString("keyStore", "karaf.ks");
String keyAlias = getString("keyAlias", "karaf");
String trustStore = getString("trustStore", "karaf.ts");
boolean createRmiRegistry = getBoolean("createRmiRegistry", true);
boolean locateRmiRegistry = getBoolean("locateRmiRegistry", true);
boolean locateExistingMBeanServerIfPossible = getBoolean("locateExistingMBeanServerIfPossible", true);
KarafMBeanServerGuard guard = new KarafMBeanServerGuard();
guard.setConfigAdmin(configurationAdmin);
rmiRegistryFactory = new RmiRegistryFactory();
rmiRegistryFactory.setCreate(createRmiRegistry);
rmiRegistryFactory.setLocate(locateRmiRegistry);
rmiRegistryFactory.setHost(rmiRegistryHost);
rmiRegistryFactory.setPort(rmiRegistryPort);
rmiRegistryFactory.setBundleContext(bundleContext);
rmiRegistryFactory.init();
mbeanServerFactory = new MBeanServerFactory();
mbeanServerFactory.setLocateExistingServerIfPossible(locateExistingMBeanServerIfPossible);
mbeanServerFactory.init();
MBeanServer mbeanServer = mbeanServerFactory.getServer();
JaasAuthenticator jaasAuthenticator = new JaasAuthenticator();
jaasAuthenticator.setRealm(jmxRealm);
connectorServerFactory = new ConnectorServerFactory();
connectorServerFactory.setServer(mbeanServer);
connectorServerFactory.setServiceUrl(serviceUrl);
connectorServerFactory.setGuard(guard);
connectorServerFactory.setRmiServerHost(rmiServerHost);
connectorServerFactory.setDaemon(daemon);
connectorServerFactory.setThreaded(threaded);
connectorServerFactory.setObjectName(objectName);
Map<String, Object> environment = new HashMap<>();
environment.put("jmx.remote.authenticator", jaasAuthenticator);
try {
connectorServerFactory.setEnvironment(environment);
connectorServerFactory.setKeyStoreAvailabilityTimeout(keyStoreAvailabilityTimeout);
connectorServerFactory.setAuthenticatorType(authenticatorType);
connectorServerFactory.setSecured(secured);
connectorServerFactory.setAlgorithm(secureAlgorithm);
connectorServerFactory.setSecureProtocol(secureProtocol);
connectorServerFactory.setKeyStore(keyStore);
connectorServerFactory.setKeyAlias(keyAlias);
connectorServerFactory.setTrustStore(trustStore);
connectorServerFactory.setKeystoreManager(keystoreManager);
connectorServerFactory.init();
} catch (Exception e) {
LOG.error("Can't init JMXConnectorServer: " + e.getMessage());
}
JMXSecurityMBeanImpl securityMBean = new JMXSecurityMBeanImpl();
securityMBean.setMBeanServer(mbeanServer);
securityMBean.setGuard(guard);
registerMBean(securityMBean, "type=security,area=jmx");
register(MBeanServer.class, mbeanServer);
keystoreInstanceServiceTracker = new ServiceTracker<>(bundleContext, KeystoreInstance.class, new ServiceTrackerCustomizer<KeystoreInstance, KeystoreInstance>() {
@Override
public KeystoreInstance addingService(ServiceReference<KeystoreInstance> reference) {
if (secured) {
try {
connectorServerFactory.init();
} catch (Exception e) {
LOG.error("Can't re-init JMXConnectorServer with SSL enabled when register a keystore:" + e.getMessage());
}
}
return null;
}
@Override
public void modifiedService(ServiceReference<KeystoreInstance> reference, KeystoreInstance service) {
}
@Override
public void removedService(ServiceReference<KeystoreInstance> reference, KeystoreInstance service) {
if (secured) {
try {
connectorServerFactory.init();
} catch (Exception e) {
LOG.error("Can't re-init JMXConnectorServer with SSL enabled when unregister a keystore: " + e.getMessage());
}
}
}
});
keystoreInstanceServiceTracker.open();
}
use of org.osgi.util.tracker.ServiceTrackerCustomizer in project karaf by apache.
the class Activator method start.
@Override
public void start(final BundleContext context) throws Exception {
threadIO = new ThreadIOImpl();
threadIO.start();
sessionFactory = new SecuredSessionFactoryImpl(context, threadIO);
sessionFactory.getCommandProcessor().addConverter(new Converters(context));
sessionFactory.getCommandProcessor().addConstant(".context", context.getBundle(0).getBundleContext());
final CopyOnWriteArraySet<CommandLoggingFilter> listeners = new CopyOnWriteArraySet<>();
filterTracker = new ServiceTracker<>(context, CommandLoggingFilter.class, new ServiceTrackerCustomizer<CommandLoggingFilter, CommandLoggingFilter>() {
@Override
public CommandLoggingFilter addingService(ServiceReference<CommandLoggingFilter> reference) {
CommandLoggingFilter service = context.getService(reference);
listeners.add(service);
return service;
}
@Override
public void modifiedService(ServiceReference<CommandLoggingFilter> reference, CommandLoggingFilter service) {
}
@Override
public void removedService(ServiceReference<CommandLoggingFilter> reference, CommandLoggingFilter service) {
listeners.remove(service);
context.ungetService(reference);
}
});
filterTracker.open();
LoggingCommandSessionListener loggingCommandSessionListener = new LoggingCommandSessionListener();
loggingCommandSessionListener.setFilters(listeners);
sessionFactory.getCommandProcessor().addListener(loggingCommandSessionListener);
try {
EventAdminListener listener = new EventAdminListener(context);
sessionFactory.getCommandProcessor().addListener(listener);
eventAdminListener = listener;
} catch (NoClassDefFoundError error) {
// Ignore the listener if EventAdmin package isn't present
}
sessionFactory.register(new ManagerImpl(sessionFactory, sessionFactory));
sessionFactoryRegistration = context.registerService(SessionFactory.class, sessionFactory, null);
actionExtender = new CommandExtender(sessionFactory);
actionExtender.start(context);
commandTracker = new CommandTracker(sessionFactory, context);
commandTracker.open();
if (Boolean.parseBoolean(context.getProperty(START_CONSOLE))) {
localConsoleManager = new LocalConsoleManager(context, sessionFactory);
localConsoleManager.start();
} else {
LOGGER.info("Not starting local console. To activate set " + START_CONSOLE + "=true");
}
}
use of org.osgi.util.tracker.ServiceTrackerCustomizer in project sling by apache.
the class AbstractSlingRepositoryManager method start.
/**
* This method actually starts the backing repository instannce and
* registeres the repository service.
* <p>
* Multiple subsequent calls to this method without calling {@link #stop()}
* first have no effect.
*
* @param bundleContext The {@code BundleContext} to register the repository
* service (and optionally more services required to operate the
* repository)
* @param config The configuration to apply to this instance.
*/
protected final void start(final BundleContext bundleContext, final Config config) {
// already setup ?
if (this.bundleContext != null) {
log.debug("start: Repository already started and registered");
return;
}
this.bundleContext = bundleContext;
this.defaultWorkspace = config.defaultWorkspace;
this.disableLoginAdministrative = config.disableLoginAdministrative;
this.repoInitializerTracker = new ServiceTracker<SlingRepositoryInitializer, SlingRepositoryInitializerInfo>(bundleContext, SlingRepositoryInitializer.class, new ServiceTrackerCustomizer<SlingRepositoryInitializer, SlingRepositoryInitializerInfo>() {
@Override
public SlingRepositoryInitializerInfo addingService(final ServiceReference<SlingRepositoryInitializer> reference) {
final SlingRepositoryInitializer service = bundleContext.getService(reference);
if (service != null) {
final SlingRepositoryInitializerInfo info = new SlingRepositoryInitializerInfo(service, reference);
synchronized (repoInitLock) {
if (masterSlingRepository != null) {
log.debug("Executing {}", info.initializer);
try {
info.initializer.processRepository(masterSlingRepository);
} catch (final Exception e) {
log.error("Exception in a SlingRepositoryInitializer: " + info.initializer, e);
}
}
}
return info;
}
return null;
}
@Override
public void modifiedService(final ServiceReference<SlingRepositoryInitializer> reference, final SlingRepositoryInitializerInfo service) {
// nothing to do
}
@Override
public void removedService(final ServiceReference<SlingRepositoryInitializer> reference, final SlingRepositoryInitializerInfo service) {
bundleContext.ungetService(reference);
}
});
this.repoInitializerTracker.open();
// If allowLoginAdministrativeForBundle is overridden we assume we don't need
// a LoginAdminWhitelist service - that's the case if the derived class
// implements its own strategy and the LoginAdminWhitelist interface is
// not exported by this bundle anyway, so cannot be implemented differently.
boolean enableWhitelist = !isAllowLoginAdministrativeForBundleOverridden();
final CountDownLatch waitForWhitelist = new CountDownLatch(enableWhitelist ? 1 : 0);
if (enableWhitelist) {
whitelistTracker = new ServiceTracker<LoginAdminWhitelist, LoginAdminWhitelist>(bundleContext, LoginAdminWhitelist.class, null) {
@Override
public LoginAdminWhitelist addingService(final ServiceReference<LoginAdminWhitelist> reference) {
try {
return super.addingService(reference);
} finally {
waitForWhitelist.countDown();
}
}
};
whitelistTracker.open();
}
// start repository asynchronously to allow LoginAdminWhitelist to become available
// NOTE: making this conditional allows tests to register a mock whitelist before
// activating the RepositoryManager, so they don't need to deal with async startup
new Thread("Apache Sling Repository Startup Thread") {
@Override
public void run() {
try {
waitForWhitelist.await();
initializeAndRegisterRepositoryService();
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting for LoginAdminWhitelist", e);
}
}
}.start();
}
Aggregations