Showing posts with label liferay web services. Show all posts
Showing posts with label liferay web services. Show all posts

Monday, May 5, 2014

Consuming Liferay JSON Web Services

Introduction:

Liferay have provided JSON web services to expose data to outside world. We can use different client to call liferay web services

In this article we will see the following clients
  1. Java Client Consuming Liferay Web services
  2. Ajax Client Consuming Liferay Web services

The following are Articles which talk about Liferay JSON web services.

Liferay 6.2 and 6.1

Liferay 6.0.6

Note:

Read above all articles so that we will have good experience with Liferay JSON web services.

Java Client Consuming Liferay Web services

We can also use pure java client to call Liferay JSON web services. We will use Apache Http Client to call these web services.

Liferay also have implements Android SDK which used Apache Http Client to Liferay JSON web services.

Apache http client is set of java classes to call normal Http URLs in java code.

Some time we may need to call http URLs from java code such scenarios we will use Apache Http Client libraries.

Now we will call Liferay JSON web services Using Apache Http Client.

The following is place you can download required Apache Http Client Jar files


Assume following is your web service URL and have one parameter

The following is Liferay JSON web service URL



Using Plugin Context

http://localhost:8080/LiferayJSONWebservices-portlet/api/jsonws/
employee/get-employee?emplyeeId=1

Using Portal Context

http://localhost:8080/api/jsonws/LiferayJSONWebservices-portlet.employee/get-employee?emplyeeId=1



Note:


In Liferay 6.1 we have used Plugin Context in the URL from Liferay 6.2 we directly used Portal context

The following is HTTP java client


public static void main(String[] args) throws ClientProtocolException,
IOException {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HttpHost targetHost = new HttpHost("localhost", 8080, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("test@liferay.com", "test"));
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
BasicHttpContext ctx = new BasicHttpContext();
// ctx.setAttribute(ClientContext.AUTH_CACHE,authCache);
// Plugin Context Use for Liferay 6.1
HttpPost post = new HttpPost("/LiferayJSONWebservices-portlet/api/jsonws/employee/get-employee");
// Portal Context Use for Liferay 6.2
// HttpPost post = new HttpPost("/api/jsonws/LiferayJSONWebservices-portlet.employee/get-employee");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("emplyeeId", "30722"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
post.setEntity(entity);
HttpResponse resp = httpclient.execute(targetHost, post, ctx);
resp.getEntity().writeTo(System.out);
httpclient.getConnectionManager().shutdown();
}


When you execute above code if you get Exception that Authenticated Access required then use following code


package com.meera.liferay;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
public class LiferayWebserviceClient {
     public static void main(String[] args) throws ClientProtocolException,
     IOException {
     ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
     HttpHost targetHost = new HttpHost("localhost", 8080, "http");
     DefaultHttpClient httpclient = new DefaultHttpClient();
     BasicHttpContext ctx = new BasicHttpContext();
     // Plugin Context Use for Liferay 6.1
     HttpPost post = new HttpPost("/LiferayJSONWebservices-portlet/api/jsonws/employee/get-employee");
     Base64 b = new Base64();
     String encoding = b.encodeAsString(new String("test@liferay.com:test").getBytes());
     post.setHeader("Authorization", "Basic " + encoding);
     List<NameValuePair> params = new ArrayList<NameValuePair>();
     params.add(new BasicNameValuePair("emplyeeId", "30722"));
     UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
     post.setEntity(entity);
     HttpResponse resp = httpclient.execute(targetHost, post, ctx);
     resp.getEntity().writeTo(System.out);
     httpclient.getConnectionManager().shutdown();
     }

}



Note:

In the code I have used Plugin context bases on your choice you can use Plugin Context or Portal Context. If you are using Liferay 6.2 then you can use Portal context in the URL.


Calling Portal Services Using Http Client

package com.meera.liferay;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
public class LiferayWebserviceClient {
     public static void main(String[] args) throws ClientProtocolException, IOException {
           HttpHost targetHost = new HttpHost("localhost", 8080, "http");
           DefaultHttpClient httpclient = new DefaultHttpClient();
           BasicHttpContext ctx = new BasicHttpContext();
           // Plugin Context Use for Liferay 6.1
           HttpPost post = new HttpPost("/api/jsonws/country/get-countries");
           Base64 b = new Base64();
        String encoding = b.encodeAsString(new String("test@liferay.com:test").getBytes());
        post.setHeader("Authorization", "Basic " + encoding);
           List<NameValuePair> params = new ArrayList<NameValuePair>();
           //params.add(new BasicNameValuePair("emplyeeId", "30722"));
           UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
           post.setEntity(entity);
           HttpResponse resp = httpclient.execute(targetHost, post, ctx);
           resp.getEntity().writeTo(System.out);
           httpclient.getConnectionManager().shutdown();

     }

}

Required Jar Files


commons-codec.jar
httpclient.jar
httpcore.jar
commons-logging.jar


Download Example and Required Jar files


Ajax Client Consumer Liferay JSON Web services

The following is simple Ajax Program Call liferay web service with Basic Authorization Header
The following example uses the get Employee JSON Web Services of Plugin portlet and in the alert it will show employee name. This is just example

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

The following is Liferay JSON web service URL


Using Plugin Context

http://localhost:8080/LiferayJSONWebservices-portlet/api/jsonws/
employee/get-employee?emplyeeId=1

OR

http://localhost:8080/LiferayJSONWebservices-portlet/api/jsonws/employee/get-employee/employee-id/1

Using Portal Context

http://localhost:8080/api/jsonws/LiferayJSONWebservices-portlet.employee/get-employee?emplyeeId=1

OR

http://localhost:8080/api/jsonws/LiferayJSONWebservices-portlet.employee/get-employee /employee-id/1



.
Note:

In Liferay 6.1 we have used Plugin Context in the URL from Liferay 6.2 we directly used Portal context

Here we are passing Authorization header type basic and we will encode 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/LiferayJSONWebservices-portlet/api/jsonws/employee/get-employee/employee-id/1',
                  dataType: "json",
                  type: "get",
                  success: function(data){
                          alert(data.employeeName);
                  },
                  beforeSend: function(xhr){
                          xhr.setRequestHeader('Authorization',make_base_auth(username, password));
                                    },
                                    complete: function(){
                                    },
                  error: function(){
                  }
                });
             
 });
</script>

           
Passing Parameters Values in Ajax call


<%@ 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/LiferayJSONWebservices-portlet/api/jsonws/ employee/get-employee',
                 data:{ emplyeeId:"1"}
                  dataType: "json",
                  type: "get",
                  success: function(data){
                          alert(data.employeeName);
                  },
                  beforeSend: function(xhr){
                          xhr.setRequestHeader('Authorization',make_base_auth(username, password));
                                    },
                                    complete: function(){
                                    },
                  error: function(){
                  }
                });
             
 });
</script>


Author

Wednesday, February 12, 2014

Liferay Plugin Portlet JSON Web Services Part-III

Before start this Article please go through following Article



Call Plugin Portlet JSON Web Services Using Plugin Portlet Context

We already developed portlet (in part-I) and once we deployed the portlet we will use portlet context to call Plugin portlet JSON web services.

Now we will use portlet context to call Plugin portlet JSON web services and here we are using portlet context so we need to configure JSON Web service servlet information in portlet web.xml file this is very important step when we want use Plugin Portlet Context to call web services and we will configure some filters too.

When we use Plugin portlet context we are the responsible for to pride authentication mechanism for web services.

In the web.xml file we need to specify the web service servlet and its URL pattern to invoke JSON Web service servlet.

The following is configuration we need to add in portlet web.xml file and web.xml file available in portlet WEB-INF directory.

Note:

The configuration and calling JSON web services using Plugin portlet context is successfully done for Liferay 6.1CE&EE.


In Liferay 6.2 it may be work however in Liferay 6.2 we can use Portal Context to call any JSON web services in Liferay and if we call web services using portal context it will use liferay portal secure mechanism to access web services.

The following is configuration and add in web.xml file of your portlet.

<filter>
         <filter-name>Secure JSON Web Service Servlet Filter</filter-name>
         <filter-class>com.liferay.portal.kernel.servlet.PortalClassLoaderFilter</filter-class>
         <init-param>
          <param-name>filter-class</param-name>
          <param-value>com.liferay.portal.servlet.filters.secure.SecureFilter</param-value>
         </init-param>
         <init-param>
          <param-name>basic_auth</param-name>
          <param-value>true</param-value>
         </init-param>
         <init-param>
          <param-name>portal_property_prefix</param-name>
          <param-value>jsonws.servlet.</param-value>
         </init-param>
       </filter>
       <filter-mapping>
         <filter-name>Secure JSON Web Service Servlet Filter</filter-name>
         <url-pattern>/api/jsonws/*</url-pattern>
       </filter-mapping>
       <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>

Once you add this in web.xml then deploy the portlet. Now we can use Plugin Portlet Context in Web service URLs.

The general URL pattern to call Plugin portlet JSON web services using Plugin Portlet Context as follows





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 plug-in portlet context name its simple as portlet name

api/jsonws:

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

service-class-name:

 service-class-name is generated from the service’s class name by removing the Service or ServiceImpl suffix and making it lower case. This is our service class name where we implemented custom method or it is simple the entity name which is in service.xml. In our example we implemented our method in EmployeeServiceImpl.java

Finally we have to use in URL as employee when we observe it’s just entity name in service.xml

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 Example:




Plugin context path
LiferayJSONWebservices-portlet
Web service servelet path
/api/jsonws
Service Class Name
EmployeeServiceImpl.java converted as employee
Service Method Name
getEmplyee(--) converted as get-employee



This is general URL pattern to call JSON web services using Plugin Portlet Context

Passing parameters and its values:

We can pass parameters in two was
  1. Query String
  2. URL Parameters

Query String

We can pass parameters as URL query string and here parameter names same as the names we have used in implementation of java method.

Query String URL Notation




Example:

public  com.meera.db.model.Employee getEmployee(long emplyeeId){
                                   
}

Web service URL with Query String Parameters As follows


Result:

{"employeeDesignation":"SoftwareEngineer",
"emplyeeId":1,"emplyeeName":"meera"}


URL Parameters

We can pass parameters to web service as URL parameters and here param name and values separated by slash (/). And here parameter notation will be based on the param names we have used in java implementation method and each capital letter in name will be separated by – and capital letter will become small latter.

URL pattern Web service Notation:




Example:

public  com.meera.db.model.Employee getEmployee(long emplyeeId){
                                   
}

Web service URL with Query String Parameters As follows


Result:

{"employeeDesignation":"SoftwareEngineer",
"emplyeeId":1,"emplyeeName":"meera"}


For Our Example Complete URL to access employee data by passing employee id is following like this



OR


Result:

{"employeeDesignation":"SoftwareEngineer",
"emplyeeId":1,"emplyeeName":"meera"}



Note:

 Some time its ask Authentication so we should pass admin credentials as URL headers
With authentication The URL like follow



OR


Result:

{"employeeDesignation":"SoftwareEngineer",
"emplyeeId":1,"emplyeeName":"meera"}



Important Portal Properties when we work with Liferay JSON web services

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


More information Please have look into following link


Note:

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

Calling Plugin Portlet JSON Web Service from Ajax

The following is simple Ajax Program Call Portal Service with Basic Authorization Header
The following example uses the get Employee JSON Web Services of Plugin portlet and in the alert it will show employee name. This is just example

Here you need look into 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 encode 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/LiferayJSONWebservices-portlet/api/jsonws/employee/get-employee/employee-id/1',
                  dataType: "json",
                  type: "get",
                  success: function(data){
                          alert(data.employeeName);
                  },
                  beforeSend: function(xhr){
                          xhr.setRequestHeader('Authorization',make_base_auth(username, password));
                                    },
                                    complete: function(){
                                    },
                  error: function(){
                  }
                });
             
 });
</script>
           
Passing Parameters Values in Ajax call

<%@ 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/LiferayJSONWebservices-portlet/api/jsonws/ employee/get-employee',
                 data:{ emplyeeId:"1"}
                  dataType: "json",
                  type: "get",
                  success: function(data){
                          alert(data.employeeName);
                  },
                  beforeSend: function(xhr){
                          xhr.setRequestHeader('Authorization',make_base_auth(username, password));
                                    },
                                    complete: function(){
                                    },
                  error: function(){
                  }
                });
             
 });
</script>

Note:

When we pass parameters values in Ajax call its nothing but passing parameters as query string URL so here we need to consider notation of passing parameters and its values in web service URL.

Passing parameters values as URL parameters are different from passing as query string.

Example:

Query String

?employeeId=1

URL Parameter

/employee-id/1


We can use Ajax code in HTML page or JSP page then you can see the result in alert.

Related Articles:




Author

Recent Posts

Recent Posts Widget

Popular Posts