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

Wednesday, October 10, 2012

Java Concurrency / Multithreading: Part 3

In Previous post (Java Concurrency / Multithreading :Part 2) learn how to initialize and use ExecutorService.

There are numerous problem domains where while designing the application you will need to implement the thread pool and each thread after completing the task, based on inputs should return a value. Futures and Callables exist exactly to solve this area.

Till now we have implemented the thread pool (in previous post) using the Runnables which do not return any value. In case a thread should return a value based on computation or work done as part of task you can use java.util.concurremt.Callable. Callable return value after execution. Callable returns an object of java.util.concurrent.Future. Future is used to check the status of task and return some value. Below is the example to use Callable and return a value

public class MyRunnable implements Callable<Long> {  
     @Override  
     public Long call() throw Exception {  
       return 5L;  
     }  
   } 

Using the Executor Framework

public class Example {

    public static void main(String[] args) {



        ExecutorService executor = Executors.newFixedThreadPool(5);

        List<Future<Long>> fList = new ArrayList<Future<Long>>();

        for (int i = 0; i < 999; i++) {

            Callable<Long> worker = new MyRunnable();

            Future<Long> submit = executor.submit(worker);

            fList.add(submit);

        }

        long sum = 0;



        for (Future<Long> future : fList) {

            try {

            sum += future.get();

            } catch (InterruptedException e) {

            e.printStackTrace();

            } catch (ExecutionException e) {

            e.printStackTrace();

            }

        }

        System.out.println("Final Sum is : " + sum);

        executor.shutdown();

    }

} 

Java Concurrency / Multithreading: Part 2

See my earlier post (Java Concurrency / Multithreading :Part 1) related to basics about java threads and concurrency.

Executor Framework

ThreadPools is the way to manage the pool of working threads and limit the creation of thread as creating a thread have resource overhead associates with it. Thus thread pools contains a work queue waiting for their turn to get executed.

In thread pool, the thread are constantly running and checking the queue for new work. As soon as the pool have a idle thread the work is assigned to one of the threads.

With Java 5 came Executor Framework under java.util.concurrent package, so that you do not need to create and manage your own pool e.g java.util.concurrent.Executor can be initialized as Executors.newfixedThreadPool(n) to create n worker threads. 

Like wise Executors.newSingleThreadExecutor(); will create a single thread pool with only one worker thread.

Example:
Creating a Runnable class
public class MyRunnable implements Runnable {
    private final long count;
    MyRunnable(long count) {
        this.count = count;
    }
    @Override
    public void run() {
        long mySum = 0;
        for (long i = 1; i < count; i++) {
            mySum = mySum + i;
        }
        System.out.println(mySum);
    }
}

Using the Executor Framework
public class Example {

    public static void main(String[] args) {

        ExecutorService executor = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 100; i++) {

            Runnable myworker = new MyRunnable(99999999L + i);

            executor.execute(myworker);

        }

        executor.shutdown();

        while (!executor.isTerminated()) {



        }

        System.out.println("Completed processing the work queue");

    }

} 


ExecutorService executor = Executors.newFixedThreadPool(5); creates a new pool of 5 worker threads.

executor.execute(myworker); adds new work in the queue for thread pool to complete.

executor.shutdown(); waits till all the work in the queue is completed. After calling this method the ExecutorService will not take any new task but once all the current tasks in the queue are complete the ExecutorService will shutdown.

To stop the ExecutorService immediately call shutdownNow() method.This will attempt to stop all executing tasks right away, and skips all submitted but non-processed tasks. There are no guarantees given about the executing tasks. Perhaps they stop, perhaps the execute until the end. It is a best effort attempt.

 executor.isTerminated() checks if the service is terminated or not.

Till now we have submitted the tasks to ExecutorService and never waited to get a return value after . Thus in case the threads should return some value then you should use java.util.concurrent.Callable. See my next post (Java Concurrency / Multithreading: Part 3) summarizing the above concept.

Tuesday, October 09, 2012

Java Concurrency / Multithreading :Part 1

Goal:

How to execute the tasks in background using Java concurrent programming. It also covers the concepts of threads, parallel programming, java.util.concurrent.Executor, java.util.concurrent.Future, java.util.concurrent.Callable framework.

Details:

What is Concurrency?

In computer world, concurrency means executing several programs simultaneously or in parallel and these programs may or may not interact with each other. Running several programs in parallel or asynchronously can add to over all performance of the task.

Process vs Threads

Both thread and process are methods of parallelizing the application. Below are the key points highlighting the differences between Process and Thread.

Process: are independent execution units. Applications are typically divided into various processes during the design phase. It cannot directly access shared data in other processes.However this is done by inter-process mechanism managed by operating system. A process might contain multiple threads.

Thread: are light weight processes and is the basic unit to which the operating system allocates processor time. A thread can execute any part of the process code, including parts currently being executed by another thread. . Every thread have its own memory cache.

Why Concurrency

  •  Efficient utilization of resources
  • Increased application throughput
  • High responsiveness
  •  Programs becomes simpler: as some of the problem domains are well suited to be represented as concurrent tasks

Disadvantages

  • With increased complexity the program design becomes more complex
  • Context Switching between threads, too many open threads will lead to context switching overheads causing the performance degrade

 Threads in Action

Threads are the core of all concurrent or parallel programing. There are 2 ways to implement thread in java.
The First one is extending java.lang.Thread class. Below is the way to create a thread:
Thread myThread =  new Thread();
Now after initialization , to start thread
myThread.start();

Create a subclass of Thread
public class CustomThread extends Thread{

 public void run(){
 System.out.println("Hello Thread");
}
}

Using the above class
CustomThread thread1 = new CustomThread();

thread1.start()
The second way is to implement the java.lang.Runnable interface.
public class MyRunnable implements Runnablee{
public void run (){

System.out.println("Hello Runnable"); 

} 

}
Using the above class
Thread thread1 =  new Thread(new MyRunnable);

thread1.start();
Next>>> Java Concurrency / Multithreading: Part 2