1 7 package org.ejtools.archive.io; 8 9 import java.io.ByteArrayInputStream ; 10 import java.io.ByteArrayOutputStream ; 11 import java.io.IOException ; 12 import java.util.Stack ; 13 import java.util.zip.ZipEntry ; 14 import java.util.zip.ZipInputStream ; 15 16 import org.ejtools.archive.Archive; 17 import org.ejtools.archive.Entry; 18 import org.ejtools.archive.JarArchive; 19 import org.ejtools.archive.JarEntry; 20 21 22 30 public abstract class StreamReader implements Reader 31 { 32 33 private Stack inStreams = new Stack (); 34 35 36 41 public void visit(Entry entry) { } 42 43 44 49 public void visit(Archive archive) 50 { 51 try 52 { 53 ZipInputStream stream = this.getZipInputStream(); 54 if (stream == null) 55 { 56 throw new IllegalStateException ("No initial input stream"); 57 } 58 59 ZipEntry ze = null; 60 while ((ze = stream.getNextEntry()) != null) 61 { 62 if ((ze != null) && (!ze.isDirectory())) 63 { 64 Entry entry = this.createEntry(ze.getName()); 65 if (entry != null) 66 { 67 entry.addTo(archive); 68 } 69 } 70 stream.closeEntry(); 71 } 72 stream.close(); 73 } 74 catch (IOException ioe) 75 { 76 ioe.printStackTrace(); 77 } 78 } 79 80 81 87 protected Entry createEntry(String uri) 88 { 89 try 90 { 91 ZipInputStream stream = this.getZipInputStream(); 92 if (stream == null) 93 { 94 throw new IllegalStateException ("No initial input stream"); 95 } 96 97 byte[] buffer = new byte[1024]; 98 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 99 int read = 0; 100 while ((read = stream.read(buffer)) > 0) 101 { 102 baos.write(buffer, 0, read); 103 } 104 byte[] content = baos.toByteArray(); 105 106 try 107 { 108 ZipInputStream jis = new ZipInputStream (new ByteArrayInputStream (content)); 109 ZipEntry ze = jis.getNextEntry(); 110 jis.close(); 111 if (ze != null) 112 { 113 Archive archive = new JarArchive(uri); 114 this.pushZipInputStream(new ZipInputStream (new ByteArrayInputStream (content))); 119 archive.accept(this); 120 this.popZipInputStream(); 121 122 return archive; 123 } 124 else 125 { 126 Entry entry = new JarEntry(uri); 127 entry.setContent(content); 128 return entry; 129 } 130 } 131 catch (Exception ioe) 132 { 133 Entry entry = new JarEntry(uri); 134 entry.setContent(content); 135 return entry; 136 } 137 } 138 catch (IOException ioe) 139 { 140 ioe.printStackTrace(); 141 } 142 return null; 143 } 144 145 146 151 protected ZipInputStream getZipInputStream() 152 { 153 return (ZipInputStream ) this.inStreams.lastElement(); 154 } 155 156 157 163 protected ZipInputStream popZipInputStream() 164 throws IOException 165 { 166 if (this.inStreams.isEmpty()) 167 { 168 return null; 169 } 170 else 171 { 172 return (ZipInputStream ) this.inStreams.pop(); 173 } 174 } 175 176 177 183 protected void pushZipInputStream(ZipInputStream stream) 184 throws IOException 185 { 186 this.inStreams.push(stream); 187 } 188 } 189 | Popular Tags |