Sunday 23 February 2014



Readers would be pleased to know that I have teamed up with Packt Publishing  to organize a Giveaway of the new book that I have written -  Developing RESTful Web Services with Jersey 2.0.

And three lucky winners stand a chance to win 3 digital copies of this book. Keep reading to find out how you can be one of the Lucky Winners.

Overview:


 


·         Implement web services using different HTTP methods and *Param Annotations
·         Create resource and sub-resource methods
·         Understand the different rules of injection and the scope of the root resource classes
·         Explore different deployment processes of applications
·         Consume web services along with different HTTP methods and *Param Annotations
·         Get acquainted with different media representations (JSON, XML, and Multipart)
·         Send/push data events from server to client
·         Generate WADL specification


How to Enter?
All you need to do is head on over to the book page and look through the product description of the book and drop a line via the comments below this post to let us know what interests you the most about this book. It’s that simple.

Winners will get an e-copy of the Book.

Deadline

The contest will close on 28th Feb, 2014. Winners will be contacted by email, so be sure to use your real email address when you comment!



































Friday 6 September 2013

JAX-RS is a framework designed to help you write RESTful applications both on the client and server side. Jersey 2.0 which provides Reference Implementation for JAX-RS 2.0.


Jersey 2.0 provides support for Java SE HTTP Server, Grizzly 2 HTTP server, Servlet 2.5 or higher containers as well as OSGi containers on the server side and HTTPURLConnection - based or Grizzly asynchronous client transport connectors. To leverage JAX-RS/Jersey server-side async features in a Servlet container, you need a container that supports Servlet 3.0 at least. Jersey supports asynchronous resource invocations on Grizzly 2 HTTP server too.


Basic JAX-RS 2.0 Example:

Project Structure




web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>JAX-RS-2.0_HelloWorld</display-name>
  <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.example</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>
</web-app>




MyResource.java

package com.example;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 * Root resource (exposed at "myresource" path)
 */
@Path("myresource")
public class MyResource {

    /**
     * Method handling HTTP GET requests. The returned object will be sent
     * to the client as "text/plain" media type.
     *
     * @return String that will be returned as a text/plain response.
     */
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getIt() {
        return "Got it!";
    }
}



index.jsp

<html>
<body>
    <h2>Jersey RESTful Web Application!</h2>
    <p><a href="webapi/myresource">Jersey resource</a>
    <p>Visit <a href="http://jersey.java.net">Project Jersey website</a>
    for more information on Jersey!
</body>
</html>


Running on Apache Tomcat Server



Clicking on "Jersey resource" link will call MyResource web service



Thats all !!!

Friday 26 July 2013


Restlet is a lightweight, comprehensive, open source REST framework for the Java platform. Restlet is suitable for both server and client Web applications. It supports major Internet transport, data format, and service description standards like HTTP and HTTPS, SMTP, XML, JSON, Atom, and WADL. A GWT port of the client-side library is also available. (Reference: http://en.wikipedia.org/wiki/Restlet)

Hello World Example

  • Project Structure


  • RestletApplication.java


package com.restlet.demo.application;

import org.restlet.Application;
import org.restlet.Restlet;
import org.restlet.routing.Router;

import com.restlet.demo.resource.HelloWorldResource;

public class RestletApplication extends Application{ 
    public synchronized Restlet createInboundRoot() {
        Router router = new Router(getContext());
        router.attach("/helloWorld",HelloWorldResource.class );
        return router;
    }
}


  • ResponseParseFactory.java

package com.restlet.demo.core;

import java.util.LinkedHashMap;

import org.apache.log4j.Logger;
import org.json.simple.JSONValue;

public class ResponseParseFactory {
 
 static Logger logger = Logger.getLogger(ResponseParseFactory.class);

 @SuppressWarnings({ "rawtypes", "unchecked" })
 public String getFailureJsonString(String msg){
  String jsonString = "";
  LinkedHashMap list = new LinkedHashMap();
  list.put("response_status", "false");
  
  list.put("result", msg+"");
  jsonString = JSONValue.toJSONString(list);
  logger.info(jsonString);
  return jsonString;
 }
 
 @SuppressWarnings({ "rawtypes", "unchecked" })
 public String getSuccessJsonString(String msg){
  String jsonString = "";
  LinkedHashMap list = new LinkedHashMap();
  list.put("response_status","true");

  list.put("result", msg);
  jsonString = JSONValue.toJSONString(list);
  logger.info(jsonString);
  return jsonString;
 }
}

  • BaseResource.java

package com.restlet.demo.resource;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Parameter;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;

import com.restlet.demo.core.ResponseParseFactory;

public abstract class BaseResource extends ServerResource{

  protected ResponseParseFactory parseFactory = null;
  protected Logger logger = Logger.getLogger(BaseResource.class);
  String jsonString="";
  
 @SuppressWarnings("rawtypes")
 @Post("json")
 public Representation doPost(Representation entity){
  Map json =null;
  jsonString = "";
  parseFactory = new ResponseParseFactory();
  try {
   JsonRepresentation represent = new JsonRepresentation(entity);
   JSONObject jsonobject = represent.getJsonObject();
   JSONParser parser = new JSONParser();
   String jsonText = jsonobject.toString();
   json = (Map) parser.parse(jsonText);
   jsonString = processRequest(json,"post");
  } catch (Exception e) {
   e.printStackTrace();
   jsonString = parseFactory.getFailureJsonString(e.getMessage());
  }
  return new StringRepresentation(jsonString, MediaType.APPLICATION_JSON);
 }
 
 
 @SuppressWarnings("rawtypes")
 @Get
 public Representation doGet(){
  Map json =null;
  parseFactory = new ResponseParseFactory();
  jsonString = "";
  try {
   json = getMapFromParam(getRequest().getResourceRef().getQueryAsForm());
   parseFactory = new ResponseParseFactory();
   jsonString = processRequest(json,"get");

  } catch (Exception e) {
   e.printStackTrace();
   jsonString = parseFactory.getFailureJsonString(e.getMessage());
  }
  return new StringRepresentation(jsonString, MediaType.APPLICATION_JSON);
 }
 
 public abstract String processRequest(Map json,String method);
  
 public static Map<String, String> getMapFromParam(Form form) {
  Map<String, String> map = new HashMap<String, String>();
  for (Parameter parameter : form) {
   map.put(parameter.getName(), parameter.getValue());
  }
  return map;
 }
 
}


  • HelloWorldResource.java

package com.restlet.demo.resource;

import java.util.Map;

import com.restlet.demo.core.ResponseParseFactory;

public class HelloWorldResource extends BaseResource {

 public String processRequest(Map json, String method) {
  String returnString = "" ;
  returnString = new ResponseParseFactory().getSuccessJsonString("Hello " + json.get("user"));
  return returnString;
 }
}

  • log4j.properties

# -----------------------------
# Appender to write to console.
# -----------------------------
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
log4j.appender.CONSOLE.file =${catalina.base}/logs/regularLogging.log
log4j.appender.CONSOLE.MaxFileSize=100KB

# ---------------------------------------------
# Appender to write to application log.
# ---------------------------------------------
log4j.appender.APPLICATIONLOG=org.apache.log4j.DailyRollingFileAppender
log4j.appender.APPLICATIONLOG.File=${catalina.base}/logs/restlet-demo.log
log4j.appender.APPLICATIONLOG.DatePattern='.'yyyy-MM-dd
#log4j.appender.APPLICATIONLOG.File=/home/devphp/public_html/restletframework/logs/APPLICATION-LOG.log
log4j.appender.APPLICATIONLOG.Encoding=UTF-8
log4j.appender.APPLICATIONLOG.layout=org.apache.log4j.PatternLayout
log4j.appender.APPLICATIONLOG.layout.ConversionPattern=%d [%5p]: %m%n

# Turn off root logging.
#log4j.rootLogger=info, APPLICATIONLOG
log4j.rootLogger=info, CONSOLE , APPLICATIONLOG


  • web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>RestletDemo</display-name>
 <servlet>
  <servlet-name>RestletServlet</servlet-name>
  <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>
  <init-param>
   <param-name>org.restlet.application</param-name>
   <param-value>com.restlet.demo.application.RestletApplication</param-value>
  </init-param>
 </servlet>
 <servlet-mapping>
  <servlet-name>RestletServlet</servlet-name>
  <url-pattern>/service/*</url-pattern>
 </servlet-mapping>
</web-app>


  • Calling Hello World Web Service


Thanks

Thursday 11 July 2013






Introduction


  • Apache CouchDB, commonly referred to as CouchDB, is an open source database that focuses on ease of use and on being "a database that completely embraces the web".
  • It is a NoSQL database that uses JSON to store data, JavaScript as its query language using MapReduce and HTTP for an API.
  • One of its distinguishing features is multi-master replication.
  • Couch is an acronym for cluster of unreliable commodity hardware
  • A CouchDB database lacks a schema, or rigid pre-defined data structures such as tables. Data stored in CouchDB is a JSON document(s).
  • The structure of the data, or document(s), can change dynamically to accommodate evolving needs.
  • CouchDB also offers a built-in administration interface accessible via web called Futon.

Main features



  • Document Storage:
    • CouchDB stores data as "documents", as one or more field/value pairs expressed as JSON. Field values can be simple things like strings, numbers, or dates; but ordered lists and associative arrays can also be used. Every document in a CouchDB database has a unique id and there is no required document schema.


  • ACID Semantics:
    • CouchDB provides ACID semantics. It does this by implementing a form of Multi-Version Concurrency Control, meaning that CouchDB can handle a high volume of concurrent readers and writers without conflict.


  • Map/Reduce Views and Indexes:
    • The stored data is structured using views. In CouchDB, each view is constructed by a JavaScript function that acts as the Map half of a map/reduce operation. The function takes a document and transforms it into a single value which it returns. CouchDB can index views and keep those indexes updated as documents are added, removed, or updated.


  • Distributed Architecture with Replication:
    • CouchDB was designed with bi-direction replication (or synchronization) and off-line operation in mind. That means multiple replicas can have their own copies of the same data, modify it, and then sync those changes at a later time.


  • REST API:
    • All items have a unique URI that gets exposed via HTTP. REST uses the HTTP methods POST, GET, PUT and DELETE for the four basic CRUD (Create, Read, Update, Delete) operations on all resources.


  • Eventual Consistency:
    • CouchDB guarantees eventual consistency to be able to provide both availability and partition tolerance.


  • Built for Offline:
    • CouchDB can replicate to devices (like smartphones) that can go offline and handle data sync for you when the device is back online.


  • Schema-Free:
    • Unlike SQL databases, which are designed to store and report on highly structured, interrelated data, CouchDB is designed to store and report on large amounts of semi-structured, document oriented data. CouchDB greatly simplifies the development of document oriented applications, such as collaborative web applications.
    • In an SQL database, the schema and storage of the existing data must be updated as needs evolve. With CouchDB, no schema is required, so new document types with new meaning can be safely added alongside the old. However, for applications requiring robust validation of new documents custom validation functions are possible. The view engine is designed to easily handle new document types and disparate but similar documents.


Installation (Ubuntu)



  • Open terminal and execute
sudo apt-get install couchdb -y


  • If the aptitude/apt-get installation gives an error message then couchdb might not have access to its pid file.


  • Fix:
sudo chown -R couchdb /var/run/couchdb
  • Need to rerun the setup script:
sudo dpkg --configure couchdb




For Verifying CouchDB, check on Futon: http://127.0.0.1:5984/_utils/index.html

*For installation on other Operating Systems - http://wiki.apache.org/couchdb/Installation


CouchDB Java Client



  • Ektorp


  • JRelax


  • jcouchdb


  • DroidCouch


  • CouchDB4J


  • LightCouch



CouchDB4J Example



  • CouchDB4J is an updated Java library for CouchDB.
  • It handles the REST style calls to the CouchDB server behind the scenes, and give you a handle on the JSON objects directly.
  • CouchDB4J uses JSON-lib to handle mapping to/from JSON objects, which makes getting/setting properties on the objects very easy.
  • You can even map Java objects to JSON objects and back to make the process easier.
  • Example:


Structure:


CouchDBCompleteDemo.java



package com.couchdb.demo;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.util.List;

import java.util.Map;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import org.json.simple.JSONValue;

import com.fourspaces.couchdb.Database;

import com.fourspaces.couchdb.Document;

import com.fourspaces.couchdb.Session;

import com.fourspaces.couchdb.ViewResults;

public class CouchDBCompleteDemo {

   static Session dbSession ;

   static Database db;

   

   public static void main(String[] args) {

       String dbName = "foodb";

       createDatabase(dbName);

       

       saveDocument(getDocument("1", "Willian", "J2EECOE", "TL", "Android"));

       saveDocument(getDocument("2", "Joanne", "J2EECOE", "Developer", "Java"));

       saveDocument(getDocument("3", "suzzane", "J2EECOE", "Sr. Developer", "Java"));

       saveDocument(getDocument("4", "Harley", "J2EECOE", "Sr. Developer", "Java"));

       saveDocument(getDocument("5", "Julian", "J2EECOE", "Developer", "Java"));

       saveDocument(getDocument("6", "Peter", "J2EECOE", "Developer", "Java"));

       getTotalDocumentCount();

       viewAllDocuments();

       viewsDemo();

//        deleteDocument("6");

//        getTotalDocumentCount();

//        deleteDatabase(dbName);

       

   }

   public static void createDatabase(String dbName){

       dbSession = new Session("localhost", 5984);

       db = dbSession.createDatabase(dbName);

       if(db==null)

           db = dbSession.getDatabase(dbName);

   }

   public static Document getDocument(String id,String name,String group,String designation,String language){

       Document doc = new Document();

       doc.setId(id);

       doc.put("EmpNO", id);

       doc.put("Name", name);

       doc.put("Group", group);

       doc.put("Designation", designation);

       doc.put("Language", language);

       return doc;

   }

   

   public static void saveDocument(Document doc){

       try {

           db.saveDocument(doc);

       } catch (Exception e) {

       }

   }

   

   public static int getTotalDocumentCount(){

       int count = db.getDocumentCount();

       System.out.println("Total Documents: " + count);

       return count;

   }

   

   public static void deleteDocument(String id){

       Document d = db.getDocument(id);

       System.out.println("Document 1: " + d);

       db.deleteDocument(d);

   }

   

   public static void deleteDatabase(String dbName){

       dbSession.deleteDatabase(dbName);

   }

   public static void viewAllDocuments(){

       ViewResults results = db.getAllDocuments();

       List<Document> documentsList = results.getResults();

       if(documentsList!=null)

       {

           for(Document doc : documentsList)

           {

               System.out.println(doc.get("id") + " : " +  doc);

           }

       }

   }

   

   public static void viewsDemo(){

       if(db!=null)

       {

Document doc = null;

           try {

               doc = db.getDocument("_design/couchview");

           } catch (Exception e1) {

               doc = null;

           }

           try {

               if(doc==null)

               {

                   doc = new Document();

                   doc.setId("_design/couchview");

                   String str = "{\"javalanguage\": {\"map\": \"function(doc) { if (doc.Language == 'Java')  emit(null, doc) } \"}, \"java_and_se\": {\"map\": \"function(doc) { if (doc.Language == 'Java' & doc.Designation == 'SE')  emit(null, doc) } \"}}";

                   doc.put("views", str);

                   db.saveDocument(doc);

               }

           } catch (Exception e) {

           }

       }

       

       try {

           DefaultHttpClient httpclient = new DefaultHttpClient();

           

           HttpGet get = new HttpGet("http://localhost:5984/foodb/_design/couchview/_view/javalanguage");

           HttpResponse response = httpclient.execute(get);

           HttpEntity entity=response.getEntity();

           InputStream instream = entity.getContent();

           

           BufferedReader reader = new BufferedReader(new InputStreamReader(instream));

           String strdata = null;

           String jsonString = "" ;

           while( (strdata =reader.readLine())!=null)

           {

//                   System.out.println(strdata);

                  jsonString += strdata;

           }

           

           System.out.println("Json String: " + jsonString);

           Map<String, Object> jsonMap = getMapFromJsonString(jsonString);

           

           if(jsonMap!=null)

           {

               System.out.println("total_rows: " + jsonMap.get("total_rows"));

               System.out.println("offset: " + jsonMap.get("offset"));

               List<Map> rowsList = (List<Map>) jsonMap.get("rows");

               if(rowsList!=null)

               {

                   for(Map row: rowsList)

                   {

                       System.out.println("----------------");

                       System.out.println("Id: " + row.get("id"));

                       System.out.println("Value: " + row.get("value"));

                       System.out.println("Name: " + ((Map)row.get("value")).get("Name"));

                       System.out.println("_id: " + ((Map)row.get("value")).get("_id"));

                       System.out.println("Language: " + ((Map)row.get("value")).get("Language"));

                       System.out.println("EmpNO: " + ((Map)row.get("value")).get("EmpNO"));

                       System.out.println("Designation: " + ((Map)row.get("value")).get("Designation"));

                       System.out.println("Group: " + ((Map)row.get("value")).get("Group"));

                   }

               }

           }

       } catch (ClientProtocolException e) {

           e.printStackTrace();

       } catch (IllegalStateException e) {

           e.printStackTrace();

       } catch (IOException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }    

   }

   

   public static Map<String, Object> getMapFromJsonString(String jsonString){

       Map<String, Object> jsonMap = (Map<String, Object>) JSONValue.parse(jsonString);

       System.out.println("Json Map: " + jsonMap);

       return jsonMap;

   }
}
Find me on Facebook! Follow me on Twitter!