Monday, September 4, 2017

AngularJs , Java Rest (JAX-RS) , RestEasy , Wildfly AS and Elastic Search CRUD Tutorial.

Hi there!
In this tutorial I have used AngularJs as the frontend , Java Restful web services and RestEasy as the backend, Elastic Search as the database and finally deployed to Wildfly Application Server.

The reason I have used RestEasy Framework is because it comes bundled with JBoss / Wildfly Application Server making it more easier to implement restful web services.

This project has two classes. UserController class which is the rest web service and the RestEasy ApplicationConfig class which is a empty class only used to bootstrap JAX-RS and not a directly used class.

Prerequisites

Elastic Search and Wildfly AS running.
Eclipse IDE.
Maven, Java installed.

Download source codes

UserController.java


package org.ashen.domain.controller;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

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


import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

@Path("/userlist")
public class userController {
 
 //userService userService=new userService();
 
 TransportClient client;

    public userController() throws UnknownHostException {
        client = new PreBuiltTransportClient(Settings.EMPTY)
        .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

    }
    
    @GET
    @Produces(MediaType.APPLICATION_JSON)

    public Map<String , Object> getAllUsers() {
        GetResponse getResponse = client.prepareGet("employee", "id", "1")
        .get();
        System.out.println(getResponse.getSource());
        return getResponse.getSource();
    } 
 

    @GET
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> getAUser(@PathParam("id") final String id) {

        GetResponse getResponse = client.prepareGet("employee", "id", id).get();
        System.out.println(getResponse.getSource());

        return getResponse.getSource();
    }
   
    
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String insert(String sname , String sage) throws IOException {

     IndexResponse response = client.prepareIndex("employee", "id", "1")
                 .setSource(jsonBuilder()
                         .startObject()
                         .field("name", sname)
                         .field("age", sage)

                         .endObject()
                 )
                 .get();
         return response.getResult().toString();

      }

    @DELETE
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public String delete(@PathParam("id") final String id) {
 
    DeleteResponse deleteResponse = client.prepareDelete("employee", "id", id).get();

        System.out.println(deleteResponse.getResult().toString());
        return deleteResponse.getResult().toString();
    }
 
 
}

The TransportClient code inside the constructor connects remotely to an Elasticsearch cluster using the transport module. It does not join the cluster, but simply gets one or more initial transport addresses and communicates with them.

RestApplicationConfig.java


package org.ashen.domain.restconfig;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

/**
 * Used to bootstrap JAX-RS.  Otherwise this class is
 * not directly used.
 *
 */
@ApplicationPath("/rest")
public class RestApplicationConfig extends Application {
 // intentionally empty
}

index.html


<html>
  <head>  
  
  <script src="lib/angular.js"></script>
    <script src="lib/angular.min.js"></script>
    <title>Sample Application</title>  
 <script type="text/javascript">
            var app = angular.module("userManagement", []);
         
            //Controller Part
            app.controller("userController", function($scope, $http) {
         
               
                $scope.userlist = [];
                $scope.userForm = {
                    id : -1,
                    userName : "",
                    age : ""
                };
         
                //load the data from server
              
                _refreshuserData();
         
                //HTTP POST/PUT methods for add/edit user 
             
                $scope.submituser = function() {
         
                    var method = "";
                    var url = "";
                    if ($scope.userForm.id == -1) {
                        //Id is absent in form data,create new user operation
                        method = "POST";
                        url = 'rest/userlist';
                    } else {
                        //Id is present in form data, edit user operation
                        method = "PUT";
                        url = 'rest/userlist';
                    }
         
                    $http({
                        method : method,
                        url : url,
                        data : angular.toJson($scope.userForm),
                        headers : {
                            'Content-Type' : 'application/json'
                        }
                    }).then( _success, _error );
                };
         
                //HTTP DELETE- delete user by Id
                $scope.deleteuser = function(user) {
                    $http({
                        method : 'DELETE',
                        url : 'rest/userlist/' + user.id
                    }).then(_success, _error);
                };
 
             // In case of edit, populate form fields and assign form.id with user id
                $scope.edituser = function(user) {
                  
                    $scope.userForm.userName = user.userName;
                    $scope.userForm.age = user.age;
                    $scope.userForm.id = user.id;
                };
         
                /* Private Methods */
                //HTTP GET- get all userlist collection
                function _refreshuserData() {
                    $http({
                        method : 'GET',
                        url : 'http://localhost:8080/angularCrudJava/rest/userlist'
                    }).then(function successCallback(response) {
                        $scope.userlist = response.data;
                    }, function errorCallback(response) {
                        console.log(response.statusText);
                    });
                }
         
                function _success(response) {
                    _refreshuserData();
                    _clearFormData()
                }
         
                function _error(response) {
                    console.log(response.statusText);
                }
         
                //Clear the form
                function _clearFormData() {
                    $scope.userForm.id = -1;
                    $scope.userForm.userName = "";
                    $scope.userForm.age = "";
                
                };
            });
        </script>
        
    <head>
    <body ng-app="userManagement" ng-controller="userController">
         <h1>
          Sample Application using AngularJs , Java 
        </h1> 
        <form ng-submit="submituser()">
            <table>
               
                <tr>
                    <th colspan="2">User Details</th>
                 </tr>
                <tr>
                    <td>Name</td>
                    <td><input type="text" ng-model="userForm.userName" /></td>
                </tr>
                <tr>
                    <td>age</td>
                    <td><input type="text" ng-model="userForm.age"  /></td>
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" value="Submit" class="blue-button" /></td>
                </tr>
            </table>
        </form>
        <table>
            <tr>
              
                <th>user</th>
                <th>age</th>
                <th>operations</th>
               
            </tr>
 
            <tr ng-repeat="userd in userlist">
            <td> {{ userd .name }}</td>
            <td >{{ userd .name }}</td>  
            <td>{{userd}}</td>
            <td><a ng-click="edituser(user)" >Edit</a> | <a ng-click="deleteuser(user)">Delete</a></td>
            </tr>
 
        </table>
 
   </body>
</html>

After downloading the project, Update the project using Maven, and set the goal as
" clean package wildfly:deploy " to deploy the application.

Test the client server interaction from Advance rest client using the below url.

http://localhost:8080/angularCrudJava/rest/userlist

and finally test the CRUD UI with this url

http://localhost:8080/angularCrudJava/

Sunday, September 3, 2017

Validation Of Duplicate and Empty Rows in JavaScript

Hi there!

In this blog post you will learn how to avoid (validate) duplication and empty rows in a table when you search and select data from a drop down list.

 So every time when I want to implement this validation at my work place I use a common function to identify the id of the selected data (object) from the drop down list and the id of already stored objects and if they are matching or equal, the function will return true hence not allowing duplicate rows. Below is the common function to avoid duplicate rows.

function containsObject(obj, list) {
    var i;
    for (i = 0; i < list.length; i++) {
        if (list[i].id === obj.id) {
            return true;
        }
    }
    return false;
}


Paste the above function somewhere in your controller and call it in the function used to add data to the table. For an example, suppose you want to add user details to a table and you have a function called "AddUserDetails".

$scope.AddUserDetails = function () {

         var tempList = { } ; 
     
         tempList.id = $scope.selectedUserDetails.id;

         templist.name= $scope.selectedUserDetails.name;

         if ( !containsObject (tempList , storedUserList )

         {
             $scope.storedUserList.push ( tempList ) ;
         }
}


The newly selected object is passed to an array called "tempList" and that object in tempList is checked with every object that is stored in the "storedUserList" array by the common function. If there are matching id's of objects in those two arrays, the function will not push the selected object to the storedUserList array.

----- Happy Coding! -----