KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > uk > ac > roe > antigen > ant > BuildGrabber


1 /*
2  * Created on 19-Dec-2004
3  */

4 package uk.ac.roe.antigen.ant;
5
6 import java.io.BufferedInputStream JavaDoc;
7 import java.io.File JavaDoc;
8 import java.io.FileOutputStream JavaDoc;
9 import java.io.IOException JavaDoc;
10 import java.io.InputStream JavaDoc;
11 import java.io.OutputStream JavaDoc;
12 import java.io.BufferedOutputStream JavaDoc;
13 import java.net.JarURLConnection JavaDoc;
14 import java.net.URL JavaDoc;
15 import java.util.Enumeration JavaDoc;
16 import java.util.jar.JarEntry JavaDoc;
17 import java.util.jar.JarFile JavaDoc;
18 import java.util.logging.Logger JavaDoc;
19
20 import uk.ac.roe.antigen.utils.CopyableFile;
21
22
23 /**
24  * Grabs a directory, or a zip file, and installs it in the temp directory for
25  * processing
26  *
27  * @author jdt
28  *
29  */

30 public class BuildGrabber {
31     /**
32      * Logger for this class
33      */

34     private static final Logger JavaDoc logger = Logger.getLogger(BuildGrabber.class.getName());
35
36
37     private CopyableFile tmpDir;
38
39     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
40         BuildGrabber grabber = new BuildGrabber();
41         try {
42             CopyableFile tmp = grabber.tmpDir;
43             logger.fine("Temporary directory: " + tmp);
44             //File testDir = new File("C:/Java/ag-integration-work");
45
URL JavaDoc jarUrl = new URL JavaDoc(
46                     "file:///C:/Documents and Settings/jdt/.maven/repository/org.astrogrid/wars/astrogrid-portal-0.7-b015p.war");
47             //File copiedDir = grabber.grab(jarUrl);
48
File JavaDoc copiedDir = grabber.grab("/foo");
49             logger.fine("Copied dir was " + copiedDir);
50             Thread.sleep(30000);
51         } finally {
52             System.out.println("Deleted? " + grabber.deleteTmp());
53         }
54     }
55
56     /**
57      * Source files are supplied as a known directory
58      *
59      * @param dir
60      * @throws IOException
61      * @return the tmp directory holding the files
62      */

63     public CopyableFile grab(File JavaDoc dir) throws IOException JavaDoc {
64         new CopyableFile(dir).copyTo(tmpDir);
65         return tmpDir;
66     }
67
68     /**
69      * Grabs contents of a jar file from a URL and unzip to a temp directory
70      *
71      * @param url
72      * of jar file
73      * @return the tmp directory holding the files
74      * @throws IOException
75      */

76     public CopyableFile grab(URL JavaDoc url) throws IOException JavaDoc {
77         String JavaDoc simpleUrl = url.toExternalForm();
78         logger.fine("Grabbing from " + simpleUrl);
79         JarURLConnection JavaDoc jarUrl = (JarURLConnection JavaDoc) new URL JavaDoc("jar:" + simpleUrl
80                 + "!/").openConnection();
81         logger.fine("Opening connection to " + jarUrl);
82         JarFile JavaDoc jarFile = jarUrl.getJarFile();
83         return grab(jarFile);
84     }
85
86     /**
87      * Grab the contents of a jar file and unzip to a temp directory
88      *
89      * @param jar
90      * the jar file
91      * @return the tmp directory holding the files
92      * @throws IOException
93      * @TODO factor this out into separate class
94      */

95     public CopyableFile grab(JarFile JavaDoc jar) throws IOException JavaDoc {
96         Enumeration JavaDoc entries = jar.entries();
97         while (entries.hasMoreElements()) {
98             JarEntry JavaDoc entry = (JarEntry JavaDoc) entries.nextElement();
99             logger.fine("Entry " + entry);
100
101             File JavaDoc copiedFileEntry = new File JavaDoc(tmpDir, entry.getName());
102             logger.fine("Copying to " + copiedFileEntry.getAbsolutePath());
103
104             if (entry.isDirectory()) {
105                 copiedFileEntry.mkdirs();
106             } else {
107                 InputStream JavaDoc is = new BufferedInputStream JavaDoc(jar
108                         .getInputStream(entry));
109                 copiedFileEntry.createNewFile();
110                 FileOutputStream JavaDoc os = new FileOutputStream JavaDoc(copiedFileEntry);
111
112                 copyStreams(is, os);
113             }
114
115         }
116         return tmpDir;
117     }
118
119     private void copyStreams(InputStream JavaDoc in, OutputStream JavaDoc out)
120             throws IOException JavaDoc {
121         int data = -1;
122         while ((data = in.read()) != -1) {
123             out.write(data);
124         }
125         out.close();
126
127         in.close();
128     }
129
130     /**
131      * Grabs stuff off the classpath and stick it in the temp directory
132      *
133      * @param path
134      * the path off the classpath to the jar
135      * @return the temp directory in which the grabbed stuff has been stuck
136      * @throws IOException
137      */

138     public CopyableFile grab(String JavaDoc path) throws IOException JavaDoc {
139         // Since this has been reimplemented, it only deals with
140
// paths that are absolute off the classpath, so any initial
141
// slash must be dropped.
142
if (path.startsWith("/")) {
143             path = path.substring(1);
144         }
145         File JavaDoc tmpJarFile = File.createTempFile("build", ".jar");
146         tmpJarFile.deleteOnExit();
147                 JarFile JavaDoc installSource = new JarFile JavaDoc(System.getProperty("java.class.path"));
148                 logger.fine("path: "+path);
149                 File JavaDoc antBuildJar = unzipFile(path,installSource, tmpDir, false);
150         /*InputStream is = new BufferedInputStream(this.getClass()
151                 .getResourceAsStream(path));
152
153         logger.fine("Copying jar to " + tmpJarFile.getAbsolutePath());
154         FileOutputStream os = new FileOutputStream(tmpJarFile);
155
156         copyStreams(is, os);
157                 */

158         JarFile JavaDoc jar = new JarFile JavaDoc(antBuildJar);
159                 unzipFile(null,jar,tmpDir,true);
160         /*Enumeration entries = jar.entries();
161         while (entries.hasMoreElements()) {
162             JarEntry entry = (JarEntry) entries.nextElement();
163             logger.fine("Entry " + entry);
164             
165
166             File copiedFileEntry = new File(tmpDir, entry.getName());
167             logger.fine("Copying to " + copiedFileEntry.getAbsolutePath());
168
169             if (entry.isDirectory()) {
170                 copiedFileEntry.mkdirs();
171             } else {
172                 copiedFileEntry.createNewFile();
173                 InputStream jarEntryStream = new BufferedInputStream(jar.getInputStream(entry));
174                 FileOutputStream copiedFileStream = new FileOutputStream(copiedFileEntry);
175
176                 copyStreams(jarEntryStream, copiedFileStream);
177             }
178         }*/

179         return tmpDir;
180
181     }
182
183     /**
184      * Unzips either one file specified by fullPathFileName or all files (if fullPathFileName is null) from srcJar to destDir
185      * @param fullPathFileName
186      * @param srcJar
187      * @param destDir
188      * @return if fullPathFileName is not null then returns the unzipped file, otherwise returns null
189      */

190     private File JavaDoc unzipFile(String JavaDoc fullPathFileName, JarFile JavaDoc srcJar, File JavaDoc destDir, boolean useFullPath) {
191        int BUFFER = 16384;
192        BufferedOutputStream JavaDoc dest = null;
193        BufferedInputStream JavaDoc is = null;
194        JarEntry JavaDoc entry;
195        String JavaDoc newFullPathFileName = null;
196        Enumeration JavaDoc e = srcJar.entries();
197         try {
198            while(e.hasMoreElements()) {
199                entry = (JarEntry JavaDoc) e.nextElement();
200                if (fullPathFileName != null && !(entry.getName().equals(fullPathFileName) )) {
201                    continue;
202                }
203
204                logger.fine("Extracting: " +entry);
205                is = new BufferedInputStream JavaDoc(srcJar.getInputStream(entry));
206                 int count;
207                 byte data[] = new byte[BUFFER];
208                int lastIndexOfSlashPlusOne = entry.getName().lastIndexOf('/')+1;
209                String JavaDoc path = null;
210                String JavaDoc fileName = null;
211                if (lastIndexOfSlashPlusOne == 0) {
212                    path = "";
213                } else {
214                    path = entry.getName().substring(0,lastIndexOfSlashPlusOne);
215                    String JavaDoc sep = File.separator;
216                    if (sep.equals("\\")) {
217                        sep = "\\\\";
218                    }
219                    path = path.replaceAll("/",sep);
220                }
221                fileName = entry.getName().substring(lastIndexOfSlashPlusOne);
222                String JavaDoc newEntryName = destDir.getAbsolutePath()+File.separator+path+fileName;
223                if (!useFullPath) {
224                    newEntryName = destDir.getAbsolutePath()+File.separator+fileName;
225                }
226                if (entry.isDirectory()) {
227                    File JavaDoc entryFile = new File JavaDoc(newEntryName);
228                    if (!entryFile.exists()) {
229                        entryFile.mkdirs();
230                    }
231                    continue;
232                }
233                newFullPathFileName = newEntryName;
234
235                 FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(newFullPathFileName);
236                 dest = new
237                   BufferedOutputStream JavaDoc(fos, BUFFER);
238                 while ((count = is.read(data, 0, BUFFER)) != -1) {
239                    dest.write(data, 0, count);
240                 }
241                 dest.flush();
242                 dest.close();
243                 is.close();
244                if (fullPathFileName != null) {
245                     return new File JavaDoc(newFullPathFileName);
246                 }
247              }
248          } catch(Exception JavaDoc ex) {
249             logger.warning(ex.getMessage());
250             ex.printStackTrace();
251          }
252
253         return null;
254     }
255
256     /**
257      * On the off chance that the system doesn't delete it, you can try to
258      * delete it yourself
259      *
260      * @return true or false depending on success
261      */

262     public boolean deleteTmp() {
263
264         return tmpDir.recursivelyDelete();
265     }
266
267     /**
268      * Set up temp directories etc
269      *
270      * @throws IOException
271      *
272      */

273     public BuildGrabber() throws IOException JavaDoc {
274         String JavaDoc systemTemp = System.getProperty("java.io.tmpdir");
275         logger.fine("System Temp Dir " + systemTemp);
276
277         tmpDir = new CopyableFile(File.createTempFile("antigen", "", new File JavaDoc(
278                 systemTemp)));
279         logger.info("Build Dir " + tmpDir);
280         //Delete any existing file
281
tmpDir.delete();
282         tmpDir.mkdirs();
283         tmpDir.deleteOnExit();
284     }
285     /**
286      * Set up temp directories etc
287      * User-supplied tmpdirectory
288      *
289      * @throws IOException
290      *
291      */

292     public BuildGrabber(File JavaDoc dir) throws IOException JavaDoc {
293         tmpDir = new CopyableFile(dir);
294         logger.info("Build Dir " + tmpDir);
295     }
296 }
Popular Tags