Month: June 2015

Difference between @Component and @Bean in Spring

Posted on Updated on

spring-logo

This is also frequently asked interview question for experience Java interview question. Most of Java developer  get confused to deliver the right answer to interviewer. Though Spring also create a lot of confusion about annotation and manual base configuration and other things but good concept and knowledge are always appreciable.

Here, In this section we will discuss difference between @component (@service,@repository and @controller) and @bean annotation.

First of all @component is a generic annotation and it can be used across the application. In enterprises or multi-layer application it is classified into @service,@repository and @controller for more code readable and understandable.

Technically on multi-layer application has application layer, Service layer,business layer and persistence layer. Subsequently annotations are used to represent it.

Different between @Component and @Bean

@Component, @Service, @Repository and @Controller annotations are used for automatic bean detection using classpath scan in Spring framework. Spring container automatically scan and identify all beans annotated by @Component, @Service, @Repository and @Controller.
Service Layer :-

@Service("userService")
public class UserService {

....

}

Persistence Layer :-

@Repository("userDAO")
public class UserDAO {

....

}

Controller / Presentational Layer :-

@Controller("userController")
public class UserController {

....

}

Root component Package defined in spring configuration xml file then spring container scan and initialized all classes present in the classpath coming under the base-package annotated.

<context:component-scan base-package="com.service" />

@Bean annotation is used to explicitly declare a single bean rather than letting spring container do it automatically. It decouples the declaration of bean from bean definition.


public class AuthenticationService {
	
	private static final Logger logger = Logger.getLogger(AuthenticationService.class);
        ...
        ...
}
@Configuration
public class AppConfig {
@Bean(name="authenticationService")
    public AuthenticationService getAuthenticationService(){
    	return new AuthenticationService();
    }
}

 

More stereotype annotation details as below :- 

  • @Component – generic and can be used across application.
  • @Service – annotate classes at service layer level.
  • @Controller – annotate classes at presentation layers level, mainly used in Spring MVC.
  • @Repository – annotate classes at persistence layer, which will act as database repository.

Disable automatic scan of @Component, @Repository, @Service, @Controller:


<beans>
<context:component-scan use-default-filters = "false" base-package="com.service" /> 
</beans>

 

Arithmetic Operation Using AngularJS

Posted on Updated on

angularjs

Another simple example to calculate Arithmetic operation like +,-,*,/,% operator between two operands.


<!DOCTYPE html >
<html ng-app="dashboard">
<head>
<title>AngularJS</title>
<script type="text/javascript" src="./js/angular.min.js"></script>
</head>
<body ng-controller="myController">
<h1>Welcome to AngularJS Example2</h1>
<table border='1'>
<tr>
<td colspan='2'>
<h2>Arithmetic Operation</h2>
</td>
</tr>
<tr>
<td>Enter First Operand</td>
<td><input type="number" ng-model="number1"></td>
</tr>
<tr>
<td>Enter Second Operand</td>
<td><input type="number" ng-model="number2"></td>
</tr>
<tr>
<td>Select Operator</td>
<td><select ng-model="operation"
ng-options="item for item in operations">
</select></td>
</tr>
<tr>
<td>Result is</td>
<td>{{result}}</td>
<tr>
<td><input type="button" ng-click="AddMe()" value="Result"></td>
</tr>
<table>
</body>

<script>
var dashboard = angular.module("dashboard", []);

dashboard.controller('myController', function($scope) {

$scope.operations = [ '+', '-', '*', '/', '%' ];
$scope.AddMe = function() {

var num1 = $scope.number1;
var num2 = $scope.number2;
switch ($scope.operation) {
case '+':
$scope.result = parseInt(num1) + parseInt(num2);
break;
case '-':
$scope.result = parseInt(num1) - parseInt(num2);
break;
case '*':
$scope.result = parseInt(num1) * parseInt(num2);
break;
case '/':
$scope.result = parseInt(num1) / parseInt(num2);
break;
case '%':
$scope.result = parseInt(num1) % parseInt(num2);
break;
default:
$scope.message = "Invalid Selection ";
break;

}
};

});
</script>

</html>

Output here :-

angular-exm-002

Simple Add Operation using AngularJS

Posted on

angularjs

Below are very simple example of AngularJS that Add two number. As discussed in “Introduction of AngularJS“, It’s  a powerful Javascript framework that is used to build a rich and dynamic web application.

In this example, we will see how to implement add operation using AngularJS. However, It is easy to write same program in Javascript or other client script language but it would be little bits hard for start-up to write using AngularJS. Here we will discuss code.

ng-app : Specify an AngularJS module to be used as the root module for the application.

Specify module name “dashboard” on root elements.

<html ng-app="dashboard">

Create an object of module “dashboard”.

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

ng-controller : The ngController directive specifies a Controller class; the class contains business logic behind the application to decorate the scope with functions and values.

Here, module has controller component in AngularJS so create a Controller using controller name and callback function…

AddMe() is defined in button  inside ng-controller “myController” so it’s implementation would be under Controller block.

dashboard.controller('myController', function($scope) {
$scope.AddMe = function() {

var num1 = $scope.number1;
var num2 = $scope.number2;

$scope.result = parseInt(num1) + parseInt(num2);
};

ng-model :- Binding the view into the model, which other directives such as input, textarea or select require.
<input type="number" ng-model="number1">

Download AngularJS Framework from angularjs.org on your file system.

  1. Create a folder on your file system like AngularJSExample1
  2. Download AngularJS Framework and put “angular.min.js” under AngularJSExample1/js/
  3. Create a index.html file under root directory AngularJSExample1.
  4. Copy and paste below html code into index.html
  5. Save and run into browser…

 


<!DOCTYPE html >
<html ng-app="dashboard">
<head>
<title>AngularJS</title>
<!--<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script> -->

<script type="text/javascript" src="./js/angular.min.js"></script>
</head>
<body ng-controller="myController">
<h1>Welcome to AngularJS</h1>
<table border='1'>
<tr>
<td colspan='2'>
<h2>Arithmetic Operation</h2>
</td>
</tr>
<tr>
<td>Enter First Operand</td>
<td><input type="number" ng-model="number1"></td>
</tr>
<tr>
<td>Enter Second Operand</td>
<td><input type="number" ng-model="number2"></td>
</tr>
<tr>
<td>Result is</td>
<td>{{result}}</td>
<tr>
<td><input type="button" ng-click="AddMe()" value="Result"></td>
</tr>
<table>
</body>

<script>
var dashboard = angular.module("dashboard", []);

dashboard.controller('myController', function($scope) {
$scope.AddMe = function() {

var num1 = $scope.number1;
var num2 = $scope.number2;

$scope.result = parseInt(num1) + parseInt(num2);
};
});
</script>

</html>

Output here : –

angular-exm-001

Introduction of AngularJS

Posted on Updated on

angularjs

What is AngularJS ?

AngularJS is a powerful and structural JavaScript framework which is easier to implement in single web applications and allows organizing large, client heavy applications into something manageable. It is an open source web application framework, free and used by thousands of developers around the world.

AngularJS is based on the MVC(Model View Control) pattern that is intended to build rich internet web applications and simplify both development and testing of applications by using MVC architecture and separating your rich internet applications into models, views and controllers. AngularJS creates single page applications, which means the browser is going to load a single page regardless of the size of your application.

AngularJS was developed by Miskohevery and Adam Abron, maintained by Google; used internally by them and MIT. It is licensed under the Apache License version 2.0. It was initially released in 2009 and the current stable release is 1.3.x (Decemeber 1, 2014).

 

AngularJS: In this section, let us summarize the basics of AngularJS.

  • Is a library written in JavaScript
  • Is not a platform or language
  • Is not a plug-in or extension
  • It extends HTML, CSS and JavaScript
  • Is not a DOM manipulation library like jQuery
  • Does not require jQuery or inheritance
  • Does not require one-way data binding and boilerplate code

Why AngularJS?

  • It is based on MVC design pattern which provides numerous ways to build web application at client side.
  • It helps to build client side applications with less code and more flexibility.
  • It extends HTML by using functionality of directives, attributes, expressions and templates to HTML.
  • AngularJS is a MVC architecture which simplifies the development and testing of applications easily for client side.
  • It is good for developing single page applications and front ends for web based applications.
  • It has flexible framework and versatile features. So it is used for both large app projects and small little applications.

Features:

AngularJS (JavaScript based framework) creates applications in a faster way by using several features such as:

  • It is a client side technology which provides powerful things to create dynamic web applications.
  • It is a MVC based framework, allows users to build proper architecture and maintainable web applications.
  • It is an open source web application framework used by thousands of developers around the world.
  • It allows use of reusable components and code reuse.
  • It makes creation of user interface (UI) easy through data binding process.
  • Declarative HTML approach.
  • It helps to divide your application into smaller parts.

Architectural Diagram and Components: Let us have a look at the architecture diagram of the AngularJS framework and its components.

angular-js-architecture

AngularJS contains modules which act as a container for different types of applications such as controllers, views, directives, factory etc. Module specifies how an application should be bootstrapped. Using modules, processes will be easier to understand; you can reuse the code, end to end tests uses modules to override the configuration etc. It is the place for creating, registering and retrieving angular modules.

Config component only accepts providers from modules, means every service, factory etc are instances of provider. It provides all these instances to routes.

The Routes are used for linking URL’s to controllers and views.

The Views are used to add sophisticated handling of user events. It uses ng-view directive that complements route service by template of the current route to the main layout (index.html) file.

The controller controls the data of AngularJS applications which are regular JavaScript objects. AngularJS defines ng-controller directive which creates new controller objects by using controller function. And new child is available to the controller function as $scope as shown in the diagram.

The views sends element or attribute to the directives which tells AngularJS’s HTML compiler to attach specific behavior to the DOM element and its children.

The factory is used to define the AngularJS service and it is called when a service needs to be instantiated.

Getting Started with AngularJS:

AngularJS is easy to start with. It provides features like two way data binding which makes custom tags, attributes which encapsulate built-in directives that make extending functionality of HTML easier.

  • It is distributed JavaScript file and can be used in a webpage by including AngularJS library as shown below:

<script src=”http:// ajax.googleapis.com/ajax/libs/ angularjs /1.2.26/ angular.min.js”>

</script>

You can also check the latest version of AngularJS on their official website.

  • You can create AngularJS application as shown below:

<htmlng-app></html>

Or

<html ng-app=”MyApp”></html>

Or

<divng-app></div>

Or

<div ng-app=”MyApp”></div>

 

The ng-app attribute is the root element of the AngularJS app.

  • Controller can be defined as shown below:

<div ng-app=” “ ng-controller=”MyController”>

<input type=”text” ng-model=”message”>

</div>

The ng-controller directive defines the application controller. The ng-model directive binds the value of HTML controls such as input fields, select etc to the application data.

  • Implement the controller by using $scope object as written below:

functionMyController($scope){

$scope.message=”Enter your name”;

}

The $scope object refers to the application model which invokes the controller that creates messageproperty in the scope.

Core Concepts: In this section we will have a detailed discussion about the core components and the concepts behind them.

  • Modules
  • Directives
  • Scope
  • Controllers
  • Expressions
  • Templates
  • Routing
  • Filters

Modules:

Modules provide excellent mechanism for dividing the application into small reusable components and specify how an application should be bootstrapped. Modules specify how you define the components in the application and makes application more readable. Each module is identified by a unique name.

Directives:

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:

Scope is an object that binds a view to the controller. In MVC structure, it refers to the application model. Scopes can watch expressions and propagate events as they are arranged in hierarchical structure.

Controllers:

Controllers are JavaScript objects that defines the actual behavior of your app. It is responsible for setting model properties and functions by using $scope object. The controller does not store state and does not interact with remote services.

Expressions:

Expressions are written inside curly braces “{{   }}” denote bindings which referrers to our application model. Expressions do not support control flow statements. AngularJS will output the data where they are used.

Templates:

Template is just old-plain-HTML that does not include any angular specific file templates. It comes with a set of live templates to create controllers etc by using template engine. Templates are used to show information from the model and controller.

Routing:

It is used for linking URL’s to controller and views. Routing is taken care by service providers called$routeProvider to handle routing which is the provider of the $route service. In other words, it’s loading of sub templates depending upon the URL of the page.

Filters:

Filters are used with expressions to transform or modify the data from the models. We can add expressions or directives using pipe character. AngularJS has some of the commonly used filters such as:

  • currency: converts number to currency format.
  • uppercase: converts strings to uppercase.
  • lowercase: converts strings to lowercase.
  • filter: selects subset of items from array.
  • orderBy: orders array by the expression such as ordered alphabetically for strings and numerically for numbers.

Example:

Let’s create one simple example using AngularJS library and create a HTML file as FirstExample.html as shown below:

Listing1: Simple AngularJS application


<!DOCTYPE html>

<html>

<head>

<script src= “http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js”></script>

</head>

<body>

<div ng-app=”” ng-controller=”MyController”>

Enter Name: <input type=”text” ng-model=”userName”><br><br>

Full Name: {{userName}}

</div>

<script>

functionMyController($scope) {

$scope.userName = “David”;

}

</script>

</body>

</html>

As discussed, we have included AngularJS JavaScript file in the HTML page which is defined within the <head> tag. The next part contains AngularJS app which is defined using the ng-app attribute runs inside the <div> tag.

The ng-controller directive defines the application controller. The AngularJS will invoke the “MyControllerwith $scope object which creates property called “usernamein the scope.

Define the model name using ng-model directive defined in the <input> tag. It binds the input field to the controller property “username”.

 

Example here :-

  1. Add two number using AngularJS
  2. Arithmetic Operation using AngularJS.

 

Spring Transaction isolation level

Posted on Updated on

Spring 3 In this discussion, we will see how Spring provided DBMS Transaction Isolation. Here we will elaborate one by one about transaction and it attributes.

Transaction : – It is a sequence of operations ( like read,update and write ) that works as a unit to accomplish a task. like Booking a ticket,Selling a item.

Isolation Level :-  Transaction specify isolation level that defines the degree to which one transaction must be isolated from other resource or data modification by other transaction. A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction

Choosing the transaction isolation level does not affect on lock that are acquired to protect the data modification But it’s control the data modification by more than one transaction by define good Isolation level. A low Isolation may be increased the ability of users to access the data at the same time that increase the number of concurrency i.e dirty read or lost of data. conversely higher Isolation level  reduces the type of concurrency effect that user may encounter.

A valid Transaction has four properties that is known as ACID.

  1. Atomicity: It says either all operation get successful or roll-back completely means if any of transaction fails then entire transaction fails.
  2. Consistency: Database remains consistent ( one valid state to other ) after every transaction.
  3. Isolation: Each instance of Transaction work separately in concurrent execution. No two or more transaction instance can be interference or visible to each other.
  4. Durability: Once the transaction is committed then it must be written permanently into Database even if power failure or system failure.

Every RDBMS supports ACID properties like Oracle,MySQL,Microsoft SQL Server,PostgreSQL or more and concept is remains same thought-out technologies.

Transaction isolation is a concept in Spring Framework that applied to Transaction and related with ACID properties.  Isolation level determined how a transaction to be visible to other transaction in concurrent execution. Lower level Isolation increase concurrency effect ( like dirty read and lost of updation) . However higher level Isolation type reduce the concurrency effect that user may encounter.

Hence,Isolation Lavel says, Changes made by one transaction on table data must be visible correctness to other transaction and data must not be dirty or corrupted. 

Isolation Level :- 

  1. Read Uncommitted
  2. Read Committed
  3. Repeatable Read
  4. Serializable

Example : –

In Spring, @Transactional annotation is use to define a Isolation level in your business layer. This mean given method execute under transaction Isolation level.


@Autowired
private UserDAO userDAO;

@Transactional(isolation=Isolation.READ_COMMITTED)
public void signUp(User user) {

  // Interact with userDAO

}

here, we have defined a signUp() to be executed in a Transaction under Isolation level READ_COMMITED.

The following table shows the concurrency side effects allowed by the different isolation levels.

Isolation Level Dirty Read Non Repeatable Read Phantom
Read uncommitted Yes Yes Yes
Read committed No Yes Yes
Repeatable read No No Yes
Snapshot No No No
Serializable No No No
  • Read committed (Database Engine default level)

Read Uncommitted

It is also called a dirty read, Occurs when a transaction allow to read a data from Database which has been modified by other running transaction and not yet committed.

Example : suppose transaction t1 fetched a row a =10 and transaction t2 update to 20 i.e a =20 again transaction t1 fetched same data which return a =20 and then transaction t2 rollback it changes then value a become 10 but still t1 can see a = 20;

Non-repeatable reads

It will happened when one transaction retrieve a row twice then fetched row value get different.

Example :-  suppose Transaction T1 fired a query (“select * from employee where id=1”)

then Second Transaction T2 updated the row values and committed.

Again T1 fired the same query then value would be different.

 

Phantom reads

A phantom read occurs when, in the course of a transaction, two identical queries are executed, and the collection of rows returned by the second query is different from the first.

Foreach vs iterator in Java

Posted on Updated on

6db3a-download Most of you are familiar with these two words. Primarily uses of  for-each is iterator over Array but it’s also used to iterator over Collections. While Iterator() method of Iterable interface  is used to iterator over Collection classes.

In Java Collection Interface, it extends to Iterable Interface which contains an Iterator() method that produced an Iterator. So we can say that all Collection classes has a Iterator() to move throughout a sequences or a collection. Since Map Interface  is not a part of Collection  so Iterator() method is not available in Map but keySet() or values() of Map Interface returns a Collection which is subsequently implemented Iterable Interface.

For-each Example here


import java.util.*;
public class ForEachCollections {
	public static void main(String[] args) {
		Collection cs = new LinkedList();
		Collections.addAll(cs, "Take the long way home".split(" "));
		for (String s : cs)
			System.out.print("‘" + s + "‘ ");
	}
} /* Output:
‘Take’ ‘the’ ‘long’ ‘way’ ‘home’ */

Since cs is a Collection, this code shows that working with foreach is a characteristic of all Collection objects.

The reason that this works is that Java SE5 introduced a new interface called Iterable which contains an iterator( ) method to produce an Iterator, and the Iterable interface is what foreach uses to move through a sequence. So if you create any class that implements Iterable, you can use it in a foreach statement:


import java.util.*;
class IterableClass implements Iterable {
	protected String[] words = ("And that is how "
			+ "we know the Earth to be banana-shaped.").split(" ");

	public Iterator iterator() {
		return new Iterator() {
			private int index = 0;

			public boolean hasNext() {
				return index < words.length;
			}

			public String next() {
				return words[index++];
			}

			public void remove() { // Not implemented
				throw new UnsupportedOperationException();
			}
		};
	}

	public static void main(String[] args) {
		for (String s : new IterableClass())
			System.out.print(s + " ");
	}
} /* /* Output:
And that is how we know the Earth to be banana-shaped.  */

The iterator( ) method returns an instance of an anonymous inner implementation of
Iterator which delivers each word in the array. In main( ), you can see that
Iterable Class does indeed work in a foreach statement.

In Java SE5, a number of classes have been made Iterable, primarily all Collection classes
(but not Maps). For example, this code displays all the operating system environment
variables:


import java.util.*;
class EnvironmentVariables {
	public static void main(String[] args) {
		for (Map.Entry entry : System.getenv().entrySet()) {
			System.out.println(entry.getKey() + ": " + entry.getValue());
		}
	}
}

System.getenv( )7
returns a Map, entrySet( ) produces a Set of Map.Entry elements,
and a Set is Iterable so it can be used in a foreach loop.

A foreach statement works with an array or anything Iterable, but that doesn’t mean that an
array is automatically an Iterable, nor is there any autoboxing that takes place


class ArrayIsNotIterable {
	static  void test(Iterable ib) {
		for (T t : ib)
			System.out.print(t + " ");
	}

	public static void main(String[] args) {
		test(Arrays.asList(1, 2, 3));
		String[] strings = { "A", "B", "C" };
		// An array works in foreach, but it’s not Iterable:
		// ! test(strings);
		// You must explicitly convert it to an Iterable:
		test(Arrays.asList(strings));
	}
}
/* /* Output:
1 2 3 A B C   */

Trying to pass an array as an Iterable argument fails. There is no automatic conversion to
an Iterable; you must do it by hand.

 

Thanks, Please post your comments.

What is difference between (| and || ) and ( & and && ) in Java.

Posted on Updated on

6db3a-downloadThe operators || and && are called conditional operators, while | and & are called bitwise operators. They serve different purposes.
Conditional operators works only with expressions that statically evaluate to boolean on both left and right side.
Bitwise operators works with any numeric operands.
If you want to perform a logical comparison, you should use conditional operators, since you will add some kind of type safety to your code.

a | b: evaluate b in any case

a || b: evaluate b only if a evaluates to false

| is the binary or operator
|| is the logic or operator

Below are some conclusion here :

the operand of every expression is evaluated before the operation is performed except for the short-circuit operators (&&, ¦¦) and ternary operator
behaviour can produce unexpected results if you’re not careful. For example, the following code illustrates what can occur if you try to set the value of a variable in an if condition and you always expect the new value to be available:

int i = 10;
int j = 12;

if( (i<j) ¦ (i=3) > 5 ) // value of i after oper: 3
if( (i<j) ¦¦ (i=3) > 5 ) // value of i after oper: 10

if( (i>j) & (i=3) > 5 ) // value of i after oper: 3
if( (i>j) && (i=3) > 5 ) // value of i after oper: 10

  • with & and ¦ both operands are always evaluated.
  • with && and ¦¦ the second operand is only evaluated when it is necessary.
  • with ¦¦ (i<j) evaluates to true; there is no need to check the other operand as ¦¦ returns true if either of the operands are true.
  • with && (i>j) evaluates to false; there is no need to check the other operand as && returns true only if both operands are true. In this case one is false so there is no need to check the other operand