Thursday, 12 November 2015

Angular JS - Data Binding

One of the main power of Angular JS is Data Binding. Data-binding in Angular apps is the automatic synchronization of data between the model and view components. The way that Angular implements data-binding lets you treat the model as the single-source-of-truth in your application. The view is a projection of the model at all times. When the model changes, the view reflects the change, and vice versa.

Types of Data Binding -
One Way -
Most of the systems bind data in only one direction: They merge template and model components together into a view. After the merge occurs, changes to the model or related sections of the view are NOT automatically reflected in the view. Worse, any changes that the user makes to the view are not reflected in the model. This means that the developer has to write code that constantly syncs the view with the model and the model with the view.
 


Two Way - 
Angular templates work differently. First the template (which is the uncompiled HTML along with any additional markup or directives) is compiled on the browser. The compilation step produces a live view. Any changes to the view are immediately reflected in the model, and any changes in the model are propagated to the view. The model is the single-source-of-truth for the application state, greatly simplifying the programming model for the developer. You can think of the view as simply an instant projection of your model.
Because the view is just a projection of the model, the controller is completely separated from the view and unaware of it. 

Angular JS Tutorial

AngularJS is a very powerful JavaScript Framework. It is used in Single Page Application (SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache license version 2.0. It is an open source web application framework maintained by google.
Sample Code:

<!doctype html>
<html ng-app>
   
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/
1.3.3/angular.min.js"></script>
   </head>
   
   <body>
      <div>
         <label>Name:</label>
         <input type = "text" ng-model = "yourName" placeholder = "Enter a name here">
         <hr />
         
         <h1>Hello {{yourName}}!</h1>
      </div>
      
   </body>
</html>

 
Advantages -
  • AngularJS provides capability to create Single Page Application in a very clean and maintainable way.
  • AngularJS provides data binding capability to HTML thus giving user a rich and responsive experience
  • AngularJS code is unit testable.
  • AngularJS uses dependency injection and make use of separation of concerns.
  • AngularJS provides reusable components.
  • With AngularJS, developer write less code and get more functionality.
  • In AngularJS, views are pure html pages, and controllers written in JavaScript do the business processing.
Disadvantages - 
  • Not Secure − Being JavaScript only framework, application written in AngularJS are not safe. Server side authentication and authorization is must to keep an application secure.
  • Not degradable − If your application user disables JavaScript then user will just see the basic page and nothing more.
 Components -
  • ng-app − This directive defines and links an AngularJS application to HTML.
  • ng-model − This directive binds the values of AngularJS application data to HTML input controls.
  • ng-bind − This directive binds the AngularJS Application data to HTML tags.
  
Core Features - 
  • Data-binding − It is the automatic synchronization of data between model and view components.
  • Scope − These are objects that refer to the model. They act as a glue between controller and view.
  • Controller − These are JavaScript functions that are bound to a particular scope.
  • Services − AngularJS come with several built-in services for example $http to make a XMLHttpRequests. These are singleton objects which are instantiated only once in app.
  • Filters − These select a subset of items from an array and returns a new array.
  • Directives − Directives are markers on DOM elements (such as elements, attributes, css, and more). These can be used to create custom HTML tags that serve as new, custom widgets. AngularJS has built-in directives (ngBind, ngModel...)
  • Templates − These are the rendered view with information from the controller and model. These can be a single file (like index.html) or multiple views in one page using "partials".
  • Routing − It is concept of switching views.
  • Model View Whatever − MVC is a design pattern for dividing an application into different parts (called Model, View and Controller), each with distinct responsibilities. AngularJS does not implement MVC in the traditional sense, but rather something closer to MVVM (Model-View-ViewModel). The Angular JS team refers it humorously as Model View Whatever.
  • Deep Linking − Deep linking allows you to encode the state of application in the URL so that it can be bookmarked. The application can then be restored from the URL to the same state.
    Dependency Injection − AngularJS has a built-in dependency injection subsystem that helps the developer by making the application easier to develop, understand, and test. 

Wednesday, 11 November 2015

ClassLoader in Java

Class loaders in Java used to load class. It works on 3 principles -
  1. Delegation - Delegation principle forward request of class loading to parent class loader and only loads the class, if parent is not able to find or load class.
  2. Visibility - It allows child class loader to see all the classes loaded by parent ClassLoader, but parent class loader can not see classes loaded by child.
  3. Uniqueness - Uniqueness principle allows to load a class exactly once, which is basically achieved by delegation and ensures that child ClassLoader doesn't reload the class already loaded by parent.
What is ClassLoader in Java?
ClassLoader in Java is a class which is used to load class files in Java. Java code is compiled into class file by javac compiler and JVM executes Java program, by executing byte codes written in class file. ClassLoader is responsible for loading class files from file system, network or any other source. There are three default class loader used in Java, Bootstrap , Extension and System or Application class loader.

1) Bootstrap ClassLoader - JRE/lib/rt.jar
2) Extension ClassLoader - JRE/lib/ext or any directory denoted by java.ext.dirs
3) Application ClassLoader - CLASSPATH environment variable, -classpath or -cp option, Class-Path attribute of Manifest inside JAR file.


How ClassLoader in Java?
Please refer below diagram - It mainly work on above listed 3 principles -
 
Delegation principles
 When a class is loaded and initialized in Java, a class is loaded in Java, when its needed. Suppose you have an application specific class called Krishna.class, first request of loading this class will come to Application ClassLoader which will delegate to its parent Extension ClassLoader which further delegates to Primordial or Bootstrap class loader. Primordial will look for that class in rt.jar and since that class is not there, request comes to Extension class loader which looks on jre/lib/ext directory and tries to locate this class there, if class is found there than Extension class loader will load that class and Application class loader will never load that class but if its not loaded by extension class-loader than Application class loader loads it from Classpath in Java. Remember Classpath is used to load class files while PATH is used to locate executable like javac or java command.
Visibility Principle
According to visibility principle, Child ClassLoader can see class loaded by Parent ClassLoader but vice-versa is not true. Which mean if class Abc is loaded by Application class loader than trying to load class ABC explicitly using extension ClassLoader will throw either java.lang.ClassNotFoundException. as shown in below Example
Example:
package krishna;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Java program to demonstrate How ClassLoader works in Java,
 * in particular about visibility principle of ClassLoader.
 *
 * @author Krishna Kumar Chourasiya
 */


public class ClassLoaderTestKrishna {
 
    public static void main(String args[]) {
        try {         
            //printing ClassLoader of this class
            System.out.println("ClassLoaderTestKrishna.getClass().getClassLoader() : "

                                 + ClassLoaderTestKrishna.class.getClassLoader());

         
            //trying to explicitly load this class again using Extension class loader
            Class.forName("krishna.ClassLoaderTest", true 

                            ,  ClassLoaderTestKrishna.class.getClassLoader().getParent());
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ClassLoaderTestKrishna.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Output:
ClassLoaderTestKrishna.getClass().getClassLoader() : sun.misc.Launcher$AppClassLoader@601bb1
11/11/2015 2:43:48 AM krishna.ClassLoaderTestKrishna main
SEVERE: null
java.lang.ClassNotFoundException: krishna.ClassLoaderTestKrishna
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at sun.misc.Launcher$ExtClassLoader.findClass(Launcher.java:229)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:247)
        at test.ClassLoaderTest.main(ClassLoaderTestKrishna.java:29)

Uniqueness Principle
According to this principle a class loaded by Parent should not be loaded by Child ClassLoader again. Though its completely possible to write class loader which violates Delegation and Uniqueness principles and loads class by itself, its not something which is beneficial. You should follow all  class loader principle while writing your own ClassLoader.

MongoDB - Connection from Remote Database

MongoDB - Connection from  Remote Database

There are multiple ways of doing this things, but I found this one is most suitable.

1. From Standalone
2. From Web Application

Make sure you have added correct maven dependency in your pom.xml like below -
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb-parent</artifactId>
    <version>1.5.2.RELEASE</version>
</dependency>
 

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>2.13.2</version>
</dependency>

 

Web Application - 

Before to use below code, please add property file having credentials and all other required details in it. Read that property file in spring-config.xml. You can use below code to read the property file -
<context:property-placeholder location='classpath:/config/configTest.properties'/>
configTest.properties
mongodb.dbname=
mongodb.host=
mongodb.port=
mongodb.username=
mongodb.password=
mongodb.authenticationdatabase=

Now below code will take the responsibility to get connected from mongodb host.

@Configuration
public class MongoConfiguration extends AbstractMongoConfiguration{
@Value("${mongodb.dbname}")
private String  dbName;

@Value("${mongodb.host}")
private String  host;

@Value("${mongodb.port}")
private Integer port;

@Value("${mongodb.username}")
private String  userName;

@Value("${mongodb.password}")
private String  password;

@Value("${mongodb.authenticationdatabase}")
private String  authenticationDatabase;

@Override
protected String getDatabaseName()  {
    return this.dbName;
}

@Override
public MongoClient mongo() throws Exception {
    List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
    ServerAddress address = new ServerAddress(host, port);
    serverAddresses.add(address);
    List<MongoCredential> credentials = new ArrayList<MongoCredential>();
    MongoCredential credential = MongoCredential.createPlainCredential(userName, authenticationDatabase, password.toCharArray());
    credentials.add(credential);
    return new MongoClient(serverAddresses, credentials);
}

@Override
@Bean
public SimpleMongoDbFactory mongoDbFactory() throws Exception {
    return new SimpleMongoDbFactory(mongo(), getDatabaseName());
}

@Override
@Bean
public MongoTemplate mongoTemplate() throws Exception {

    final MongoTemplate mongoTemplate = new MongoTemplate(mongo(), getDatabaseName());
    mongoTemplate.setWriteConcern(WriteConcern.SAFE);
    return mongoTemplate;
}


Standalone Java Program -

A standalone Java Program which tells about how to connect with remote MongoDB server from Java Code.

    String database = "TestDev";
    String username = "user@test.COM";
    String pass = "XXXXX";
    char[] password = pass.toChogram arArray();

    try {
        List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
        ServerAddress address = new ServerAddress("hostname", portnumber);
        serverAddresses.add(address);
        List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        MongoCredential credential = MongoCredential.createPlainCredential(username, "$external", password);
        credentials.add(credential);
        MongoClient mongoClient1 = new MongoClient(serverAddresses, credentials);
        DB db = mongoClient1.getDB(database);
        System.out.println(db.getCollectionNames());
        System.out.println("Done");
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }



MongoDB - CRUD operations

 The createCollection() Method

MongoDB db.createCollection(name, options) is used to create collection.

Syntax:

Basic syntax of createCollection() command is as follows
db.createCollection(name, options)
In the command, name is name of collection to be created. Options is a document and used to specify configuration of collection
Options like- capped, autoIndexID, size, max

While inserting the document, MongoDB first checks size field of capped collection, then it checks max field.

Examples:

Basic syntax of createCollection() method without options is as follows
>use krishnamongodb
switched to db krishnamongodb
>db.createCollection("homecollection")
{ "ok" : 1 }
>
You can check the created collection by using the command show collections
>show collections
homecollection
system.indexes
 
Following example shows the syntax of createCollection() method with few important options:
>db.createCollection("homecol", { capped : true, autoIndexID : true, size : 3142800, max : 10000 } )
{ "ok" : 1 }
>
 

 
NOTE: 
In mongodb you don't need to create collection. MongoDB creates collection automatically, when you insert some document.
>db.homecollection.insert({"name" : "Krishna Kumar"})
>show collections
homecol
homecollection
system.indexes
>
 

The drop() Method

MongoDB's db.collection.drop() is used to drop a collection from the database.
Syntax:

Basic syntax of drop() command is as follows -

db.COLLECTION_NAME.drop()



Method - insert()

To insert data into MongoDB collection, you need to use MongoDB's insert() or save()method.

Syntax

Basic syntax of insert() command is as follows:
>db.COLLECTION_NAME.insert(document)

Example

>db.hcomecol.insert({
   _id: ObjectId(7df78ad8902c),
   title: 'MongoDB Overview', 
   description: 'MongoDB is NOSql database',
   by: 'Krishna Kumar Chourasiya',
   url: 'http://mongodbworkspace.blogspot.in/',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 1000
})
 
Here homecol is our collection name, as created in previous tutorial. If the collection doesn't exist in the database, then MongoDB will create this collection and then insert document into it.
In the inserted document if we don't specify the _id parameter, then MongoDB assigns an unique ObjectId for this document.

_id is 12 bytes hexadecimal number unique for every document in a collection. 12 bytes are divided as follows:
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)
To insert multiple documents in single query, you can pass an array of documents in insert() command.

NOTE

To insert the document you can use db.homecol.save(document) also. If you don't specify _id in the document then save() method will work same as insert() method. If you specify _id then it will replace whole data of document containing _id as specified in save() method.

Insert Boolean Data

While inserting boolean data, you need to make sure you are using proper boolean keywords like (true,false). It should always start from lower case not from capital case.

Example: 
db.UserCredential.insert({"flag":true}) WriteResult({ "nInserted" : 1 }) db.UserCredential.insert({"flag":false}) WriteResult({ "nInserted" : 1 })

Method - delete()

MongoDB's remove() method is used to remove document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag.
  1. Deletion Criteria : (Optional) deletion criteria according to documents will be removed.
  2. justOne : (Optional) if set to true or 1, then remove only one document.

Syntax:

Basic syntax of remove() method is as follows
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)


Save Vs Update

MongoDB's update() and save() methods are used to update document into a collection. The update() method update values in the existing document while the save() method replaces the existing document with the document passed in save() method.

MongoDB - Update()

The update() method updates values in the existing document.

Syntax:

Basic syntax of update() method is as follows
>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)
By default mongodb will update only single document, to update multiple you need to set a paramter 'multi' to true.

MongoDB - Save()

The save() method replaces the existing document with the new document passed in save() method

Syntax

Basic syntax of mongodb save() method is shown below:
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})



How to avoid Duplicate Entry

To avoid duplicate entries in mongodb, Use an index with the {unique:true} option.
MongoDB indexes may optionally impose a unique key constraint, which guarantees that no documents are inserted whose values for the indexed keys match those of an existing document.


 For Example - 
db.homeCollections.ensureIndex({name:1},{unique:true});


If you wish for null values to be ignored from the unique key, then you have to also make the index sparse, by also adding the sparse option:

For Example - 

db.users.ensureIndex({email:1},{unique:true, sparse:true});

MongoDB - Create/Drop Database

The use Command

MongoDB use DATABASE_NAME is used to create database. The command will create a new database, if it doesn't exist otherwise it will return the existing database.

Syntax:
Basic syntax of use DATABASE statement is as follows:
use DATABASE_NAME
 
 
Example
>use krishnamongodb
switched to db krishnamongodb
 
 
To check your currently selected database use the command db
>db krishnamongodb
If you want to check your databases list, then use the command show dbs.
>show dbs 
local 0.78125GB 
test 0.23012GB

Your created database (krishnamongodb) is not present in list. To display database you need to insert atleast one document into it. To insert the document you need to create Collection first.

The dropDatabase() Method

MongoDB db.dropDatabase() command is used to drop a existing database.

Syntax:

Basic syntax of dropDatabase() command is as follows:
 
db.dropDatabase()

This will delete the selected database. If you have not selected any database, then it will delete default 'test' database

Example:

First, check the list available databases by using the command show dbs
>show dbs
local                0.78125GB
krishnamongodb       0.23012GB
test                 0.23012GB
>
 
If you want to delete new database <krishnamongodb>, then dropDatabase() command would be as follows:

>use krishnamongodb
switched to db krishnamongodb
>db.dropDatabase()
>{ "dropped" : "krishnamongodb", "ok" : 1 }
>
 
Now check list of databases
>show dbs
local      0.78125GB
test       0.23012GB
>



MongoDB - Advantages

In MongoDB there is no concept of relationship. A relational database has a typical schema design that shows number of tables and the relationship between these tables.

Why should use MongoDB
  • Document Oriented Storage : Data is stored in the form of JSON style documents
  • Index on any attribute
  • Replication & High Availability
  • Auto-Sharding
  • Rich Queries
  • Fast In-Place Updates
  • Professional Support By MongoDB
Where should use MongoDB?
  • Big Data
  • Data Hub
Windows Installation steps - Follow below link
                                                  Latest Mongodb Installer 


Advantages of MongoDB over RDBMS
  • Uses internal memory for storing the (windowed) working set, enabling faster access of data  
  • No Schema : It is document database in which one collection holds different different 
  • documents. Number of fields, content and size of the document can be differ from one document to another.
  • Structure of a single object is clear
  • No complex joins
  • Deep query-ability. MongoDB supports dynamic queries on documents using a document-based query language that's nearly as powerful as SQL
  • Ease of scale-out: MongoDB is easy to scale
    Conversion / mapping of application objects to database objects not needed 

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