KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lucane > common > net > ObjectZipper


1 /*
2  * Lucane - a collaborative platform
3  * Copyright (C) 2004 Gilles Viguie <gilles.viguie@free.fr>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  */

19 package org.lucane.common.net;
20
21 import java.io.IOException JavaDoc;
22 import java.io.Serializable JavaDoc;
23 import java.io.ByteArrayInputStream JavaDoc;
24 import java.io.ObjectInputStream JavaDoc;
25 import java.io.ByteArrayOutputStream JavaDoc;
26 import java.io.ObjectOutputStream JavaDoc;
27 import java.util.zip.GZIPInputStream JavaDoc;
28 import java.util.zip.GZIPOutputStream JavaDoc;
29
30 /**
31  * Convert objets to GZipped bytes
32  */

33 public class ObjectZipper
34 {
35     /**
36      * Zip object to bytes
37      * @param object the object to zip
38      * @return the byte array
39      */

40     public static byte[] objectToBytes(Serializable JavaDoc object)
41     throws IOException JavaDoc
42     {
43         ByteArrayOutputStream JavaDoc bo = new ByteArrayOutputStream JavaDoc();
44         GZIPOutputStream JavaDoc go = new GZIPOutputStream JavaDoc(bo);
45         ObjectOutputStream JavaDoc oo = new ObjectOutputStream JavaDoc(go);
46         
47         oo.writeObject(object);
48         oo.flush();
49         go.finish();
50         
51         return bo.toByteArray();
52     }
53     
54     /**
55      * Unzip bytes to object
56      * @param bytes the zipped bytes
57      * @return the object
58      */

59     public static Serializable JavaDoc bytesToObject(byte[] bytes)
60     throws IOException JavaDoc, ClassNotFoundException JavaDoc
61     {
62         ByteArrayInputStream JavaDoc bi = new ByteArrayInputStream JavaDoc(bytes);
63         GZIPInputStream JavaDoc gi = new GZIPInputStream JavaDoc(bi);
64         ObjectInputStream JavaDoc oi = new LucaneObjectInputStream(gi);
65         
66         return (Serializable JavaDoc)oi.readObject();
67     }
68 }
Popular Tags