1 package org.catacomb.util;
2
3
4 import java.io.File;
5
6 import java.util.ArrayList;
7
8 import org.catacomb.report.E;
9
10 import java.io.FileOutputStream;
11
12 import java.io.BufferedWriter;
13 import java.io.OutputStreamWriter;
14
15 import java.util.jar.JarOutputStream;
16 import java.util.jar.JarEntry;
17
18 import java.util.HashSet;
19
20 public class FileAccumulator {
21
22 File rootDir;
23
24 ArrayList<File> allFiles;
25
26
27 DirRef rootRef;
28
29
30 HashSet<File> fileHS;
31
32 public FileAccumulator(File rd) {
33 rootDir = rd;
34 rootRef = new DirRef("");
35 allFiles = new ArrayList<File>();
36 fileHS = new HashSet<File>();
37 }
38
39
40
41 public void addIfNew(File f) {
42 if (fileHS.contains(f)) {
43
44 } else {
45 add(f);
46 }
47 }
48
49
50 public void add(File f) {
51 allFiles.add(f);
52 fileHS.add(f);
53
54
55
56 DirRef pd = rootRef;
57 for (String s : FileUtil.getPathElements(rootDir, f)) {
58 if (pd.containsDir(s)) {
59 pd = pd.getDir(s);
60 } else {
61 DirRef npd = new DirRef(s);
62 pd.add(npd);
63 pd = npd;
64 }
65 }
66
67 FileRef fr = new FileRef(f);
68 pd.add(fr);
69
70
71 }
72
73
74
75 public void saveJar(File fzin) {
76 File fz = fzin;
77 if (fz.getName().endsWith(".jar")) {
78
79 } else {
80 fz = new File(fz.getParentFile(), fz.getName() + ".jar");
81 }
82
83
84 try {
85 FileOutputStream fos = new FileOutputStream(fz);
86 JarOutputStream zos = new JarOutputStream(fos);
87 OutputStreamWriter osw = new OutputStreamWriter(zos);
88 BufferedWriter bw = new BufferedWriter(osw);
89
90 for (File f : allFiles) {
91 String relpath = FileUtil.getRelativeDirectory(f, rootDir) + "/" + f.getName();
92
93 String s = FileUtil.readStringFromFile(f);
94 zos.putNextEntry(new JarEntry(relpath));
95 bw.write(s, 0, s.length());
96 bw.flush();
97 zos.closeEntry();
98 }
99
100 osw.close();
101
102
103 } catch (Exception ex) {
104 E.error("jar write error " + ex);
105 }
106 }
107
108
109
110 public void addJavaSource(String scrdir, String path) {
111
112
113 File fsc = new File(rootDir, scrdir);
114 String[] sa = path.split("\\.");
115
116 for (int i = 0; i < sa.length-1; i++) {
117 fsc = new File(fsc, sa[i]);
118 }
119
120 String sl = sa[sa.length-1];
121 if (sl.equals("*")) {
122 if (fsc.exists() && fsc.isDirectory()) {
123 for (File f : fsc.listFiles()) {
124 addIfNew(f);
125 }
126 } else {
127 E.warning("cant add wildcard imports " + path);
128 }
129
130
131 } else {
132 File f = new File(fsc, sl + ".java");
133 if (f.exists()) {
134 addIfNew(f);
135 } else {
136 E.warning("missing script file? " + f + " for import " + path);
137 }
138 }
139 }
140
141
142
143 public void addJavaSourceSiblings(String scrdir, String pathin) {
144 String path = pathin;
145 if (path.endsWith(".*")) {
146 addJavaSource(scrdir, path);
147
148 } else {
149 path = path.substring(0, path.lastIndexOf("."));
150 path = path + ".*";
151 addJavaSource(scrdir, path);
152 }
153
154
155
156 }
157
158
159 }