01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.util;
05:
06: import java.io.File;
07: import java.io.FileOutputStream;
08:
09: /**
10: * A little utility class that will write class files to disk.
11: */
12: public abstract class AbstractClassDumper {
13:
14: private final File adaptedRoot = getFileRoot();
15:
16: public synchronized void write(String name, byte[] b) {
17: if (adaptedRoot == null) {
18: return;
19: }
20:
21: name = name.replace('.', '/') + ".class";
22: FileOutputStream fos = null;
23:
24: try {
25: try {
26: String pattern = File.separator.replaceAll("\\\\",
27: "\\\\\\\\");
28: String[] strings = new File(adaptedRoot, name)
29: .getAbsolutePath().split(pattern);
30:
31: final StringBuffer sb;
32: if (adaptedRoot.getAbsolutePath().startsWith("/")) {
33: sb = new StringBuffer("/");
34: } else {
35: sb = new StringBuffer();
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 dir = new File(sb.toString());
44: if (!dir.exists()) {
45: dir.mkdirs();
46: }
47:
48: File outFile = new File(adaptedRoot, name);
49: System.out.println("Writing resource: " + outFile);
50: System.out.flush();
51: fos = new FileOutputStream(outFile);
52: fos.write(b);
53: } finally {
54: if (fos != null) {
55: fos.close();
56: }
57: }
58: } catch (Exception e) {
59: e.printStackTrace();
60: }
61: }
62:
63: private File getFileRoot() {
64: try {
65: boolean writeToDisk = (System
66: .getProperty(getPropertyName()) != null);
67: if (!writeToDisk) {
68: return null;
69: }
70:
71: String userHome = System.getProperty("user.home");
72:
73: if (userHome != null) {
74: File homeDir = new File(userHome);
75: if (homeDir.isDirectory() && homeDir.canWrite()) {
76: return new File(homeDir, getDumpDirectoryName());
77: }
78: }
79:
80: return null;
81: } catch (Exception e) {
82: // you can get a SecurityException here, but we shouldn't blow up just b/c of that
83: e.printStackTrace();
84: return null;
85: }
86: }
87:
88: protected abstract String getDumpDirectoryName();
89:
90: protected abstract String getPropertyName();
91: }
|