Saturday, November 10, 2012

Part 2: Accessing and Using Liferay JSON Web Services

In previous post, I have worked on introducing all basics about JSON Web Services.
In this post the focus is on accessing and consuming the the services and example

To Restrict a method from being exposed as service, just annotate the method with:
@JSONWebService(mode = JSONWebServiceMode.IGNORE)

To define custom HTTP method name instead of using the default, just annotate the method with:
@JSONWebService(value = "get-user", method = "GET")
public User getUserById( ...

Thus above service will be exposed and accessed as

http://localhost:8080/api/jsonws/user/get-user

instead of 

http://localhost:8080/api/jsonws/user/get-user-by-id

To further customize the URL and remove the serviceClassname, just annotate the method with:
@JSONWebService("/get-user")
public User getUserById(..

Thus above service will be exposed and accessed as

http://localhost:8080/api/jsonws/get-user

instead of 

http://localhost:8080/api/jsonws/user/get-user-by-id

Portal Configuration

JSON Web Services can be enabled or disabled by setting the below portal property:
json.web.service.enabled=true
by default the services are enabled and the property is set to true.

Enabling/Disabling particular HTTP methods
jsonws.web.service.invalid.http.methods=DELETE,POST,PUT
causes portal to accept only GET requests and ignore the HTTP methods specified above.

Below is the comma separated list of public service methods that can be accessed by unauthenticated user:
For all methods as unauthenticated use below
jsonws.web.service.public.methods=*  
For is methods as unauthenticated use below

jsonws.web.service.public.methods=is*

Accessing service via HTML form


<form action="http://localhost:8080/api/jsonws/user/get-user-by-id" method="GET">
        <input type="hidden" name="userId" value="10172"/>
        <input type="submit" value="submit"/>
</form>
When submitted will result in response consisting of User object as JSON string.

Accessing service via Java based Apache HttpClient API 

Below is the example to access the Liferay services using the Apache HTTPClient API
public static void get() throws Exception {
  HttpHost targetHost = new HttpHost("localhost", 8080, "http");
  DefaultHttpClient httpclient = new DefaultHttpClient();
  httpclient.getCredentialsProvider().setCredentials(
    new AuthScope(targetHost.getHostName(), targetHost.getPort()),
    new UsernamePasswordCredentials("test", "test"));

  // Create AuthCache instance
  AuthCache authCache = new BasicAuthCache();
  // Generate BASIC scheme object and add it to the local
  // auth cache
  BasicScheme basicAuth = new BasicScheme();
  authCache.put(targetHost, basicAuth);

  // Add AuthCache to the execution context
  BasicHttpContext ctx = new BasicHttpContext();
  ctx.setAttribute(ClientContext.AUTH_CACHE, authCache);

  HttpPost post = new HttpPost(
    "/api/jsonws/user/get-user-by-id"); 
  List<NameValuePair> params = new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("userId", "10172"));
  
  UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
  post.setEntity(entity);
  HttpResponse resp = httpclient.execute(targetHost, post, ctx);
  System.out.println(resp.getStatusLine());
  resp.getEntity().writeTo(System.out);
  httpclient.getConnectionManager().shutdown();
 }


When submitted will result in response consisting of User object as JSON string.

Go to  Next post Part 3: Custom Liferay Plugin JSON Web Services

References:
The article is my summarized view while working on the topic and references have been taken from Liferay community and documentation

Part 1: Introduction Liferay JSON Web Services

JSON Web Services provide convenient way access to portal service layer methods by exposing them as JSON HTTP API. This makes services methods easily accessible using HTTP requests, not only from JavaScript within the portal, but also from any JSON-speaking client.

Registering JSON web services


While using Service Builder to build services via service.xml append each entity definition with remote-service="true" to create and enable web services for the entity.  By doing this All remote-enabled services (i.e. entities with remote-service="true" in service.xml) are exposed as JSON Web Services.

When Service Builder creates each -Service.java interface for a remote-enabled service, the @JSONWebService annotation is added on the class level of that interface. Therefore, all of the public methods of that interface become registered and available as JSON Web Services.

On server startup a restricted scanning is done on portal and service jar files for the classes that uses @JSONWebService annotation. Post this the annotation are loaded and service methods are exposed as JSON based API.

For example UserService looks as below:
@JSONWebService
public interface UserService{
...
}

 Accessing Services

Below is the convention used to access any service exposed by default Liferay bundle
http://[server]:[port]/api/jsonws/[service-class-name]/[service-method-name] 
service-class-name is the name generated from service class name, 
by removing the Service or ServiceImpl suffix and converting it to a 
lowercase name.
service-method-name is generated from the service method name, 
by converting the camel-case method name to a lowercase separated-by-dash name
For example UserService can be accessed as:
@JSONWebService
public interface UserService{

 public User getUserById(long userId) {...}
}


http://localhost:8080/api/jsonws/user-service/get-user-by-id

All methods prefixed with get, has, is are pre assumed to be readonly and thus are exposed as GET methods, leaving rest as POST methods.

Non-public service methods require the user to be registered before invoking the method and accessed as

http://[server]:[port]/api/secure/jsonws/[service-class-name]/[service-method-name]http://localhost:8080/api/jsonws/user-service/get-user-by-id

Viewing list of default liferay bundle service

You can view all the registered and available service listing ay accessing the below url
http://localhost:8080/api/jsonws
 
In my next post, I have further detailed about configuring and 
accessing the JSON Web services 
 
References:
The article is my summarized view while working on the topic and references have been taken from Liferay community and documentation