Saturday, 22 October 2016

Angular Modal Service Example

Creating a Modal Service
To make a custom modal service you first need to reference the Angular UI Bootstrap script And Angular Modal Service in your main page:
<script src="scripts/bootstrap.js"></script>
<script src="scripts/angular-modal-service.min.js"></script>

Add a dependency in your application

var app = angular.module('myApp',['angularModalService'])

Modal in your Controller


Inject ModalService into your controller, directive or service and call the displayModal() function to show a modal:

app.controller('MyController', function($scope, ModalService) {

  ModalService.displayModal({
    templateUrl: "template/modalTemplate.html",
    controller: "MyModalController"
  }).then(function(modal) {
    //it's a bootstrap element, use 'modal' to show it
    modal.element.modal();
    modal.close.then(function(result) {
      console.log(result);
    });
  });
);
You will invoked "displayModal()" on clicking of the button. This function will load HTML from template/modalTemplate.html and adds it to DOM. MyModalController a separate controller specific to the Modal only. Please follow the comment mentioned in the code ass well.
Later on the above code will create the instance of MyModalController.
When this is done, the promise returned by the displayModal() function resolves and you get a modal object. This object contains the element created. If it's a Bootstrap modal just call modal to show it.
The controller that is created always has one extra parameter injected into it - a function called close. Call this function to close the modal, anything you pass to it is passed to the caller as the result object. You can use this result object in promise.
You can pass a number of milliseconds to wait before destroying the DOM element as an optional second parameter to close() function.
app.controller('MyModalController', function($scope, close) {
  close("Hello World!");
});

Example - Click Here 

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

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

Wednesday, 20 January 2016

Lift Web Framework - Hello World

A step by step process to create a lift web project. There are 2 ways to do this - 

1. Download and Run Lift :
To install and run Lift, the only prerequisite is to have Java 1.5 or later installed.(Preferred 1.8)
Instructions for installing Java can be found here.
Once you have Java, the following instructions will download, build, and start a basic
Lift application.

For Windows :
• Visit http://liftweb.net/download and locate the link to the most recent ZIP version
of Lift 2.6 and save this to disk.
• Extract the contents of the ZIP file.
• Navigate in Explorer to the extracted folder, and once inside, navigate into sca‐
la_210 and then lift_basic.
• Double-click sbt.bat to run the build tool; a Terminal window should open.
• Required libraries will be downloaded automatically.
• At the SBT prompt (>), type container:start .
• You may find Windows Firewall blocking Java from running. If so, opt to “allow
access.”
• Start your browser and go to http://127.0.0.1:8080/
• When you’re done, type exit at the SBT prompt to stop your application from
running

2. Create project using SBT :
If you want to create the lift web project without using the ZIP files, then follow the below steps.
First of all, you will need to configure SBT and the Lift project yourself. We need only five small files for creating the project.

a. First, create an SBT plugin file at project/plugins.sbt (all file names are given relative to the project root directory):

         
addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "0.9.0")
This file tells SBT that you will be using the xsbt-web-plugin and chooses the correct
version based upon your version of SBT.


b. Next, create an SBT build file, build.sbt:

   
organization := "org.krishna.com"

name := "Lift_Using_SBT"

version := "0.1-SNAPSHOT"

scalaVersion := "2.11.0"

seq(com.github.siasia.WebPlugin.webSettings :_*)

libraryDependencies ++= {
val liftVersion = "2.6"
Seq(
"net.liftweb" %% "lift-webkit" % liftVersion % "compile",
"org.eclipse.jetty" % "jetty-webapp" % "8.1.7.v20120910" %"container,test",
"org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" %
"container,compile" artifacts Artifact("javax.servlet", "jar", "jar")
)
}

Feel free to change the various versions, though be aware that certain versions of Lift
are only built for certain versions of Scala.
Now that you have the basics of an SBT project, you can launch the sbt console. It should
load all the necessary dependencies, including the proper Scala version, and bring you
to a prompt.

c. Next, create the following file at src/main/webapp/WEB-INF/web.xml:

<!DOCTYPE web-app SYSTEM "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<filter>
<filter-name>LiftFilter</filter-name>
<display-name>Lift Filter</display-name>
<description>The Filter that intercepts Lift calls</description>
<filter-class>net.liftweb.http.LiftFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LiftFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

The web.xml file tells web containers, such as Jetty as configured by xsbt-web-plugin ,to pass all requests on to Lift.

d. Next, create a sample index.html file at src/main/webapp/index.html for our Lift app to
load. For example:

<!DOCTYPE html>
<html>
<head>
<title>Lift using SBT</title>
</head>
<body>
<h1>Welcome, you now have a working Lift installation</h1>
</body>
</html>
e. Finally, set up the basic Lift boot settings by creating a Boot.scala file at src/main/scala/bootstrap/liftweb/Boot.scala. The following contents will be sufficient:

package bootstrap.liftweb
import net.liftweb.http.{Html5Properties, LiftRules, Req}
import net.liftweb.sitemap.{Menu, SiteMap}
/**
* A class that's instantiated early and run. It allows the application
* to modify lift's environment
*/
class Boot {
def boot {
// where to search snippet
LiftRules.addToPackages("org.knoldus.com.Lift_Using_SBT")
// Build SiteMap
def sitemap(): SiteMap = SiteMap(
Menu.i("Home") / "index"
)
// Use HTML5 for rendering
LiftRules.htmlProperties.default.set((r: Req) =>
new Html5Properties(r.userAgent))
}
}
You have a working web lift project
To run the application, follow below command : 
sbt ~container:start
To browse the application, open http://localhost:8080
 
 To get the sample code, just clone the project from here


3 Cheers !!!


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