1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.commons.weaver.test;
20
21 import java.io.File;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.net.URL;
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.junit.Rule;
30 import org.junit.rules.TemporaryFolder;
31
32
33
34
35 public abstract class WeaverTestBase {
36
37 @Rule
38 public TemporaryFolder temporaryFolder = new TemporaryFolder();
39
40 private File targetFolder;
41
42 private List<String> classPathEntries;
43
44 private static final String TARGET_FOLDER = "target";
45
46 public void cleanup() {
47 targetFolder = null;
48 }
49
50
51
52
53
54
55 protected void addClassForScanning(Class<?> clazz) throws IOException {
56 String clazzDirName = clazz.getPackage().getName().replace(".", "/");
57 File targetDirFile = new File(getTargetFolder(), clazzDirName);
58 targetDirFile.mkdirs();
59
60 String fileName = baseName(clazz) + ".class";
61 String clazzFileName = clazzDirName + "/" + fileName;
62 URL clazzUrl = getClass().getClassLoader().getResource(clazzFileName);
63 File targetClazzFile = new File(targetDirFile, fileName);
64
65 byte[] buffer = new byte[0xFFFF];
66
67 FileOutputStream fos = new FileOutputStream(targetClazzFile);
68
69 InputStream inputStream = clazzUrl.openStream();
70 int len;
71 while ((len = inputStream.read(buffer)) > 0) {
72 fos.write(buffer, 0, len);
73 }
74 fos.flush();
75 fos.close();
76
77 for (Class<?> inner : clazz.getClasses()) {
78 addClassForScanning(inner);
79 }
80 }
81
82 private String baseName(Class<?> clazz) {
83 if (clazz.getDeclaringClass() == null) {
84 return clazz.getSimpleName();
85 }
86 final StringBuilder result = new StringBuilder();
87 Class<?> current = clazz;
88 while (current != null) {
89 if (result.length() > 0) {
90 result.insert(0, '$');
91 }
92 result.insert(0, current.getSimpleName());
93 current = current.getDeclaringClass();
94 }
95 return result.toString();
96 }
97
98
99
100
101 protected File getTargetFolder() {
102 if (targetFolder == null) {
103 targetFolder = new File(temporaryFolder.getRoot(), TARGET_FOLDER);
104 }
105 return targetFolder;
106 }
107
108 protected List<String> getClassPathEntries() {
109 if (classPathEntries == null) {
110 classPathEntries = new ArrayList<String>(1);
111 try {
112 classPathEntries.add(getTargetFolder().getCanonicalPath());
113 } catch (IOException ioe) {
114 throw new RuntimeException(ioe);
115 }
116 }
117
118 return classPathEntries;
119 }
120
121 }