@Path("Boat") public class BoatAPI { @Path("fetchboatingtypes") @GET @Produces(MediaType.APPLICATION_JSON) public Response fetchBoatingTypeList() { String returnValue = null; Response response = null; try { HouseBoatService houseBoatService = Factory .createHouseBoatService(); MapboatingTypes = houseBoatService .getBoatingTypes(); returnValue = JSONParser.toJson(boatingTypes); response = Response.status(Status.OK).entity(returnValue).build(); } catch (Exception e) { String returnString = "{\"message\":\"" + AppConfig.PROPERTIES.getProperty(e.getMessage()) + "\"}"; response = Response.status(Status.SERVICE_UNAVAILABLE) .entity(returnString).build(); } return response; }
application.controller("BookingController",
function($scope, $http) {
$scope.bookingForm = {};
$scope.boatingMap = null;
$scope.bookingForm.location = null;
$scope.bookingForm.boatingType = null;
$scope.bookingForm.dateOfRide = null;
$scope.bookingForm.noOfPeople = null;
$scope.bookingForm.contactNo = null;
$scope.bookingForm.message = null;
$scope.generateList = function() {
$http.get(URI + "Boat/fetchboatingtypes").then(
function(response) {
$scope.boatingMap = response.data;
$scope.bookingForm.message = null;
}, function(response) {
$scope.bookingForm.message = response.data.message;
$scope.boatingMap = null;
});
};
});
@Path("Boat")
public class BoatAPI {
. . .
}
http://<>:< >/< >/api/<<@Path Value>>
@Path("/{boatid}")
@Path("Boat")
public class BoatAPI {
@Path("fetchboatingtypes")
@GET
public Response fetchBoatingTypeList() {
. . .
}
}
@Path("fetchboatingtypes") @GET @Produces(MediaType.APPLICATION_JSON) public Response fetchBoatingTypeList() { String returnValue = null; Response response = null; try { // Code to invoke DAO HouseBoatService houseBoatService = Factory .createHouseBoatService(); MapboatingTypes = houseBoatService .getBoatingTypes(); // Sending the response as JSON string returnValue = JSONParser.toJson(boatingTypes); response = Response.status(Status.OK).entity(returnValue).build(); } catch (Exception e) { String returnString = "{\"message\":\"" + AppConfig.PROPERTIES.getProperty(e.getMessage()) + "\"}"; response = Response.status(Status.SERVICE_UNAVAILABLE) .entity(returnString).build(); } return response; }
application.controller("BookingController", function($scope, $http) { $scope.bookingForm = {}; $scope.boatingMap = null; $scope.bookingForm.location = null; $scope.bookingForm.boatingType = null; $scope.bookingForm.dateOfRide = null; $scope.bookingForm.noOfPeople = null; $scope.bookingForm.contactNo = null; $scope.bookingForm.message = null; // Consuming web service with URI (Boat/fetchboatingtypes) using $http $scope.generateList = function() { $http.get("http://localhost:2002/HouseBoats/api/" + "Boat/fetchboatingtypes").then( function(response) { $scope.boatingMap = response.data; $scope.bookingForm.message = null; }, function(response) { $scope.bookingForm.message = response.data.message; $scope.boatingMap = null; }); }; });
@DELETE @Path("/{empid}") public Response deleteEmployee(@PathParam("empid") int empId) { . . . }
@DELETE
@Path("/{empid}")
@Produces(MediaType.TEXT_PLAIN)
public Response deleteEmployee(@PathParam("empid") int empId) {
. . .
}
@DELETE @Path("/{empid}") @Produces(MediaType.TEXT_PLAIN) public Response deleteEmployee(@PathParam("empid") int empId) { String message = null; Response result = null; try { // CODE TO CALL SERVICE CLASS METHOD FOR DELETING EMPLOYEE DETAILS message = "SERVICE.DELETE_EMPLOYEE_SUCCESS from DELETE for EMPLOYEE ID : " + empId; result = Response.status(Status.OK).entity(message).build(); } catch (Exception e) { if (e.getMessage().contains("DAO")) { result = Response.status(Status.SERVICE_UNAVAILABLE).entity(e.getMessage()).build(); } else { result = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build(); } } return result; }
app.controller('deleteEmpDetails',function($http,$scope) { $http.delete('http://localhost:1002/001-EmployeeWebService/api/Boat/2'). // Parameter passed along with URI : 2 then(function(response) { $scope.message = response.data; },function(response) { $scope.message = response.data; }) });
@SuppressWarnings({ "rawtypes", "unchecked" })
public class JSONParser {
public static Object jsonToBean(String jsonInput, Class class1)
throws Exception {
JsonObject jsonObj = Json.createReader(new StringReader(jsonInput))
.readObject();
Object object = null;
try {
object = class1.newInstance();
Field fieldArray[] = class1.getDeclaredFields();
for (Field field : fieldArray) {
// To know the Json type of the field
// System.out.println(jsonObj.get(field.getName())+" "+jsonObj.get(field.getName()).getValueType());
field.setAccessible(true);
if (jsonObj.containsKey(field.getName())) {
// Sets the value for field type
// Number,String,boolean,Object[Calendar,AnyUserdefined
// Object]
setFieldData(jsonObj, field, object);
if (jsonObj.get(field.getName()).getValueType()
.equals(ValueType.ARRAY)) {
System.out.println(field.getName() + " "
+ field.getType().getCanonicalName());
if (field.getType().getCanonicalName()
.contains("java.util.Map")) {
// JsonArray
// jsonArray=jsonObj.getJsonArray(field.getName());
ParameterizedType listType = (ParameterizedType) field
.getGenericType();
Class keyClass = (Class) listType
.getActualTypeArguments()[0];
Class valueClass = (Class) listType
.getActualTypeArguments()[1];
System.out.println("hi" + keyClass + " "
+ valueClass);
}
// If object type is list
else if (field.getType().getCanonicalName()
.contains("java.util.List")) {
// Get the ParameterizedType of List
ParameterizedType listType = (ParameterizedType) field
.getGenericType();
Class listClass = (Class) listType
.getActualTypeArguments()[0];
JsonArray jsonArray = jsonObj.getJsonArray(field
.getName());
List list = new ArrayList();
// List of String
if (listClass.getCanonicalName().contains("String")) {
for (int i = 0; i < jsonArray.size(); i++) {
list.add(jsonArray.getString(i));
}
}
// List of Integer
else if (listClass.getCanonicalName().contains(
"Integer")) {
for (int i = 0; i < jsonArray.size(); i++) {
list.add(jsonArray.getInt(i));
}
}
// list of user defined object
else {
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject jsonObject = jsonArray
.getJsonObject(i);
Object obj = getUserDefinedObject(listClass, jsonObject, field);
list.add(obj);
}
}
field.set(object, list);
}
}
}
}
System.out.println(object);
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Problem in input data", e);
}
return object;
}
private static Object getUserDefinedObject(Class listClass,
JsonObject jsonObject, Field field) throws Exception {
Object obj = Class.forName(listClass.getName()).newInstance();
Field fieldBean[] = listClass.getDeclaredFields();
for (Field field2 : fieldBean) {
field2.setAccessible(true);
setFieldData(jsonObject, field2, obj);
}
return obj;
}
// Getting Calender object from JsonObject
private static Calendar getCalendarFromJSON(JsonObject jsonObj, Field field) {
JsonObject calJsonObj = jsonObj.getJsonObject(field.getName());
Calendar actualCalObject = Calendar.getInstance();
actualCalObject.set(Calendar.DATE, calJsonObj.getInt("DATE"));
actualCalObject.set(Calendar.MONTH, calJsonObj.getInt("MONTH"));
actualCalObject.set(Calendar.YEAR, calJsonObj.getInt("YEAR"));
return actualCalObject;
}
// For setting primitive types,Calendar, User defined
private static void setFieldData(JsonObject jsonObj, Field field,
Object object) throws Exception {
// System.out.println(jsonObj.get(field.getName())+" "+jsonObj.get(field.getName()).getValueType());
if (jsonObj.get(field.getName()).getValueType().equals(ValueType.STRING)) {
field.set(object, jsonObj.getString(field.getName()));
} else if (jsonObj.get(field.getName()).getValueType().equals(ValueType.NUMBER)) {
if (field.getType().getCanonicalName().contains("Integer"))
field.set(object, jsonObj.getInt(field.getName()));
else if (field.getType().getCanonicalName().contains("Long")) {
Long value = Long.parseLong(jsonObj.get(field.getName())
.toString());
field.set(object, value);
} else if (field.getType().getCanonicalName().contains("Double")) {
Double value = Double.parseDouble(jsonObj.get(field.getName())
.toString());
field.set(object, value);
} else if (field.getType().getCanonicalName().contains("Float")) {
Float value = Float.parseFloat(jsonObj.get(field.getName())
.toString());
field.set(object, value);
} else if (field.getType().getCanonicalName().contains("Short")) {
Short value = Short.parseShort(jsonObj.get(field.getName())
.toString());
field.set(object, value);
} else if (field.getType().getCanonicalName().contains("Byte")) {
Byte value = Byte.parseByte(jsonObj.get(field.getName())
.toString());
field.set(object, value);
}
} else if (jsonObj.get(field.getName()).getValueType()
.equals(ValueType.TRUE)) {
field.set(object, jsonObj.getBoolean(field.getName()));
} else if (jsonObj.get(field.getName()).getValueType()
.equals(ValueType.FALSE)) {
field.set(object, jsonObj.getBoolean(field.getName()));
} else if (jsonObj.get(field.getName()).getValueType()
.equals(ValueType.OBJECT)) {
// Object of Calendar type with only date,month,year
if (field.getType().getCanonicalName()
.contains("java.util.Calendar")) {
Calendar actualCalObject = getCalendarFromJSON(jsonObj, field);
field.set(object, actualCalObject);
}
else {
JsonObject jsonObject2 = jsonObj.getJsonObject(field.getName());
Object resultObj = getUserDefinedObject(field.getType(),
jsonObject2, field);
field.set(object, resultObj);
}
}
}
// Convert given object into Json String
public static String beanToJson(Object input) {
String jsonString = null;
JsonObjectBuilder mainObjectBuilder = Json.createObjectBuilder();
try {
Class class1 = input.getClass();
if(class1.getCanonicalName().contains("List")|| class1.getCanonicalName().contains("ArrayList")){
List list=(List)input;
jsonString=addListObject( list.get(0).getClass(), input).toString();
}
else{
Field fields[] = input.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Object fieldValue = field.get(input);
if (fieldValue != null) {
// System.out.println(field.getType().getCanonicalName()+field.getName());
addFieldData(mainObjectBuilder, field.getType()
.getCanonicalName(), field.getName(),
fieldValue, field);
} else {
mainObjectBuilder.add(field.getName(), JsonValue.NULL);
}
}
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = Json.createWriter(stringWriter);
jsonWriter.writeObject(mainObjectBuilder.build());
jsonString = stringWriter.getBuffer().toString();
}
} catch (IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonString;
}
private static void addFieldData(JsonObjectBuilder builder, String type,
String name, Object input, Field field) {
if (type.contains("String")) {
builder.add(name, input.toString());
} else if (type.contains("Integer")) {
builder.add(name, Integer.parseInt(input + ""));
} else if (type.contains("Long")) {
builder.add(name, Long.parseLong(input.toString()));
} else if (type.contains("Double")) {
builder.add(name, Double.parseDouble(input.toString()));
} else if (type.contains("Float")) {
builder.add(name, Float.parseFloat(input.toString()));
} else if (type.contains("Short")) {
builder.add(name, Short.parseShort(input.toString()));
} else if (type.contains("Byte")) {
builder.add(name, Byte.parseByte(input.toString()));
} else if (type.equalsIgnoreCase("Boolean")) {
builder.add(name, Boolean.parseBoolean(input.toString()));
} else if (type.equalsIgnoreCase("Character")
|| type.equalsIgnoreCase("char")) {
builder.add(name, input.toString().charAt(0));
} else if (type.contains("java.util.Calendar")) {
addCalendarObject(builder, name, input);
} else if (type.contains("java.util.ArrayList")
|| type.contains("java.util.List")) {
ParameterizedType listType = (ParameterizedType) field.getGenericType();
Class listClass = (Class) listType.getActualTypeArguments()[0];
JsonArray array=addListObject(listClass, input);
builder.add(field.getName(), array);
} else {
builder.add(name, generateJsonObject(input));
}
}
private static JsonArray addListObject( Class listClass,
Object input) {
List list = (List) input;
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
// System.out.println("Type "+listClass.getCanonicalName());
String name = listClass.getCanonicalName();
for (Object object : list) {
if (name.contains("String")) {
arrayBuilder.add(object.toString());
} else if (name.contains("Integer")) {
arrayBuilder.add(Integer.parseInt(object.toString()));
} else if (name.contains("Long")) {
arrayBuilder.add(Long.parseLong(object.toString()));
} else if (name.contains("Float")) {
arrayBuilder.add(Float.parseFloat(object.toString()));
} else if (name.contains("Double")) {
arrayBuilder.add(Double.parseDouble(object.toString()));
} else if (name.contains("Byte")) {
arrayBuilder.add(Byte.parseByte(object.toString()));
}
else {
arrayBuilder.add(generateJsonObject(object));
}
}
return arrayBuilder.build();
}
private static void addCalendarObject(JsonObjectBuilder builder,
String name, Object input) {
Calendar calendar = (Calendar) input;
JsonObjectBuilder calObjBuilder = Json.createObjectBuilder();
calObjBuilder.add("DATE", calendar.get(Calendar.DATE))
.add("MONTH", calendar.get(Calendar.MONTH))
.add("YEAR", calendar.get(Calendar.YEAR));
builder.add(name, calObjBuilder.build());
}
private static JsonObject generateJsonObject(Object input) {
JsonObject jsonObject = null;
Field fields[] = input.getClass().getDeclaredFields();
JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
try {
for (Field field : fields) {
field.setAccessible(true);
Object fieldValue = field.get(input);
if (fieldValue != null) {
addFieldData(jsonObjectBuilder, field.getType()
.getCanonicalName(), field.getName(), fieldValue,
field);
} else {
jsonObjectBuilder.add(field.getName(), JsonValue.NULL);
}
}
jsonObject = jsonObjectBuilder.build();
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
// System.out.println(jsonObject);
return jsonObject;
}
}
@Path("Boat") public class BoatAPI { @Path("book") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response booking(String dataRecieved) throws Exception { Response response = null; String string = dataRecieved; try { // Converting JSON into Bean HouseBoatBooking houseBoatBooking = JSONParser.fromJson(string,HouseBoatBooking.class); // Code to invoke DAO HouseBoatService houseBoatService = Factory .createHouseBoatService(); houseBoatBooking = houseBoatService.bookHouseBoat(houseBoatBooking); String successMessage = this.getBookingSuccessMessage(houseBoatBooking); houseBoatBooking = new HouseBoatBooking(); houseBoatBooking.setMessage(successMessage); // Sending the response as JSON string String returnString = JSONParser.toJson(houseBoatBooking); response = Response.status(Status.OK).entity(returnString).build(); } catch (Exception e) { e.printStackTrace(); String errorMessage = AppConfig.PROPERTIES.getProperty(e.getMessage()); HouseBoatBooking houseBoatBooking = new HouseBoatBooking(); houseBoatBooking.setMessage(errorMessage); String returnString = JSONParser.toJson(houseBoatBooking); response = Response.status(Status.SERVICE_UNAVAILABLE) .entity(returnString).build(); } return response; } @Path("fetchboatingtypes") @GET @Produces(MediaType.APPLICATION_JSON) public Response fetchBoatingTypeList() { . . . } }
application.controller("BookingController",
function($scope, $http) {
$scope.bookingForm = {};
$scope.boatingMap = null;
$scope.bookingForm.location = null;
$scope.bookingForm.boatingType = null;
$scope.bookingForm.dateOfRide = null;
$scope.bookingForm.noOfPeople = null;
$scope.bookingForm.contactNo = null;
$scope.bookingForm.message = null;
$scope.generateList = function() {
...
};
$scope.bookingForm.submitTheForm = function() {
$scope.bookingForm.message = null;
$scope.bookingForm.dateOfRide = $scope.bookingForm.dateOfRide.toLocaleString()
var data = angular.toJson($scope.bookingForm);
$http.post(URI + "Boat/book", data).then(function(response) {
$scope.bookingForm.message = response.data.message;
}, function(response) {
$scope.bookingForm.message = response.data.message;
});
};
}
@PUT
public Response updateEmployee(String emp) {
. . .
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateEmployee(String emp) {
. . .
}
@PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateEmployee(String emp) { String message = null; Response result = null; try { // Converting JSON string into appropriate bean object Employee input = (Employee) JSONParser.jsonToBean(emp, Employee.class); // CODE TO CALL DAO CLASS METHOD FOR UPDATING EMPLOYEE DETAILS message = "SERVICE.UPDATE_EMPLOYEE_SUCCESS from PUT"; String jsonMessage = "{\"message\":\"" + message + "\"}"; result = Response.status(Status.OK).entity(jsonMessage).build(); } catch (Exception e) { if (e.getMessage().contains("DAO")) { String error = "{\"message\":\"" + e.getMessage() + "\"}"; result = Response.status(Status.SERVICE_UNAVAILABLE).entity(error).build(); } else { String error = "{\"message\":\"" + e.getMessage() + "\"}"; result = Response.status(Status.BAD_REQUEST).entity(error).build(); } } return result; }
app.controller('updateEmpDetails',function($http,$scope){ $scope.employee= {}; var data = angular.toJson($scope.employee); // JSON.Stringify(); $http.put('http://localhost:1002/WebService/api/Boat',data). then(function(response) { $scope.message = response.data.message; },function(response) { $scope.message = response.data.message; }) });
http://<>:< >/< >/api
$http.get(". . ./Boat/fetchboatingtypes").then(function(response){...},function(response){...}); $http.put('. . ./Boat',data).then(function(response){...},function(response){...}); $http.post(". . ./Boat/book", data).then(function(response) {...}, function(response) {...}); $http.delete('.../Boat/2').then(function(response){...},function(response){...});
$http.get(url,config).then(function(response){...},function(response){...})
$http.post(url,data,config).then(function(response){...},function(response){...})
$http.put(url,data,config).then(function(response){...},function(response){...})
$http.delete(url,config).then(function(response){...},function(response){...})
Response.status(Status.OK).entity(returnValue).build(); Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build() Response.status(Status.SERVICE_UNAVAILABLE).entity(returnString).build();
1xx: Informational "100" : Continue 2xx: Success "200" : OK "204" : No Content 4xx: Client Error "400" : Bad Request "404" : Not Found 5xx: Server Error "500" : Internal Server Error "503" : Service Unavailable
@Path("Boat") public class BoatAPI { @Path("fetchboatingtypes") @GET @Produces(MediaType.APPLICATION_JSON) public Response fetchBoatingTypeList() { ... } @DELETE @Path("/{empid}") @Produces(MediaType.TEXT_PLAIN) public Response deleteEmployee(@PathParam("empid") int empId) { . . . } @Path("book") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response booking(String dataRecieved) throws Exception { . . . } @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateEmployee(String emp) { . . . } }
@javax.ws.rs.Path
@javax.ws.rs.GET @javax.ws.rs.POST @javax.ws.rs.PUT @javax.ws.rs.DELETE
@javax.ws.rs.PathParam
@Produces @Consumes
var email = angular.module('EmailApp', [ 'ngRoute', 'ngCookies' ]);
var cookieId = $cookies.get("cookieId");
var email = angular.module('EmailApp', [ 'ngRoute', 'ngCookies' ]);
// Added an error route for errors related to cookies
email.config([ '$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {
templateUrl : 'partials/login.html',
controller : 'LoginController'
}).when('/inbox/', {
templateUrl : 'partials/inbox.html',
controller : 'InboxController'
}).when('/messages/:msgid', {
templateUrl : 'partials/message.html',
controller : 'MessageController'
}).when('/error', {
templateUrl : 'partials/error.html'
}).otherwise({
redirectTo : '/login'
});
} ]);
//Config to allow cookies
/*email.config(['$httpProvider',function($httpProvider){
$httpProvider.defaults.withCredentials=true;
//$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
}]);*/
user=null;
email.controller('LoginController', [ '$scope', '$location',
'DataService', function($scope, $location, service) {
// Logic to validate credentials
$scope.validateCredentials = function() {
$scope.errorMessage = null;
var username = $scope.username;
var password = $scope.password;
service.validateUser(username, password, function(isValid) {
if (isValid) {
path = "/inbox";
user=username;
$location.path(path);
} else {
$scope.errorMessage = "Invalid Credentials. Try again";
user=null;
}
});
}
} ]);
email.controller('InboxController', [ '$scope', '$location',
'DataService', function($scope, $location, service) {
$scope.pNum = 1;
$scope.pSize = 2;
$scope.username = user;
service.getUserMessages( function(userMessages) {
if (userMessages != "error")
$scope.messageList = userMessages;
else
$location.path("/error");
});
} ]);
email.controller('MessageController', [ '$scope', '$routeParams', '$location',
'DataService', function($scope, $routeParams, $location, service) {
user_id = $routeParams.username;
msg_id = $routeParams.msgid;
service.getMessage(msg_id, function(msg) {
if (msg != "error")
$scope.msg = msg;
else
$location.path("/error");
});
} ]);
email.filter('paginate', function() {
return function(msgList, pageNo, pageSize) {
var start = (pageNo - 1) * pageSize;
var end = start + pageSize;
console.log(start + " " + end);
return msgList.slice(start, end)
};
});
email.factory('DataService', [ '$http', function($http) {
var uri = "http://localhost:9644/EmailAppWebService/api/users";
return {
validateUser : function(uname, pwd, successCallback) {
var valid = false;
var validateuri = uri + "/authenticate";
credentials={username:uname,password:pwd};
data=angular.toJson(credentials);
console.log(data)
$http.post(validateuri,data).then(function(response) {
console.log("data"+response.data)
data=response.data;
if (data == "false")
valid = false;
else{
valid=true;
}
successCallback(valid);
},function(){});
},
// Changed this method to get the username from the cookies automatically sent by browser
getUserMessages : function(successCallback) {
var userMessages;
var allMessagesUri = uri + "/user/messages";
$http.get(allMessagesUri).then(function(response) {
successCallback(response.data);
});
},
// Changed this method to get the username from cookies
getMessage : function(msgid, successCallback) {
//var cookieId = $cookies.get("cookieId");
var msg;
var messageUri = uri + "/user/messages/" + msgid;
$http.get(messageUri).then(function(response) {
successCallback(response.data);
});
}
}
} ]);
List: Link tgs Dropdown