Monday, June 29, 2015

Access Webserice - REST

once web service up and running we need to test that app. Alos when we are given end point of REST web app we need to verify.
We can just type the URI and get the details or response given from REST web service.
IF we get the URI for GET request for the example app We built,

http://localhost:8080/Rest/rest/employeeservices/getemployeedetail?employeeId=1

accessing through browser will give us the output

<employee>
<dateOfJoining>01-02-2001</dateOfJoining>
<department>Sales</department>
<email>test@example.com</email>
<employeeId>675436</employeeId>
<firstName>John</firstName>
<lastName>Smith</lastName>
</employee>


but here we don't have much options.
here we get the output in xml format. But if you can remember our service implementation it produces both "xml" and "json"

Thursday, June 25, 2015

Creating WebService

Let's create a web service.
We will use maven as build tool and it will makes our life easy.
I will be using STS , Spring Tool Suite.

First we create a maven  web project using STS.
It will have below structure.
Web Project structure



you can build war file using maven tool.
Go to folder where "pom.xml" file exists. and open a command window
execute the maven command

===============
mvn clean package
==============

above command will build the war file.
eg: Here my folder path is "C:\eclipseWorkSpace\2015-01-19_SpringSecurity\Rest>"  where "pom.xml" file reside and remember this the basic web project create with maven using STS. you can create a web project using maven commands directly also. So when i execute the command "mvn clean package " in the command line I have to change the directory to the above mention folder where "pom.xml" resides.
you will see the war file will be created inside target directory. "C:\eclipseWorkSpace\2015-01-19_SpringSecurity\Rest\target"

Web project structure after building war file - Rest.war created

Now get the war file and deploy in the tomcat.
to deploy copy "Rest.war" and paste it inside "webapps" folder inside tomcat.

To refresh your knowledge in tomcat, we can get the tomcat from site and unzip and go to "bin" folder
Here in my case it is "C:\Softwares\Apache\Apache Tomcat\Apache Tomcat 8.0.3\apache-tomcat-8.0.3\bin" and open commad window. set the path to bin directory. execute the command "catalina.bat run"

===================================
C:\Softwares\Apache\Apache Tomcat\Apache Tomcat 8.0.3\apache-tomcat-8.0.3\bin>catalina.bat run
===================================

you will see the starting of the tomcat and trace will shown in the same command window.
If you need you can also run "startup " also, but it will have a seperate window open and run tomcat.

Now you application is deployed in tomcat and to test open browser and type "http://localhost:8080/Rest/" and you will see the default message or default page created with the app showing "Hello World!" in the browser.

Steps we did so far
========
1. create a maven web project using STS
2. build the project using maven - command line "mvn clean package"
3. deploy the web project "war file" in the  tomcat and view in the browser.

Above are the simple steps to create a default web project , pakage war file , deploy and test whether create project really works.

Below are the inside of the files created in the web project. Initially we do not have lots of files only basic files and folder structure will be as shown above and i won't try to explain it again.

Web.xml
======================================================================
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
</web-app>
======================================================================

index.jsp
======================================================================
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
======================================================================

pom.properties
======================================================================
#Generated by Maven
#Fri Jun 26 10:41:37 IST 2015
version=0.0.1-SNAPSHOT
groupId=com.webservice.rest
artifactId=Rest

======================================================================

pom.xml
======================================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.webservice.rest</groupId>
  <artifactId>Rest</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Rest Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>Rest</finalName>
  </build>
</project>
======================================================================

Now let's go to create the web service application.
Here we use Apache CXF , spring , Jaxon, JAXB

First I will add all coding 

REST Web Service
---------------------
All dependencies

Pom.xml
======================================================================
<modelVersion>4.0.0</modelVersion>
<groupId>com.webservice.rest</groupId>
<artifactId>Rest</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT&lt;/version>
<name>Rest Maven Webapp</name>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope&gt;
</dependency>

<!-- Spring Dependencies -->
<dependency>
<groupId>org.springframework</groupId&gt;
<artifactId>spring-core&lt;/artifactId>
<version>4.1.2.RELEASE&lt;/version>
</dependency>
<dependency>
<groupId>org.springframework</groupId&gt;
<artifactId>spring-context</artifactId>
<version>4.1.2.RELEASE&lt;/version>
</dependency>
<dependency>
<groupId>org.springframework</groupId&gt;
<artifactId>spring-web&lt;/artifactId>
<version>4.1.2.RELEASE&lt;/version>
</dependency>
<dependency>
<groupId>org.springframework</groupId&gt;
<artifactId>spring-beans</artifactId>
<version>4.1.2.RELEASE&lt;/version>
</dependency>

<!-- XML dependency -->
<dependency>
<groupId>javax.xml.bind&lt;/groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>

<!-- Apache CXF Dependencies -->
<dependency>
<groupId>org.apache.cxf&lt;/groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId&gt;
<version>2.7.13</version>
</dependency>
<dependency>
<groupId>org.apache.cxf&lt;/groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>2.7.13</version>
</dependency>
<dependency>
<groupId>org.apache.cxf&lt;/groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>2.7.13</version>
</dependency>
<dependency>
<groupId>org.apache.cxf&lt;/groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId&gt;
<version>2.7.13</version>
</dependency>
<!-- Jackson The JSON Producer dependency -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.13</version>
</dependency>
</dependencies>
<build>
<finalName>Rest</finalName>
</build>
</project>

======================================================================

web.xml
======================================================================
<?xml version="1.0" encoding="UTF-8"?>
id="WebApp_ID" version="3.0">


<display-name>Archetype Created Web Application</display-name&gt;

<welcome-file-list>
<welcome-file>index.jsp&lt;/welcome-file>
</welcome-file-list>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/beans.xml</param-value>
</context-param>

<servlet>
<servlet-name>CXFServlet</servlet-name&gt;
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class&gt;
</servlet>

<servlet-mapping>
<servlet-name>CXFServlet</servlet-name&gt;
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

</web-app>

======================================================================

Employee.java    -->model class
======================================================================
package com.rest.cxfrestservice.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "employee")
public class Employee {
private String firstName;
private String lastName;
private String employeeId;
private String email;
private String dateOfJoining;
private String department;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmployeeId() {
return employeeId;
}

public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getDateOfJoining() {
return dateOfJoining;
}

public void setDateOfJoining(String dateOfJoining) {
this.dateOfJoining = dateOfJoining;
}

public String getDepartment() {
return department;
}

public void setDepartment(String department) {
this.department = department;
}

}

======================================================================

EmployeeDao .java --> dao class
======================================================================
package com.rest.cxfrestservice.dao;

import com.rest.cxfrestservice.model.Employee;

public class EmployeeDao {
public Employee getEmployeeDetails(String employeeId) {
Employee emp = new Employee();
emp.setDateOfJoining("01-02-2001");
emp.setDepartment("Sales");
emp.setEmail("test@example.com");
emp.setEmployeeId("675436");
emp.setFirstName("John");
emp.setLastName("Smith");
return emp;
}
}

======================================================================

CxfRestService .java  -->  Interface for Employee Service.
======================================================================
package com.rest.cxfrestservice.service;

import javax.jws.WebService;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 * Interface for Employee Service.
 * 
 * @author APRASAD
 * 
 */

@Path("/")
@WebService(name="employeeService" , targetNamespace="http://localhost/cxf-rest/example")
public interface CxfRestService {

@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/getemployeedetail")
public Response getEmployeeDetails(
@QueryParam("employeeId") String employeeId);
}

======================================================================

CxfRestServiceImpl .java --> implementation of for Employee Service.
======================================================================
package com.rest.cxfrestservice.service;

import javax.ws.rs.core.Response;

import org.springframework.beans.factory.annotation.Autowired;

import com.rest.cxfrestservice.dao.EmployeeDao;

public class CxfRestServiceImpl implements CxfRestService {

@Autowired
private EmployeeDao employeeDao;

public Response getEmployeeDetails(String employeeId) {
if (employeeId == null) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
return Response.ok(employeeDao.getEmployeeDetails(employeeId)).build();
}
}

======================================================================

bean.xml
======================================================================

<import resource="classpath:META-INF/cxf/cxf.xml" />
<context:component-scan base-package="com.rest.*" />

<jaxrs:server id="employeeService" address="/employeeservices"&gt;
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</jaxrs:providers>
<jaxrs:serviceBeans>
<ref bean="cxfServiceImpl" />
</jaxrs:serviceBeans>
<jaxrs:extensionMappings&gt;
<entry key="xml" value="application/xml" />
<entry key="json" value="application/json" />
</jaxrs:extensionMappings&gt;
</jaxrs:server>

<bean id="cxfServiceImpl" class="com.rest.cxfrestservice.service.CxfRestServiceImpl" />
<bean id="employeeDao" class="com.rest.cxfrestservice.dao.EmployeeDao" />
</beans>
======================================================================


access above depolyed jar with


you will get out as

======================================================================
<employee>
<dateOfJoining>01-02-2001</dateOfJoining>
<department>Sales</department>
<employeeId>675436</employeeId>
<firstName>John</firstName>
<lastName>Smith</lastName>
</employee>
======================================================================



======================================================================

<grammars/>
<resource path="/">
<resource path="getemployeedetail">
<method name="GET">
<request>
<param name="employeeId" style="query" type="xs:string"/>
</request>
<response>
<representation mediaType="application/xml"/&gt;
<representation mediaType="application/json"/&gt;
</response>
</method>
</resource>
</resource>
</resources>
</application>
======================================================================

Tuesday, May 5, 2015

Error in Running Java Project in Eclipse

I got the below error in my eclipse. The reason is I have selected a compiler and run time (jre) in two different versions.


-------------------------------------------------------------------------------
Exception in thread "main" java.lang.UnsupportedClassVersionError: com/concurrency/RunnableWithLamda : Unsupported major.minor version 52.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
----------------------------------------------------------------------------------------------


To solve the above error.
First go to
select the project --> right cick
go to "Properties" --> select java compiler .... let's say we have selected 1.8
Then   in below you will see a message that JRE is set to some version eg:1.7
So change it to 1.8 or higher version than the compiler version

In my case I have given 1.8 version for compiler and 1.7 for the JRE.

Important : UnsupportedClassVersionError
when you get the above mentioned error, always look for the JRE version you have selected.
mostly this error may come due to JRE version lower being lower than the compiler version.


Monday, April 20, 2015

Modules and Routes

This summary is not available. Please click here to view the post.

Friday, April 17, 2015

Creating View and Controller

this is the second article continue with angular basics and followed with the http://cgenit.blogspot.com/2015/04/angular.html

Here we are going to discuss the first major concept, View and controller.
Angular provides a nice mechanism called view and controller which enhances the readability and re-usability of the code.

controller has the data and the function. controller bind to view with something called $scope.
This is the glue between controller and the view.
Controller need not to know anything about the View and View does not want to know anything about the Controller. This achieved simply by using the concept of $scope.

angular has lots of objects defined with the $ sign and you will see them as you dig up more with the angular.

Let's go to example, let's try to do the same example we did to customer data set using Controller.


---------------------------------------------------------------------------------------------------------------

<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div>
<p>
Name: <input type="text" data-ng-model="name">
</p>
{{name}}
</div>

<div data-ng-controller="SimpleController">
<h3>Looping with the ng-repeat Directive</h3>
<ul>
<li
data-ng-repeat="customer in customers | filter:name | orderBy:'city'">{{customer.name
| uppercase}}- {{customer.city | lowercase}}</li>
</ul>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('SimpleController', function($scope) {

$scope.customers = [ {
name : 'Shaun',
city : 'Phoenix'
}, {
name : 'Dilan',
city : 'Chicago'
}, {
name : 'Mike',
city : 'NewYork'
} ];
});
</script>
</body>
</html>

-------------------------------------------------------------------------------------------------------------------

We haven't change the logic used in previous example in http://cgenit.blogspot.com/2015/04/angular.html

Here we have introduced a Controller.
Before that we have given a name to the application "myApp". If you see the opening HTML tag you will that.
Then we move to definition of the Controller.

We have defined inside separate area , as a separate script. If you familiar with packaging and modularising , now you should see that.

We are defining the Controller in a separate script, inside "script" tags.

First, we define a variable or a holder for application.
     var app = angular.module('myApp', []);
we have defined a variable "app" or module  with module giving our application name "myApp"
don't worry about empty braces.. well that's for dependency injection.. or we can say module myApp depend on applications, can be given inside those.

Second , then we define the Controller
    we define the controller as function. this is more like simple java-script function. we have included $scope in the Controller definition. This is scope which acts as a glue between Controller and the View.

As we have included Controller inside a separate script , you can simply include that into separate file and include in the main file.

So when we are using Controller , with use of  data-ng-controller  , we give the name of the Controller we are using. the functions and the data defined within the scope of the specified Controller will be available. In this case , we have given inside a div tag, and "SimpleController" Controller data and functions will be available within the div tag.

So when you run the above code , you will see the same output as the previous example.