dev@hk2.java.net

Re: HK2 on OSGi

From: Martin Soch <martin.soch_at_oracle.com>
Date: Fri, 17 Jan 2014 13:04:35 +0100

Hello Tang,

thanks for the tip. However the osgi-adapter is started (bundle with ID
25). Attaching a run-log-file so you see what is going on there.

Sahoo also mentioned (in separate email) that creating ServiceLocator
every time getEventService(name) is called might cause returning null.
However it looks like false alarm too.

Any other ideas/tips ?

Thanks
Martin

On 17.1.2014 10:58, Tang Yong wrote:
> also cc sahoo, a point: hk2-osgi-adapter bundle must be started.
>
> Thanks
> Tang
>
> Martin Soch wrote:
>> Hello HK2 developers,
>>
>> I am evaluating HK2 and I am experiencing troubles with named services
>> when running in OSGi environment.
>> I would like to dynamically create named services with the following
>> code snippet:
>>
>> public EventService getEventService(String name) {
>> EventService es = locator.getService(EventService.class, name);
>> if (es == null) {
>> // there is no service in the registry with given name ->
>> create it
>> DynamicConfigurationService dcs =
>> locator.getService(DynamicConfigurationService.class);
>> DynamicConfiguration config =
>> dcs.createDynamicConfiguration();
>> Descriptor d = createEventServiceDescriptor(name);
>> config.bind(d);
>> config.commit();
>> es = locator.getService(EventService.class, name);
>> }
>> return es;
>> }
>>
>> private Descriptor createEventServiceDescriptor(String name) {
>> return BuilderHelper.link(EventServiceImpl.class).
>> to(EventService.class).
>> named(name).
>> in(Singleton.class).
>> build();
>> }
>>
>> "EventService" is the interface/contract and the "EventServiceImpl" is
>> the implementation of that interface.
>> The getEventService(String) works fine when running as standalone Java
>> application but in OSGi environment it always returns "null".
>>
>> Under OSGi I am using hk2-osgi-adapter to obtain the ServiceLocator
>> with the following code:
>>
>> Main main = (Main) bundleContext.getService((ServiceReference)
>> bundleContext.getServiceReference(Main.class));
>> ModulesRegistry registry = (ModulesRegistry)
>> bundleContext.getService((ServiceReference)
>> bundleContext.getServiceReference(ModulesRegistry.class));
>> StartupContext ctx = new StartupContext();
>> ServiceLocator l = main.createServiceLocator(registry, ctx, null, null);
>>
>> where ModulesRegistry means com.sun.enterprise.module.ModulesRegistry,
>> Main means com.sun.enterprise.module.bootstrap.Main and bundleContext
>> is instance of org.osgi.framework.BundleContext.
>>
>> Do you have any idea why I am always getting null under OSGi ?
>> I am using ProSyst implementation of OSGi and HK2-2.2.0-b27 from Maven
>> repo.
>>
>> Thanks
>> Martin
>>
>