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.kit.ObjectReference; 014import com.thoughtworks.proxy.toys.delegate.Delegating; 015import com.thoughtworks.proxy.toys.delegate.DelegationMode; 016 017import java.io.DataInput; 018import java.io.DataOutput; 019import java.io.File; 020import java.io.IOException; 021import java.io.RandomAccessFile; 022 023/** 024 * @author Jörg Schaible 025 */ 026public class DelegateToyExample { 027 028 public static void packageOverviewExample1() { 029 ThreadLocal<Boolean> threadLocal = new ThreadLocal<Boolean>() { 030 @Override 031 protected Boolean initialValue() { 032 return Boolean.TRUE; 033 } 034 }; 035 036 // Make a delegate of com.thoughtworks.proxy.kitObjectReference using the Reflection Proxy class 037 @SuppressWarnings("unchecked") 038 ObjectReference<Boolean> ref = Delegating.proxy(ObjectReference.class) 039 .with(threadLocal) 040 .build(); 041 System.out.println("This ObjectReference has an initial value of <" + ref.get() + ">"); 042 } 043 044 public static DataInput getDataInput(File f) throws IOException { 045 RandomAccessFile raf = new RandomAccessFile(f, "rw"); 046 raf.writeBytes("Content"); 047 raf.seek(0); 048 049 // Make a delegate of java.io.DataInput using the Reflection Proxy class 050 return Delegating.proxy(DataInput.class) 051 .with(raf) 052 .mode(DelegationMode.DIRECT) 053 .build(); 054 } 055 056 public static void packageOverviewExample2() throws IOException { 057 File tempFile = File.createTempFile("Toy", null); 058 try { 059 DataInput dataInput = getDataInput(tempFile); 060 String line = dataInput.readLine(); 061 System.out.println("Data read: " + line); 062 DataOutput dataOutput = DataOutput.class.cast(dataInput); 063 dataOutput.writeBytes("This line will not be reached!"); 064 } catch (ClassCastException e) { 065 System.out.println("Could not cast to DataOutput: " + e.getMessage()); 066 } finally { 067 tempFile.delete(); 068 } 069 } 070 071 public static void main(String[] args) throws IOException { 072 System.out.println(); 073 System.out.println(); 074 System.out.println("Running Delegate Toy Examples"); 075 System.out.println(); 076 System.out.println("Example 1 of Package Overview:"); 077 packageOverviewExample1(); 078 System.out.println(); 079 System.out.println("Example 2 of Package Overview:"); 080 packageOverviewExample2(); 081 } 082}