Saturday 6 April 2013

Junit-3



TestCase- class should be inherited for the test case class where all the method starts 
with testX(),testY()

TestSuite- class should be inherited 

public class XTest extends TestCase {
    public File file;
    public XTest(File file) {
           super(file.toString());
           this.file = file;
    }
    public void testX() {
           fail("Failed: " + file);
    }
}
public class XTestSuite extends TestSuite {
    public static Test suite() {
           TestSuite suite = new TestSuite("XTestSuite");
           File[] files = new File(".").listFiles();
           for (File file : files) {
                       suite.addTest(new XTest(file));
           }
           return suite;
    }
}

Junit-4



@RunWith(Parameterized.class)- class should be annotated like this

@Parameters -parameter method should be annotated and the method signature- public 

static Collection<Object[]> getFiles(){}

@Test- should be given for methods

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class TestY {
    @Parametererized.Parameters
    public static Collection<Object[]> getFiles() {
           Collection<Object[]> params = new ArrayList<Object[]>();
           for (File f : new File(".").listFiles()) {
                       Object[] arr = new Object[] { f };
                       params.add(arr);    }
           return params;
    }
    private File file;
    public TestY(File file) {
           this.file = file;
    }
    @Test
    public void testY() {
           fail(file.toString());
    }

}

Tuesday 2 April 2013

Java5.0 - Generics


Purpose of Generics:
            To make object type checking for java collection at compile time.
              Ex:     List<E> list = new ArrayList<E>();
                                    E denoted the type.
List<Integer> list = new ArrayList<Integer>();
Pros :
Ø  It  provide abstraction over types
               Class,interface,method can be parametrized by Types.
Ø  It  makes type safe code possible
                To avoid ClassCastException at runtime.
Ø  It provides readability.
Ø  Inheritance relationship between generic classes themselves still exists.
                   Ex: List<Integer> list = new ArrayList<Integer>();
Ø  Entries in a collection maintain inheritance relationship.
             Ex: ArrayList<Number> list = new ArrayList<Number>();
                      list.add(new Integer(10));
                      list.add(new Long(20L));
Ø  Use of Wildcard type arugument.
      Collection<?> means collection of unknown type.
          Ex:  void printValues(Collection<?> coll){
                      for(Object o:coll){
                           s.o.p(o);
                      }
              }
             Collection<String> collStrings = new ArrayList<String>();
             printValues(collStrings);
             Collection<Integer>  collIntegers = new LinkedList<Integer>();
             printValues(collIntegers);
Ø  Use of   Bounded wildcard.(bound the unknown type to be a subtype of another type)
                      Ex:  void  printValues(Collection<? extends Number> coll ){
                              }
              Collection<Integer>  collIntegers = new LinkedList<Integer>();
              printValues(collIntegers);
             Collection<Long>  collLongs = new LinkedList< Long >();
              printValues(collLongs);
Ø  Type erasure – generic type information are removed in the resulting byte-code after compilation. So it becomes a RawType.
           Ex:  List<Integer>  list;   will converted to List  list;
Ø  Creating own generic class.
           Public class  Car<S,I>{
                S s;
                I i;
           public Car(S s,I i){
                   s=s;
                    i=i;
            }
        }  
        Car<String,Integer> car1= new Car<String,Integer>(“RollsRoyce”,new Integer(007));       
Cons:
Ø  It does not allow subtyping because ClassCastException might occur at runtime.
          Ex: ArrayList<Object> list = new ArrayList<Integer>();    
Ø  There is no inheritance relationship between type arguments of a generic class.

Java5.0 - Annotations

Ø  Annotation is meant to remove the boiler-plate code.
Ø  Earlier annotation types were transient, @deprecated javadoc tag.
Ø  It is also known as metadata.
Ø  The facility provided by java5.0 for annotation are
a)    A syntax for declaring annotation types
Ex:  public @interface  Car {
         String companyName();
         String model();
         String type()  default "[economy]";
}
b)   A syntax for annotating declarations
c)    APIs for reading annotaions
d)   A class file representation for annotaions
e)   An annotation processing tool
     

Monday 1 April 2013

Spring3.0 - DAO

     From spring2.5 & 3.0 version simplejdbctemplate has namedparameterjdbctemplate support.

Ø  simplejdbctemplate are wrapped through simplejdbcdaosupport
Ø  ParametrizedRowmapper interface is used for retrieveing objects(mapRow should be overriden)
Ø  using namedparameters in queries- provided through :name,:dob- pass value through hashmap(setting string,object-string will be name,dob..)
Datasource can be configured in following ways
1)jndi-Jee:jndi-lookup tag with resource-ref attribute set to true, which says that its an java application server and java:com/env/  is preappended  before the jndi-name.
2)connection pooling through commons-dbcp- basicdatasource
3)jdbc datasource - singleconnectiondatasource(only one instance of datasource available),drivermanagerdatasource(connection not pooled)

jdbctemplates are as follows
           jdbctemplate,simplejdbctemple,namedparameterjdbctemplate.

Exception
       DataAccessException-wraps all other exceptions such as sqlexception,databaseerrorexception,readexception and so on
       DataAccessException is runtime exception
 

Spring3.0 - Core

New features of Spring 3.0

Ø  Spring Expression Language
Ø  IoC enhancements/Java based bean metadata
Ø  General-purpose type conversion system and field formatting system
Ø  Object to XML mapping functionality (OXM) moved from Spring Web Services project
Ø  Comprehensive REST support
Ø  @MVC additions
Ø  Declarative model validation
Ø  Early support for Java EE 6
Ø  Embedded database support

2.5.1 Core APIs updated for Java 5

Ø  BeanFactory interface returns typed bean instances as far as possible:
                      T getBean(Class<T> requiredType)
                      T getBean(String name, Class<T> requiredType)
                      Map<String, T> getBeansOfType(Class<T> type) 
Ø  Spring's TaskExecutor interface now extends java.util.concurrent.Executor:
                     extended AsyncTaskExecutor supports standard Callables with Futures
Ø  New Java 5 based converter API and SPI:
                      stateless ConversionService and Converters
                      superseding standard JDK PropertyEditors
Advantages of autowiring.
Ø  It can significantly reduce the volume of configuration required.
Ø  It can cause configuration to keep itself up to date as your objects evolve. For example, if you need to add an additional dependency to a class, that dependency can be satisfied automatically without the need to modify configuration. Thus there may be a strong case for autowiring during development, without ruling out the option of switching to explicit wiring when the code base becomes more stable.

Disadvantages of autowiring:

Ø  Spring is careful to avoid guessing in case of ambiguity which might have unexpected results, the relationships between Spring-managed objects are no longer documented explicitly.
Ø  Wiring information may not be available to tools that may generate documentation from a Spring container.

Bean scopes
Ø  singleton
Ø  prototype
Ø  request
Ø  session
Ø  global-session- if not portlet based application it will act like session

Dependency check modes
Ø  none- no dependency checking
Ø  simple- To check look for primitive types and collections if not unsatisfieddependencyexception will be thrown
Ø  objects- To check for objects  if not unsatisfieddependencyexception will be thrown
Ø  all- of all types primitive,objects,collection and so on.
           <bean id="CustomerBean" class="com.mkyong.common.Customer"                                           dependency-check="simple">

Creating our own Annotation based bean
Ø  @Required  - Helps to ensure the autowire object should be instantiated
      empty interface should be declared with
Ø  @Retention(RetentionPolicy.RUNTIME)
Ø  @Target(ElementType.MEthod)
Ø  @{empty interface name} on autowiring the element [ provide above the setter  method]

Bean instantiation through class
Ø  @Configuration - Provided for class that is to be configured as config file
Ø  @Bean(name="ab") - Provided for autowired bean class [instead of giving in <bean > tag we can use it like this]
Ø  AnnotationConfigApplicationContext(AppCofg.class) -
Helps to call the configuration class

postconstructor preconstructor
Ø  @PostConstruct
Ø  @PreConstruct
Annotated to call and after the method in the class

Pre-Post callback methods

Ø  int-method - called after the constructor & @postconstruct is called
Ø  destroy-method - called after @preconstruct is called [ like finally block]

interfaces - intializingbean,disposablebean
Ø  initializingbean- afterPropertySet method has to be implemented
Ø  disposblebean - destroy method should be implemented