Liferay Development

Liferay Consulting

Liferay Training

Your Trusted Liferay Solutions Partner

Saturday, March 21, 2020

Liferay JAX-RS OSGi Rest Module Development

The following are basic steps to create sample Liferay SOGi rest module.
  1. Create Liferay OSGi Rest Module
  2. Create JAX-RS Resource Class
  3. Implement Required Rest Services with JAX-RS Annotations
  4. Override getSingletons method in Application component to add Resources and Providers to set Collection
  5. Add Required Dependencies (Jackson libraries)
  6. Build and Deploy
  7. Validating Rest API

Follow the below Liferay JAX-RS OSGi Module Introduction blog before proceeding further.


Module GitHub Source

Get project source code from following location.

Gradle


Maven


Create Liferay OSGi Rest Module

We have different ways to create Liferay OSGi modules and we need to create rest Liferay OSGi module. While creating Liferay OSGi module need to select rest project template. It will create basic rest module.


Create JAX-RS Resource Class

We need to create JAX-RS resource class that is where all rest services implementation is available.


Example is available in GitHub and you can download and take the resource class as reference.

Implement Required Rest Services with JAX-RS Annotations

Assume we are going to provide employee rest services then we need to implement resource class. We have to provide different endpoints which support GET, PUT, DELETE and POST methods.  We can use JAX-RS annotation to implement service methods.

 Follow the below reference to implement your resources class and methods.


Example


@Path("/employee")
@GET
@POST
@PUT
@DELETE
@Path("{id}")
@Produces("application/json")
@Consumes("application/json")


Override getSingletons method in Application component

 We have to override getSingletons method to add Resources and Provides to set collections. This is the way to registered all resources and providers with JAX-RS application. Jackson JSON provider will provide the capability of Marshaling and Un- Marshaling of objects.

Example:

     
@Override
       public Set<Object> getSingletons() {
            
             Set<Object> singletons = new HashSet<Object>();
             //add the automated Jackson marshaller for JSON.
             singletons.add(new JacksonJsonProvider());
            
             // add Employee REST endpoints (resources)
             singletons.add(new EmployeeResource());
             return singletons;
       }


Add Required Dependencies (Jackson libraries)

Project may require Jackson libraries at build and run time. Add following libraries as dependencies to module based on build tool.

Follow below JAX-RS introduction blog to find required dependencies for Gradle and Maven


Important Note

Before use Jackson features in modules, we have to deploy Jackson OSGi modules in Liferay Module Framework. Deploy the following Jackson OSGi module jar files in Liferay Portal “osgi/modules” directory.

Find all modules in the GitHub



jackson-core-2.10.3.jar
jackson-databind-2.10.3.jar
jackson-jaxrs-base-2.10.3.jar
jackson-module-jaxb-annotations-2.10.3.jar
jackson-annotations-2.10.3.jar
jackson-jaxrs-json-provider-2.10.3.jar



Make sure all module should be in active state. Use Gogo shell to check status of modules




Build and Deploy

Locate project and use required commands to build and deploy module.

Module Build

Maven Build


mvn clean install

OR

mvnw clean install



Gradle Build


gradlew build

OR

gradle build


Module Deployment

If bundle support plugin already added in project build file then it will deploy to Liferay Module Framework with following commands

Gradle deploy

Add following bundle support plugin in module “build.gradle” file


liferay {
    liferayHome = "C:/Liferay/Liferay7.2/liferay-workspace/bundles"
    deployDir = file("${liferayHome}/osgi/modules")
}


Deploy module command


gradlew deploy

OR

gradle deploy


Maven Deployment

Add bundle support plugin in module “pom.xml” file and update liferay home path.

<plugin>
<groupId>com.liferay</groupId>
<artifactId>com.liferay.portal.tools.bundle.support</artifactId>
<version>3.5.4</version>
<executions>
<execution>
<id>deploy</id>
<goals>
<goal>deploy</goal>
</goals>
<phase>pre-integration-test</phase>
</execution>
</executions>
<configuration>
<liferayHome>C:/Liferay/Liferay7.2/liferay-workspace/bundles</liferayHome>
</configuration>
</plugin>


Run following maven goals to deploy module


mvn bundle-support:deploy

OR

mvnw bundle-support:deploy


Make sure module jar should be in osgi/module directory and it should be in active state in Liferay Module framework. Use Gogo shell commands to check module status.

Module status


Module is available in “osgi/modules”



Validating Rest API

Prerequisite

Add Postman google chrome extension to chrome browser.

Launch post man

Test Add Employee API End-point

Method: POST
Authorization Basic: User Liferay Admin credentials
Select Request Body and Provide sample JSON data to create employee

{
    "lastName": "Liferay",
    "firstName": "Rest",
    "country": "NYC"
}

Content type is “application/json

Basic Authorization screen

Example post request


Once provided details click on send request then you can out of employee object.

Test Get Employee API end-point

Method: POST
Authorization Basic: Use Liferay Admin credentials
Select Request Body and Provide sample JSON data to create employee.
Example Get request


We can try all end points which is available in the module.

Troubleshooting

If you encountered “JAXB-API has not been found on module path exception” follow the below blog post.


If you encountered “Access denied” while accessing REST end-point, it means you might not provide valid credentials for authorization.

Java Client

Example Java Client to Access Rest end-points


             OkHttpClient client = new OkHttpClient();

             MediaType mediaType = MediaType.parse("application/json");
             RequestBody body = RequestBody.create(mediaType, "{\n    \"lastName\": \"Prince1\",\n    \"firstName\": \"Meera1\",\n    \"country\": \"MI\"\n}");
             Request request = new Request.Builder()
               .url("http://localhost:9090/o//liferaysavvy/employee")
               .post(body)
               .addHeader("authorization", "Basic dGVzdEBsaWZlcmF5LmNvbTp0ZXN0")
               .addHeader("content-type", "application/json")
               .addHeader("cache-control", "no-cache")
               .build();

             Response response = client.newCall(request).execute();


Generate Base64 Encoded string for Basic Authorization

   
        String name = "test@liferay.com";
        String password = "test";
        String authString = name + ":" + password;
        byte[] bytesEncoded = Base64.encodeBase64(authString.getBytes());
        String bytesEncodedStr = new String(bytesEncoded);
        System.out.println("encoded value is " + bytesEncodedStr);


Curl Command

curl -X POST \
  http://localhost:9090/o//liferaysavvy/employee \
  -H 'authorization: Basic dGVzdEBsaWZlcmF5LmNvbTp0ZXN0' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -d '{
    "lastName": "Prince1",
    "firstName": "Meera1",
    "country": "MI"
}'

Note:

This is sample example to show REST services in Liferay OSGi and It does not have real database interactions. In the method implantation you can call Liferay service builder services to interact with Database.

This example Rest module not enabled with OAuth authorization, we can go to control panel portal configuration and enable OAuth to module.
Author

0 comments :

Post a Comment

Recent Posts

Recent Posts Widget

Popular Posts