下面列出了org.osgi.framework.ServiceListener#org.osgi.service.component.ComponentContext 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Activate
protected void activate(ComponentContext ctxt) {
try {
APIKeyMgtDataHolder.initData();
log.debug("Key Manager User Operation Listener is enabled.");
// Register subscription datastore related service
serviceRegistration = ctxt.getBundleContext().registerService(
Axis2ConfigurationContextObserver.class.getName(), new ServerStartupListener(), null);
serviceRegistration = ctxt.getBundleContext().registerService(
ServerStartupObserver.class.getName(), new ServerStartupListener(), null);
// Register KeyManagerDataService
serviceRegistration = ctxt.getBundleContext().registerService(KeyManagerDataService.class.getName(),
new KeyManagerDataServiceImpl(), null);
if (log.isDebugEnabled()) {
log.debug("Identity API Key Mgt Bundle is started.");
}
} catch (Exception e) {
log.error("Failed to initialize key management service.", e);
}
}
protected void activate(ComponentContext ctxt) {
try {
ConfigurationContext mainConfigCtx = configContextService.getServerConfigContext();
AxisConfiguration mainAxisConfig = mainConfigCtx.getAxisConfiguration();
BundleContext bundleCtx = ctxt.getBundleContext();
String enablePoxSecurity = ServerConfiguration.getInstance()
.getFirstProperty("EnablePoxSecurity");
if (enablePoxSecurity == null || "true".equals(enablePoxSecurity)) {
mainAxisConfig.engageModule(POX_SECURITY_MODULE);
} else {
log.info("POX Security Disabled");
}
bundleCtx.registerService(SecurityConfigAdmin.class.getName(),
new SecurityConfigAdmin(mainAxisConfig,
registryService.getConfigSystemRegistry(),
null),
null);
bundleCtx.registerService(Axis2ConfigurationContextObserver.class.getName(),
new SecurityAxis2ConfigurationContextObserver(),
null);
log.debug("Security Mgt bundle is activated");
} catch (Throwable e) {
log.error("Failed to activate SecurityMgtServiceComponent", e);
}
}
protected synchronized void activate(ComponentContext ctx) {
this.ctx = ctx;
if (log.isDebugEnabled()) {
log.debug("Data Source Capp deployer activated");
}
if (log.isDebugEnabled()) {
log.debug("Data Source Capp deployer activated");
}
try {
//register data source deployer as an OSGi service
DataSourceCappDeployer dataSourceDeployer = new DataSourceCappDeployer();
this.ctx.getBundleContext().registerService(
AppDeploymentHandler.class.getName(), dataSourceDeployer, null);
} catch (Throwable e) {
log.error("Failed to activate Data Source Capp Deployer", e);
}
}
@Test
public void testSeveralObjectNames() throws Exception {
ComponentContext ctx = Mockito.mock(ComponentContext.class);
Dictionary props = new Hashtable();
Mockito.when(ctx.getProperties()).thenReturn(props);
props.put("object.name.system", "java.lang:*");
props.put("object.name", "org.something.else:*");
props.put("object.name.karaf", "org.apache.karaf:type=http");
props.put("object.name.2", "whatever");
props.put("object.name-invalid", "not expected");
JmxCollector collector = new JmxCollector();
Assert.assertNull(collector.getObjectNames());
collector.activate(ctx);
List<String> objectNames = new ArrayList<>(collector.getObjectNames());
Collections.sort(objectNames);
Assert.assertEquals(4, objectNames.size());
Assert.assertEquals("java.lang:*", objectNames.get(0));
Assert.assertEquals("org.apache.karaf:type=http", objectNames.get(1));
Assert.assertEquals("org.something.else:*", objectNames.get(2));
Assert.assertEquals("whatever", objectNames.get(3));
}
protected void deactivate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("De-activating b Management Service Component");
}
try {
if (serviceRegistration != null) {
serviceRegistration.unregister();
}
if (log.isDebugEnabled()) {
log.debug("Current Sensor Management Service Component has been successfully " +
"de-activated");
}
} catch (Throwable e) {
log.error("Error occurred while de-activating Iot Device Management bundle", e);
}
}
@Activate
protected void activate(ComponentContext context) {
appId = coreService.registerApplication(APP_NAME);
KryoNamespace.Builder serializer = KryoNamespace.newBuilder()
.register(KryoNamespaces.API)
.register(Phase.class);
phasedRecoveryStore = storageService.<DeviceId, Phase>consistentMapBuilder()
.withName("onos-sr-phasedrecovery")
.withRelaxedReadConsistency()
.withSerializer(Serializer.using(serializer.build()))
.build();
compCfgService.registerProperties(getClass());
modified(context);
log.info("Started");
}
/**
* initialize the cep service here.
*
* @param context
*/
@Activate
protected void activate(ComponentContext context) {
this.eventBrokerHandler = new EventBrokerHandler(context);
// need to differ the bundle deployment if the Qpid bundle is in the plugins directory and it is not
// started
boolean isQpidBundlePresent = false;
final BundleContext bundleContext = context.getBundleContext();
for (Bundle bundle : bundleContext.getBundles()) {
if (bundle.getSymbolicName().equals("org.wso2.carbon.qpid")) {
isQpidBundlePresent = true;
break;
}
}
if (isQpidBundlePresent) {
// if the Qpid bundle is present we register an event broker handler
// so that the qpid compoent will notify that.
context.getBundleContext().registerService(EventBundleNotificationService.class.getName(), this
.eventBrokerHandler, null);
} else {
this.eventBrokerHandler.startEventBroker();
}
}
/**
* Method to activate bundle.
*
* @param context OSGi component context.
*/
protected void activate(ComponentContext context) {
try {
// if -Dmigrate option is used.
String migrate = System.getProperty("migrate");
if (Boolean.parseBoolean(migrate)) {
log.info("Executing Migration client : " + MigrationClient.class.getName());
MigrationClient migrationClientImpl = new MigrationClientImpl();
migrationClientImpl.execute();
}
if (log.isDebugEnabled()) {
log.debug("WSO2 EI migration bundle is activated");
}
} catch (Throwable e) {
log.error("Error while initiating Config component", e);
}
}
@Activate
protected void activate(ComponentContext context) {
log.debug("Activating component...");
APIManagerConfiguration configuration = ServiceReferenceHolder.getInstance().getAPIMConfiguration();
if (configuration != null) {
if (!configuration.getThrottleProperties().getJmsConnectionProperties().isEnabled()) {
return;
}
} else {
log.warn("API Manager Configuration not properly set.");
}
JMSListenerStartupShutdownListener jmsListenerStartupShutdownListener =
new JMSListenerStartupShutdownListener();
registration = context.getBundleContext()
.registerService(ServerStartupObserver.class, jmsListenerStartupShutdownListener, null);
registration = context.getBundleContext()
.registerService(ServerShutdownHandler.class, jmsListenerStartupShutdownListener, null);
}
@Activate
public void activate(ComponentContext context) {
configService.registerProperties(getClass());
setupCodecs();
messageReceivingExecutor = receiveOnIOLoopThread
? MoreExecutors.directExecutor()
: Executors.newFixedThreadPool(
totalReceiverThreads,
groupedThreads("onos/net-perf-test", "receiver-%d"));
registerMessageHandlers();
startTest();
reporter.scheduleWithFixedDelay(this::reportPerformance,
reportIntervalSeconds,
reportIntervalSeconds,
TimeUnit.SECONDS);
logConfig("Started");
}
protected void activate(ComponentContext context) {
if (log.isDebugEnabled()) {
log.debug("Activating GoogleConnectorServiceComponent");
}
try {
GoogleProvisioningConnectorFactory googleProvisioningConnectorFactory = new GoogleProvisioningConnectorFactory();
context.getBundleContext().registerService(AbstractProvisioningConnectorFactory.class.getName(), googleProvisioningConnectorFactory, null);
if (log.isDebugEnabled()) {
log.debug("Google Identity Provisioning Connector bundle is activated");
}
} catch (Throwable e) {
log.error("Error while activating Google Identity Provisioning Connector", e);
}
}
@Modified
public void modified(ComponentContext context) {
boolean oldValue = monitorHosts;
readComponentConfiguration(context);
if (probeRate > 0) {
monitor.setProbeRate(probeRate);
} else {
log.warn("ProbeRate cannot be less than 0");
}
if (oldValue != monitorHosts) {
if (monitorHosts) {
startMonitoring();
} else {
stopMonitoring();
}
}
}
@Before
public void setUp() {
registerVolatileStorageService();
readyService = getService(ReadyService.class);
assertThat(readyService, is(notNullValue()));
thingRegistry = getService(ThingRegistry.class);
assertThat(thingRegistry, is(notNullValue()));
modelRepository = getService(ModelRepository.class);
assertThat(modelRepository, is(notNullValue()));
modelRepository.removeModel(TESTMODEL_NAME);
ComponentContext componentContextMock = mock(ComponentContext.class);
when(componentContextMock.getBundleContext()).thenReturn(bundleContext);
hueThingHandlerFactory = new TestHueThingHandlerFactoryX(componentContextMock) {
@Override
protected ThingHandler createHandler(final Thing thing) {
if (thing instanceof Bridge) {
return new TestBridgeHandler((Bridge) thing);
} else {
return new BaseThingHandler(thing) {
@Override
public void handleCommand(ChannelUID arg0, Command arg1) {
};
@Override
public void initialize() {
updateStatus(ThingStatus.ONLINE);
}
};
}
}
};
finished = false;
bundle = FrameworkUtil.getBundle(TestHueThingHandlerFactoryX.class);
removeReadyMarker();
}
protected void activate(ComponentContext ctxt) {
try {
// Registering email message sending module on user operation for entitlement component
ctxt.getBundleContext().registerService(NotificationSendingModule.class.getName(),
new EmailSendingModule(), null);
if (log.isDebugEnabled()) {
log.debug("Email notification sending module is activated");
}
} catch (Throwable t) {
// Catching throwable, since there may be throwable throwing while initiating
log.error("Error while registering email notification sending module", t);
}
}
/**
* The deactivate method for this OSGi component, this will be called by the
* OSGi container upon bundle deactivation (result of the 'addon uninstall'
* command)
*
* @param context the component context can be used to get access to the
* OSGi container (ie find out if certain bundles are active)
*/
protected void deactivate(ComponentContext context) {
getMetadataDependencyRegistry().deregisterDependency(
PhysicalTypeIdentifier.getMetadataIdentiferType(),
getProvidesType());
// removeMetadataTrigger(new JavaType(
// "org.springframework.stereotype.Controller"));
removeMetadataTrigger(MODAL_DIALOGS);
}
@Activate
public void activate(ComponentContext context) {
store.setDelegate(delegate);
eventDispatcher.addSink(FlowRuleEvent.class, listenerRegistry);
deviceService.addListener(deviceListener);
cfgService.registerProperties(getClass());
modified(context);
idGenerator = coreService.getIdGenerator(FLOW_OP_TOPIC);
local = clusterService.getLocalNode().id();
log.info("Started");
}
protected void activate(final ComponentContext cContext) {
context = cContext.getBundleContext();
getMetadataDependencyRegistry().registerDependency(
DatatablesMetadata.getMetadataIdentiferType(),
getProvidesType());
getMetadataDependencyRegistry()
.registerDependency(
WebFinderMetadata.getMetadataIdentiferType(),
getProvidesType());
getMetadataDependencyRegistry().addNotificationListener(this);
}
@Activate
@SuppressWarnings("unchecked")
protected void activate(ComponentContext componentContext) {
initDimensionMap();
modified((Map<String, Object>) componentContext.getProperties());
this.resourceBundleTracker = new ResourceBundleTracker(componentContext.getBundleContext(), this);
this.resourceBundleTracker.open();
}
protected void activate(ComponentContext ctxt) {
try {
BasicAuthenticator basicAuth = new BasicAuthenticator();
ctxt.getBundleContext().registerService(ApplicationAuthenticator.class.getName(), basicAuth, null);
if (log.isDebugEnabled()) {
log.info("BasicAuthenticator bundle is activated");
}
} catch (Throwable e) {
log.error("SAMLSSO Authenticator bundle activation Failed", e);
}
}
@Activate
public void activate(ComponentContext context) {
try {
BundleContext bundleContext = context.getBundleContext();
cryptoServiceRegistration = bundleContext
.registerService(CryptoService.class, this.defaultCryptoService, null);
if (log.isDebugEnabled()) {
log.debug(String.format("'%s' has been registered as an implementation of '%s'",
defaultCryptoService.getClass().getCanonicalName(),
CryptoService.class.getCanonicalName()));
}
privateKeyRetrieverRegistration = bundleContext
.registerService(PrivateKeyRetriever.class, this.defaultCryptoService, null);
if (log.isDebugEnabled()) {
log.debug(String.format("'%s' has been registered as an implementation of '%s'",
defaultCryptoService.getClass().getCanonicalName(),
PrivateKeyRetriever.class.getCanonicalName()));
log.debug("'org.wso2.carbon.crypto.impl' bundle has been activated.");
}
} catch (Exception e) {
String errorMessage = "An error occurred while activating org.wso2.carbon.crypto.impl component";
log.error(errorMessage, e);
}
}
/**
* Extracts properties from the component configuration context.
*
* @param context the component context
*/
private void readComponentConfiguration(ComponentContext context) {
Dictionary<?, ?> properties = context.getProperties();
String updatedMac = Tools.get(properties, GATEWAY_MAC);
gatewayMac = updatedMac != null ? updatedMac : GATEWAY_MAC_DEFAULT;
log.info("Configured. Gateway MAC is {}", gatewayMac);
}
@Activate
protected void activate(ComponentContext context) {
try {
logger.debug("ntask-integration bundle is activated.");
} catch (Throwable e) {
logger.error("Could not activate NTaskService. Error: " + e.getMessage(), e);
}
}
protected void activate(ComponentContext ctxt) {
log.info("Initializing the BPMN Analytics Core component");
try {
BPMNAnalyticsCoreServerHolder bpmnAnalyticsCoreHolder = BPMNAnalyticsCoreServerHolder.getInstance();
initAnalyticsServer(bpmnAnalyticsCoreHolder);
BPMNAnalyticsCoreService bpsAnalyticsService = new BPMNAnalyticsCoreService();
bpsAnalyticsService.setBPMNAnalyticsCoreServer(
bpmnAnalyticsCoreHolder.getBPMNAnalyticsCoreServer());
// Register BPS analytics Service OSGI Service
ctxt.getBundleContext().registerService(BPMNAnalyticsCoreService.class.getName(),
bpsAnalyticsService, null);
} catch (Throwable e) {
log.error("Failed to initialize the BPMN Analytics Core Service component.", e);
}
}
/**
* Register itself into metadataDependencyRegister and add metadata trigger
*
* @param context the component context
*/
protected void activate(ComponentContext cContext) {
context = cContext.getBundleContext();
getMetadataDependencyRegistry().registerDependency(
PhysicalTypeIdentifier.getMetadataIdentiferType(),
getProvidesType());
addMetadataTrigger(new JavaType(GvNIXDatatables.class.getName()));
}
@Deactivate
protected void deactivate(ComponentContext ctxt) {
Set<Map.Entry<Integer, MessageFlowReporterThread>> threadEntries = reporterThreads.entrySet();
for (Map.Entry<Integer, MessageFlowReporterThread> threadEntry : threadEntries) {
MessageFlowReporterThread reporterThread = threadEntry.getValue();
if (reporterThread != null && reporterThread.isAlive()) {
reporterThread.shutdown();
// This should wake up the thread if it is asleep
reporterThread.interrupt();
// Otherwise some of the collected data may not be sent to the observers
for (int i = 0; i < 50; i++) {
if (!reporterThread.isAlive()) {
break;
}
if (log.isDebugEnabled()) {
log.debug("Waiting for the mediation tracer reporter thread to terminate");
}
try {
Thread.sleep(100);
} catch (InterruptedException ignore) {
}
}
}
}
// Stops config reporting threads
for (MediationConfigReporterThread configReporterThread : configReporterThreads.values()) {
if (configReporterThread != null && configReporterThread.isAlive()) {
configReporterThread.shutdown();
configReporterThread.interrupt();
}
}
log.debug("DAS service statistics data publisher bundle is deactivated");
}
@Activate
public void activate(ComponentContext context) {
eventExecutor = Executors.newSingleThreadExecutor(groupedThreads("onos/group", "event"));
store.setDelegate(delegate);
eventDispatcher.addSink(GroupEvent.class, listenerRegistry);
deviceService.addListener(deviceListener);
cfgService.registerProperties(getClass());
modified(context);
log.info("Started");
}
@Modified
protected void modified(ComponentContext ctx) {
Dictionary<?, ?> properties = ctx.getProperties();
if (properties != null) {
auditEnabled = Boolean.parseBoolean(get(properties, AUDIT_ENABLED));
auditLogger = get(properties, AUDIT_LOGGER);
auditLog = LoggerFactory.getLogger(auditLogger);
log.info("Reconfigured; auditEnabled={}; auditLogger={}", auditEnabled, auditLogger);
}
}
protected void activate(final ComponentContext context) {
if (log.isDebugEnabled()) {
log.debug("Activating MockIaasServiceComponent...");
}
Runnable mockIaasActivator = new Runnable() {
@Override
public void run() {
try {
if (!MockIaasConfig.getInstance().isEnabled()) {
log.debug("Mock IaaS is disabled, Mock IaaS service component is not activated");
return;
}
ComponentStartUpSynchronizer componentStartUpSynchronizer =
ServiceReferenceHolder.getInstance().getComponentStartUpSynchronizer();
// Wait for stratos manager to be activated
componentStartUpSynchronizer.waitForComponentActivation(Component.MockIaaS,
Component.StratosManager);
MockIaasService mockIaasService = new MockIaasServiceImpl();
context.getBundleContext().registerService(MockIaasService.class.getName(), mockIaasService, null);
log.info("Mock IaaS service registered");
componentStartUpSynchronizer.setComponentStatus(Component.MockIaaS, true);
log.info("Mock IaaS service component activated");
} catch (Exception e) {
log.error("An error occurred when starting mock instances", e);
}
}
};
Thread mockIaasActivatorThread = new Thread(mockIaasActivator);
mockIaasActivatorThread.start();
}
@SuppressWarnings("unchecked")
@Activate
public void activate(ComponentContext context) {
this.properties = context.getProperties();
if (this.properties.get("ignored.categories") != null) {
ignoredCategories = ((String)this.properties.get("ignored.categories")).split(",");
}
if (this.properties.get("location.disabled") != null) {
locationDisabledCategories = ((String) this.properties.get("location.disabled")).split(",");
}
}
@SuppressWarnings("unchecked")
public void activate(ComponentContext context) {
properties = context.getProperties();
String type = getProperty(properties, "type", "process-jmx");
String process = getProperty(properties, "process", null);
String objectName = getProperty(properties, "object.name", null);
Dictionary<String, String> serviceProperties = new Hashtable<String, String>();
serviceProperties.put("decanter.collector.name", type);
this.type = type;
this.process = process;
this.objectName = objectName;
}