Wednesday, December 05, 2012

Part 3: Custom Liferay Plugin JSON Web Services

Go to Previous post Part 2: Custom Liferay Plugin JSON Web Services
Below is the step by step setup to expose and consume a plugin portlet service as JSON web service.

Step 1: Create a liferay plugin portlet

Step 2: Create a custom service

Using Liferay Service builder create a service. For example

The service.xml will look like below:
<service-builder package-path="com.rdg.api">
 <author>rishidev.gupta</author>
 <namespace>ServiceAPI</namespace>

 <entity name="Bridge" remote-service = "true" local-service="true" human-name="Bridge">
  <reference package-path="com.liferay.counter" entity="Counter"></reference>
  <reference package-path="com.liferay.portal" entity="User"></reference>
  <reference package-path="com.liferay.portlet.journal" entity="JournalArticle"></reference>
 </entity>
</service-builder>

Step 3: Build the service using liferay service builder 

Step 4: Writing a custom method to be exposed

public class BridgeLocalServiceImpl extends BridgeLocalServiceBaseImpl {

 public String getBridge(String str) throws PortalException {
  System.out.println("You have successfully requested for: " + str);
  return "You have successfully requested for: " + str;

 }
}
public class BridgeServiceImpl extends BridgeServiceBaseImpl {
 public String getBridge(String str) throws PortalException {
  return bridgeLocalService.getBridge(str);
 }
}
Now rebuild the service.

Step 5: Configuring web.xml 

To make sure that your custom portlets can be scanned, and their service can become part of the JSON API. For this you must add the following in portlets web.xml:


     <servlet>
        <servlet-name>JSON Web Service Servlet</servlet-name>
        <servlet-class>com.liferay.portal.kernel.servlet.PortalClassLoaderServlet</servlet-class>
        <init-param>
            <param-name>servlet-class</param-name>
            <param-value>com.liferay.portal.jsonwebservice.JSONWebServiceServlet</param-value>
        </init-param>
        <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>JSON Web Service Servlet</servlet-name>
        <url-pattern>/api/jsonws/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>JSON Web Service Servlet</servlet-name>
        <url-pattern>/api/secure/jsonws/*</url-pattern>
    </servlet-mapping>

This enables the servlet that is responsible for scanning JSON web services configuration. Now deploy the plugin portlet in a running tomcat server.

Step 6: Consuming JSON Web Service

 To list registered services on portlet, 
http://localhost:8080/<portlet-context>/api/jsonws
 
To access service using browser
http://localhost:8080//service-api-portlet/api/jsonws/bridge/get-bridge?&str=rishidev.gupta 

No comments:

Post a Comment