001/* 002 * (c) 2005, 2009, 2010 ThoughtWorks Ltd 003 * All rights reserved. 004 * 005 * The software in this package is published under the terms of the BSD 006 * style license a copy of which has been included with this distribution in 007 * the LICENSE.txt file. 008 * 009 * Created on 29-Jun-2005 010 */ 011package proxytoys.examples.overview; 012 013import com.thoughtworks.proxy.factory.CglibProxyFactory; 014import com.thoughtworks.proxy.toys.decorate.Decorating; 015import com.thoughtworks.proxy.toys.decorate.Decorator; 016 017import java.io.File; 018import java.lang.reflect.Method; 019import java.util.Arrays; 020import java.util.Iterator; 021import java.util.List; 022 023 024/** 025 * @author Jörg Schaible 026 */ 027public class DecorateToyExample { 028 029 public static void packageOverviewExample1() { 030 031 List<String> list = Arrays.asList("1", "2", "3"); 032 033 @SuppressWarnings({"serial", "unchecked"}) 034 Decorator<Iterator> decorator = new Decorator<Iterator>() { 035 @Override 036 public Object decorateResult(Iterator proxy, Method method, Object[] args, Object result) { 037 if (method.getName().equals("next")) { 038 return Integer.valueOf(String.class.cast(result)); 039 } else { 040 return result; 041 } 042 } 043 }; 044 045 046 // Make a decorator of an Iterator using the Reflection Proxy class 047 @SuppressWarnings("unchecked") 048 Iterator<Integer> intIter = Decorating.proxy(Iterator.class) 049 .with(list.iterator()) 050 .visiting(decorator) 051 .build(); 052 while (intIter.hasNext()) { 053 Integer i = intIter.next(); 054 System.out.println(i); 055 } 056 } 057 058 public static void packageOverviewExample2() { 059 File file = new File("."); 060 @SuppressWarnings("serial") 061 Decorator<File> decorator = new Decorator<File>() { 062 @Override 063 public Object[] beforeMethodStarts(File proxy, Method method, Object[] args) { 064 System.out.print("Called: " + method.getName()); 065 return super.beforeMethodStarts(proxy, method, args); 066 } 067 068 @Override 069 public Object decorateResult(File proxy, Method method, Object[] args, Object result) { 070 System.out.println(" ==> " + result); 071 return result; 072 } 073 }; 074 075 // Make a decorator of java.io.File using CGLIB 076 File decoratedFile = Decorating.proxy(file) 077 .visiting(decorator) 078 .build(new CglibProxyFactory()); 079 decoratedFile.exists(); 080 decoratedFile.isFile(); 081 decoratedFile.isDirectory(); 082 } 083 084 public static void main(String[] args) { 085 System.out.println(); 086 System.out.println(); 087 System.out.println("Running Decorate Toy Examples"); 088 System.out.println(); 089 System.out.println("Example 1 of Package Overview:"); 090 packageOverviewExample1(); 091 System.out.println(); 092 System.out.println("Example 2 of Package Overview:"); 093 packageOverviewExample2(); 094 } 095}