Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

Difference between revisions of "Tutorial: Exposing a Jax REST service as an OSGi Remote Service"

Line 91: Line 91:
  
 
<source lang="java">
 
<source lang="java">
import javax.ws.rs.*;
+
import javax.ws.rs.GET;
 
+
import javax.ws.rs.Produces;
@Path("/helloservice")
+
import javax.ws.rs.Path;
public class HelloResource {
+
  
 +
// The Java class will be hosted at the URI path "/helloworld"
 +
@Path("/helloworld")
 +
public class HelloWorldResource implements HelloWorldService {
 +
   
 +
    // The Java method will process HTTP GET requests
 
     @GET
 
     @GET
     @Path("/sayhello")
+
    // The Java method will produce content identified by the MIME Media
     public String sayHello() {
+
    // type "text/plain"
         return "Hello There";
+
     @Produces("text/plain")
 +
     public String getMessage() {
 +
        // Return some textual content
 +
         return "Hello World";
 
     }
 
     }
 
}
 
}
Line 107: Line 114:
  
 
<pre>
 
<pre>
curl http://localhost:8080/mycontext/helloservice/sayhello
+
curl http://localhost:8080/helloworld
 
</pre>
 
</pre>
  
This would return "Hello There" when accessed.
+
This would return "Hello There".
  
 
For this tutorial we will use a service for accessing a simple database of Students.  [https://github.com/ECF/JaxRSProviders/blob/master/examples/com.mycorp.examples.student.webapp.host/src/com/mycorp/examples/student/webapp/host/StudentResource.java Here is a Jax-RS implementation class].  Notice the annotations on the public methods.  These annotations signal to the Jax-RS implementation that these methods are to be exposed as remote services.  When included in a webapp (war file) with the necessary Jax-RS implementation libraries and dependencies on (e.g.) a Tomcat server, this service would be exposed for web-based remote access.
 
For this tutorial we will use a service for accessing a simple database of Students.  [https://github.com/ECF/JaxRSProviders/blob/master/examples/com.mycorp.examples.student.webapp.host/src/com/mycorp/examples/student/webapp/host/StudentResource.java Here is a Jax-RS implementation class].  Notice the annotations on the public methods.  These annotations signal to the Jax-RS implementation that these methods are to be exposed as remote services.  When included in a webapp (war file) with the necessary Jax-RS implementation libraries and dependencies on (e.g.) a Tomcat server, this service would be exposed for web-based remote access.

Revision as of 16:00, 3 September 2015


Introduction

Jax RESTful Web Services (Jax-RS) is a popular standard/specification for exposing services for web-based remote access, with a number of implementations (e.g. Resteasy, Jersey, and CXF and more appearing all the time.

This tutorial will show the use of ECF's OSGi Remote Services to expose an arbitrary Jax-RS service as an OSGi Service and thereby gain the advantages of using OSGi Services, such as superior handling of service dynamics, service versioning, and a clear separation of service contract from service implementation.

ECF's implementation of OSGi Remote Services is unique because it provides open APIs for customizing or replacing distribution providers. Distribution providers are responsible for the actual transmission of remote service calls: marshalling the method arguments, unmarshalling return values, and transport of the call to and from the service host. ECF has a number of provider implementations, including a relatively new one based upon Jax-RS. The git repo containing this provider and the examples from this tutorial may be found here. This provider is based upon the Jax-RS specification, and uses the Jersey implementation from the Orbit project. This provider is small, modular, and extensible, allowing the easy customization or substitution of alternative Jax-RS implementations.

This tutorial will guide through

  1. Describing how Jax-RS services are defined
  2. Declaring an example Jax-RS remote service so that it may be used as an OSGi Remote Service
  3. Demonstrating how to use the Remote Service for accessing the underlying Jax-RS service

Jax-RS Services

With Jax-RS, typically a server-side implementation 'resource' class is annotated with Jax-RS specified java annotations. For example:

import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;
 
// The Java class will be hosted at the URI path "/helloworld"
@Path("/helloworld")
public class HelloWorldResource implements HelloWorldService {
 
    // The Java method will process HTTP GET requests
    @GET
    // The Java method will produce content identified by the MIME Media
    // type "text/plain"
    @Produces("text/plain")
    public String getMessage() {
        // Return some textual content
        return "Hello World";
    }
}

The @Path and @Get annotations are used by the Jax-RS implementation on the server to expose the sayHello method for access by a client via using an URL such as:

curl http://localhost:8080/helloworld

This would return "Hello There".

For this tutorial we will use a service for accessing a simple database of Students. Here is a Jax-RS implementation class. Notice the annotations on the public methods. These annotations signal to the Jax-RS implementation that these methods are to be exposed as remote services. When included in a webapp (war file) with the necessary Jax-RS implementation libraries and dependencies on (e.g.) a Tomcat server, this service would be exposed for web-based remote access.

In order to make this student database service available for clients/consumers as an OSGi Remote Service, it's useful to abstract an interface with the appropriate methods and including the same Jax-RS annotations. Here is such an interface for the StudentResouce

package com.mycorp.examples.student;
 
import java.util.List;
 
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
 
@Path("/studentservice")
public interface StudentService {
 
	@GET
	@Produces(MediaType.APPLICATION_XML)
	@Path("/students")
	List<Student> getStudents();
 
	@GET
	@Produces(MediaType.APPLICATION_XML)
	@Path("/students/{studentId}")
	Student getStudent(@PathParam("studentId") String id);
 
	@POST
	@Produces(MediaType.APPLICATION_XML)
	@Path("/students/add/{studentName}")
	Student addStudent(@PathParam("studentName") String studentName);
 
	@POST
	@Consumes(MediaType.APPLICATION_XML)
	@Produces(MediaType.APPLICATION_XML)
	@Path("/students/update")
	Student updateStudent(Student student);
 
	@DELETE
	@Path("/students/delete/{studentId}")
	@Produces(MediaType.APPLICATION_XML)
	Student deleteStudent(@PathParam("studentId") String studentId);
}

Please note: the method signatures and annotations are exactly the same as those given on the actual Jax-RS service resource class. A bundle project with this service interface and dependencies is provided here.

Note also that the annotations are only those standardized by the Jax-RS specification (i.e. in javax.ws.rs.* packages), and so are not bound to any Jax-RS implementation.

With this interface and the ECF Remote Service Jax-RS provider bundles and their dependencies, we can create a client/consumer application that uses this remote service. ECF's implementation will dynamically create a proxy implementation of the StudentService interface, and make it available to the consumer.

As an OSGi service, it can be discovered and made available in several ways, but the easiest is to have the proxy instance injected via Declarative Services. Here is the java code for a Declarative Services component that dynamically injects the StudentService

package com.mycorp.examples.student.client;
 
import java.util.List;
 
import com.mycorp.examples.student.Student;
import com.mycorp.examples.student.StudentService;
 
public class StudentServiceClient {
 
        // Called by Service Component Runtime when a StudentService is discovered by RSA
	void bindStudentService(StudentService service) {
		System.out.println("Discovered student service=" + service);
		// Get students
		List<Student> originalStudents = service.getStudents();
		// Print list
		System.out.println("students=" + originalStudents);
		// Get first student
		Student s = originalStudents.get(0);
		System.out.println("Student 0=" + s);
		if (s != null) {
			// Get this student via id
			s = service.getStudent(s.getId());
			System.out.println("Student with id=" + s.getId() + "=" + s);
		}
		// Add a new student
		Student newStudent = service.addStudent("April Snow");
		System.out.println("Created student=" + newStudent);
		// Update with grade
		newStudent.setGrade("First");
		newStudent = service.updateStudent(newStudent);
		System.out.println("Updated student=" + newStudent);
		// Delete student
		System.out.println("Deleted student=" + service.deleteStudent(newStudent.getId()));
	}
}

When called by the DS/SCR runtime, this code in the bindStudentService method invokes all the available StudentService proxy methods. At that time, these proxy calls will be automatically turned into valid Jax-RS client calls by the constructed proxy.

Remote Service Discovery

There are several ways to discover an OSGi Remote Service, but for the purposes of this tutorialwe will use EDEF (Endpoint Description Extension Format), an OSGi-standardized xml-based file format for describing an OSGi Remote Service. See Static File-based Discovery of Remote Service Endpoints for background on EDEF. For this tutorial here is the EDEF for this service, and here is the project containing this EDEF.

Jax-RS Student Service Server

For testing, this project was used to create a Tomcat 7 server (no OSGi) with a webapp that exposes the StudentResource as a Jax-RS service using JBoss' Resteasy implementation. Notice that in this case the server is not using OSGi, and is using the Resteasy Jax-RS implementation, rather than the Jersey implementation used on the client.

Running the Jax-RS OSGi Service Client

Triggering the RSA discovery by starting the bundle containing the studentserviceEDEF.xml file results in the creation of a StudentService proxy and it's injection into the StudentServiceClient.bindStudentService method. Once injected the service instance methods are called, resulting in the following OSGi console output:

osgi> Discovered student service=com.mycorp.examples.student.StudentService.proxy@org.eclipse.ecf.remoteservice.RemoteServiceID[containerID=URIID [uri=http://localhost:8080/studentresource/rs];containerRelativeID=0]
students=[Student [id=94381a53-b2b9-4cb4-ab36-1e8db4643f2f, name=Joe Senior, grade=First, address=Address [street=111 Park Ave, city=New York, state=NY, postalCode=11111]]]
Student 0=Student [id=94381a53-b2b9-4cb4-ab36-1e8db4643f2f, name=Joe Senior, grade=First, address=Address [street=111 Park Ave, city=New York, state=NY, postalCode=11111]]
Student with id=94381a53-b2b9-4cb4-ab36-1e8db4643f2f=Student [id=94381a53-b2b9-4cb4-ab36-1e8db4643f2f, name=Joe Senior, grade=First, address=Address [street=111 Park Ave, city=New York, state=NY, postalCode=11111]]
Created student=Student [id=391d2e3e-de8a-4dea-a9d6-26a408737eee, name=April Snow, grade=null, address=null]
Updated student=Student [id=391d2e3e-de8a-4dea-a9d6-26a408737eee, name=April Snow, grade=First, address=null]
Deleted student=Student [id=391d2e3e-de8a-4dea-a9d6-26a408737eee, name=April Snow, grade=First, address=null]

Summary

By using ECF's implementation of OSGi Remote Services and the ECF Jax-RS provider, it's easy to create dynamic OSGi Remote Services proxies to access the Jax-RS service. The annotated interface (e.g. StudentService above) can easily be created from the server's Jax-RS resource class.

It's also possible to create a custom distribution provider based upon alternative Jax-RS implementations, or customize the existing provider to meet security and other requirements.

Background and Related Articles

Getting Started with ECF's OSGi Remote Services Implementation

OSGi Remote Services and ECF

Asynchronous Proxies for Remote Services

Static File-based Discovery of Remote Service Endpoints

Download ECF Remote Services/RSA Implementation

How to Add Remote Services/RSA to Your Target Platform

Back to the top