Tuesday, 27 September 2016

Custom Directive Isolated Scope

Javascript Code:

var app = angular.module("myApp",[]);

app.controller("Ctrl1",function($scope){
    $scope.name = "Krishna";
    $scope.reverseName = function(){
        $scope.name = $scope.name.split('').reverse().join('');
    };
});
app.directive("myDirective", function(){
    return {
        restrict: "EA",
        scope: {},
        template: "<div>Your name is : {{name}}</div>"+
        "Change your name : <input type='text' ng-model='name'/>"
    };
});

HTML:
<div ng-app="myApp">
     <div ng-controller="Ctrl1">
        <h2 ng-click="reverseName()">Hey {{name}}, Click me to reverse your name</h2>
        <div my-directive class='directive'></div>
    </div>
</div>

We just created a directive with an isolated scope. Notice, even the parent scope has a name “Krishna”, the textbox inside directive is blank. This is because of the new Isolated scope doesn’t know anything about its parent scope.

But, can we pass some values from the parent scope to the directives now?

Yes ! Not only that, we might need to handle situations like invoking callbacks in parent scope, two-way binding between parent & directives scope ..etc

To access any parent scope data, we need to pass that to our directive explicitly. This is achieved by setting properties on the scope object in the DDO. Imagine these properties as interfaces of the directive to communicate with outside scope. Another important thing is that, these properties also MUST be set as the attributes of the directive html element.

Lets go in deep .......

Javascript code

 var app = angular.module("myApp", []);
 app.controller("MainCtrl", function( $scope ){
    $scope.name = "Krishna";
    $scope.color = "#333333";
    $scope.reverseName = function(){
     $scope.name = $scope.name.split("").reverse().join("");
    };
    $scope.randomColor = function(){
        $scope.color = '#'+Math.floor(Math.random()*16777215).toString(16);
    };
});
myApp.directive("myDirective", function(){
    return {
        restrict: "EA",
        scope: {
            name: "@",
            color: "=",
            reverse: "&"
        },
        template: [
            "<div class='line'>",
            "Name : <strong></strong>;  Change name:<input type='text' ng-model='name' /><br/>",
            "</div><div class='line'>",
            "Color : <strong style='color:'></strong>;  Change color:<input type='text' ng-model='color' /><br/></div>",
            "<br/><input type='button' ng-click='reverse()' value='Reverse Name'/>"
        ].join("")  
    };
});

It’s clear that, the controller MainCtrl creates the parent scope. This parent scope has following properties and methods -

  • name = "Krishna"
  • color =  "#333333"
  • reverseName = function for reversing the name
  • randomColor = function for generating random color code

Similarly, we’ve created our directive in Isolated scope by setting an object literal in the DDO. Now our scope object has some properties:

scope: {
        name: "@",
        color: "=",
        reverse: "&"
    }

We can see the scope properties are used in directive scope. Mostly the directive’s templates and link function are going to consume the scope properties. The behaviour of these properties again depends on their values –– also known as Prefixes –– provided. 

These Prefixes are used to bind the parent scope’s methods and properties to the directive scope. All these prefixes receives data from the attributes of the directive element.

There’re 3 types of prefixes AngularJS provides -

1. "@"   (  Text binding / one-way binding )
2. "="   ( Direct model binding / two-way binding )
3. "&"   ( Behaviour binding / Method binding  )


HTML Code:

<div my-directive 
  class="directive"
  name="{{name}}" 
  reverse="reverseName()" 
  color="color" >
</div>

When the directive encounters a prefix in the scope property, it will look for an attribute ( with same property name ) on directive’s html element. However, we can provide a different mapping between property and attributes. This is done by giving a separate attribute name after the prefix. Look at below code.
scope : {
    name: "@"
}

The above will be mapped to an attribute “name” in the directive. Now let’s see what happens if we change the code like below:

scope : {
    name: "@parentName"
}

At this time, the name property will be looking for an attribute “parent-name” in the html element to get its value. Simply, any string after the Prefixes should match the attribute name.

  • The “@” prefix is a one-way binding between the directive scope and parent scope. It always expects the mapped attribute to be an expression. This is very important; because to make the “@” prefix work, we need to wrap the attribute value inside {{}}. Since “@” is creating a one-way binding between the parent and directive scope, any changes made in the parent scope will reflect inside the directive scope, but not the other way. “@” prefix is really useful when our directive needs to be initialised with some data from parent scope.                        
  • Secondly we have the “=” prefix. It creates a two-way binding between the parent and directive scope. The most important point about “=” prefix is, it’ll always expect the attribute value to be the model name. That means you cannot provide an expression as the value of attribute mapped to “=” prefix. This is useful, when any of our directive scope property to be same as the parent scope property.                                                                           
  • Finally, we’re going to talk about the last prefix. The “&” prefix is also known as a "Method Binding". This is used to bind any methods from the parent scope to the directive scope. This will be particularly useful when our directive needs to execute any callbacks in the parent scope. Look at the code to see how attribute value for the “&” prefix to be set.                                              
That’s it ! 

$filter Vs Custom Filter

Filters are used for formatting data displayed to the user on View.

They can be used in view templates, controllers or services.Angular comes with a collection of built-in filters, but it is easy to define your own as well.

Custom Filter: If you wan to some modification on the set of data OR on a specific situation you want to do some modifications/replace/manipulation go for custom filter.

For Example:
I have a set of data, on each element I want to do some modification while iterating the dataset.
{userId : "1234", userName:"Krishna Kumar Chourasiya","userEmail":"kchourasiya@gmail.com"}

I want to read above json and display on below format:

User Id: 1234
User Name: Krishna Kumar Chourasiya
User Email: kchourasiya@gmail.com


HTML:

<div ng-repeat="(key, dataSet) in dataSets">
   <div>{{key | titleCase}} </div>
</div>


JS Code:

App.filter('titleCase', function() {
  return function(input) {
    
    var newStr = input.charAt(0).toUpperCase();
    for (var i = 1; i < input.length; i++) {
        var char = input[i];
        if (char.match(/[A-Z]/)) {
            newStr += ' ' + char;
        }
        else {
            newStr += char;
        }
    }
    
    return newStr;
  };

Saturday, 13 February 2016

Scope of the Directives in AngularJS

Directives

Directives are the most powerful building blocks in Angular JS application. The most powerful aspect of Directive is "Scope". Lets deep dive in it....

Scopes in AngularJS

The scope object in Angular JS works as Glue between View and the parts (directives, controllers and services. Whenever the AngularJS application is bootstrapped, a rootScope object is created. Each scope created by controllers, directives and services are prototypically inherited from rootScope.

Scope inside a directive

All directives have a scope associated with them. They use this scope for accessing data/methods inside the template and link function. By default, unless explicitly set, directives don’t create their own scope. Therefore, directives use their parent scope ( usually a controller ) as their own.

However, AngularJS allows us to change the default scope of directives by passing a configuration object known as directive definition object. A directive definition object –DDO – is a simple JavaScript object used for configuring the directive’s behaviour, template.....etc. 

Example:
var app = angular.module("myApp",[]);
app.directive("myDirective",function(){
    return {
        restrict: "EA",
        scope: true,
        link: function(scope, elem, attr){
            // code goes here ...
        }
    }   
 });

In the above example, the values of scope property decides how the actual scope is created and used inside a directive. These values can be either “false”, “true” or “{}”.


Different types of directive scopes

There are three types of scopes:
1.       Shared scope
2.       Inherited scope
3.       Isolated scope


Scope: False ( Directive uses its parent scope )

Example: A simple directive to render a div and a textbox that can show and change a name. The name property gets the initial value from the Ctrl1 scope ( parent scope of the directive ).

JavaScript:
var app = angular.module("myApp",[]);
app.controller("Ctrl1",function($scope){
    $scope.name = "Krishna";
    $scope.reverseName = function(){
        $scope.name = $scope.name.split('').reverse().join('');
    };
});
app.directive("myDirective", function(){
    return {
        restrict: "EA",
        scope: false,
        template: "<div>Your name is : {{name}}</div>"+
        "Change your name : <input type='text' ng-model='name' />"
    };
});


HTML:
<div ng-app="myApp">
    <div ng-controller="Ctrl1">
        <h2 ng-click="reverseName()">Hey {{name}}, Click me to reverse your name</h2>
        <div my-directive></div>
    </div>
</div>

In the above example, If we change the name inside the textbox, notice the header name also gets changed. Since there’s no scope provided in the DDO, the directive uses its parent scope. Therefore, any changes we make inside the directive are actually reflected in the parent scope. Similarly, parent Ctrl1 scope has a method to reverse the name and this gets triggered when we click on the header. Now as we expect, clicking on the header should reverse the name inside the directive too.


Scope: True ( Directive gets a new scope )
When directive scope is set to “true”, AngularJS will create a new scope object and assign to the directive. This newly created scope object is proto-typically inherited from its parent scope ( the controller scope where it’s been used ).


var app = angular.module("myApp",[]);
app.controller("Ctrl1",function($scope){
    $scope.name = "Krishna";
    $scope.reverseName = function(){
        $scope.name = $scope.name.split('').reverse().join('');
    };
});
app.directive("myDirective", function(){
    return {
        restrict: "EA",
        scope: true,
        template: "<div>Your name is : {{name}}</div>"+
        "Change your name : <input type='text' ng-model='name' />"
    };
});

First, try clicking on the header. We can see that the name gets reversed inside controller Ctrl1 and the directive. Next, change the name inside the textbox; the parent scope is not at all affected. 

Scope : { } ( Directive gets a new isolated scope )
When an object literal is passed to the scope property, A new scope has been created. This new scope also known as Isolated scope because it is completely detached from its parent scope.

Example:
var app = angular.module("myApp",[]);
app.directive("myDirective",function(){
    return {
        restrict: "EA",
        scope: {},
        link: function(scope,elem,attr){
            // code goes here ...
        }
    }   
 });

The recommended way of setting the scope on DDO while creating custom directives. Why in this way -
  • It’ll make sure that our directive is generic, and placed anywhere inside the application. Parent scope is not going to interfere with the directive scope.
Though it’s called as an Isolated scope, AngularJS allows to communicate with the parent scope using some special symbols knows as prefixes. Because of course there are still situations where the directive needs to be able to exchange data with parent scope.





Angular JS + Spring REST Hello World JSON Example

Create maven web based application in eclipse - copy paste below code

web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_2_3.xsd"
    version="2.3">
  <display-name>Archetype Created Web Application</display-name>
 
   <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
       <!--  <url-pattern>*.htm</url-pattern> -->
        <url-pattern>*.json</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans    
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="com.krishna" />
    <mvc:annotation-driven />
    <bean name="jsonTemplate" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
</beans>

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.krishna</groupId>
<artifactId>springhomeweb</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springhomeweb Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.0.1.RELEASE</spring.version>
<com.fasterxml.jackson-version>2.4.1</com.fasterxml.jackson-version>
</properties>


<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

<!-- Spring dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${com.fasterxml.jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${com.fasterxml.jackson-version}</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${com.fasterxml.jackson-version}</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
</dependencies>
<build>
<finalName>springhomeweb</finalName>
</build>
</project>

index.jsp
<div ng-app="myApp">
<div ng-controller="AppController">
<div ng-view></div>
<div ui-view></div>
<a href="#/login">Login</a>&nbsp; <a href="#/register">Registration</a>
<a ng-click="reload();" class="navbar-brand" title="Refresh" href="#"
data-translate>Refresh</a>
</div>
</div>

AppConrtroller.js
var myApp = angular.module('myApp', ['ngRoute']);

myApp.controller('AppController', ['$scope','appService', '$route',
                                     function($scope,appService,$route) {
  $scope.loginSubmit = function(login){
 alert(login.userName);
 appService.submitLogin(login);
  };
  $scope.register = function(user){
 alert("In registration : "+user.firstName);
 appService.register(user);
  };
  $scope.reload = function(){
 alert("Refreshing....");
 $route.reload();
  };
 }]);



appService.js
myApp.service('appService',['$http','$location',function($http,$location) {

// For User Login
this.submitLogin = function(login){
console.log("login json: "+login);
$http({
   url: "user/login.json",
   data: login,
   method: "POST",
   headers: {
       "Content-Type": "application/json"
   }
}).success(function(response){
alert("Login: "+response);
}).error(function(error){
alert("Login: "+error);
});
};

// For User Registration
this.register = function(user){
$http({
url: "user/register.json",
data: user,
method: "POST",
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
alert("Registration: "+response);
$location.replace("login.jsp");
}).error(function(error){
alert("Registration: "+error);
});
};
}]);

AppRouteProvider.js
myApp.config(function ($routeProvider) {
    $routeProvider
   .when('/login',{
templateUrl:'login.jsp',
controller: 'AppController'
})
.when('/register',{
templateUrl:'registration.jsp',
controller: 'AppController'
})
.otherwise({
redirectTo:'/'
});
});


MainController.java
package com.krishna.controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.krishna.model.Login;
import com.krishna.model.LoginResponse;
import com.krishna.model.User;

/**
 * @author Krishna Kumar
 *
 */
@RestController
@RequestMapping("/user")
public class MainController {
@RequestMapping(value = "/login.json", method = RequestMethod.POST)
public LoginResponse validateLogin(@RequestBody Login login){
System.out.println("Param Value: "+login.getUserName());
LoginResponse lr = new LoginResponse();
lr.setSuccess("Success Found");
return lr;
}

@RequestMapping(value = "/register.json", method = RequestMethod.POST)
public String register(@RequestBody User user){
System.out.println("Param Value Registration: "+user.getUserName());
return "User Registered Successfully.";
}

}

Saturday, 6 February 2016

Singleton Design Pattern in Java

Definition: A singleton class is a class that is instantiated only once. This is typically accomplished by creating a static field in the class representing the class. A static method exists on the class to obtain the instance of the class and is typically named something such as getInstance(). The creation of the object referenced by the static field can be done either when the class is initialized or the first time that getInstance() is called. The singleton class typically has a private constructor to prevent the singleton class from being instantiated via a constructor. Rather, the instance of the singleton is obtained via the static getInstance() method.

Code Description:
The SingletonSolution class is an example of a typical singleton class. It contains a private static SingletonSolution field. It has a private constructor so that the class can't be instantiated by outside classes. It has a public static getInstance() method that returns the one and only SingletonSolution instance. If this instance doesn't already exist, the getInstance() method creates it. The SingletonSolution class has a public sayHello() method that can be used to test the singleton.


SingletonSolution.java

package com.krishna;

public class SingletonSolution {

 private static SingletonSolution singletonSolution = null;

 private SingletonSolution () {
 }

 public static SingletonSolution getInstance() {
  if (singletonSolution == null) {
   singletonSolution = new SingletonSolution ();
  }
  return singletonSolution ;
 }

 public void sayHello() {
  System.out.println("Hello!! Krishna Kumar Chourasiya !!!");
 }
}

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

The SingltonSolutionMain class obtains a SingletonSolution singleton class via the call to the static SingletonSolution.getInstance(). We call the sayHello() method on the singleton class. Executing the SingltonSolutionMain class outputs "Hello !! Krishna Kumar Chourasiya !!!" to standard output. 

SingltonSolutionMain.java

package com.krishna;

public class Demo {

 public static void main(String[] args) {
  SingletonSolution singletonSolution = SingletonSolution.getInstance();

  singletonSolution.sayHello();
 }

}



Example of Lambda Expressions and Streams in Java 8

Create a Java Class and your favorite editor and run the below code ---

public static void filter(List<String> names, Predicate condition1, Predicate condition2) {
        //names.forEach(str -> System.out.println("Java 8 ::: "+str));
        names.stream().filter(condition1.and(condition2)).forEach(str -> System.out.println("--- Java 8 ::: "+str));
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
       
        List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
        IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics();
        System.out.println("Java 8 ::: ++ "+stats.getAverage());
        System.out.println("Java 8 ::: ++ "+stats.getCount());
        System.out.println("Java 8 ::: ++ "+stats.getMax());
        System.out.println("Java 8 ::: ++ "+stats.getSum());
       
        List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);
        List<Integer> s2Number = numbers.stream().map(i -> i*i).distinct().sorted().collect(Collectors.toList());
        Collections.reverse(s2Number);
         System.out.println(s2Number);
       
        List<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany", "Italy", "U.K.","Canada");
        String G7Countries = G7.stream().map(x -> x.toUpperCase()).collect(Collectors.joining());
        System.out.println(G7Countries);
       
        List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
        double total = 0.0;
        for (Integer cost : costBeforeTax) {
              double price = cost + .12*cost;
              total = total + price;
            
        }
         System.out.println(total);
        costBeforeTax.stream().map((cost) -> cost + .12*cost).forEach(cost -> System.out.println("Java8 Cost : "+cost));
        double sum  = costBeforeTax.stream().mapToDouble((cost) -> cost + .12*cost).sum();

        System.out.println("java8 : sum : "+sum);
       
        List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
        Predicate<String> first = s -> ((String) s).startsWith("J");
       
        Predicate<String> second = (p) -> ((String)p).length() > 3;
       
        filter(languages, first, second);
       
       
        List<String> features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
        for (String feature : features) {
           System.out.println(feature);
        }
       
        features.forEach(s -> System.out.println("Java8 : "+s));
       
        new Thread(new Runnable() {
            public void run(){
                System.out.println("Before Java 8");
                System.out.println("I m in thread.");
            }
        }).start();
       
        new Thread(() -> {
            System.out.println("After Java 8");
            System.out.println("I m in Java 8 Thread");
        }).start();
    }

Java8 Comparator Example


public static void main(String[] args) {
        Book book1 = new Book("Head First Java", 38.9f,5);
        Book book2 = new Book("Thinking in Java", 30.0f,3);
        Book book3 = new Book("Effective Java", 50.0f, 8);
        Book book4 = new Book("Code Complete", 42.5f, 9);

        List<Book> listBooks = Arrays.asList(book1, book2, book3, book4);

        System.out.println("Before sorting:");
        System.out.println(listBooks);

        Comparator<Book> titleComparator = new Comparator<Book>() {
            public int compare(Book book1, Book book2) {
                return book1.getTitle().compareTo(book2.getTitle());
            }
        };

        Collections.sort(listBooks, titleComparator);

        System.out.println("\nAfter sorting by title:");
        System.out.println(listBooks);
       
        Comparator<Book> ascOldEnough = (Book b1, Book b2) -> (int) (b1.getOldEnough() - b2.getOldEnough());

        Comparator<Book> descPriceComp = (Book b1, Book b2) -> (int) (b2.getPrice() - b1.getPrice());

        Collections.sort(listBooks, descPriceComp);

        System.out.println("\nAfter sorting by descending price:");
        System.out.println(listBooks);
       
        Collections.sort(listBooks, ascOldEnough);
        System.out.println("\nAfter sorting by descending old enough: +++");
        System.out.println(listBooks);
        Collections.sort(listBooks, (b1, b2) -> (int) (b1.getPrice() - b2.getPrice()));

        System.out.println("\nAfter sorting by ascending price:");
        System.out.println(listBooks);
    }

Monads in Scala

Monads belongs to Advance Scala   concepts. It  is not a class or a trait; it is a concept. It is an object which covers other object. A Mon...