Thursday, October 25, 2012

XML vs Annotations

XML
Annotations
More verbose because has to duplicate a lot of information like class names and method names from your code.

Less verbose since class names and method names are part of your code.
Less robust due to duplication of information which introduces multiple points for failure. If you misspell a method name then the application will fail.
More robust because annotations are processed with your code and checked by the compiler for any discrepancies and
inaccuracies.

More flexible since processed separately from the code.
Since it is not hard-coded can be changed later. Your deployment team has a great flexibility to inspect and modify the configuration.
Less flexible since annotations are embedded in Java comment style within your code.

For example, to define a stateless session EJB 3.0 with annotations, which can serve both local and remote clients:

@Stateless
@Local ({LocalCounter.class})
@Remote ({RemoteCounter.class})
public class CounterBean implements LocalCounter,
RemoteCounter {
...
}

XML files can express complex relationships and hierarchical structures at the expense of being verbose.

Annotations can hold only a small amount of configuration information and most of plumbing has to be done in the framework.


Which one to use? Annotations are suitable for most application needs. XML files are more complex and can be used to address more advanced issues. XML files can be used to override default annotation values. Annotations cannot be used if you do not have access to source-code. The decision to go with annotation or XML depends upon the architecture behind the framework.

For example Spring is primarily based on XML and EJB 3.0 is primarily based on annotations, but both support annotations and XML to some degree. EJB 3.0 uses XML configuration files as an optional overriding mechanism and Spring uses annotations to configure some Spring services.

ref element

The ref element is the final element allowed inside a property definition element. It is used to set the value of the specified property to be a reference to another bean managed by the container, a collaborator, so to speak. As mentioned in a previous section, the referred-to bean is considered to be a dependency of the bean who's property is being set, and will be initialized on demand as needed (if it is a singleton bean it may have already been initialized by the container) before the property is set. All references are ultimately just a reference to another object, but there are 3 variations on how the id/name of the other object may be specified, which determines how scoping and validation is handled.





<ref bean="someBean"/>
Specifying the target bean by using the bean attribute of the ref tag is the most general form, and will allow creating a reference to any bean in the SAME BeanFactory/ApplicationContext (whether or not in the same XML file), or parent BeanFactory/ApplicationContext. The value of the bean attribute may be the same as either the id attribute of the target bean, or one of the values in the name attribute of the target bean.
  



  <ref local="someBean"/>


Specifying the target bean by using the local attribute leverages the ability of the XML parser to validate XML id references within the SAME file. The value of the local attribute must be the same as the id attribute of the target bean. The XML parser will issue an error if no matching element is found in the same file. As such, using the local variant is the best choice (in order to know about errors are early as possible) if the target bean is in the same XML file.




  
  <ref parent="someBean"/>


Specifying the target bean by using the parent attribute allows a reference to be created to a bean which is in a parent BeanFactory (or ApplicationContext) of the current BeanFactory (or ApplicationContext). The value of the parent attribute may be the same as either the id attribute of the target bean, or one of the values in the name attribute of the target bean, and the target bean must be in a parent BeanFactory or ApplicationContext to the current one. The main use of this bean reference variant is when there is a need to wrap an existing bean in a parent context with some sort of proxy (which may have the same name as the parent), and needs the original object so it may wrap it.

Wednesday, October 24, 2012

CopyOnWriteArrayList and ConcurrentHashMap

CopyOnWriteArrayList ( introduced in Java 1.5 )
  
CopyOnWriteArrayList vs Array List in Java

CopyOnWriteArrayList and ConcurrentHashMap are concurrent Collection classes introduced in Java 5 Concurrency. 

A CopyOnWriteArrayList implement List interface like ArrayList, Vector and LinkedList but it’s a thread-safe collection and it achieves its thread-safety in a slightly different way than Vector or other thread-safe collection class.
ArrayList is not thread safe so any simultaneous thread can access and modify the content of list simultaneously.Here lies the dangerous, ConcurrentModificationException (Runtime exception). When one thread is Iterating over an ArrayList and any other thread(which may be the same thread)  modify the content of list and when we again call next() on the iterator ,we get this exception. Which means that no thread can modify the ArrayList while an Iterator is iterating over this. We can solve this by surrounding the code that try to modify this list in a synchronized block with some lock so that the thread trying to modify the ArrayList wait for the iterator to complete.
This seems simple solution but not an efficient one where there are many threads iteration over an ArrayList because each thread has to wait for a considerable time.
Another possible solution could be to use CopyOnWriteArrayList instead of ArrayList. This is same as ArrayList with one difference. All operations that change the contents of a CopyOnWriteArrayList collection cause the underlying array to be replaced with a copy of itself before the contents of the array are changed. Any active iterators will continue to see the unmodified array, so there is no need for locks. Iterators created by a CopyOnWriteArrayList object cannot change the underlying array. Though these iterators do have methods for changing the underlying collection, their implementations throw an UnsupportedOperationException instead of modifying the underlying collection.
 As name suggests CopyOnWriteArrayList creates copy of underlying ArrayList with every mutation operation e.g. add or set. Normally CopyOnWriteArrayList is very expensive because it involves costly Array copy with every write operation but it’s very efficient if you have a List where Iteration outnumber mutation e.g. you mostly need to iterate the ArrayList and don't modify it too often. Iterator of CopyOnWriteArrayList is fail-safe and doesn't throw ConcurrentModificationException even if underlying CopyOnWriteArrayList is modified once Iteration begins because Iterator is operating on separate copy of ArrayList. Consequently all the updates made on CopyOnWriteArrayList is not available to Iterator. In this Java Collection tutorial we will see What is CopyOnWriteArrayList in Java, Difference between ArrayList and CopyOnWriteArrayList in Java and One simple Java program example on How to use CopyOnWriteArrayList in Java.

Difference between CopyOnWriteArrayList and ArrayList in Java.

1) First and foremost difference between CopyOnWriteArrayList and ArrayList in Java is that CopyOnWriteArrayList is a thread-safe collection.
 while ArrayList is NOT thread-safe and cannot be used in multi-threaded environment.

2) Second difference between ArrayList and CopyOnWriteArrayList is that
 Iterator of ArrayList is fail-fast and throw ConcurrentModificationException once detect any modification in List once iteration begins
 Iterator of CopyOnWriteArrayList is fail-safe and DOESN’T throw ConcurrentModificationException.

3) Third difference between CopyOnWriteArrayList vs ArrayList is that Iterator of former doesn't support remove operation while Iterator of later supports remove() operation.



ConcurrentHashMap ( introduced in Java 1.5 )

1) First significant difference between HashMap and ConcurrentHashMap is that later is thread-safe and can be used in concurrent environment WITHOUT external synchronization. Though it doesn't provide same level of synchronization as achieved by using Hashtable but it’s enough for most practical purpose.

2) You can make HashMap synchronized by wrapping it on Collections.synchornizedMap(HashMap) which will return a collection which is almost equivalent to Hashtable, where every modification operation on Map is locked on Map object while in case of ConcurrentHashMap, thread-safety is achieved by dividing whole Map into different partition based upon Concurrency level and only locking particular portion instead of locking whole Map.
ConcurrentHashMap’s accomplish this by a very simple mechanism. Instead of a map wide lock, the collection maintains a list of 16 locks by default, each of which is used to guard (or lock on) a single bucket of the map. This effectively means that 16 threads can modify the collection at a single time (as long as they’re all working on different buckets). Infact there is no operation performed by this collection that locks the entire map. The concurrency level of the collection, the number of threads that can modify it at the same time without blocking, can be increased. However a higher number means more overhead of maintaining this list of locks.

3) ConcurrentHashMap is more scalable and performs better than Synchronized HashMap in multi-threaded environment while in Single threaded environment both HashMap and ConcurrentHashMap gives comparable performance, where HashMap only slightly better.

In Summary Main difference between ConcurrentHashMap and HashMap in Java Collection turns out to be thread-safety, Scalability and Synchronization.
ConcurrentHashMap is better choice than synchronized HashMap if you are using them as cache, which is most popular use case of a Map in Java application. ConcurrentHashMap is more scalable and outperform when number of reader threads outnumber number of writer threads.


LinkedHashSet ( introduced in Java 1.4 )

A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order. When you iterate through a HashSet the order is unpredictable, while a LinkedHashSet lets you iterate through the elements in the order in which they were inserted.

Tuesday, October 23, 2012

What Is JUnit



What Is JUnit ?
  • It is a software testing FRAMEWORK for unit testing.
  • It is written in Java and designed to test Java applications.
  • It is an Open Source Software maintained by the JUnit.org community.

JUnit is a simple, open source framework to write and run repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. 

JUnit features include:
  • Assertions for testing expected results
  • Test fixtures for sharing common test data
  • Test runners for running tests
JUnit was originally written by Erich Gamma and Kent Beck.


JUnit Lifecycle
A JUnit 3.8 test case class contains a setUp() method, a tearDown() method and multiple testXXX() methods. When calling a test runner to run this test class, the runner will execute those methods in a specific order giving the test case class an execution life cycle like this:
setUp()
testXXX1()
tearDown()

setUp()
testXXX2()
tearDown()

setUp()
testXXX3()
tearDown()

...


Why Do You Use JUnit to Test Your Code?
  • I believe that writing more tests will make me more productive, not less productive.
  • I believe that tests should be done as soon as possible at the code unit level.
  • I believe that using JUnit makes unit testing easier and faster.


What Is JUnit TestCase?
JUnit TestCase is the base class, junit.framework.TestCase, used in JUnit 3.8 that allows you to create a test case. TestCase class is no longer supported in JUnit 4.4.
A test case defines the fixture to run multiple tests. To define a test case
  • Implement a subclass of TestCase
  • Define instance variables that store the state of the fixture
  • Initialize the fixture state by overriding setUp
  • Clean-up after a test by overriding tearDown
Each test runs in its own fixture so there can be no side effects among test runs. Here is an example:
import junit.framework.*;
// by FYICenter.com
public class MathTest extends TestCase {
    protected double fValue1;
    protected double fValue2;

    protected void setUp() {
        fValue1= 2.0;
        fValue2= 3.0;
    }
 
    public void testAdd() {
        double result= fValue1 + fValue2;
        assertTrue(result == 5.0);
    }
}



How To Compile a JUnit Test Class?
Compiling a JUnit test class is like compiling any other Java classes. The only thing you need watch out is that the JUnit JAR file must be included in the classpath. For example, to compile the test class HelloTest.java described previously, you should do this:
javac -cp junit-4.4.jar HelloTest.java

dir HelloTest.* 
   453 HelloTest.class
   183 HelloTest.java
The compilation is ok, if you see the HelloTest.class file.

How To Run a JUnit Test Class?
A JUnit test class usually contains a number of test methods. You can run all test methods in a JUnit test class with the JUnitCore runner class. For example, to run the test class HelloTest.java described previously, you should do this:
java -cp .;
junit-4.4.jar org.junit.runner.JUnitCore HelloTest

JUnit version 4.4
.
Time: 0.015

OK (1 test)
This output says that 1 tests performed and passed.

How To Write a JUnit Test Method?
  • You need to mark the method as a JUnit test method with the JUnit annotation: @org.junit.Test.
  • A JUnit test method must be a "public" method. This allows the runner class to access this method.
  • A JUnit test method must be a "void" method. The runner class does not check any return values.
  • A JUnit test should perform one JUnit assertion - calling an org.junit.Assert.assertXXX() method.
Here is a simple JUnit test method:
import org.junit.*; 
// by FYICenter.com
...
    @Test public void testHello() {
        String message = "Hello World!";
        Assert.assertEquals(12, message.length());
    }

What Is JUnit TestSuite?
JUnit TestSuite is a container class, junit.framework.TestSuite, used in JUnit 3.8 that allows you to group multiple test cases into a collection and run them together. TestSuite class is no longer supported in JUnit 4.4.
Each test runs in its own fixture so there can be no side effects among test runs. Here is an example:
import junit.framework.*;
// by FYICenter.com
public class RunTestSuite {
    public static void main(String[] a) {
        TestSuite suite = new TestSuite(MathTest.class);
 TestResult result = new TestResult();
        suite.run(result);
        System.out.println("Was it successful? "
            +result.wasSuccessful());
        System.out.println("How many tests were there? "
            +result.runCount());
    }
}


What Happens If a JUnit Test Method Is Declared as "private"?
If a JUnit test method is declared as "private", the compilation will pass ok. But the execution will fail. This is because JUnit requires that all test methods must be declared as "public". For example:
type HelloTestPrivate.java

import org.junit.Test;
import static org.junit.Assert.*;
// by FYICenter.com
public class HelloTestPrivate {
    @Test private void testHello() {
        String message = "Hello World!";
        assertEquals(12, message.length());
    }
}

javac -cp junit-4.4.jar HelloTestPrivate.java

java -cp .;junit-4.4.jar org.junit.runner.JUnitCore 
   HelloTestPrivate
JUnit version 4.4
.E
Time: 0
There was 1 failure:
1) initializationError0(HelloTestPrivate)
java.lang.Exception: Method testHello should be public
at org.junit.internal.runners.MethodValidator.validateTestMethod
at org.junit.internal.runners.MethodValidator.validateInstanceMe
at org.junit.internal.runners.MethodValidator.validateMethodsFor
at org.junit.internal.runners.JUnit4ClassRunner.validate(JUnit4C
at org.junit.internal.runners.JUnit4ClassRunner.<init>(JUn
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeC
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Del
at java.lang.reflect.Constructor.newInstance(Constructor.java:51
at org.junit.internal.requests.ClassRequest.buildRunner(ClassReq
at org.junit.internal.requests.ClassRequest.getRunner(ClassReque
at org.junit.internal.requests.ClassesRequest.getRunner(ClassesR
at org.junit.runner.JUnitCore.run(JUnitCore.java:109)
at org.junit.runner.JUnitCore.run(JUnitCore.java:100)
at org.junit.runner.JUnitCore.runMain(JUnitCore.java:81)
at org.junit.runner.JUnitCore.main(JUnitCore.java:44)

FAILURES!!!
Tests run: 1,  Failures: 1

What Happens If a JUnit Test Method Is Declared to Return "String"?
If a JUnit test method is declared to return "String", the compilation will pass ok. But the execution will fail. This is decause JUnit requires that all test methods must be declared to return "void". For example:
type HelloTestNonVoid.java

import org.junit.Test;
import static org.junit.Assert.*;
// by FYICenter.com
public class HelloTestNonVoid {
    @Test public String testHello() {
        String message = "Hello World!";
        assertEquals(12, message.length());
        return message;
    }
}

javac -cp junit-4.4.jar HelloTestNonVoid.java

java -cp .;junit-4.4.jar org.junit.runner.JUnitCore 
   HelloTestNonVoid

JUnit version 4.4
.E
Time: 0
There was 1 failure:
1) initializationError0(HelloTestNonVoid)
java.lang.Exception: Method testHello should be void
        at org.junit.internal.runners.MethodValidator.validateTe
        at org.junit.internal.runners.MethodValidator.validateIn
        at org.junit.internal.runners.MethodValidator.validateMe
        at org.junit.internal.runners.JUnit4ClassRunner.validate
        at org.junit.internal.runners.JUnit4ClassRunner.<init>(J
        at sun.reflect.NativeConstructorAccessorImpl.newInstance
        at sun.reflect.NativeConstructorAccessorImpl.newInstance
        at sun.reflect.DelegatingConstructorAccessorImpl.newInst
        at java.lang.reflect.Constructor.newInstance(Constructor
        at org.junit.internal.requests.ClassRequest.buildRunner(
        at org.junit.internal.requests.ClassRequest.getRunner(Cl
        at org.junit.internal.requests.ClassesRequest.getRunner(
        at org.junit.runner.JUnitCore.run(JUnitCore.java:109)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:100)
        at org.junit.runner.JUnitCore.runMain(JUnitCore.java:81)
        at org.junit.runner.JUnitCore.main(JUnitCore.java:44)

FAILURES!!!
Tests run: 1,  Failures: 1







Assertion

Assertions are disabled by default in Sun's JVM. You can selectively enable them by class loader, package, or class by calling some new methods of the ClassLoader class, or more commonly via command-line arguments when you invoke the Java Virtual Machine. The command-line arguments aren't part of the spec, but in Sun's implementation you would use the -ea and -da options to enable and disable assertions, respectively. For example, to enable all assertions except for those in the com.astrel.util package, you would write

java -ea -da:com.astrel.util MyApp
If you then wanted to reenable assertions for the Heap class within com.astrel.util, you could write
java -ea -da:com.astrel.util \
-ea:com.astrel.util.Heap MyApp
Although the ClassLoader methods can be invoked at any time, they'll only affect classes loaded after the call. In other words, the status of a class's assertions - enabled or disabled - is determined once and for all when the class is loaded.

StatementDescription
fail(String)Let the method fail. Might be used to check that a certain part of the code is not reached. Or to have failing test before the test code is implemented.
assertTrue(true) / assertTrue(false)Will always be true / false. Can be used to predefine a test result, if the test is not yet implemented.
assertTrue([message], boolean condition)Checks that the boolean condition is true.
assertsEquals([String message], expected, actual)Tests that two values are the same. Note: for arrays the reference is checked not the content of the arrays.
assertsEquals([String message], expected, actual, tolerance)Test that float or double values match. The tolerance is the number of decimals which must be the same.
assertNull([message], object)Checks that the object is null.
assertNotNull([message], object)Checks that the object is not null.
assertSame([String], expected, actual)Checks that both variables refer to the same object.
assertNotSame([String], expected, actual)Checks that both variables refer to different objects.

Thursday, October 18, 2012

SQL





There are different types of joins available in SQL:

INNER JOIN: This join returns rows when there is at least one match in both the tables.

LEFT OUTER JOIN: This join returns all the rows from the left table in conjunction with the matching rows from the right table. If there are no columns matching in the right table, it returns NULL values.

RIGHT OUTER JOIN: This join returns all the rows from the right table in conjunction with the matching rows from the left table. If there are no columns matching in the left table, it returns NULL values.

FULL OUTER JOIN: This join combines left outer join and right outer join. It returns row from either table when the conditions are met and returns null value when there is no match.

SELF JOIN: is used to join a table to itself, as if the table were two tables, temporarily renaming at least one table in the SQL statement.

CARTESIAN JOIN: returns the cartesian product of the sets of records from the two or more joined tables.  It equates to an inner join where the join-condition always evaluates to True or where the join-condition is absent from the statement (i.e. no WHERE clause)



The following is the position of the HAVING clause in a query:
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY




 Subqueries 

SQL> SELECT *
     FROM CUSTOMERS
     WHERE ID IN (SELECT ID
                  FROM CUSTOMERS
                  WHERE SALARY > 4500);

Subqueries with the INSERT Statement:

SQL> INSERT INTO CUSTOMERS_BKP
     SELECT * FROM CUSTOMERS
     WHERE ID IN (SELECT ID
                  FROM CUSTOMERS);

Subqueries with the UPDATE Statement:

SQL> UPDATE CUSTOMERS
     SET SALARY = SALARY * 0.25
     WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
                   WHERE AGE >= 27 );

Subqueries with the DELETE Statement:

SQL> DELETE FROM CUSTOMERS
     WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
                   WHERE AGE > 27 );





Wednesday, October 3, 2012

Bean Life Cycle



Spring Bean represents a POJO component performing some useful operation. All Spring Beans reside within a Spring Container also known as IOC Container. The Spring Framework is transparent and thereby hides most of the complex infrastructure and the communication that happens between the Spring Container and the Spring Beans. This section lists the sequence of activities that will take place between the time of Bean Instantiation and hand over of the Bean reference to the Client Application.
  • The Bean Container finds the definition of the Spring Bean in the Configuration file.
  • The Bean Container creates an instance of the Bean using Java Reflection API.
  • If any properties are mentioned, then they are also applied. If the property itself is a Bean, then it is resolved and set.

If the Bean class implements 
  • the BeanNameAware interface, then the method setBeanName() will be called by passing the name of the Bean.
  • the BeanClassLoaderAware interface, then the method setBeanClassLoader() will be called by passing an instance of the ClassLoader object that loaded this bean.
  • the BeanFactoryAware interface, then the method setBeanFactory() will be called by passing an instance of BeanFactory object.



  • If there are any BeanPostProcessors object associated with the BeanFactory that loaded the Bean, then 

  • The method postProcessBeforeInitialization() will be called even before the properties for the Bean are set.
  1. If the Bean class implements the InitializingBean interface, then the method afterPropertiesSet() will be called once all the Bean properties defined in the Configuration file are set.
  2. If the Bean definition in the Configuration file contains a 'init-method' attribute, then the corresponding method definition in the Bean class will be called.

  • The postProcessAfterInitialization() method will be called if there are any Bean Post Processors attached for the Bean Factory object.
  1. If the Bean class implements the DisposableBean interface, then the method destroy()will be called when the Application no longer needs the bean reference.
  2. If the Bean definition in the Configuration file contains a 'destroy-method' attribute, then the corresponding method definition in the Bean class will be called.