Uncategorized

Difference between Association,Aggregation,Composition and Inheritance

Posted on

via Difference between Association,Aggregation,Composition and Inheritance

Advertisements

Building ReactJS Example with Event Handling

Posted on

Here is another simple example of ReactJS in which bunch of CommentBox components has been created and wrapped into a Board layer which is also a React Component and therefore events are binding to Save & Edit button under CommentBox component.

Set of comments text is initialized in parent Component i.e Board and each comment text is getting rendered into CommentBox Component by iteration.

Here is complete code:-

                <!DOCTYPE html>
        <html>

        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width">
            <title></title>
        </head>

        <body>
            <div id="content"></div>
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
            
            <script type="text/babel">

                class CommentBox extends React.Component{
                constructor(props){
                    super(props);
                    this.state = {
                    editable : false
                    };
                }

                save(event){
                    this.props.updateCommentText(this.refs.commentTxt.value,this.props.index);
                    this.setState({
                        editable:false
                    })
                }
                remove(){
                    this.props.removeCommentText(this.props.index);
                    
                }
                edit(){
                    this.setState({
                        editable:true
                    })
                }
                renderForm(){
                    return (
                    <div className="row">
                        <div><textArea ref="commentTxt" name="commentBox" defaultValue={this.props.children}></textArea></div>
                        <button type="button" className="btn btn-danger" onClick={this.save.bind(this)}>Save</button>
                    </div>
                    );
                }
                renderHtml(){  
                    return (
                        <div className="row">
                        <div>{this.props.children}</div>    
                        <button type="button" className="btn btn-danger" onClick={this.edit.bind(this)}>Edit</button>
                        <button type="button" className="btn btn-success" onClick={this.remove.bind(this)}>Remove</button>
                        </div>
                    );
                }

                render() {
                    if(this.state.editable){
                        return this.renderForm(this);
                    }else{
                        return this.renderHtml(this);
                    }
                }
                }

            class Board extends React.Component{
                constructor(props){
                    super(props);
                    this.state ={
                        comments:[
                            'Techical Comments',
                            'Wordpress Comments',
                            'Facebook Comments'
                        ]
                    }
                }
                updateComment(text,i){
                    console.log("Saving Comment..."+text+" index ["+i+"]")
                    var arr = this.state.comments;
                    arr[i] = text;
                    this.setState({comments:arr})
                }
                removeComment(i){
                    console.log("Removing Comment..." + "index ["+i+"]")
                    var arr = this.state.comments;
                    arr.splice(i,1);
                    console.log("After removing a record :"+arr)
                    this.setState({comments:arr});
                }    

                eachComment(text,i){
                    return (
                                <CommentBox key={i} index={i} updateCommentText={this.updateComment.bind(this)}  removeCommentText={this.removeComment.bind(this)}> {text}</CommentBox> 
                            );
                }

                render(){
                    return(
                        <div className="container-fluid">{
                        this.state.comments.map(this.eachComment.bind(this))
                        }
                        </div>
                    );
                }
            } 
            ReactDOM.render(
                <Board />
                , document.getElementById('content'))
            </script>
        </body>

        </html>

Building First ReactJS Example

Posted on Updated on

 

 

Below is sample example of ReactJS in which a counter variable is an increment or decrement by 1 on onClick event that is binding with a button.

Here is a complete example.

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title></title>
  </head>
  <body>
    <div id="content"></div>

    <script src="https://fb.me/react-0.14.7.js"></script>
    <script src="https://fb.me/react-dom-0.14.7.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
    
    
    <script type="text/babel">

        class CounterValue extends React.Component{
        constructor(props){
            super(props);
            this.state = {
            counter : 0
            };
        }

        onIncrementClickHandler() {
            this.setState({counter:this.state.counter +1})
        }

        onDecrementClickHandler() {
            if(this.state.counter == 0 ){
                return;
            }else{
             this.setState({counter:this.state.counter -1})
            }
        }
        render() {
            return (
            <div>
                <input type="button" onClick={this.onIncrementClickHandler.bind(this)} value="Increment"/>
                <input type="button" onClick={this.onDecrementClickHandler.bind(this)} value="Declement"/>
                <div>Counter value is  : {this.state.counter}</div>
                </div>
            );
        }
        }

      ReactDOM.render(<CounterValue />, document.getElementById('content'))
    </script>
  </body>
</html>

Command Design Pattern

Posted on Updated on

Command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time.

  1.  Decouple the caller and receiver call so the caller doesn’t know about receiver or receiver doesn’t know about a caller, they are communicating with Command layer.
  2. Allows requests to be encapsulated as objects, thereby allowing clients to be parametrized with different requests.
  3. delegates a request to a command object instead of implementing a particular request directly.

Key Points:-

Client – creates a ConcreteCommand object and sets its receiver.
Invoker – Asks the command to carry out the request;
Command – it is performing as “tokens” that are created by one client that knows what need to be done and passed to another client that has the resources for doing it.
Receiver –  knows how to perform the operations;

Below is snippet code for Command Design Pattern.

Command.Java – Here, Command decouples the object that invokes the operation from the one that knows how to perform it

package com.design.db;

public interface Command {
    Task submit();
}

DBSaveCommand.Java

package com.design.db;

public class DBSaveCommand implements Command {

    private final Object toBeObject;
    private final Class<?> persistCollection;
    private Receiver receiver = new DBProcessor();

    public DBSaveCommand(Class<?> persistCollection, Object object) {
        this.persistCollection = persistCollection;
        this.toBeObject = object;
    }

    @Override
    public Task submit() {
        try {
            this.receiver.save(this.persistCollection, this.toBeObject);
        } catch (Exception e) {
            return () -> e.getMessage();
        }
        return () -> new String("Save");
    }
}


DBRemoveCommand.Java

package com.design.db;

public class DBRemoveCommand implements Command {

    private final Object toBeObject;
    private final Class<?> persistCollection;
    private Receiver receiver = new DBProcessor();

    public DBRemoveCommand(Class<?> persistCollection, Object object) {
        this.persistCollection = persistCollection;
        this.toBeObject = object;
    }

    @Override
    public Task submit() {
        try {
            this.receiver.remove(this.persistCollection, this.toBeObject);
        } catch (Exception e) {
            return () -> e.getMessage();
        }
        return () -> new String("Delete");
    }
}


DBFetchByIdCommand.Java

package com.design.db;

public class DBFetchByIdCommand implements Command {

    private final Long toBeObject;
    private final Class<?> persistCollection;
    private Receiver receiver = new DBProcessor();

    public DBFetchByIdCommand(Class<?> persistCollection, Long object) {
        this.persistCollection = persistCollection;
        this.toBeObject = object;
    }

    @Override
    public Task submit() {
        try {
            return () -> this.receiver.fetchById(this.persistCollection, this.toBeObject);
        } catch (Exception e) {
            return () -> e.getMessage();
        }
    }
}

DBFetchAllCommand.Java

package com.design.db;

public class DBFetchAllCommand implements Command {
    private final Class<?> persistCollection;
    private Receiver receiver = new DBProcessor();

    public DBFetchAllCommand(Class<?> persistCollection) {
        this.persistCollection = persistCollection;
    }

    @Override
    public Task submit() {
        try {
            return () -> this.receiver.fetchAll(this.persistCollection);
        } catch (Exception e) {
            return () -> e.getMessage();
        }
    }
}

Receiver.Java

package com.design.db;

import java.util.Collection;

public interface Receiver {

    void save(Class<?> persistCollection, Object object);

    void remove(Class<?> persistCollection, Object object);

    Object fetchById(Class<?> persistCollection, Long id);

    Collection<?> fetchAll(Class<?> persistCollection);
}



DBRequestProcessor.Java – All the operation are perform here and only Command knows about the receiver and invokes the method of a receiver that is passed on through parameters.

package com.design.db;

import java.util.Collection;
import java.util.Collections;

public class DBRequestProcessor implements Receiver {


    @Override
    public void save(Class<?> persistCollection, Object object) {
        System.out.println("Entity Save");
    }

    @Override
    public void remove(Class<?> persistCollection, Object object) {
        System.out.println("Entity Removed");
    }

    @Override
    public Object fetchById(Class<?> persistCollection, Long id) {
        return id;
    }

    @Override
    public Collection fetchAll(Class<?> persistCollection) {
        return Collections.EMPTY_LIST;
    }
}

Invoker.Java

package com.design.db;

public interface Invoker {
    Task invoke(Command command);
}


DBCommandInvoker.Java – Invoker only know how to execute the Command and unknown about their concrete implementation of Command Interface.

package com.design.db;

public class DBCommandInvoker implements Invoker {


    public DBCommandInvoker() {
    }

    @Override
    public Task invoke(Command command) {
        return command.submit();
    }
}

Task.Java

package com.design.db;

public interface Task<T> {
    T get();
}


SqlRepository.Java :- This is Client here, which decides which command to be executed. to execute the Command, it passes to invoker object i.e DBCommandInvoker.

package com.design.db;

import java.util.Collection;

public class SqlRepository {

    private Invoker dbCommandInvoker = new DBCommandInvoker();

    public void save(Class zlass, Object payload) {
        dbCommandInvoker.invoke(new DBSaveCommand(zlass, payload));
    }

    public void remove(Class zlass, Long id) {
        dbCommandInvoker.invoke(new DBRemoveCommand(zlass, id));
    }

    public Object fetchById(Class zlass, Long id) {
        return dbCommandInvoker.invoke(new DBFetchByIdCommand(zlass, id)).get();
    }

    public Collection fetchAll(Class zclass) {
        return (Collection) dbCommandInvoker.invoke(new DBFetchAllCommand(zclass)).get();
    }
}


What is Directive in AngularJS?

Posted on Updated on

What is Directive in AngularJS?

Directives are core building blocks of AngularJS which are used to create custom HTML tags and can be placed in element names, attributes and comments. Directives can be used as HTML directives which build complex widgets with layered functionality.

Scope in Directive in AngularJS?

Unlike the other MVC frameworks, AngularJS doesn’t have specific classes or functions to create model objects. Instead, AngularJS extended the raw JavaScript objects with custom methods and properties. These objects, also known as scope in AngularJS terms, work as a glue between the view and other parts ( directives, controllers and services ) inside the AngularJS application.

Whenever the AngularJS application is bootstrapped, a rootScope object is created. Each scope created by controllers, directives and services are prototypically inherited from rootScope. AngularJS documentation is one of the best resources to learn how scope inheritance works: see Scopes in AngularJS. Understanding how scope inheritance works will be useful in following sections.

Directive Types:

You can implement the following types of directives:

The restrict option is typically set to:

  • 'A' – only matches attribute name
  • 'E' – only matches element name ( by Default )
  • 'C' – only matches class name
  • 'M' – only matches comment

These restrictions can all be combined as needed:

  • 'AEC' – matches either attribute or element or class name

 

Link – Programmatically modify resulting DOM element instances, add event listeners, and set up data binding.

Compile – Programmatically modify the DOM template for features across copies of a directive, as when used in ng-repeat. Your compile function can also return link functions to modify the resulting element instances.

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 –– let’s call it as DDO –– is a simple JavaScript object used for configuring the directive’s behaviour,template..etc. Check out AngularJS docs about DDO.

scope values can be either “false”“true” or “{}” in AngularJS directive.

Different types of directive scopes

Scope : False ( Directive uses its parent scope )

There will be no scope created in DDO therefore Directive use it parent scope. Any change made on the directive scope will be reflected in parent scope and vice versa. Both Controller and Directive scope will be in sync.

Scope : true ( Directive get new  scope )

it gets its own scope by setting up scope equals to true and assigned to directive.  This newly created scope object is prototypically inherited from its parent scope ( the controller scope where it’s been used ).

Let’s see difference between setting two  scope:false and scope:true

  • When scope is set to “true”, AngularJS will create a new scope by inheriting parent scope ( usually controller scope, otherwise the application’s rootScope ). Any changes made to this new scope will not reflect back to the parent scope. However, since the new scope is inherited from the parent scope, any changes made in the Ctrtroller ( the parent scope ) will be reflected in the directive scope.
  • When scope is set to “false”, the controller Controller and directive are using the same scope object. This means any changes to the controller or directive will be in sync.

Scope : { } ( Directive gets a new isolated scope )

Till now, we saw two situations for directive scope creation. In the third type, we are going to set scope property in DDO to an Object literal. When an object literal is passed to the scope property, things are bit different. This time, there will be a new scope created for the directive, but it will not be inherited from the parent scope. This new scope also known as Isolated scope because it is completely detached from its parent scope.

  • 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. The next section is dedicated to Isolated scope and its properties.

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 )
  1. 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.
  2. 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.
  3. 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.

 

Create a new Groovy project using maven

Posted on Updated on

This is a first exercise of writing a groovy program in IntelliJ IDE. See the first post of What is Groovy here?

Below is the complete example of Groovy using maven setup.

  • Create a folder as Project name i.e GroovyExample in your project folder.
  • Create an XML ( pom.xml )file under GroovyExample folder and named it as pom.xml.
  • Copy and paste the content of pom.xml as given inline below.
  • Open IntelliJ IDE and Click on File-> Open and select pom.xml file under GroovyExample folder by navigating it through.
  •  While importing all dependencies in given pom.xml into your project then you can start writing Groovy program.
  • Right click on Project and Create a directory i.e /src/main/groovy under which all groovy file will be placed.
  • Next, Select /groovy folder and right-click to create a new Groovy file.
  • Give proper groovy file name and click OK.
  • A Groovy file will be open then continue with Groovy code as given.

Maven POM.xml file

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>GroovyExample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <!--http://start.spring.io/-->
    <name>GroovyExample</name>
    <description>Demo project for Groovy Example</description>


    <dependencies>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerId>groovy-eclipse-compiler</compilerId>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.codehaus.groovy</groupId>
                        <artifactId>groovy-eclipse-compiler</artifactId>
                        <version>2.7.0-01</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.eclipse.jdt.groovy.core.groovyNature</projectnature>
                    </additionalProjectnatures>
                    <sourceIncludes>
                        <sourceInclude>**/*.groovy</sourceInclude>
                    </sourceIncludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Groovy file here :-

groovy-first-example

What is Groovy?

Posted on Updated on

 

What is Groovy?

Groovy is an optionally Typed, Dynamically language that runs on JVM. It is tightly integrated with the Java Language and its feature is enabled as rich and  Java friendly.

Groovy supports standard Java constructs including annotations, generics, static imports, enums, varargs and lambda expression.

Groovy source code is compiled into Java byte-code by the Groovy compiler. To run Groovy code in a Java virtual machine, only the Groovy JAR file must be present in the classpath at runtime.

A Groovy source files ends with the .groovy extension. This file can contain a Groovy script or a Groovy class.

Compatibility with Java

Groovy runs on the JVM and can use Java libraries. Every Groovy type is a subclass ofjava.lang.Object.

Groovy does currently not support Java 8 lambda expressions.

Reasons to use Groovy

Groovy focus on simplicity and very productive.

  • Simplification : – Groovy does not require a semicolon to terminate the line. return type can be omitted, by default Groovy return the last expression of the line as return type. public keyword can be omitted, it is a Default in Groovy, Also it allows optional typing.
  • Ease of use – Groovy has list, maps and regular expressions directly build into the language.
  • Simplification in I/O – parsing and creating XML, JSON and files are very simple with Groovy.
  • Flexibility – Groovy allows to change classes and methods at runtime, e.g. if a method is called which does not exist on a class, the class can intercept this call and react to it. This allows for example that Groovy provides a very flexible builder pattern.
  • Easy to use : – Groovy has list, maps and regular expressions directly build into the language.
  • Simplification in I/O – parsing and creating XML, JSON and files are very simple with Groovy.

Setup Groovy in IntelliJ:-

Steps to follow to install Groovy in you IntelliJ.

  • Open IntellJ IDE.
  • Go to File->Settings -> plugin
  •  Choose Groovy in plugin Text box and install.
  • Once Groovy get installed in your IDE, then you will able to create a Groovy file and run it.
  • groovy-setup

 

Exercise :-