1 26 27 package net.sourceforge.groboutils.codecoverage.v2.logger; 28 29 import net.sourceforge.groboutils.util.datastruct.v1.HashCache; 30 31 import java.io.BufferedWriter ; 32 import java.io.File ; 33 import java.io.FileWriter ; 34 import java.io.IOException ; 35 import java.io.Writer ; 36 37 38 52 public class CacheDirChannelLogger extends DirectoryChannelLogger 53 implements Runnable , HashCache.ObjectManager 54 { 55 private final HashCache openedFiles; 56 57 58 public CacheDirChannelLogger( File baseDir, int cacheSize ) 59 { 60 super( baseDir ); 61 if (baseDir != null) 62 { 63 if (cacheSize <= 0) 67 { 68 cacheSize = CacheDirChannelLoggerFactory.DEFAULT_CACHESIZE; 69 } 70 this.openedFiles = new HashCache( this, cacheSize ); 71 addShutdownHook(); 72 } 73 else 74 { 75 this.openedFiles = null; 76 } 77 } 78 79 80 92 public void cover( String classSignature, short methodIndex, 93 short markIndex ) 94 { 95 if (this.baseDir != null) 96 { 97 File f = getClassFile( this.baseDir, classSignature ); 98 Writer w = null; 99 try 100 { 101 char[] out = createCoverString( methodIndex, markIndex ); 102 synchronized (this) 103 { 104 w = (Writer )this.openedFiles.get( f ); 105 if (w != null) 106 { 107 w.write( out ); 108 } 109 } 110 } 111 catch (IOException ioe) 112 { 113 ioe.printStackTrace(); 115 116 this.baseDir = null; 118 } 119 } 120 } 121 122 123 126 public void run() 127 { 128 synchronized( this ) 129 { 130 this.openedFiles.clear(); 131 } 132 } 133 134 135 138 public Object createObject( Object key ) 139 { 140 File f = (File )key; 141 try 142 { 143 BufferedWriter bw = new BufferedWriter ( 145 new FileWriter ( f.toString(), true ) ); 146 return bw; 147 } 148 catch (IOException ioe) 149 { 150 ioe.printStackTrace(); 152 153 this.baseDir = null; 155 156 return null; 158 } 159 } 160 161 162 169 public void cleanUpObject( Object key, Object obj ) 170 { 171 if (obj != null) 172 { 173 Writer w = (Writer )obj; 174 try 175 { 176 w.flush(); 177 w.close(); 178 } 179 catch (IOException ioe) 180 { 181 ioe.printStackTrace(); 182 } 183 } 184 } 185 186 187 188 protected void finalize() throws Throwable 189 { 190 run(); 192 193 super.finalize(); 194 } 195 196 197 protected void addShutdownHook() 198 { 199 Class c = Runtime .class; 200 try 201 { 202 java.lang.reflect.Method m = c.getMethod( 203 "addShutdownHook", new Class [] { Thread .class } ); 204 Thread t = new Thread ( this, 205 this.getClass().getName()+" shutdown hook" ); 206 m.invoke( Runtime.getRuntime(), new Object [] { t } ); 207 } 208 catch (Exception ex) 209 { 210 System.err.println(this.getClass().getName()+ 212 " should only be run in a JDK 1.3 compatible JVM."); 213 ex.printStackTrace(); 214 } 215 } 216 } 217 218 | Popular Tags |