...
The start method needs to look for a Log Service, and register a service listener to track it. If a log service is available, it logs a message.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
public void start() { // When starting, look for an LogService ref = context.getServiceReference(LogService.class.getName()); if(ref != null) { log = (LogService) context.getService(ref); // Log a starting message log.log(level,"The component instance " + manager.getInstanceName() + " is starting"); } // Registered a service listenner try { context.addServiceListener(this,"(OBJECTCLASS="+LogService.class.getName()+")"); } catch (InvalidSyntaxException e) { e.printStackTrace(); } } |
...
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
public void stateChanged(int state) { // log the state changed events if(log != null) { if(state == InstanceManager.VALID) { log.log(level, "The component instance " + manager.getInstanceName() + " becomes valid"); } if(state == InstanceManager.INVALID) { log.log(level, "The component instance " + manager.getInstanceName() + " becomes invalid"); } } } |
Implementation of the Service Listener interface
To track the availability of the Log Service, the start method has registered the handler as a service listener. So, the handler class needs to implement the Service Listener interface. This interface contains a method called when a service appears, disappears or is modified. The start method has registered a service listener with a filter. So the handler will received only service events matching the filter. (In our case, only service events referring to a Log Service).
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
public void serviceChanged(ServiceEvent event) { // Check if the service event does not infers with the log service if(ref == null && event.getType() == ServiceEvent.REGISTERED) { ref = event.getServiceReference(); log = (LogService) context.getService(ref); // ask the component manager to check the component instance state manager.checkInstanceState(); } if(ref != null && event.getType() == ServiceEvent.UNREGISTERING && ref == event.getServiceReference()) { //The log service goes away log = null; context.ungetService(ref); ref = context.getServiceReference(LogService.class.getName()); if(ref != null) { log = (LogService) context.getService(ref); } else { manager.checkInstanceState(); } } } |
...
Note: the file path need to used
two '\' instead of one '\'
Conclusion
In this document, we present how-to develop handler for you components. We describe two small examples : a log handler and a properties handler. See the handler proposition section of the iPOJO documentation to see available handlers or to propose your own handler.