Tuesday, February 11, 2014

Working with Liferay Portal JSON Web Services

Introduction:

Liferay have support to REST API from this we can create restful web services and the data format is JSON.

Liferay have inbuilt support for create JSON web services.

Liferay already have many portal JSON web services these are simple URL calls so that we can get the JSON data and we can use any where to consume web services.

We have two kinds of Web services
  1. Portal Web Services
  2. Plugin Portlet Web services

Note:

I am going to discuss only Portal Web Service in the following article.

Portal Web Services:

Portal web services are related to liferay portal that include many and all are related to portal level data.

These web services have authentication mechanism when we access these services user should be valid authenticated user.

We can see all portal JSON web service by accessing following URL


The following screen shows you JSON portal web service


From this we can see all web services and different code snippets to call web services
Here all web services required authentication then only we can access the data as JSON format.

How can I see the different code snippets for web service call?

In left hand side we have many panels each panel represent one service entity and each service entity has different web services.

Assume now we want get countries and we need to look for Country Entity and click on get-countries link then you can see following screen



Now we have to click on invoke button


Now we have different code examples when you click on menu you can see different code example

Most important code like Java Script Example and URL example

Java Script Example

Liferay.Service(
  '/country/get-countries',
  function(obj) {
    console.log(obj);
  }
);

Note:

The above java script code only will work in liferay applications.

URL Example



Note:

We can access above URL in web browser so that you can see JSON data and we will use this URL in Ajax call then we can get the JSON data as response and we can use this web service URL in any other application or any other clients.


If any web service method needs parameters then we need to pass parameters to get the data

Example

Get Country by Name




Note:

In the above scenarios we should login as admin into the portal then only we can see the data. Because it need admin user to access web services.

If we not login into portal and when we access any web service URL then we will get following Exception



Accessing Portal JSON Web Services:

When we access portal JSON web service we need to override some portal properties using portal-ext.propertis file.

Generally Portal JSON web services not allowed call from other client by default, so we need to do some configuration then only other clients can access

We need provide valid user credential when we call web service generally we will use admin credentials to call web services.

In the portal when we call web services it will check host name and authentication credentials, if both are valid then only it will allow to access JSON web services

We need follow following steps when we access portal JSON web services.

Step: 1

We need to override following portal properties so that it will allow calling liferay JSON web services, we need register host names and we need to tell what are methods allow to public access

The following properties we need to write in portal-ext.properties file.


json.service.auth.token.hosts.allowed=127.0.0.1,SERVER_IP
json.service.auth.token.enabled=false
jsonws.web.service.public.methods=*
 jsonws.servlet.hosts.allowed=127.0.0.1,SERVER_IP


Step: 2

We need to pass valid user credentials as Http Headers. Generally we use liferay portal admin to access these services

The following is example URL




Note:

Sometime browser not allows pass credentials in URL so we need pass in the program as Authorization header and type is basic.

The following is simple Ajax Program Call Portal Service with Basic Authorization Header
The following example uses the get Countries JSON Web Services and in the alert it will show country. This is just example

Here you need look the part how to pass Authorization header in the request this is very important.

Here we are passing Authorization header type basic and we will encoded the user credentials.

<%@ include file="init.jsp"%>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).on('ready',function(){
            var username ="test@liferay.com";
            var password ="test"
            function make_base_auth(user, password) {
              var tok = user + ':' + password;
              var hash = btoa(tok);
              return "Basic " + hash;
            }
                $.ajax({
                  url: 'http://localhost:8080/api/jsonws/country/get-countries',
                  dataType: "json",
                  data:{},
                  type: "get",
                  success: function(data){
                          alert(data[0].name);
                  },
                  beforeSend: function(xhr){
                          xhr.setRequestHeader('Authorization',make_base_auth(username, password));
                                    },
                                    complete: function(){
                                    },
                  error: function(){
                  }
                });
             
 });
</script>

Note:

Simple place above code in HTML page or JSP page then you can see the result in alert.

How do JSON web service URL will generate and custom JOSN web service creation?

Go through following link


All JSON web services will be checked by Authenticate Verifier filter

When we observer following code configuration in liferay-web.xml we can understand

<filter-mapping>
                        <filter-name>JSON Web Service Servlet Filter</filter-name>
                        <url-pattern>/api/jsonws/*</url-pattern>
                        <dispatcher>FORWARD</dispatcher>
                        <dispatcher>INCLUDE</dispatcher>
                        <dispatcher>REQUEST</dispatcher>
            </filter-mapping>
<filter>
<filter-name>JSON Web Service Servlet Filter</filter-name>
<filter-class>com.liferay.portal.servlet.filters.authverifier.AuthVerifierFilter</filter-class>
<init-param>
<param-name>portal_property_prefix</param-name>
<param-value>jsonws.servlet.</param-value>
</init-param>
</filter>

Properties related to AuthVerifierFilter

#
    # The auth verifier filter is used to verify whether a request is
    # authenticated or not.
    #
    com.liferay.portal.servlet.filters.authverifier.AuthVerifierFilter=true


Apart from above things we need consider following properties also when we work with Liferay Portal JSON web Services

##
## JSON Web Service
##

    #
    # Set this property to true to enable JSON web services. Note that setting
    # this to false will cause portlets that make JSON web service calls from
    # working.
    #
    json.web.service.enabled=true

    #
    # Input a list of comma delimited HTTP methods that are not accessible. For
    # example, if you want to have a read only API, then set this property to
    # "DELETE,POST,PUT".
    #
    jsonws.web.service.invalid.http.methods=

    #
    # Set this property to true to ensure that a JSON web service action can
    # only be invoked by its expected HTTP method.
    #
    # For example, the annotation
    # com.liferay.portal.kernel.jsonwebservice.JSONWebService may configure the
    # expected HTTP method for an action to be a GET request. However, the URL
    # for that GET request may be too long, and so you may need to call that
    # with a POST request. Setting this property to false loosens this
    # requirement and allows the POST request to invoke an action that is
    # supposed to only be called by a GET request.
    #
    jsonws.web.service.strict.http.method=false

    #
    # The property "jsonws.web.service.paths.excludes" denotes patterns for JSON
    # web service action paths that are not allowed even if they match one of
    # the patterns set in "jsonws.web.service.paths.includes".
    #
    jsonws.web.service.paths.excludes=

    #
    # The property "jsonws.web.service.paths.includes" denotes patterns for JSON
    # web service action paths that are allowed. Set a blank pattern to allow
    # any service action path.
    #
    jsonws.web.service.paths.includes=
##
## JSON Servlet
##

    #
    # See the properties "main.servlet.hosts.allowed" and
    # "main.servlet.https.required" on how to protect this servlet.
    #
    json.servlet.hosts.allowed=
    json.servlet.https.required=false

##
## JSON Web Service Servlet
##

    #
    # See the properties "main.servlet.hosts.allowed" and
    # "main.servlet.https.required" on how to protect this servlet.
    #
    jsonws.servlet.hosts.allowed=
    jsonws.servlet.https.required=false



Tips to find web service URL
  1. Login as admin into liferay portal
  2. And access http://localhost:8080/api/jsonws/ URL
  3. Find for your Service in Left side Menu
  4. Click on desired service
  5. Click on URL example there you can find web service URL

The following screen for access and find the portal JSON web services URLs



Portal JSON Webservice URL Pattern

To access the portal JSON web services we need to use following URL pattern




Server:

 It’s your domain name or host name if you are in local the its “localhost”

Port:

It’s your application server port number.

plugin-context:

 It’s our liferay portlet context and we will represent portal context simple with Slash (/)

api/jsonws:

This is path for call JSON Web Service servlet this is configured in liferay portal web.xml

service-class-name:

Service class name is a service entity name in service.xml file. We have different entries in liferay portal

service-method-name:

Service-method-name is generated from the service’s method name by converting its camel case to lower case and using dashes (-) to separate words

Finally our Complete URL like this for our get Cuntries method:




Portal context path
/
Web service servelet path
/api/jsonws
Service Class Name/service entity name
country
Service Method Name
getCuntiries(--) converted as get-countries



Passing parameters and its values:

We can pass parameters in two was
  1. Query String
  2. URL pattern and separated param name and value by slash(/)

Complete URL example with query string




Complete URL by URL pattern:




For Our Example Complete URL to access country by name and we passing name as url parameter.


http://localhost:8080/api/jsonws/country/get-country-by-name/name/india


Note:

The entire article we discussed about portal services and in the next article I will explain about Liferay Plugin Portlet JSON web services.

All above observation I have done in Liferay 6.2 CE versions so please make sure there may be small changes when use other versions.

More details about liferay JSON web services

Author

0 comments :

Post a Comment

Recent Posts

Recent Posts Widget

Popular Posts