Thursday, 7 September 2017

Liferay 7 with Restful Web services

What is REST?

REST stands for REpresentational State Transfer. REST is a web standards based architecture and uses HTTP Protocol for data communication. It revolves around resources where every component is a resource and a resource is accessed by a common interface using HTTP standard methods. 

Installations:


  • Liferay Eclipse Neon IDE: 
  • Liferay CE Portal  tomcat GA4 :
  • Jersey
OSGI Component offers  Jersey Application as bridge to create REST service and which make easy for us create REST services on the fly than the service builder. Liferay 7 IDE has REST Template project creation to easy the development.

Creating Rest Project:

1.Open eclipse
2.Open Perspective and change to Liferay Workspace
3.Create the Workspace for your project.
        àOpen Package Explorer.
        àRight Click New-LiferayWorkspace Project.
        àEnter Workspace Name -next-Finish.
4.In create Package Explorer
        à Right Click New- Liferay Module Project.
        àType Project Name
        àSelect Build Type
                * gradle-module
        àSelect Project Template Name-(rest)
        àFinsh


5.In create Package Explorer(Creating Service)
        à Right Click New- Liferay Module Project.
        àType Project Name
        àSelect Build Type
                * gradle-module
        àSelect Project Template Name-(Service-builder)
        àFinsh
After clicking on finish the project structure will be as follow.
Example: Workspace-sample
                Potlet name – leave-rest
As shown in below image.

Provide Component class name and package path. This package path is added to Bundle Symbolic
Name 

  • bnd.bnd template file is:
    1. Bundle-Name: leave-rest
      Bundle-SymbolicName: org.javasavvy.leave.rest
      Bundle-Version: 1.0.0
      ConfigurationPath: /configuration
      Include-Resource: configuration=src/main/resources/configuration
  • update gradle dependencies with below and run the gradle build task. Refresh the gradle project again to affect the dependency changes (Right click on project  -> Select Gradle -> Select Gradle Refresh)
    1. dependencies {
       compileOnly group: "javax.ws.rs", name: "javax.ws.rs-api", version: "2.0.1"
       compileOnly group: "org.osgi", name: "org.osgi.service.component.annotations", version: "1.3.0"
       compileOnly group: "com.liferay.portal", name: "com.liferay.portal.kernel", version: "2.0.0"
       compileOnly group: "com.liferay.portal", name: "com.liferay.util.java", version: "2.0.0"
       compileOnly group: "com.liferay.portal", name: "com.liferay.portal.impl", version: "2.0.0"
       compileOnly project(":modules:leave-core:leave-core-api")
       compileOnly project(":modules:leave-core:leave-core-service")
      }
  • RESTExtenderConfiguraiton: What is REST Extender configuration??  OSGI is running in JVM container as OSGI container holds object,services etc.  How OSGI will detect REST Context paths??
    • REST Extenders will track the services in the OSGI on specified end points. REST Extenders are need to publish API over the contextPaths, which need to be specified in RESTExtenderConfiguration file.
    • contextPaths=/leave-rest
  • CXFPublisherEndpointPublisherConfiguration
    1. contextPath=/leave-rest
      authVerifierProperties=auth.verifier.PortalSessionAuthVerifier.urls.includes=*
  •  Liferay creates REST Component with sample methods, so edit the LeaveRestComponent class that returns Leave objects as JSON
    1. @ApplicationPath("/leave")
      @Component(immediate = true, service = Application.class)
      public class LeaveRestApplication extends Application {
      
       public Set<Object> getSingletons() {
        return Collections.<Object>singleton(this);
       }
       
       private HrmsLocalService hrmsLocalService;
       
         @Reference(unbind="-")
            public void setHrmsLocalService(HrmsLocalService hrmsLocalService){
                this.hrmsLocalService=hrmsLocalService;
             }
      
       @GET
       @Produces("text/plain")
       public String working() {
        return "It works!";
       }
      
       @GET
       @Path("/morning")
       @Produces("text/plain")
       public String hello() {
        return "Good morning!";
       }
      
       @GET
          @Path("/leave-info/{companyProfileId}")
          @Produces(MediaType.APPLICATION_JSON)
         public String getLeave(@PathParam("companyProfileId") long companyProfileId){
            Hrms hrms = null;
            Status status = new Status();
            String jsonString = null;
            System.out.println("leave-info invodked");
           try {
            hrms = hrmsLocalService.getHrms(companyProfileId);
                jsonString = JSONFactoryUtil.serialize(hrms);
               } catch (Exception e) {
                   if(e instanceof NoSuchHrmsException) {
                       status.setMessage("NO Leave Entity Found");
                       status.setStatus(250);
                       jsonString = JSONFactoryUtil.serialize(status);
                 }
                e.printStackTrace();
            }
            return jsonString;
        }
      
      }
  •  run deploy gradle task and deploy the OSGI container.
What next??  Liferay loads REST Extender configuration and creates REST resources, but some times if you access REST URL,it may give 404 error.  We need to manually create REST Extender configuration in Control panel or update existing configuration.

Liferay REST Extender Configuration :

In this step, we need to update REST Extender configuration in the control panel section of admin
  1. Click on Control Panel -> Configuration -> System Settings 
  2. Search for REST
  3. Click on REST Extender
  4. You can  see that rest extender configuration will be already created.so just update this config again.
  5. Click on the configuration and you can see the deployed  OSGI module “leave-rest” with specified context paths. Click + icon if any additional context paths required.
  6. Click on update and access the web services in the url :http://localhost:8080/o/leave-rest/leave/morning
  7. Liferay 7 starts with context /o unlike in Liferay 6 with /c
  8. Hope you have the entry created already with leave-web application and access the leave info with leave Id.
    • http://localhost:8080/o/leave-rest/leave/leave-info/1

No comments:

Post a Comment

Liferay 7 with Restful Web services

What is REST? REST stands for  RE presentational  S tate  T ransfer. REST is a web standards based architecture and uses HTTP Protocol f...