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! -----





Sunday, July 9, 2017

Simple CRUD application with User Authentication and Registration using PHP Codeigniter Framework

Hi there!
This is a News application which can perform User Authentication and Registration for users and also performs CRUD operations of News item using MVC architecture. News item contains title and text content. I have used WAMP software bundle.

First of all, create a database named "testdb" and a table named "news".

CREATE DATABASE `testdb`;
use `testdb`;

--
-- Table structure for table `news`
--

CREATE TABLE IF NOT EXISTS `news` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(128) NOT NULL,
`slug` varchar(128) NOT NULL,
`text` text NOT NULL,
PRIMARY KEY (`id`),
KEY `slug` (`slug`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

--
-- Dumping data for table `news`
--

INSERT INTO `news` (`id`, `title`, `slug`, `text`) VALUES
(1, 'Test', 'test', 'Hello World !!'),
(2, 'What is Lorem Ipsum?', 'what-is-lorem-ipsum', 'Lorem Ipsum is simply dummy text.');


Click here to download the full code from GitHub.







Thursday, July 6, 2017

Weather Monitoring System - Java Socket Programming and Java RMI.

This is a client and server application developed using NetBeans IDE 8.2 to measure the average rainfall, Humidity, Temperature and Air pressure of the base stations around the country. This system has used Java Socket programming and Java Remote Method Invocation to communicate between sensor, server and client.

A Sensor emulator program is used to send randomly generated data to the server periodically during 1 hour intervals through sockets and the data between server to client is sent using Remote Method Invocation.


Client thereby execute the login GUI and authenticate the Monitoring Stations(clients). After the authentication the weather details are sent to the Weather GUI to be shown for the user.

Click here to download the source code from GitHub.

Sequence Diagram

High Level Architectural Diagram with Software components.




Friday, June 30, 2017

Pharmacy Management System - SLIIT Project NodeJs , AngularJs , MongoDB

This is a pharmacy management system for a hospital developed for the 3rd year first semester final project by 4 members. The system will manage all the pharmaceutical operations to provide comprehensive pharmacy services. Basic features of this system would be managing the drug inventory, patient medical profiles, drug dispensing and prescription management. The main users of this system would be the chief pharmacist, assistant pharmacists, and doctors. They have to login to the system in order to use the services available.

The main benefits of this system are reducing manual data entry, reducing human errors, saves time, and increased efficiency. The system is able to generate customized reports on each of the services when required.

Technologies Used 

  • AngularJS for the front end
  • Github 
  • MongoDB ,Mongoose Library,  ExpressJS and NodeJS for the backend.
  • JetBrains WebStorm IDE


Backend is an API running JSON based web services. The front-end application communicates with the back end only using these web services. 

My part was to monitor the drug stock level and decide whether to re-order from drug suppliers via email after the approval of chief pharmacist if drug levels are low and record supplier details.

Click here to download the source code from GitHub.









Thursday, June 29, 2017

ng-model in AngularJS

Models in Angular.JS are represented by the "ng-model" directive. The primary purpose of this directive is to bind the "view" to the "model".

The ng-model attribute is used for,

  • Binding controls such as input, text area and select in the view into the model. 
  • Provide a validation behavior - for example a validation can be added to a textbox that only numeric characters can be entered into the textbox. 
  • The ng-model attribute maintains the state of the control (By state, we mean that the control and the data is bound to be always kept in sync. If the value of our data changes , it will automatically change the value in the control and vice versa)

Monday, May 1, 2017

Simple JavaScript Application with MEAN


In this tutorial we will allow users to enter a first name and a last name that will save to the MongoDB database.

I have used JetBrains WebStorm IDE for this tutorial.

Create a project in Webstorm to get started.
.
First step is to create a file that will contain the code for our Node.js server. So create a file and call it as app.js  and include the below code.



In order for express , body-parser and mongoose to work you should install them to the package,json file as dependencies.

First, go to the directory of the project and run these commands in the command prompt.

1. npm init  - The command prompt will ask you some questions and it will create the package.json                           file.

2.Then run these commands.

         npm install express --save

         npm install mongoose --save

         npm install body-parser --save

After installing them you can open the package.json file and see whether those frameworks have been installed properly.

Create a html file and call it as index.html and paste the below code.

<!DOCTYPE html>
<html>
  <head>
    <title>Intro to Node and MongoDB</title>
  </head>

  <body>
   
    <form method="post" action="/addname">
      <label>Enter Your Name</label><br>
      <input type="text" name="firstName" placeholder="Enter first               name..." required>
      <input type="text" name="lastName" placeholder="Enter last name..."       required>
      <input type="submit" value="Add Name">
    </form>
  </body>
</html>


After doing so save the code and go to the project directory open the command prompt and run node app.js to start our server.

Make sure your mongod is running. 

Open up a browser and navigate to the url

http://localhost:3000

Enter your first name and last name in the input fields and then click the “Add Name” button. You should get back text that says the name has been saved to the database.








Monday, March 13, 2017

How I built a simple calculator using AngularJS in less than 15mins

Hi there! Yeah you read that right!
I'm starting to love AngularJS framework. I should have used this framework for my previous academic projects since this feature called data binding eliminates much of the code.

Before we start there are three components of AngularJS that you should know to understand how this simple calculator works. 😏 
  1. ng-app - This directive defines and links an AngularJS application to HTML.
  2. ng-model - Binds the values of AngularJS application data to HTML input controls.
  3. ng-bind - Binds the AngularJS application to HTML tags
  4. ng-controller - It defines the application controller.Controller is a JavaScript Object created by                           a standard JavaScript Constructor.

Now that we know these main components lets get started!!!

If you have read my previous articles on JavaScript then you'll see that I have separated the HTML part and JavaScript part in separate files and I did the same here.


HTML part!




As you can see this HTML code is fairly simple! The ng-app and ng-controller is declared in a single div element rather than declaring them in an extra level.

And also we have 2 input boxes and select element which has ng-model to bind the values entered into the input boxes to the AngularJS application data. 

The last part we have a function call {{ result() }} in the directive which is interesting! 

JavaScript part!




An AngularJS module (angular.module() ) defines an application and it is a container for the different parts of an application,
In the JavaScript part we create a angular module and controller and we declare the result as an attribute of the current scope. 
And when you make a controller in AngularJS, you pass the $scope object as an argument.

.controller( "      " , function($scope) {

 $scope.result = function() {}

}

And the last part of the JavaScript code calculating the math operations are simple which is familiar hence not worth going in detail.

Happy coding!!! ✌👍

--Ashen Jayasinghe--




Tuesday, February 21, 2017

Javascript Tutorial



First I will be explaining the answers for the questions in the 2nd lab sheet in detail and the screenshots of the working code will be shown at the end of each question.

1)

//write a function as a variable that prints "Hello World" to console and another function which //accepts that variable.


var printHello = function () {

console.log("Hello World");

}

printHello(); //calling function


// The argument passed to the second function should be executed as a function inside the body.

function getInstance (hello) {

hello();

}

//Call the second function passing the first function as the argument.

getInstance(printHello);



Okay now we are done with the first question!!! 😄😄 Moving on to the 2nd question.
   

2) 

Use curly brackets to create JSON like JavaScript object and add properties and functions to the object.


3 )

  • Declare a global variable named vehicleName in the window object
                            window.vehicleName = "Toyota";


  •   Declare a method named printVehicleName to print out the vehicle name
                                     function printvehicleName() {

                 console.log("Vehicle Name = " + this.vehicleName);
                           }                                 

  •  Declare an object named Vehicle(using object literal notation) which have a variable called vehicleName and declare a function named getVehicleName and assign it with the printVehicleName
                                       var Vehicle = {

                        vehicleName:"Nissan",
                        amount:100,
                        id:001,
                        getVehicleName:printvehicleName //.bind(window)                                    
                       };


  •  Execute the printVehicleName function and the getVehicleName functions to see the results
                                       printVehicleName();

                      Vehicle.getVehicleName();


  Correct the getVehicleName to print out the global variable vehicleName using the this keyword.

                        function printVehicleName() {

              console.log(this); // this prints the global vehicle name 'Toyota'

              console.log("Vehicle Name = " + this.vehicleName); // prints 'Nissan'
                       
                    }




            
4)
    Create a separate function using JavaScript closure which accepts the tax percentage and returns a function which accepts the amount and returns the amount after adding tax percentage. Try adding tax percentage to ‘this’ object and check if it works.


5)

Write a function to call GitHub API (https://api.github.com/users) and get users and return the users to the caller.