KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > util > AdaptedClassDumper


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.util;
5
6 import java.io.File JavaDoc;
7 import java.io.FileOutputStream JavaDoc;
8
9 /**
10  * A little utility class that will write class files to disk.
11  */

12 public class AdaptedClassDumper {
13
14   private final static File JavaDoc adaptedRoot = getFileRoot();
15
16   private AdaptedClassDumper() {
17     //
18
}
19
20   public synchronized static void write(String JavaDoc name, byte[] b) {
21     if (adaptedRoot == null) { return; }
22
23     name = name.replace('.', '/') + ".class";
24     FileOutputStream JavaDoc fos = null;
25
26     try {
27       try {
28         String JavaDoc pattern = File.separator.replaceAll("\\\\", "\\\\\\\\");
29         String JavaDoc[] strings = new File JavaDoc(adaptedRoot, name).getAbsolutePath().split(pattern);
30
31         final StringBuffer JavaDoc sb;
32         if (adaptedRoot.getAbsolutePath().startsWith("/")) {
33           sb = new StringBuffer JavaDoc("/");
34         } else {
35           sb = new StringBuffer JavaDoc();
36         }
37
38         for (int i = 0; i < strings.length - 1; i++) {
39           sb.append(strings[i]);
40           sb.append(File.separatorChar);
41         }
42
43         File JavaDoc dir = new File JavaDoc(sb.toString());
44         if (!dir.exists()) {
45           dir.mkdirs();
46         }
47
48         File JavaDoc outFile = new File JavaDoc(adaptedRoot, name);
49         System.out.println("Writing resource: " + outFile);
50         fos = new FileOutputStream JavaDoc(outFile);
51         fos.write(b);
52       } finally {
53         if (fos != null) {
54           fos.close();
55         }
56       }
57     } catch (Exception JavaDoc e) {
58       e.printStackTrace();
59     }
60   }
61
62   private static File JavaDoc getFileRoot() {
63     try {
64       boolean writeToDisk = (System.getProperty("tc.classloader.writeToDisk") != null);
65       if (!writeToDisk) { return null; }
66
67       String JavaDoc userHome = System.getProperty("user.home");
68
69       if (userHome != null) {
70         File JavaDoc homeDir = new File JavaDoc(userHome);
71         if (homeDir.isDirectory() && homeDir.canWrite()) { return new File JavaDoc(homeDir, "adapted"); }
72       }
73
74       return null;
75     } catch (Exception JavaDoc e) {
76       // you can get a SecurityException here, but we shouldn't blow up just b/c of that
77
e.printStackTrace();
78       return null;
79     }
80   }
81
82 }
83
Popular Tags