Wednesday, November 12, 2014

Polymorphism Example

package InheritancePolymorphism;

public class InheritancePolymorphism {
public void Method1(){
System.out.println("supermethod");

}


}
package InheritancePolymorphism;

import org.junit.Test;




public class Main {
@Test
public void Method1() {
InheritancePolymorphism[] tests={new SubClass1(),new SubClass2()};
for(InheritancePolymorphism test:tests){
test.Method1();
}
}

}
package InheritancePolymorphism;

public class SubClass1 extends InheritancePolymorphism{

public SubClass1() {
}
public void Method1(){
System.out.println("subclass1");
}

}
package InheritancePolymorphism;

public class SubClass2 extends InheritancePolymorphism{

public SubClass2() {
}
public void Method1(){
System.out.println("subclass2");
}

}

Inheritance Example

package Inheritance;

public class GeneralClass {
Version1Program version1=new Version2Program();

private Object test;
GeneralClass(Object test){
this.test=test;


}
void GenaralMethod(){
version1.PrintCommom3();

}




}

package Inheritance;

import java.math.BigDecimal;

import org.junit.Test;


public class Main {
@Test
public void Method1() {
GeneralClass generalclass=new GeneralClass(new Object());
generalclass.GenaralMethod();
}

}
package Inheritance;

import java.math.BigDecimal;

public class Version1Program {

private String common1;
private String common2;
private BigDecimal common3;
@SuppressWarnings({ "unused", "rawtypes" })
private Class[] test;

Version1Program() {
common1="common1default";
common2="common2default";
common3=new BigDecimal(0);
}
Version1Program(String common1,String common2, BigDecimal common3){
this.common1=common1;
this.common2=common2;
this.common3=common3;
}
Version1Program(Class<?> test){
this(new Class []{test});
}
Version1Program(Class<?> test[]){
this.test=test;
}

Version1Program(String common2)
{
this(null,common2,null);
}
Version1Program(BigDecimal common3)
{
this(null,null,common3);
}

public void PrintCommom1() {
System.out.println(common1);

}
public void PrintCommom2() {
System.out.println(common2);

}
public void PrintCommom3() {
System.out.println(common3);

}


}
package Inheritance;

import java.math.BigDecimal;

public class Version2Program extends Version1Program{
private String common11;
private String common22;
private BigDecimal common33;
@SuppressWarnings({ "unused", "rawtypes" })
private Class[] array;

Version2Program() {
common11="common11default";
common22="common22default";
common33=new BigDecimal(00);
}
Version2Program(String common1,String common2, BigDecimal common3){
super(common1,common2,common3);
this.common11=common1;
this.common22=common2;
this.common33=common3;
}
Version2Program(String common11)
{
this(common11,null,null);
}

Version2Program(BigDecimal common33)
{
this(null,null,common33);
}
Version2Program(@SuppressWarnings("rawtypes") Class[] array){
this.array=array;
}

public void PrintCommom11() {
System.out.println(common11);

}
public void PrintCommom22() {
System.out.println(common22);

}
public void PrintCommom33() {
System.out.println(common33);

}
public void PrintCommom3() {
System.out.println("I love you ............");

}


}

Generics Example

package Generics;

import java.math.BigDecimal;

import org.junit.Test;

class GenericsTest<T > {
private T t;

GenericsTest(T t) {
this.t = t;
}

void Method(String test) {
if (t.equals(test)) {
System.out.println("iiiiiiiiiiiii");

}

}

}
class GenericsTest1 <T extends Object > {
private T t;

GenericsTest1(T t) {
this.t = t;
}

void Method(String test) {
if (t.equals(test)) {
System.out.println("iiiiiiiiiiiii");

}

}

}

public class Generics {
@Test
public void M1(){
GenericsTest<BigDecimal> generics = new GenericsTest<BigDecimal>(new BigDecimal(0));
generics.Method("test");

}

}

Framework designing Tips

// if you are writing framework then the object identifatication level should be there for framework .For example Object Class is super for java .So,in framework specific we need a minimium definition of object how it should look like.Like for example of thee are suppose when loading in tomcat there are 2000 objects then 2000 object should have a common behaviour that is not default object class behaviour but our system specific behavior .Like Comapring is the object is null.Like a method check Object(Interface definition){

//interface.isNull(){
// so it works for all the objects of the system .So this functionality can be provided via frameork part
//}
 abstract class AbstractTest {
Object test;
void MethodSuper(){

}
AbstractTest(Object test){
this.test=test;

}
void Method2Super1(){

}
void Method2Super2(){

}
abstract void SubClassSpecified();



}
 abstract class AbstractTest1 {
Object test;
void MethodSuper2(){

}
AbstractTest1(Object test){
this.test=test;

}
void Method2Super2(){

}
abstract void SubClassSpecified();



}



public class AddBusineessLogic implements SuperCommonTask {

@Override
public void display() {
System.out.println("add result");

}

@Override
public void appliationErro() {
System.out.println("this is application error Add case ");

}

@Override
public void systemErro() {
System.out.println("this is systemerror Add case");

}

@Override
public void validatenput() {
}

@Override
public void ShowError() {
}

@Override
public void IsErrorPresent() {
}

}


public class BusinessLogic {
public int Add(int a,int b){
return a+b;
}
int Subtract(int a,int b){
return a-b;
}
int Divide(int a,int b){
return a%b;
}

}



public class ClientClass {
SuperCommonTask add = new AddBusineessLogic();
SuperCommonTask multiply = new MultiplyBusineessLogic();
SuperCommonTask divide = new DivideBusineessLogic();
CommonPointOfOperation CommonPointOfOperationadd = new CommonPointOfOperation(
add);
BusinessLogic businesslogic=new BusinessLogic();
void EntryPoint(int a ,int b){
add.validatenput();
}

}

public class CommonPointOfOperation {
SuperCommonTask SuperCommon;

CommonPointOfOperation(SuperCommonTask SuperCommon) {
this.SuperCommon = SuperCommon;
}

void ShowError() {
SuperCommon.appliationErro();
}

void ShowApplicationError() {
SuperCommon.appliationErro();
}

void ShowsystemError() {
SuperCommon.systemErro();

}
}

public class DivideBusineessLogic implements SuperCommonTask {
@Override
public void display() {
System.out.println("Multiply result");

}

@Override
public void appliationErro() {
System.out.println("this is application error Multiply case ");

}

@Override
public void systemErro() {
System.out.println("this is systemerror Multiply  case");

}

@Override
public void validatenput() {
// TODO Auto-generated method stub
}

@Override
public void ShowError() {
// TODO Auto-generated method stub
}

@Override
public void IsErrorPresent() {
// TODO Auto-generated method stub
}

}


public class InheritancePolymorphism {
void Method1(){
System.out.println("supermethod");
}

}


 class Client {
private State1 state;

public State1 getState() {
return state;
}

public void setState(State1 state) {
this.state = state;
}
}




public class Main {

/**
* @param args
*/
public static void main(String[] args) {
Client client=new Client();
client.setState(State1.cancel);
State1 state1=client.getState();
System.out.println(state1+ state1.getTest());
State1[] test=State1.values();
for(State1 state:test){
System.out.println(state.getTest()+state);;
}

}
}


public class MultiplyBusineessLogic implements SuperCommonTask {
@Override
public void display() {
System.out.println("Multiply result");

}

@Override
public void appliationErro() {
System.out.println("this is application error Multiply case ");

}

@Override
public void systemErro() {
System.out.println("this is systemerror Multiply  case");

}

@Override
public void validatenput() {
// TODO Auto-generated method stub
}

@Override
public void ShowError() {
// TODO Auto-generated method stub
}

@Override
public void IsErrorPresent() {
// TODO Auto-generated method stub
}

}

public class State1{
public static enum Test{
create("1")
,cancel("3")
,read("3")
,update("2")
,initread("3")
,initcancel("3")
,initupdate("3");

Test(String test){
this.test=test;
}
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}

}
}
public interface SuperCommonTask {
void display();

void appliationErro();

void systemErro();
void validatenput();
void ShowError();
void IsErrorPresent();

}


Tuesday, November 11, 2014

Garbage Collection Analysis


public class GarbageTest {
public static void main(String args[]){
int y = 1;


// for (int x=0; y<10; x++)
// {
// System.out.println("test");
// }
for (int x=0; x<100000000; x++)
{
System.out.println("test");
}


}

}

Executor Framework Example

mport java.util.ArrayList;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Test {
    private static final int NTHREDS = 10;

    public static void main(String[] args) {
      final Counter counter = new Counter();
      List<Future<Integer>> list = new ArrayList<Future<Integer>>();

      ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
      for (int i = 0; i < 500; i++) {
        Callable<Integer> worker = new  Callable<Integer>() {
          @Override
          public Integer call() throws Exception {
            int number = counter.increment();
            System.out.println(number);
            return number ;
          }
        };
        Future<Integer> submit= executor.submit(worker);
        list.add(submit);

      }
   
   
      // This will make the executor accept no new threads
      // and finish all existing threads in the queue
      executor.shutdown();
      // Wait until all threads are finish
      while (!executor.isTerminated()) {
      }
      Set<Integer> set = new HashSet<Integer>();
      for (Future<Integer> future : list) {
        try {
          set.add(future.get());
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (ExecutionException e) {
          e.printStackTrace();
        }
      }
      if (list.size()!=set.size()){
        throw new RuntimeException("Double-entries!!!");
      }

    }


Wednesday, October 1, 2014

Byte Code Engineering Example

package compare;

public class ImplementRunnable1 implements Runnable1{


@Override
public void method() {
System.out.println("Test");

}
void Method1(){
System.out.println("hhhhh");
method() ;


}

}


package compare;


import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

import org.objectweb.asm.*;
import org.objectweb.asm.attrs.*;

public class ImplementRunnable1Dump implements Opcodes {
// public static void main(String[] args) throws Exception {
//
// }

public static byte[] dump() throws Exception {

ClassWriter cw = new ClassWriter(0);
FieldVisitor fv;
MethodVisitor mv;
AnnotationVisitor av0;

cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, "compare/NoRunnable",
null, "java/lang/Object", new String[] { "compare/Runnable1" });

cw.visitSource("NoRunnable.java", null);

{
fv = cw.visitField(ACC_PRIVATE, "x", "Ljava/lang/String;", null,
null);
fv.visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>",
"()V");
mv.visitInsn(RETURN);
Label l1 = new Label();
mv.visitLabel(l1);
mv.visitLocalVariable("this", "Lcompare/NoRunnable;", null,
l0, l1, 0);
mv.visitMaxs(1, 1);
mv.visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC, "method", "()V", null, null);
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out",
"Ljava/io/PrintStream;");
mv.visitLdcInsn("Test");
mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println",
"(Ljava/lang/String;)V");
Label l1 = new Label();
mv.visitLabel(l1);
mv.visitInsn(RETURN);
Label l2 = new Label();
mv.visitLabel(l2);
mv.visitLocalVariable("this", "Lcompare/NoRunnable;", null,
l0, l2, 0);
mv.visitMaxs(2, 1);
mv.visitEnd();
}
{
mv = cw.visitMethod(0, "Method1", "()V", null, null);
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out",
"Ljava/io/PrintStream;");
mv.visitLdcInsn("hhhhh");
mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println",
"(Ljava/lang/String;)V");
Label l1 = new Label();
mv.visitLabel(l1);
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKEVIRTUAL, "compare/NoRunnable",
"method", "()V");
Label l2 = new Label();
mv.visitLabel(l2);
mv.visitInsn(RETURN);
Label l3 = new Label();
mv.visitLabel(l3);
mv.visitLocalVariable("this", "Lcompare/NoRunnable;", null,
l0, l3, 0);
mv.visitMaxs(2, 1);
mv.visitEnd();
}
cw.visitEnd();

return cw.toByteArray();
}
}


package compare;

public class NoRunnable {
void Method1(){
System.out.println("i");
}

}


package compare;

public interface Runnable1 {
void method();

}


package compare;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.junit.Test;

public class TestP {
@Test
public void  MethodTest() throws IOException, Exception{
ImplementRunnable1Dump d=new ImplementRunnable1Dump();
  File outputDir=new File("bin/compare");
       DataOutputStream dout=new DataOutputStream(new FileOutputStream(new File(outputDir,"NoRunnable.class")));
       dout.write(d.dump());
NoRunnable y=new NoRunnable();
y.Method1();
}

}

Tuesday, September 30, 2014

Tuning Process

Performance Principles
Common Performance Problems
Performance Methodology
Development and Performance
Monitoring Operating System Performance
Monitor CPU Usage
Monitor Network I/O
Monitor Disk I/O
Monitor Virtual Memory Usage
Monitor and Identify Lock Contention
Monitoring the JVM
HotSpot Generational Garbage Collector
Monitor the Garbage Collector with Command Line Tools
Monitor the Garbage Collector with VisualVM
Monitor the JIT Compiler
Throughput and Responsiveness
Performance Profiling
NetBeans Profiler, Oracle Solaris Studio, and jmap/jhat
Profile CPU Usage
Profile JVM Heap
Find Memory Leaks
Identify Lock Contention
Heap Profiling Anti-patters
Method Profiling Anti-patterns
Garbage Collection Schemes
Garbage Collection
Generational Garbage Collection
GC Performance Metrics
Garbage Collection Algorithms
Types of Garbage Collectors
JVM Ergonomics
Garbage Collection Tuning
Tune the Garbage Collection
Select the Garbage Collector
Interpret GC Output
Language Level Concerns and Garbage Collection
The best practices for Object Allocation
Invoking the Garbage Collector
Reference Types in Java
The use of Finalizers
Performance Tuning at the Language Level
String-efficient Java Applications
Collection Classes
Using Threads
Using I/O Efficiently


On the other hand, good object-oriented design actually encourages many small methods
and significant polymorphism in the method hierarchy

However, this technique cannot be applied Ofreilly - Java Performance Tuning
- 9 -
when it is too difficult to determine method calls at compile time, as is the case for many Java
methods.

A lot of time (in CPU cycles) passes while the user is reacting to the application interface. This time
can be used to anticipate what the user wants to do (using a background low priority thread), so that
precalculated results are ready to assist the user immediately. This makes an application appear
blazingly fast.

 Multiuser response times depending on the number of users (if applicable)
 Systemwide throughput (e.g., number of transactions per minute for the system as a whole,
or response times on a saturated network, again if applicable)
 The maximum number of users, data, files, file sizes, objects, etc., the application supports
 Any acceptable and expected degradation in performance between minimal, average, and
extreme values of supported resources

You must specify target times for each benchmark. You should specify ranges: for example, best
times, acceptable times, etc.

CPU time (the time allocated on the CPU for a particular procedure)
 The number of runnable processes waiting for the CPU (this gives you an idea of CPU
contention)
 Paging of processes
 Memory sizes
 Disk throughput
 Disk scanning times
 Network traffic, throughput, and latency
 Transaction rates
 Other system values


For distributed applications , you need to break down measurements into times spent on each
component, times spent preparing data for transfer and from transfer (e.g., marshalling and
unmarshalling objects and writing to and reading from a buffer), and times spent in network
transfer. Each separate machine used on the networked system needs to be monitored during the test
if any system parameters are to be included in the measurements. T



Any decoupling, indirection, abstraction, or extra layers in the design are highly likely to be
candidates for causing performance problems. You should include all these elements in your design
if they are called for. But you need to be careful to design using interfaces in such a way that the
concrete implementation allows any possible performance optimizations to be incorporated. Design
elements that block, copy, queue, or distribute also frequently cause performance problems. These
elements can be difficult to optimize, and the design should focus attention on them and ensure that
they can either be replaced or that their performance is targeted.
[7]
 Asynchronous and background
events can affect times unpredictably, and their effects need to be clearly identified by benchmark
testing.


The behavior and efficiency of the garbage collector used can heavily influence the performance and responsiveness of an application thatfs taking advantage of it


Clocks per CPU instruction, usually referred to as CPI, for an application is a ratio of the number of CPU clock ticks used per CPU instruction. CPI is a measure of the efficiency of generated code that is produced by a compiler. A change in the application, JVM, or operating system that reduces the CPI for an application will realize an improvement in its performance since it takes advantage of better and more optimized generated code.



1.using verbosege option with the VM to print out garbage collector staticstics,it gives idea how often garbage collector is running .
2.application partioning ,data compressing
3.Larger heap take longer to collect garbage
young generation,old generation,permanent generation --- see it
5.Most employ a gstop the worldh collection, meaning the running
application must stop processing while the GC is engaged.
? Therefore frequent or large amounts of collection affect the
performance of your application.There are four garbage collector
6.use most updated jdk
7Hints are added to the command line start up of an application, such as
g-XX:+UseAdaptiveGCBoundaryh to allow the Garbage Collector to
change the allotted space between Young and Old Generations.
8.gThe Garbage Collector runs too frequently / is too slow.h

 Try to reduce the number of temporary objects that are created.
 If all else fails, carefully consider using a different garbage collector.
 The Parallel Compactor (good for multiple CPUs where response
time isnft as important as overall throughput) can be selected with
the -XX:+UseParallelGC command line option.
 The Parallel Compacting Collector (good for multiple CPUs where
response time is more important) can be selected with the
XX:ParallelGCThreads=n command line option.
9.gThe Garbage Collector...h (cont.)

The Concurrent Mark-Sweep Collector (good for apps running on
machines with few CPUs that needs more frequent garbage
collection) can be selected with the -XX:+UseConcMarkSweepGC
command line option.

9.Monitor and identify lock contention
10.Select the Garbage Collector
11.Invoking the Garbage Collector
12.Interpret GC Output
13.Garbage Collection Algorithms
Types of Garbage Collectors
14.Tune garbage collectors
15.Tune Just in Time (JIT) compilers
16.Examine and tune 64 bit JVMs
? Optimize the JVM for Multi-core platforms
17.Tune 64 bit JVM for different application requirements
o Tune a 64 bit JVM for a specific application
18.Optimize the JVM for Multi-core platforms
19.Select collector that best fits application characteristics and
requirements
20.Measure frequency and duration of collections

21.The algorithms and parameters used by GC can have dramatic effects on performance

22.Demonstrates that an application that spends 10% of its time in garbage collection can lose 75% of its throughput when scaled out to 32 processors
23.permanent generation
holds all the reflective data of the virtual machine itself, such as class and method objects
24.Young generation ? all new objects are created here. Majority of GC activity takes place here and is usually fast (Minor GC).
Old generation ? long lived objects are promoted (or tenured) to the old generation. Fewer GCfs occur here, but when they do, it can be lengthy (Major GC).
25.The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.
26.Yound generation collector

Serial Copying Collector
All J2SEs (1.4.x default)
Stop-the-world
Single threaded
Parallel Copying Collector
-XX:+UseParNewGC
JS2E 1.4.1+ (1.5.x default)
Stop-the-world
Multi-threaded
Parallel Scavenge Collector
-XX:UseParallelGC
JS2E 1.4.1+
Like Parallel Copying Collector
Tuned for very large heaps (over 10GB) w/ multiple CPUs
Must use Mark-Compact Collector in Old Generation


Old generation collector :

Mark-Compact Collector
All J2SEs (1.4.x default)
Stop-the-world
Single threaded
Train (or Incremental) Collector
-Xincgc
About 10% performance overhead
All J2SEs
To be replaced by CMS Collector
Concurrent Mark-Sweep (CMS) Collector
-XX:+UseConcMarkSweepGC
J2SE 1.4.1+ (1.5.x default (-Xincgc))
Mostly concurrent
Single threaded


28.Lots of cast
29.Replace multiple objects by sinlge object or few

30 String test=new String("test");
String test=new String("test");
two objects if used
String test="test";
String test1="test";
two points to same objects
vector is synchronized
hashtable  is synchronized  and hashmap is not

Important to understand

the internal representation of a Java object and an internal representation of a Java class are very similar. From this point on let me just call them Java objects and Java classes and you'll understand that I'm referring to their internal representation. The Java objects and Java classes are similar to the extent that during a garbage collection both are viewed just as objects and are collected in exactly the same way. So why store the Java objects in a separate permanent generation? Why not just store the Java classes in the heap along with the Java objects?

Classes also have classes that describe their content.


important
//he permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.

//dynamic binding is slower than static binding,

//Minimize Subclasses and Method Overriding

How spring transaction API is designed and works with multi threading

Every thread have common value of operation like what type of operation to go Or standard protocol when to commit ,when to rollback,how many transaction object to create so it is set once and use by all threads

Whether every thread share same object,Or for every thread the object is different.If they share it will be singleton and need synchronization .

Creating a common scenario of data for db operation for all thread by setting as singleton

there are lost of set method in a class in DataSourceTransactionManager.So,first make sure what is common protocol  for all threads

MultiThreading Data Select

package org.apache.tomcat.jdbc.pool.jmx;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

public class MockCommonDao extends SqlMapClientDaoSupport {

ArrayList<ArrayList> listOlists = new ArrayList<ArrayList>();

public List selectByExample(List<Object> example)
   {
List<Future<Object>> listOlists = null;
ExecutorService executor = Executors.newFixedThreadPool(example.size());
List<TransactionImpl> callingList = new ArrayList<MockCommonDao.TransactionImpl>();
for (int i = 0; i < example.size(); i++) {
             TransactionImpl localImpl = new TransactionImpl(example.get(i));
             callingList.add(localImpl);
         }
try {
           
listOlists = executor.invokeAll(callingList);

         } catch (InterruptedException e) {
           
         }
         return listOlists;
       

               
   
     
   }
private String getClassNameFromExample(Object example)
   {
       String tableName = example.getClass().getName();
       int cnt = tableName.indexOf("Example");
       int last = tableName.lastIndexOf('.');
       tableName = tableName.substring(last + 1, cnt);
       return tableName.toUpperCase();
   }
 private class TransactionImpl implements Callable<Object>{
 private Object example;


 TransactionImpl(Object Criteria) {
           this.example = Criteria;

       }


@Override
public Object call() throws Exception {

            List list = getSqlMapClientTemplate().queryForList((new StringBuilder(String.valueOf(getClassNameFromExample(example)))).append(".ibatorgenerated_selectByExample").toString(), example);
            listOlists.add((ArrayList) list);
            return listOlists;
 }
 }}





Best Approaches for transaction control

Approach one
Catch the exception.Do not apply transaction to any method.If exception is thrown catch it and set  checkforcommit=false.If false pro-grammatically rollback the transaction using spring provided classes . Other wise programmatically commit the transaction

MultiThreading and Exception

Class ThreadException {

TestKl0t1Example example = new TestKl0t1Example();
TestKl0t1Example.Criteria criteria = example.createCriteria();
criteria.andT1trnoEqualTo(new BigDecimal(dto.getTranNo()))

List<Object> dbResult = getCommonDao()
.selectByExampleDltmOff(example);


t1 = (TestKl0t1) dbResult.get(0);
List<TestKl0t1> results = new ArrayList<TestKl0t1>();
for (int i = 0; i < dbResult.size(); i++) {
results.add((TestKl0t1) dbResult.get(i));
}
ExecutorService executor = Executors.newFixedThreadPool(dbResult
.size());
List<Transactiompl> callingList = new ArrayList<ThreadException.Transactiompl>();
for (int i = 0; i < dbResult.size(); i++) {
Transactiompl localImpl = new Transactiompl(dbResult.get(i));
callingList.add(localImpl);
}
List<Future<TestKl0t1>> results1 = null;

try {

results1 = executor.invokeAll(callingList);

// executor.shutdown();
// while (!executor.isTerminated()) {
// executor=null;
// }

} catch (Exception e) {
executor = null;

}
executor = null;

}
Class Transactiompl extends RequestContextAwareCallable{
Transactiompl(Object readTestKl0t1) {
this.t1 = (TestKl0t1) readTestKl0t1;

}



public TestKl0t1 onCall() throws InterruptedException {
beginTransaction();





public abstract class RequestContextAwareCallable<V> implements Callable<V> {

private final RequestAttributes requestAttributes;
private Thread thread;

public RequestContextAwareCallable() {
this.requestAttributes = RequestContextHolder
.getRequestAttributes();
this.thread = Thread.currentThread();
}

public V call() throws Exception {
try {
RequestContextHolder.setRequestAttributes(requestAttributes);
return onCall();
} catch (Exception e) {
System.out.println("Oh boy, something broke!");
e.printStackTrace();
rollbackTransaction();
checkforcommit=false;
throw e;


}

finally {
if (Thread.currentThread() != thread) {
RequestContextHolder.resetRequestAttributes();
}

thread = null;
}
}

public abstract V onCall() throws Exception;
public void beginTransaction() {

DefaultTransactionDefition txDef = new DefaultTransactionDefition();
txDef.setPropagationBehavior(0);
txStatus = txManager.getTransaction(txDef);
}

public void commitTransaction() {
if (txStatus != null) {
if (!txStatus.isCompleted())
txManager.commit(txStatus);
} else {
System.out.println("error");
}
}

public void rollbackTransaction() {
if (txStatus != null) {
if (!txStatus.isCompleted())
txManager.rollback(txStatus);
} else {
System.out.println("rollbackcalled");
}
}
}

@Override
public void resetGlobalVariables() {
// TODO Auto-generated method stub

}

private PlatformTransactionManager txManager;

public void setTxManager(PlatformTransactionManager txManager) {
this.txManager = txManager;
}

public PlatformTransactionManager getTxManager() {
return txManager;
}

Example 5

<aop:config>
<aop:aspect id="ResetGlobalVariablesInterceptor" ref="resetGlobalVariablesAspect">
<aop:pointcut id="resetGlobalVariablesPointcut" expression="execution(* *..*BServiceImpl.executeRealBatch(..)) " />
<aop:pointcut id="resetGlobalVariablesPointcut1" expression="execution(* com.utility.occasionalbatch.server.service.impl.*ServiceImpl.execute(..))" />
<aop:pointcut id="resetGlobalVariablesPointcut12" expression="execution(public * *..*EServiceImpl.*(..)) or execution(public * *..*QServiceImpl.*(..)) or execution(public * *..*LServiceImpl.*(..)) or execution(* *..KKC*ServiceImpl.*(..))
and not execution(* com.sample..*(..)) and not execution(* com.extend..*(..)) and not execution(* com.utility.occasionalbatch..*(..))" />
<aop:before pointcut-ref="resetGlobalVariablesPointcut12" method="resetGlobalVariablesMaster" />
<aop:before pointcut-ref="resetGlobalVariablesPointcut" method="resetGlobalVariables" />
<aop:before pointcut-ref="resetGlobalVariablesPointcut1" method="resetGlobalVariables1" />
</aop:aspect>
</aop:config>

<bean id="resetGlobalVariablesAspect" class="com.extend.aop.ResetGlobalVariablesInterceptor">
<property name="order" value="125" />
</bean>

Example 3

<aop:config>
<aop:aspect id="InterceptorForComponentCall" ref="interceptorForComponentCall">
<aop:pointcut id="pointCutForComponentCall" expression="execution(* *..MMC*ServiceImpl.*(..)) or execution(* *..MMC0010BServiceImpl.*(..))" />
<aop:before pointcut-ref="pointCutForComponentCall" method="setPGMID" />
</aop:aspect>
</aop:config>
<bean id="interceptorForComponentCall" class="com.extend.aop.InterceptorForComponentCall">
<property name="order" value="135" />
</bean>

Example 2

<aop:config>
<aop:aspect id="PGMIDIntercepter" ref="pgmIDAspect">
<aop:pointcut id="pgmIDPointcut" expression="execution(* *..BBC*ServiceImpl.*(..)) or execution(* *..BBC0010BServiceImpl.*(..))" />
<aop:before pointcut-ref="pgmIDPointcut" method="setPGMIDBefore" />
</aop:aspect>
</aop:config>
<bean id="pgmIDAspect" class="com.extend.aop.PGMIDInterceptor">
<property name="order" value="90" />
</bean>

  <aop:config>
<aop:aspect id="InterceptorForComponentCall" ref="interceptorForComponentCall">
<aop:pointcut id="pointCutForComponentCall" expression="execution(* *..BBC*ServiceImpl.*(..)) or execution(* *..BBC0010BServiceImpl.*(..))" />
<aop:before pointcut-ref="pointCutForComponentCall" method="setPGMID" />
</aop:aspect>
</aop:config>

Example 1

<bean id="whitespaceAspect" class="com.extend.aop.TrimInterceptor" />
  <aop:config>
    <aop:aspect ref="TrimwhitespaceAspect">
      <aop:pointcut id="trimWhitespacePointCut"
        expression="execution(* com.base.dao.CommonDAO.selec*(..)) )" />
      <aop:after-returng pointcut-ref="trimWhitespacePointCut"
        method="trimWhitespaces" returng="returnedData" />
    </aop:aspect>
  </aop:config>

Monday, September 29, 2014

Providing ability to software to add feature dynamically

 provide common functions of batch processing
 provide the ability to manage an application exception.
 provide the ability to manage the application log.
And provide the ability to create Excel.
And provide the ability to create PDF.
Intercept (service calls, Dao call) the various processes, and to provide the ability to realize the call of common functions.

 provide the ability to record access, login logout to each function.
provide the function according to the preferred language of the user, controls the display language of the screen fields.
To provide the ability to control the display of dialog language message according to the preferred language of the user
 provide the ability to hold the common information of the authentication information
Among the information stored in the preconditioned master, provide a function of holding the information to be cached in the entire system.

Providing ability for database access control

Ways ho hold data of the client on server

Adding ability to software for features

Features controlled by DB data .According to setting performed on DB master ,features behaves in polymorphic way according to data present on precondition and post condition master modules

Ways for enabling and disabling feature

Internationalization and Localization.
Custom tag with different attributes .The value of attributes controlled from configuration files .Like db ,xml or other

Preloading and Lazy loading Beans

Employee emp = (Employee) factory.getBean("employeeBean"); // 2
Even though "beans.xml" configuration file is loaded with BeanFactory container in line number 1, none of the beans will be instantiated. Instantiation takes place only at line number 2, where bean called "employeeBean" is requested from container. Since the class is instantiated at getBean() method call, time spend to return this method will vary depending on the instantiated object.


ApplicationContext context =
            new ClassPathXmlApplicationContext("beans.xml"); // 1
Employee emp = (Employee) context.getBean("employeeBean"); // 2
As all singleton beans are instantiated by container at line number 1, this line will take some considerable time to complete. However line number 2 will return the bean instance immediately since instances are already available inside the container.


destroy-method="close">

The init-methodattribute specifies a
method that is to be called on the beanimmediately upon instantiation. Similarly,
destroy-method specifies a method that is called just before a bean is removed from
the container.In our case



When some Web Application Shut downs Spring's web-based ApplicationContext handles shutting down gracefully but for a non web application if you want the container to shutdown gracefully and call the relevant destroy callbacks on your singleton beans, you will need to register a shutdown hook with the JVM.

So for registering a shutdown hook that enables the graceful shutdown for the relevant Spring IoC container, we simply need to call the registerShutdownHook () method that is declared on the AbstractApplicationContext class.

public final class Test {

public static void main(final String[] args) throws Exception {

AbstractApplicationContext ctx= new ClassPathXmlApplicationContext(new String []{"test.xml"});
ctx.registerShutdownHook();
// app runs here...
// main method exits, hook is called prior to the app shutting down...
}
}

when container is shut down it is destroyed .But in our case the bean is never destroyed and application context is also not shutdown unless tomcat is restarted .context.close()destroyed.and at that time the destroy method that is defined in bean definition file is called for example in our case it is close which is called
'

destroy-methodspecifies a method that is called just before a bean is removed from
the container.

Web Service Testing Example



package testingWS;

import groovyx.net.http.ContentType;

import org.junit.Before;
import org.junit.Test;

import com.jayway.restassured.RestAssured;
import com.jayway.restassured.path.json.JsonPath;
import com.jayway.restassured.response.Response;

import static com.jayway.restassured.RestAssured.expect;
import static com.jayway.restassured.RestAssured.get;
import static com.jayway.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.*;


public class TestingUsingRestAssured {

 @Before
   public void setUp(){
    //  do something
   }



@Test
public void testUserFetchesSuccess() {
expect().
body("id", equalTo(12)).
body("firstName", equalTo("Tim")).
body("lastName", equalTo("Tester")).
when().
get("/abc/users/id/12");
}


@Test
   public void testGetProducts(){
       expect().statusCode(200).contentType(ContentType.JSON)
       .when().get("/abc/users/id/1");
   }



// testing a simple response containing some JSON data
@Test
public void testGetSingleUser() {
 expect().
   statusCode(200).
   body(
     "firstName", equalTo("Tim"),
     "lastName", equalTo("Testerman"),
     "id", equalTo(1)).
   when().
   get("/abc/users/single-user");
}

@Test
public void testGetSingleUse1r() {
given().
pathParam("id",1).
expect().
statusCode(200).
body("id", equalTo(1),
"firstName", equalTo("Tim")).

when().
get("/abc/users/id");
}




//we’re using JsonPath to programatically test the returned JSON structure we’re
//using JsonPath to programatically test the returned JSON structure
@Test
public void testGetSingleUserProgrammatic() {

  Response res = get("/abc/users/single-user");

  assertEquals(200, res.getStatusCode());

  String json = res.asString();
  JsonPath jp = new JsonPath(json);

  assertEquals("Tim", jp.get("firstName"));
  assertEquals("Testerman", jp.get("lastName"));
  assertEquals(1, jp.get("id"));
}







// handling basic authentication
// Response Status: 401 Unauthorized/ 200 Status Ok (when logged in with username=admin and password=admin)
/* @Test
public void testAuthenticationWorking() {
  // we're not authenticated, service returns "401 Unauthorized"
  expect().
    statusCode(401).
  when().
  get("/abc/users/secure/person");
  // with authentication it is working
  expect().
    statusCode(200).
  when().
    with().
      authentication().basic("admin", "admin").
  get("/abc/users/secure/person");
}*/


/* @Test
public void testCreateuser() {
  final String firstName = "Tim";
  final String lastName = "Tester";

  given().
    parameters(
      "firstName", firstName,
      "lastName", lastName).
  expect().
    body("firstName", equalTo(firstName)).
    body("lastName", equalTo(lastName)).
  when().
  get("/abc/users/create");
}*/

}