1 8 package com.nightlabs.editor2d.iofilter; 9 10 import java.io.IOException ; 11 import java.io.InputStream ; 12 import java.io.OutputStream ; 13 import java.util.zip.ZipEntry ; 14 import java.util.zip.ZipInputStream ; 15 import java.util.zip.ZipOutputStream ; 16 17 import com.nightlabs.io.IOFilter; 18 import com.nightlabs.io.ReadException; 19 import com.nightlabs.io.WriteException; 20 21 public abstract class AbstractZipFilter 22 implements IOFilter 23 { 24 25 public AbstractZipFilter() { 26 super(); 27 } 28 29 32 protected boolean useZip = true; 33 public boolean isUseZip() { 34 return useZip; 35 } 36 public void setUseZip(boolean useZip) { 37 this.useZip = useZip; 38 } 39 40 44 protected int compressLevel = 9; 45 public int getCompressLevel() { 46 return compressLevel; 47 } 48 public void setCompressLevel(int compressLevel) 49 { 50 if (compressLevel > 9) 51 compressLevel = 9; 52 else if (compressLevel < 0) 53 compressLevel = 0; 54 55 this.compressLevel = compressLevel; 56 } 57 58 61 public Object read(InputStream in) 62 throws ReadException 63 { 64 if (isUseZip()) 65 return readZip(in); 66 else 67 return readStream(in); 68 } 69 70 76 protected Object readZip(InputStream in) 77 { 78 try { 79 ZipInputStream zipStream = new ZipInputStream (in); 80 ZipEntry entry = zipStream.getNextEntry(); 81 Object o = readStream(zipStream); 82 zipStream.close(); 83 closeReadStream(); 84 return o; 85 } 86 catch (IOException e) { 87 throw new RuntimeException (e); 88 } 89 } 90 91 97 protected abstract Object readStream(InputStream in); 98 99 102 public void write(Object o, OutputStream out) 103 throws WriteException 104 { 105 if (isUseZip()) 106 writeZip(o, out, getEntryName()); 107 else 108 writeStream(o, out); 109 } 110 111 118 protected void writeZip(Object o, OutputStream out, String entryName) 119 { 120 try { 121 ZipOutputStream zipStream = new ZipOutputStream (out); 122 zipStream.setLevel(compressLevel); 123 ZipEntry entry = new ZipEntry (entryName); 124 zipStream.putNextEntry(entry); 125 126 writeStream(o, zipStream); 127 128 zipStream.closeEntry(); 129 zipStream.finish(); 130 zipStream.close(); 131 132 closeWriteStream(); 133 } catch (IOException e) { 134 throw new RuntimeException (e); 135 } 136 } 137 138 protected abstract void closeReadStream(); 139 protected abstract void closeWriteStream(); 140 141 147 protected abstract void writeStream(Object o, OutputStream out); 148 149 152 public abstract String getEntryName(); 153 154 157 public abstract String getFileExtension(); 158 159 162 public abstract String getDescription(); 163 } 164 | Popular Tags |