OSGI+CDI: strange behaviour with system printers detecting

90 views Asked by At

I have CDI+OSGI javase application. CDI-Weld,OSGI-felix and pax-cdi. And I have the following code in "CDI-main"

@ApplicationScoped
public class Foo{

    public void postCreate(@Observes ContainerInitialized event, BundleContext ctx) throws Exception {
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        System.out.println("$Number of print services: " + printServices.length);
        for (PrintService printer : printServices)
            System.out.println("$Printer: " + printer.getName()); 
    }
  }

When I run this application I will get the following output(although I have printers with right drivers!)

$Number of print services:0

Notice, the first sign is $; If I add the following code to bundle activator and start it

public class Activator implements BundleActivator {

    public void start(BundleContext context) throws Exception {
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        System.out.println("#Number of print services: " + printServices.length);
        for (PrintService printer : printServices)
            System.out.println("#Printer: " + printer.getName());
    }

    public void stop(BundleContext context) throws Exception {
  }
}

Notice, first sign is #.Then all my printers are detected:

#Number of print services: 1
#Printer: MF3110
Jun 14, 2015 1:47:34 PM org.jboss.weld.bootstrap.WeldStartup startContainer...
....
$Number of print services: 1
$Printer: MF3110

How to explain it?

2

There are 2 answers

0
nasioman On

Is PrintServiceLookup defined in a separate bundle or use code which is from separate OSGI Service? Might it be related to osgi services cardinality?

0
Oliver Marienfeld On

In your first code snippet, PrintServiceLookup.lookupPrintServices is called in a different LifeCycle Phase than in the second snippet.

In the first example, the Container or Extender might not have satisfied all dependencies for PrintServiceLookup when lookupPrintServices is called.

In the second example, these dependencies are likely to be satisfied since lookupPrintServices is called in a Bundle Activator's start method - which is being called by the Container during the STARTING phase. In the STARTING phase, all dependencies of the Bundle are already resolved by the Container.

Hope I could help.