1 23 package org.infoglue.deliver.util; 24 25 import java.io.ByteArrayInputStream ; 26 import java.io.ByteArrayOutputStream ; 27 import java.io.ObjectInputStream ; 28 import java.io.ObjectOutputStream ; 29 import java.util.zip.GZIPInputStream ; 30 import java.util.zip.GZIPOutputStream ; 31 32 import org.apache.log4j.Logger; 33 34 39 public class CompressionHelper 40 { 41 private final static Logger logger = Logger.getLogger(CompressionHelper.class.getName()); 42 43 public byte[] compress(String string) 44 { 45 byte[] bytes = null; 46 47 try 48 { 49 ByteArrayOutputStream fos = new ByteArrayOutputStream (); 50 GZIPOutputStream gz = new GZIPOutputStream (fos); 51 ObjectOutputStream oos = new ObjectOutputStream (gz); 52 oos.writeObject(string); 53 oos.flush(); 55 oos.close(); 56 fos.close(); 57 bytes = fos.toByteArray(); 58 59 return bytes; 60 } 61 catch(Exception e) 62 { 63 logger.error("An error occurred when we tried to compress a string:" + e.getMessage(), e); 64 } 65 66 try 67 { 68 bytes = string.getBytes("UTF-8"); 69 } 70 catch (Exception e) 71 { 72 logger.error("An error occurred when we tried to just return the uncompressed bytes:" + e.getMessage(), e); 73 } 74 75 return bytes; 76 } 77 78 public String decompress(byte[] bytes) 79 { 80 try 81 { 82 ByteArrayInputStream fis = new ByteArrayInputStream (bytes); 83 GZIPInputStream gs = new GZIPInputStream (fis); 84 ObjectInputStream ois = new ObjectInputStream (gs); 85 String decompressed1 = (String )ois.readObject(); 86 ois.close(); 87 fis.close(); 88 return decompressed1; 89 } 90 catch(Exception e) 91 { 92 logger.error("An error occurred when we tried to decompress a string:" + e.getMessage(), e); 93 } 94 95 return ""; 96 } 97 98 } 99 | Popular Tags |