Java Code Examples for org.osgi.service.component.ComponentContext

The following examples show how to use org.osgi.service.component.ComponentContext. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: carbon-apimgt   Source File: APIKeyMgtServiceComponent.java    License: Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 2
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);
    }
}
 
Example 3
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);
    }
}
 
Example 4
Source Project: karaf-decanter   Source File: TestMapAttribute.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 5
Source Project: product-iots   Source File: ServiceComponent.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 6
Source Project: onos   Source File: PhasedRecoveryManager.java    License: Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example 7
Source Project: carbon-commons   Source File: EventBrokerBuilderDS.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 8
Source Project: product-ei   Source File: MigrationServiceComponent.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }

}
 
Example 9
Source Project: carbon-apimgt   Source File: JMSListenerComponent.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 10
Source Project: onos   Source File: MessagingPerfApp.java    License: Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example 11
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);
        }
    }
 
Example 12
Source Project: onos   Source File: HostManager.java    License: Apache License 2.0 6 votes vote down vote up
@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();
        }
    }
}
 
Example 13
@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();
}
 
Example 14
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);
        }
    }
 
Example 15
/**
 * 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);
}
 
Example 16
Source Project: onos   Source File: FlowRuleManager.java    License: Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example 17
protected void activate(final ComponentContext cContext) {
    context = cContext.getBundleContext();
    getMetadataDependencyRegistry().registerDependency(
            DatatablesMetadata.getMetadataIdentiferType(),
            getProvidesType());
    getMetadataDependencyRegistry()
            .registerDependency(
                    WebFinderMetadata.getMetadataIdentiferType(),
                    getProvidesType());
    getMetadataDependencyRegistry().addNotificationListener(this);
}
 
Example 18
Source Project: smarthome   Source File: I18nProviderImpl.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@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();
}
 
Example 19
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);
    }
}
 
Example 20
Source Project: micro-integrator   Source File: CryptoImplComponent.java    License: Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 21
Source Project: onos   Source File: K8sSwitchingArpHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 22
Source Project: micro-integrator   Source File: NtaskService.java    License: Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 23
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);
    }
}
 
Example 24
/**
 * 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()));
}
 
Example 25
@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");
}
 
Example 26
Source Project: onos   Source File: GroupManager.java    License: Apache License 2.0 5 votes vote down vote up
@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");
}
 
Example 27
Source Project: onos   Source File: AuditManager.java    License: Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 28
Source Project: attic-stratos   Source File: MockIaasServiceComponent.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 29
Source Project: karaf-decanter   Source File: LogAppender.java    License: Apache License 2.0 5 votes vote down vote up
@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(",");
    }
}
 
Example 30
Source Project: karaf-decanter   Source File: JmxProcessCollector.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}