another bugfix
[org.ibex.util.git] / src / org / ibex / util / GetDep.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.util;
6 import java.util.*;
7 import java.net.*;
8 import java.io.*;
9 import java.util.zip.*;
10
11 public final class GetDep {
12
13     public static void main(String[] s) throws Exception {
14         if (s.length < 2) {
15             System.out.println("usage: java "+GetDep.class.getName()+" <url> <jarfile>");
16             return;
17         }
18         fetch(s[1], s[0]);
19     }
20
21     public static void fetch(String path, String url) throws Exception {
22         InputStream is = fetch(url);
23         FileOutputStream fos = new FileOutputStream(path);
24         while(true) {
25             byte[] buf = new byte[1024 * 16];
26             int numread = is.read(buf, 0, buf.length);
27             if (numread == -1) break;
28             fos.write(buf, 0, numread);
29         }
30         fos.close();
31     }
32
33     public static InputStream fetch(String url) throws Exception {
34         String scheme = url.substring(0, url.indexOf(':'));
35         if (scheme.equals("zip") || scheme.equals("tgz")) {
36             int bang = url.lastIndexOf('!');
37             String path = url.substring(bang + 1);
38             url = url.substring(url.indexOf(':')+1, bang);
39             InputStream rest = fetch(url);
40             if (scheme.equals("zip")) {
41                 ZipInputStream zis = new ZipInputStream(rest);
42                 while(true) {
43                     ZipEntry ze = zis.getNextEntry();
44                     if (ze == null) break;
45                     if (ze.getName().equals(path)) return zis;
46                 }
47                 throw new RuntimeException("could not find file within archive");
48             } else {
49                 Tar.TarInputStream tis = new Tar.TarInputStream(new GZIPInputStream(rest));
50                 while(true) {
51                     Tar.TarEntry te = tis.getNextEntry();
52                     if (te == null) break;
53                     if (te.getName().equals(path)) return tis;
54                 }
55                 throw new RuntimeException("could not find file within archive");
56             }
57         } else {
58             URL u = new URL(url);
59             return u.openConnection().getInputStream();
60         }
61     }
62
63 }