Apache Karaf + Pax CDI + OSGI Command and Function

OSGI Command and Function

In the Previous post we saw how to implement OSGI Service PAX CDI Implementation



Let us see how we can use OSGI Command

osgi.command.scope
osgi.command.function

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>osgi.example</groupId>
<artifactId>osgi-example-parent</artifactId>
<version>1.0</version>
</parent>
<artifactId>osgi-example-cmd</artifactId>
<packaging>bundle</packaging>

<dependencies>
<dependency>
<groupId>osgi.example</groupId>
<artifactId>osgi-example-osgi.api</artifactId>
<version>1.0</version>
</dependency>
</dependencies>

</project>


bnd.bnd

Bundle-Name: PAX CDI CMD
Require-Capability org.ops4j.pax.cdi.extension; filter:="(&(extension=pax-cdi-extension)(version>=${version;==;${pax.cdi.version}})(!(version>=${version;=+;${pax.cdi.version}})))", osgi.extender; filter:="(osgi.extender=pax.cdi)"
Import-Package javax.enterprise.*; version="1.0", *;,

OSGI Command  Class

@OsgiServiceProvider
Link the Class to expose the osgi command with scope = task and function = get

@Inject
@OsgiService
Inject the exposed OSGI Service which we created in the Previous post.

package com.cmd.service;

import javax.inject.Inject;

import org.ops4j.pax.cdi.api.OsgiService;
import org.ops4j.pax.cdi.api.OsgiServiceProvider;
import org.ops4j.pax.cdi.api.Properties;
import org.ops4j.pax.cdi.api.Property;

import com.osgi.api.HelloService;

@OsgiServiceProvider(classes=TaskGetCommand.class)
@Properties(//
{
 @Property(name = "osgi.command.scope", value = "task"),
 @Property(name = "osgi.command.function", value = "get")
})
public class TaskGetCommand {

    @Inject @OsgiService
    HelloService helloService;

    public String get(String id) throws Exception {
        return helloService.sayHello(id);
    }

}

Create a empty META-INF/beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

Project Structure is shown as below


Apache Karaf Bundle Installation

karaf@root()> install  -s mvn:com.osgi/osgi-example-cmd/1.0



Now we can see that task and hit tab button it will list the command we registered in OSGI

task:get test

It invokes the @OsgiServiceProvider(classes = HelloService.class) which is implemented by HelloServiceImpl
It print the Hello Message on the console.






Comments

Popular posts from this blog

Apache Karaf + Pax CDI OSGI Service

Apache CXF CDI in Karaf (Using CXF and CDI 1.1 (JSR-346))

OSGI + PAX CDI + Drools + Karaf