Thursday, June 23, 2016

RESTful WebService using Jersey, AngularJS, MySQL (Small application to maintain users - Usermaintenance)

RESTful WebService using Jersey, AngularJS, MySQL

In this application, we will use AngularJS at the front-end and MySQL at the back-end. Moreover, Angular will communicate with database to store and fetch information using RESTful webservices. Obviously, we would be using JSON format for transfer of data from angular to rest and vice versa.




Following some steps to achieve this task and our output will be as below:




a) Libraries required:

jersey-server 1.9
mysql-connector-java 5.1.10
(com.google.code.gson) gson 2.2.1


b) Create a property file named as configuration.properties and write following lines:

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql:///um
jdbc.user = root 


c) Create a package named as com.gag and Create a class named as                               ReadFromPropertiesFile.java and write following lines in it:


package com.gag;

import java.io.InputStream;
import java.util.Properties;

public class ReadFromPropertiesFile {

Properties properties = null;

ReadFromPropertiesFile() {
try {
InputStream is = ReadFromPropertiesFile.class.getClassLoader()
.getResourceAsStream("configuration.properties");
properties = new Properties();
properties.load(is);
} catch (Exception e) {
System.out.println("aaaa " + e);
}
}

public String getURL() {
try {
return properties.getProperty("jdbc.url");
} catch (Exception e) {
System.out.println("getURL:" + e);
}
return "";
}

}


d) Create a class named as ConnectDB.java and write following lines in it:

package com.gag;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.logging.Logger;

public class ConnectDB {

static ReadFromPropertiesFile obj = new ReadFromPropertiesFile();

public static Connection connect() {

Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(obj.getURL(), "root", "");
} catch (Exception e) {
System.out.println("ConnectDB:  " + e);
Logger.getLogger(ConnectDB.class + "");
}
return conn;
}
}


e) Create a POJO class named as Customer.java and write following lines in it:

package com.gag;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

private int id;
private String name, email;

public int getId() {
return id;

}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

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

@Override
public String toString() {
return "{\"id\":\"" + id + "\",\"name\":\"" + name + "\",\"email\":\""
+ email + "\"}";
}
}

f) Create a class CustomerServices.java and write following lines in it:

package com.gag;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class CustomerServices {

public List<Customer> getAllCustomers() {
List<Customer> lst = new ArrayList();
try {
Connection conn = ConnectDB.connect();
PreparedStatement pstmt = conn
.prepareStatement("select * from customer");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Customer obj = new Customer();
obj.setId(rs.getInt("id"));
obj.setName(rs.getString("name"));
obj.setEmail(rs.getString("email"));
lst.add(obj);
}
} catch (Exception e) {
System.out.println(e);
}
return lst;
}

public String addCustomer(Customer obj) {
try {
Connection conn = ConnectDB.connect();
PreparedStatement pstmt = conn
.prepareStatement("insert into customer values(?,?,?)");
pstmt.setInt(1, obj.getId());
pstmt.setString(2, obj.getName());
pstmt.setString(3, obj.getEmail());
int i = pstmt.executeUpdate();
if (i > 0) {
return "{\"msg\":\"Customer Created\"}";
}
} catch (Exception e) {
System.out.println("addCustomer: " + e);
}
return "{\"msg\":\"Failed to  Create Customer\"}";
}

public String updateCustomer(Customer obj) {
try {
Connection conn = ConnectDB.connect();
PreparedStatement pstmt = conn
.prepareStatement("update customer set name=?,email = ? where id = ?");
pstmt.setString(1, obj.getName());
pstmt.setString(2, obj.getEmail());
pstmt.setInt(3, obj.getId());
int i = pstmt.executeUpdate();
if (i > 0) {
return "{\"msg\":\"Customer Updated\"}";
}
} catch (Exception e) {
System.out.println("updateCustomer: " + e);
}
return "Failed to  Update Customer";
}

public String delCustomer(int id) {
try {
Connection conn = ConnectDB.connect();
PreparedStatement pstmt = conn
.prepareStatement("delete from customer where id = ?");
pstmt.setInt(1, id);
int i = pstmt.executeUpdate();
if (i > 0) {
return "{\"msg\":\"Customer Deleted\"}";
}
} catch (Exception e) {
System.out.println("delCustomer: " + e);
}
return "Failed to  Delete Customer";
}
}


g) Create a class named as CustomerAPI.java in which we will write our RESTful  webservice code:

package com.gag;

import java.util.List;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.google.gson.Gson;

@Path("/customer")
public class CustomerAPI {

@GET
@Path("/getCustomers")
@Produces("application/json")
public String feed() {
String feeds = null;
try {
List<Customer> lstCustomers = null;
CustomerServices customerServices = new CustomerServices();
lstCustomers = customerServices.getAllCustomers();
Gson gson = new Gson();
System.out.println(gson.toJson(lstCustomers));
feeds = gson.toJson(lstCustomers);
} catch (Exception e) {
System.out.println("Exception Error"); // Console
}
return feeds;
}

@POST
@Path("/addCustomer")
@Produces(MediaType.APPLICATION_JSON)
public Response createCustomer(Customer customer) {
System.out.println();
String result = "";
try {
CustomerServices customerServices = new CustomerServices();
result = customerServices.addCustomer(customer);
} catch (Exception e) {
System.out.println("Exception Error  " + e); // Console
}
return Response.status(200).entity(result).build();
}

@PUT
@Path("/updateCustomer/id/{id}/name/{name}/email/{email}")
public String updateCustomer(@PathParam("id") int id,
@PathParam("name") String name, @PathParam("email") String email) {
String result = "";
try {
CustomerServices customerServices = new CustomerServices();
Customer obj = new Customer();
obj.setId(id);
obj.setName(name);
obj.setEmail(email);
result = customerServices.updateCustomer(obj);
} catch (Exception e) {
System.out.println("Exception Error  " + e); // Console
}
return result;
}

@DELETE
@Path("/delCustomer/id/{id}")
public String delCustomer(@PathParam("id") int id) {
String result = "";
try {
CustomerServices customerServices = new CustomerServices();
result = customerServices.delCustomer(id);
} catch (Exception e) {
System.out.println("Exception Error  " + e); // Console
}
return result;
}
}

h) Create a xml file named as web.xml and write following code in it:

<!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>
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.gag</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

</web-app>


i) In the last, to use this API, we need a client, so we will use angularjs along with jquery and html. Following is the code in index.jsp file or any html file you can create:

<html>
<head>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script type="text/javascript">
var myapp = angular.module("myApp", []);
myapp
.controller(
"umcontroller",
function($scope, $http) {
$scope.employees = [];
$scope.form = {
id : "",
name : "",
email : ""
};
_refreshPageData();
$scope.check = "";
$scope.submitCustomer = function() {
if ($scope.form.check == "check") {
method = "PUT";
url = 'http://localhost:8088/CustomerJerseyRestAPI/rest/customer/updateCustomer/id/'
+ $scope.form.id
+ "/name/"
+ $scope.form.name
+ "/email/"
+ $scope.form.email;
} else {
method = "POST";
url = 'http://localhost:8088/CustomerJerseyRestAPI/rest/customer/addCustomer';
}
$http({
method : method,
url : url,
data : angular.toJson($scope.form),
headers : {
'Content-Type' : 'application/json'
}
}).then(function successCallback(response) {
$scope.form.check = "";
_success(response);
}, function errorCallback(response) {
alert("ERROE:: " + response);
});
};
$scope.removeEmployee = function(employee) {
$http(
{
method : 'DELETE',
url : 'http://localhost:8088/CustomerJerseyRestAPI/rest/customer/delCustomer/id/'
+ employee.id
}).then(function successCallback(response) {
_success(response);
}, function errorCallback(response) {
alert("ERROE:: " + response);
});
};

$scope.editEmployee = function(employee) {
$scope.form.name = employee.name;
$scope.form.email = employee.email;
$scope.form.id = employee.id;
$scope.form.check = "check";
};
function _refreshPageData() {
$http(
{
method : 'GET',
url : 'http://localhost:8088/CustomerJerseyRestAPI/rest/customer/getCustomers/'
}).then(function successCallback(response) {
$scope.employees = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
}

function _success(response) {
_refreshPageData();
_clearForm()
}

function _error(response) {
console.log(response.statusText);
}
function _clearForm() {
$scope.form.name = "";
$scope.form.email = "";
$scope.form.id = "";
}

$scope.clearForm = function() {
_clearForm();
}
});
</script>
</head>
<body ng-app="myApp" ng-controller="umcontroller">

<div class="generic-container" ng-controller="umcontroller">
<div class="panel panel-default">
<div class="panel-heading">
<span class="lead">Usermaintenance</span>
</div>
<div class="formcontainer">
<form ng-submit="submitCustomer()">
<div class="row">
<input type="hidden" ng-model="form.id" /> <input type="hidden"
ng-model="form.check" />
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="id">Id</label>
<div class="col-md-7">
<input type="text" ng-model="form.id" name="id"
class="username form-control input-sm"
placeholder="Enter your Id" required ng-minlength="1" />

</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="name">Name</label>
<div class="col-md-7">
<input type="text" ng-model="form.name" id="name"
class="username form-control input-sm"
placeholder="Enter your name" required ng-minlength="3" />

</div>
</div>
</div>


<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="email">Email</label>
<div class="col-md-7">
<input type="text" ng-model="form.email" id="email" name="email"
class="form-control input-sm"
placeholder="Enter your Email [This field is validation free]" />
</div>
</div>
</div>



<div class="row">
<div class="form-actions floatRight">
<input type="submit" value="{{!form.check ? 'Add' : 'Update'}}"
class="btn-sm" ng-disabled="myForm.$invalid">
<button type="button" ng-click="clearForm()"
class="btn-sm">Reset Form</button>
</div>
</div>

</form>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<span class="lead">Users</span>
</div>
<div class="tablecontainer">
<table class="table table-hover">
<thead>
<tr>
<th>ID.</th>
<th>Name</th>
<th>Email</th>
<th width="20%"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="u in employees">
<td><span ng-bind="u.id"></span></td>
<td><span ng-bind="u.name"></span></td>
<td><span ng-bind="u.email"></span></td>
<td>
<button type="button" ng-click="editEmployee(u)"
class="btn btn-success custom-width">Edit</button>
<button type="button" ng-click="removeEmployee(u)"
class="btn btn-danger custom-width">Remove</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>

</body>
</html>