KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > java > source > TestUtil


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.java.source;
21
22 import java.io.BufferedInputStream JavaDoc;
23 import java.io.BufferedOutputStream JavaDoc;
24 import java.io.BufferedReader JavaDoc;
25 import java.io.File JavaDoc;
26 import java.io.FileFilter JavaDoc;
27 import java.io.FileInputStream JavaDoc;
28 import java.io.FileOutputStream JavaDoc;
29 import java.io.FileReader JavaDoc;
30 import java.io.IOException JavaDoc;
31 import java.io.InputStream JavaDoc;
32 import java.io.OutputStream JavaDoc;
33 import java.util.Enumeration JavaDoc;
34 import java.util.Iterator JavaDoc;
35 import java.util.Properties JavaDoc;
36 import java.util.zip.ZipEntry JavaDoc;
37 import java.util.zip.ZipFile JavaDoc;
38 import junit.framework.TestCase;
39 import org.netbeans.junit.NbTestCase;
40
41
42 /**
43  *
44  * @author Petr Hrebejk
45  */

46 public class TestUtil {
47         
48     public static final String JavaDoc RT_JAR = "jre/lib/rt.jar";
49     public static final String JavaDoc SRC_ZIP = "src.zip";
50     
51     /** Creates a new instance of TestUtil */
52     private TestUtil() {
53     }
54     
55     public static void copyFiles( File JavaDoc destDir, String JavaDoc... resourceNames ) throws IOException JavaDoc {
56         copyFiles(getDataDir(), destDir, resourceNames);
57     }
58     
59     public static void copyFiles( File JavaDoc sourceDir, File JavaDoc destDir, String JavaDoc... resourceNames ) throws IOException JavaDoc {
60
61         for( String JavaDoc resourceName : resourceNames ) {
62             
63             File JavaDoc src = new File JavaDoc( sourceDir, resourceName );
64             
65             if ( !src.canRead() ) {
66                 TestCase.fail( "The test requires the file: " + resourceName + " to be readable and stored in: " + sourceDir );
67             }
68             
69             InputStream JavaDoc is = new FileInputStream JavaDoc( src );
70             BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc( is );
71                         
72             File JavaDoc dest = new File JavaDoc( destDir, resourceName );
73             File JavaDoc parent = dest.getParentFile();
74             
75             if ( !parent.exists() ) {
76                 parent.mkdirs();
77             }
78             
79             dest.createNewFile();
80             BufferedOutputStream JavaDoc bos = new BufferedOutputStream JavaDoc( new FileOutputStream JavaDoc( dest ) );
81             
82             copyFile( bis, bos );
83         }
84     }
85     
86     public static void unzip( ZipFile JavaDoc zip, File JavaDoc dest ) throws IOException JavaDoc {
87         
88         for( Enumeration JavaDoc<? extends ZipEntry JavaDoc> e = zip.entries(); e.hasMoreElements(); ) {
89             ZipEntry JavaDoc entry = e.nextElement();
90             File JavaDoc f = new File JavaDoc( dest, entry.getName() );
91             if ( entry.isDirectory() ) {
92                 f.mkdirs();
93             }
94             else {
95                 f.getParentFile().mkdirs();
96                 f.createNewFile();
97                 BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc( zip.getInputStream( entry ) );
98                 BufferedOutputStream JavaDoc bos = new BufferedOutputStream JavaDoc( new FileOutputStream JavaDoc( f ) );
99                 copyFile( bis, bos );
100             }
101         }
102         
103     }
104     
105     public static File JavaDoc createWorkFolder() throws IOException JavaDoc {
106         File JavaDoc tempFile = File.createTempFile( "TestWorkDir", null );
107         tempFile.delete();
108         tempFile.mkdir();
109         return tempFile;
110     }
111     
112     public static FileFilter JavaDoc createExtensionFilter( boolean folders, final String JavaDoc ... extensions ) {
113         return new ExtensionFileFilter( folders, extensions );
114     }
115     
116     public static void removeWorkFolder( File JavaDoc file ) {
117         deleteRecursively( file );
118     }
119     
120     /** Good for debuging content of large collections.
121      * Prints out readable diff of the collections passed as parameters.
122      */

123     public static String JavaDoc collectionDiff( Iterable JavaDoc c1, Iterable JavaDoc c2 ) {
124         return collectionDiff( c1.iterator(), c2.iterator() );
125     }
126     
127     public static String JavaDoc collectionDiff( Iterator JavaDoc it1, Iterator JavaDoc it2 ) {
128         
129           StringBuilder JavaDoc sb = new StringBuilder JavaDoc();
130         
131           int index = 0;
132           boolean printing = false;
133           while( it1.hasNext() ) {
134                  
135              Object JavaDoc o1 = it1.next();
136              
137              Object JavaDoc o2 = it2.hasNext() ? it2.next() : null ;
138
139              if ( !o1.equals( o2 ) ) {
140                  if ( !printing ) {
141                      printing = true;
142                      sb.append("\n");
143                  }
144                  sb.append( index + " " + o1 + " -> " + ( o2 == null ? "NULL" : o2 ) + "\n" );
145              }
146              else if ( printing ) {
147                  printing = false;
148              }
149              
150              index++;
151           }
152           
153           if ( it2.hasNext() ) {
154               sb.append( "\n" );
155           }
156           while( it2.hasNext() ) {
157               sb.append( index + " [NULL]" + " -> " + it2.next() + "\n" );
158               index ++;
159           }
160                   
161           return sb.toString();
162     }
163     
164     public static String JavaDoc fileToString( File JavaDoc file ) throws IOException JavaDoc {
165         
166         BufferedReader JavaDoc reader = new BufferedReader JavaDoc( new FileReader JavaDoc( file ) );
167         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
168         
169         for( String JavaDoc line = reader.readLine(); line != null; line = reader.readLine() ) {
170             //System.out.println("L " + line);
171
sb.append( line ).append( "\n" );
172         }
173         
174         return sb.toString();
175     }
176     
177     /** Returns the tests data folder. Containing sample classes
178      */

179     public static File JavaDoc getDataDir() {
180         return TemporaryTestCase.getDataFolder();
181     }
182     
183     /** Returns current jdk directory
184      */

185     public static File JavaDoc getJdkDir() {
186     
187     Properties JavaDoc p = System.getProperties();
188     String JavaDoc javaHomeProp = p.getProperty( "java.home" );
189     
190     if ( javaHomeProp == null ) {
191         throw new IllegalStateException JavaDoc( "Can't find java.home property ");
192     }
193     else {
194         File JavaDoc jre = new File JavaDoc( javaHomeProp );
195         if ( !jre.canRead() ) {
196         throw new IllegalStateException JavaDoc( "Can't read " + jre );
197         }
198         File JavaDoc dir = jre.getParentFile();
199         if ( !jre.canRead() ) {
200         throw new IllegalStateException JavaDoc( "Can't read " + dir);
201         }
202         return dir;
203     }
204     }
205     
206     
207     /** Returns given JDK file
208      * @param path Relative path to the JDK file.
209      * @return the file
210      * @throws IllegalArgumentException if the file can't be found or read.
211      */

212     public static File JavaDoc getJdkFile( String JavaDoc path ) {
213     File JavaDoc dir = getJdkDir();
214     
215     File JavaDoc f = new File JavaDoc( dir, path );
216     
217     if ( f.canRead() ) {
218         return f;
219     }
220     else {
221         throw new IllegalArgumentException JavaDoc( "Can't read file " + f );
222     }
223         
224     }
225     
226     
227     // Private methods ---------------------------------------------------------
228

229     private static int BLOCK_SIZE = 16384;
230     
231     private static void copyFile( InputStream JavaDoc is, OutputStream JavaDoc os ) throws IOException JavaDoc {
232         byte[] b = new byte[ BLOCK_SIZE ];
233         int count = is.read(b);
234
235         while (count != -1)
236         {
237          os.write(b, 0, count);
238          count = is.read(b);
239         }
240
241         is.close();
242         os.close();
243     }
244     
245     /** Recursively deletes the complete folder srtucture
246      */

247     private static void deleteRecursively( File JavaDoc file ) {
248         
249         if ( file.isDirectory() ) {
250             File JavaDoc[] files = file.listFiles();
251             for( File JavaDoc f : files ) {
252                 deleteRecursively( f );
253             }
254         }
255         
256         file.delete();
257     }
258     
259     
260 // public static void printInsane( Object... roots ) {
261
//
262
// System.gc();
263
// System.gc();
264
// System.out.println( "FREE MEMORY :" + ( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() ) );
265
// System.out.println("");
266
//
267
// final CountingVisitor cv = new CountingVisitor();
268
// try {
269
// ScannerUtils.scan( null, cv, Arrays.asList( roots ), true );
270
// }
271
// catch ( Exception e ) {
272
// e.printStackTrace();
273
// }
274
//
275
// Set ordered = new TreeSet(new Comparator() {
276
// public int compare(Object c1, Object c2) {
277
// int diff = cv.getSizeForClass((Class)c2)
278
// cv.getSizeForClass((Class)c1);
279
//
280
// if (diff != 0 || c1 == c2) return diff;
281
// return ((Class)c1).getName().compareTo(((Class)c2).getName());
282
// }
283
// });
284
//
285
// ordered.addAll(cv.getClasses());
286
//
287
// System.out.println("Usage: [instances class.Name: totalSizeInBytes]");
288
// for (Iterator it = ordered.iterator(); it.hasNext();) {
289
// Class cls = (Class)it.next();
290
// System.out.println(cv.getCountForClass(cls) + " " +
291
// cls.getName() + ": " + cv.getSizeForClass(cls));
292
// }
293
//
294
// System.out.println("total: " + cv.getTotalSize() + " in " +
295
// cv.getTotalCount() + " objects.");
296
// System.out.println("Classes:" + cv.getClasses().size());
297
//
298
//
299
//
300
//
301
// }
302

303     
304       // Private innerclasses --------------------------------------------------
305

306       private static class ExtensionFileFilter implements FileFilter JavaDoc {
307           
308           private boolean folders;
309           private String JavaDoc[] extensions;
310           
311           public ExtensionFileFilter( boolean folders, String JavaDoc... extensions ) {
312               this.folders = folders;
313               this.extensions = extensions;
314           }
315           
316                     
317           public boolean accept( File JavaDoc file ) {
318           
319               if ( folders && file.isDirectory() ) {
320                   return true;
321               }
322                             
323               for( String JavaDoc ext : extensions ) {
324                   if ( file.getName().endsWith( ext ) ) {
325                       return true;
326                   }
327               }
328               
329               return false;
330           }
331           
332           
333       }
334       
335       private static class TemporaryTestCase extends NbTestCase {
336     
337           private static TemporaryTestCase INSTANCE = new TemporaryTestCase();
338           
339           TemporaryTestCase() {
340               super( TemporaryTestCase.class.toString() );
341           }
342           
343           public static File JavaDoc getDataFolder() {
344               return INSTANCE.getDataDir();
345           }
346           
347       }
348       
349     
350 }
351
Popular Tags