Saturday, October 20, 2012

Build a RESTful Web service with Java

Representational state transfer (REST) is a architectural style of designing loosely coupled applications based on web-standards and the HTTP protocol. It relies on a stateless, client-server, cacheable communications protocol -- and in virtually all cases, the HTTP protocol is used.The hardest part of building a RESTful application is deciding on the resources you want to expose. Once you've done that, using the open source Restlet framework makes building RESTful Web services a snap. This tutorial guides you step-by-step through the fundamental concepts of REST and building applications with Restlets.

Step 1: Create a dynamic web project in Eclipse and add the jars shown in the figure in the lib folder under the WEB-INF



























Step 2: Add the Restful nature in the the project using fallowing entry in the 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>FirstProject</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  <servlet-name>ServletAdaptor</servlet-name>
  <servlet-class>
   com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>ServletAdaptor</servlet-name>
  <url-pattern>/REST/*</url-pattern>
 </servlet-mapping>
</web-app>


Step 3:Create the Employee class as fallows and annotted it with the @Path,@Produce and @Get annotations
package com.rajkrrsingh.blogspot;


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

@Path("/employee")
public class Employee {
 
 @GET
 @Produces(MediaType.TEXT_HTML)
 public String getEmployee(){
  return "<html> " + "<title>" + "Employee Details" + "</title>"
          + "<body><h1>" + "Employee Name is Dummy Employee" + "</body></h1>" + "</html> ";
 }

}

Step 4: now run the dynamic web application on the tomcat server and access the fallowing URL


http://localhost:8080/RESTfulProject/REST/employee


Here is the browser output


















Step 5:you can use jersy api or Apache HttpClient api to the test the webservice by creating a client,here I have created the client using the jersy api

package com.rajkrrsingh.blogspot.client;

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class Main {
 
 public static void main(String[] args) {
  ClientConfig config = new DefaultClientConfig();
     Client client = Client.create(config);
     WebResource service = client.resource(getBaseURI());
     System.out.println(service.path("REST").path("employee").accept(MediaType.TEXT_HTML).get(String.class));
  
 }
 
 private static URI getBaseURI() {
     return UriBuilder.fromUri("http://localhost:8080/RESTfulProject").build();
   }


}

After running this main class as a java application you will find the fallowing output on the console


<html> <title>Employee Details</title><body><h1>Employee Name is Dummy Employee</body></h1></html>

Sunday, October 14, 2012

Spring AOP Tutorial

Here I am going you to demonstrate a Spring AOP with the help of AspectJ,for that you need to create a java project in Eclipse and add the spring library apart from spring jar we need to have aspect jars in my class path for that reason I have created a AspectJ library and included the jars in the lib as shown in the figure.





















Step 2: Create Model class Mp3Player Class and the Tuner class as created here

package com.rajkrrsinghblogspot.model;

public class Mp3Player {
 
 private String mp3PlayerName;

 public String getMp3PlayerName() {
  return mp3PlayerName;
 }

 public void setMp3PlayerName(String mp3PlayerName) {
  this.mp3PlayerName = mp3PlayerName;
 }

}


Tuner.java

package com.rajkrrsinghblogspot.model;

public class Tuner {
 
 private String tunerName;

 public String getTunerName() {
  return tunerName;
 }

 public void setTunerName(String tunerName) {
  this.tunerName = tunerName;
 }

}


Step 2: Create the MusicService class as fallows:
package com.rajkrrsingh.blogspot.service;

import com.rajkrrsinghblogspot.model.Mp3Player;
import com.rajkrrsinghblogspot.model.Tuner;


public class MusicService {
 
 private Mp3Player mp3Player;
 private Tuner myTuner;
 
 public Mp3Player getMp3Player() {
  return mp3Player;
 }
 public void setMp3Player(Mp3Player mp3Player) {
  this.mp3Player = mp3Player;
 }
 public Tuner getMyTuner() {
  return myTuner;
 }
 public void setMyTuner(Tuner myTuner) {
  this.myTuner = myTuner;
 }
 
 
}


Step 3:Now create Aspect which are the focal point of the tutorial,in my case I am going to create a logging aspect as fallows in which I used annotation @Aspect to know the application that I am writing this class as Aspect,the @Before and @After annotation are used with my advice loggingAdvice and anothetLoggingAdvice these advice will run when the getMp3PlayerName() method will execute.look at the configuration that are self explanatory as well
package com.rajkrrsinghblogspot.aspect;
 
 import org.aspectj.lang.annotation.After;
 import org.aspectj.lang.annotation.Aspect;
 import org.aspectj.lang.annotation.Before;
 
 @Aspect
 public class MyLoggingAspect {
  
  @Before("execution(public String getMp3PlayerName())")
  public void loggingAdvice(){
   System.out.println("Advice : Before the extecution of the getMp3PlayerName Method");
  }
  
  @After("execution(public String getMp3PlayerName())")
  public void anothetLoggingAdvice(){
   System.out.println("Advice : After the extecution of the getMp3PlayerName Method");
  }
 
 }


Step 4: Create spring.xml in the src folder to configure all the beans in the application as shown
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
 xmlns:context="http://www.springframework.org/schema/context">

 <aop:aspectj-autoproxy/>
 
 <bean id="mp3ply" class="com.rajkrrsinghblogspot.model.Mp3Player">
  <property name="mp3PlayerName" value="Sony Mp3Player"/>
 </bean>
 
 <bean id="tuner" class="com.rajkrrsinghblogspot.model.Tuner">
  <property name="tunerName" value="Philipse"/>
 </bean>
 
 <bean id="musicService" class="com.rajkrrsingh.blogspot.service.MusicService" >
  <property name="mp3Player" ref="mp3ply"/>
  <property name="myTuner" ref="tuner"/>
 </bean>

 <bean id="myLogginAspect" class="com.rajkrrsinghblogspot.aspect.MyLoggingAspect" />
</beans>


Step 5: Now create Main class to test this out
package com.rajkrrsinghblogspot.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.rajkrrsingh.blogspot.service.MusicService;

public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {
  //BeanFactory factory = new XmlBeanFactory(new FileSystemResource("spring.xml"));
  
  ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
  MusicService ms = (MusicService) ctx.getBean("musicService");
  System.out.println(ms.getMp3Player().getMp3PlayerName());

 }

}


Step 6: we are all set now,run the main class: