1 26 27 package org.nightlabs.editor2d.iofilter; 28 29 import java.io.IOException ; 30 import java.io.InputStream ; 31 import java.io.OutputStream ; 32 import java.util.zip.ZipEntry ; 33 import java.util.zip.ZipInputStream ; 34 import java.util.zip.ZipOutputStream ; 35 36 import org.nightlabs.io.AbstractIOFilter; 37 import org.nightlabs.io.ReadException; 38 import org.nightlabs.io.WriteException; 39 40 public abstract class AbstractZipFilter 41 extends AbstractIOFilter 42 { 43 44 public AbstractZipFilter() { 45 super(); 46 } 47 48 51 protected boolean useZip = true; 52 public boolean isUseZip() { 53 return useZip; 54 } 55 public void setUseZip(boolean useZip) { 56 this.useZip = useZip; 57 } 58 59 63 protected int compressLevel = 9; 64 public int getCompressLevel() { 65 return compressLevel; 66 } 67 public void setCompressLevel(int compressLevel) 68 { 69 if (compressLevel > 9) 70 compressLevel = 9; 71 else if (compressLevel < 0) 72 compressLevel = 0; 73 74 this.compressLevel = compressLevel; 75 } 76 77 80 public Object read(InputStream in) 81 throws ReadException 82 { 83 if (isUseZip()) 84 return readZip(in); 85 else 86 return readStream(in); 87 } 88 89 95 protected Object readZip(InputStream in) 96 { 97 try { 98 ZipInputStream zipStream = new ZipInputStream (in); 99 ZipEntry entry = zipStream.getNextEntry(); 100 Object o = readStream(zipStream); 101 zipStream.close(); 102 closeReadStream(); 103 return o; 104 } 105 catch (IOException e) { 106 throw new RuntimeException (e); 107 } 108 } 109 110 116 protected abstract Object readStream(InputStream in); 117 118 121 public void write(Object o, OutputStream out) 122 throws WriteException 123 { 124 if (isUseZip()) 125 writeZip(o, out, getEntryName()); 126 else 127 writeStream(o, out); 128 } 129 130 137 protected void writeZip(Object o, OutputStream out, String entryName) 138 { 139 try { 140 ZipOutputStream zipStream = new ZipOutputStream (out); 141 zipStream.setLevel(compressLevel); 142 ZipEntry entry = new ZipEntry (entryName); 143 zipStream.putNextEntry(entry); 144 145 writeStream(o, zipStream); 146 147 zipStream.closeEntry(); 148 zipStream.finish(); 149 zipStream.close(); 150 151 closeWriteStream(); 152 } catch (IOException e) { 153 throw new RuntimeException (e); 154 } 155 } 156 157 protected abstract void closeReadStream(); 158 protected abstract void closeWriteStream(); 159 160 166 protected abstract void writeStream(Object o, OutputStream out); 167 168 171 public abstract String getEntryName(); 172 } 173 | Popular Tags |