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);
    }

Thursday, 28 January 2016

Scala Singleton And Companion Objects

Scala classes cannot have static variables or methods. Instead a Scala class can have what is called a singleton object, or sometime a companion object.

A singleton object is declared using the object keyword. Here is an example:



object MainObject {
    def sayHello() {
        println("Hello Krishna Kumar Chourasiya!");
    }
}
 
 
This example defines a singleton object called MainObject. You can call the method sayHello() like this: 

MainObject.sayHello();

Notice, how you write the full name of the object before the method name. No object is instantiated. It is like calling a static method in Java, except you are calling the method on a singleton object instead.

Companion Objects

 When a singleton object is named the same as a class, it is called a companion object. A companion object must be defined inside the same source file as the class. Here is an example:

class MainClass {
    def sayHello() {
        println("Hello! Krishna Kumar Chourasiya");
    }
}

object MainClass {
    def sayHi() {
        println("Hi! Krishna Kumar Chourasiya");
    }
}

In this class you can both instantiate Mainlass and call sayHello() or call the sayHi() method on the companion object directly, like this:

var aMainObj : MainClass = new MainClass();
aMainObj.sayHello();    // print - Hello! Krishna Kumar Chourasiya

MainClass.sayHi();    // print - Hi! Krishna Kumar Chourasiya



 3 Cheers !!!







Example of the Typeclass Pattern in Scala

What is a type class and why do I need it?

Type classes are useful to solve several fundamental challenges in programming languages. In particular, type classes support retroactive extension: the ability to extend existing software modules with new functionality without needing to touch or re-compile the original source.
 
The Scala library includes a few typeclasses such as scala.math.Numeric and scala.math.Ordering, and Scalaz is all typeclasses.

Scala enables the typeclass pattern using traits and implicits, and whilst Scala’s implementation is more verbose than Haskell’s, it comes with greater flexibility. Haskell only allows a single typeclass instance globally, whereas Scala allows any number to be available.

Furthermore, Scala allows default implementations to be made available if no others can be found.
For a deeper understanding see the references at the bottom of the blog.

Example
(You can copy and run this code in your favorite IDE like IntelliJ/Eclipse ....) 

package test.home

/*
 * The trait defines a concept which in this case is a transformer  that transforms a type T into a R.
 */
trait Transformer[T, R] {
  def transform(t: T): R
}

/*
 * This is a companion object for the typeclass giving default implementations for the typeclass.
 * These implementations are found after local implicits, so you can still override the default
 * behaviour. For more about the search order see [3].
 */
object Transformer {
  implicit object IntToStringTransformer extends Transformer[Int, String] {
      def transform(t: Int) = {
        println("I m in IntToStringTransfer");
        t.toString
      }
    }
}

// This is something that makes use of the typeclass
trait Transform {

  // The implicit Transformer, transformer, supplies an appropriate transformer for the method
  def transformTrait[T, R](t: T)(implicit transformer: Transformer[T, R]): R = {
     println("I m in transformTrait()");
    transformer.transform(t)
  }
}

// These examples will drop back to the default implementations in the Transformer's companion object
object ExampleWithDefaults extends App with Transform {
  println(transformTrait(5))
}


//Output would be
I m in transform()
I m in IntToStringTransfer
5

Hope I am able to resolve your confusion about typeclass in scala

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