KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > speedo > mapper > lib > Object2StringSerializer


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

18 package org.objectweb.speedo.mapper.lib;
19
20 import org.objectweb.util.monolog.api.Logger;
21 import org.objectweb.util.monolog.api.BasicLevel;
22 import org.objectweb.speedo.api.Debug;
23 import org.objectweb.speedo.tools.StringReplace;
24 import org.objectweb.asm.ClassWriter;
25 import org.objectweb.asm.Constants;
26 import org.objectweb.asm.CodeVisitor;
27
28 import java.io.IOException JavaDoc;
29 import java.io.ObjectOutputStream JavaDoc;
30 import java.io.ObjectInputStream JavaDoc;
31 import java.io.ByteArrayInputStream JavaDoc;
32 import java.io.File JavaDoc;
33 import java.io.FileOutputStream JavaDoc;
34
35 /**
36  * This class contains primitive to serialize and deserialize an Object into a
37  * java Stirng.
38  *
39  * @author S.Chassande-Barrioz
40  */

41 public abstract class Object2StringSerializer {
42
43     public final static String JavaDoc JDO_FILE_NAME_PROP = "jdoFileName";
44
45     /**
46      * Serializes an object into a String
47      *
48      * @param o is the java object to serialize
49      * @return the java object serialized into a String
50      * @throws java.io.IOException occurs if the java serialization fails
51      */

52     public static String JavaDoc serialize(Object JavaDoc o) throws IOException JavaDoc {
53         java.io.ByteArrayOutputStream JavaDoc baos = new java.io.ByteArrayOutputStream JavaDoc();
54         ObjectOutputStream JavaDoc oos = new ObjectOutputStream JavaDoc(baos);
55         oos.writeObject(o);
56         oos.close();
57         byte[] bs = baos.toByteArray();
58         baos.close();
59         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(bs.length);
60         for (int i = 0; i < bs.length; i++) {
61             sb.append((char) (bs[i] & 0XFF));
62         }
63         return sb.toString();
64     }
65
66     /**
67      * Deserializes a String into a java object.
68      *
69      * @param s is the string containing a serialized java object
70      * @return the deserialized java object
71      * @throws IOException occurs if the deserialization fails
72      * @throws ClassNotFoundException occurs a class of a deserialized java
73      * object is not present.
74      */

75     public static Object JavaDoc deserialize(String JavaDoc s) throws IOException JavaDoc, ClassNotFoundException JavaDoc {
76         byte[] bs = new byte[s.length()];
77         for (int i = 0; i < bs.length; i++) {
78             bs[i] = (byte) s.charAt(i);
79         }
80         ObjectInputStream JavaDoc ois = new ObjectInputStream JavaDoc(new ByteArrayInputStream JavaDoc(bs));
81         Object JavaDoc o = ois.readObject();
82         ois.close();
83         return o;
84     }
85
86
87     public static String JavaDoc serialize(String JavaDoc output, String JavaDoc jdoFileName, Object JavaDoc jmi, Logger logger) throws IOException JavaDoc {
88         String JavaDoc className = jdoFileName2ClassName(jdoFileName);
89
90         if (Debug.ON && logger.isLoggable(BasicLevel.DEBUG)) {
91             logger.log(
92                 BasicLevel.DEBUG,
93                 "Serialize the Jorm Meta Information into the class '"
94                     + className
95                     + "' into the directory '"
96                     + output
97                     + "'.");
98         }
99     
100         //Serialize the object into a String
101
String JavaDoc value = Object2StringSerializer.serialize(jmi);
102         
103         // Generate class
104
ClassWriter cw = generateJavaClass(className, value);
105         // Write class file on disk
106

107         writeJavaClass(className, cw, output);
108         
109         return output + File.separatorChar + className;
110     }
111
112     private static ClassWriter generateJavaClass(final String JavaDoc className, final String JavaDoc value) {
113         
114         ClassWriter cw = new ClassWriter(true);
115
116         String JavaDoc str = StringReplace.replaceChar(File.separatorChar, '/', className);
117         
118         cw.visit(Constants.V1_1, Constants.ACC_PUBLIC, //access
119
str, //name
120
"org/objectweb/speedo/mapper/lib/Object2StringSerializer", //superName
121
new String JavaDoc[0], //interfaces
122
str // sourcefile
123
);
124         //implement an empty public constructor
125
CodeVisitor c = cw.visitMethod(Constants.ACC_PUBLIC, "<init>", "()V", null, null);
126         c.visitVarInsn(Constants.ALOAD, 0);
127         c.visitMethodInsn(
128             Constants.INVOKESPECIAL,
129             "org/objectweb/speedo/mapper/lib/Object2StringSerializer",
130             "<init>",
131             "()V");
132         c.visitInsn(Constants.RETURN);
133         c.visitMaxs(0, 0);
134
135         //implement the getSerializedObject method
136
c = cw.visitMethod(Constants.ACC_PUBLIC, "getSerializedObject", "()Ljava/lang/String;", null, null);
137         c.visitTypeInsn(Constants.NEW, "java/lang/StringBuffer");
138         c.visitInsn(Constants.DUP);
139         c.visitMethodInsn(Constants.INVOKESPECIAL, "java/lang/StringBuffer", "<init>", "()V");
140         final int SPLIT_SIZE = 5000;
141         int nbSplit = value.length() / SPLIT_SIZE;
142         for (int i = 0; i < nbSplit; i++) {
143             int j = i * SPLIT_SIZE;
144             String JavaDoc s = value.substring(j, j + SPLIT_SIZE);
145             c.visitLdcInsn(s);
146             c.visitMethodInsn(
147                 Constants.INVOKEVIRTUAL,
148                 "java/lang/StringBuffer",
149                 "append",
150                 "(Ljava/lang/String;)Ljava/lang/StringBuffer;");
151         }
152         int last = value.length() % SPLIT_SIZE;
153         if (last > 0) {
154             c.visitLdcInsn(value.substring(SPLIT_SIZE * nbSplit));
155             c.visitMethodInsn(
156                 Constants.INVOKEVIRTUAL,
157                 "java/lang/StringBuffer",
158                 "append",
159                 "(Ljava/lang/String;)Ljava/lang/StringBuffer;");
160         }
161         c.visitMethodInsn(Constants.INVOKEVIRTUAL, "java/lang/StringBuffer", "toString", "()Ljava/lang/String;");
162         c.visitInsn(Constants.ARETURN);
163         c.visitMaxs(1, 1);
164         
165         return cw;
166     }
167     
168         
169     public static Object JavaDoc deserialize(String JavaDoc jdoFileName, ClassLoader JavaDoc cl, Logger logger)
170             throws Exception JavaDoc {
171         String JavaDoc className = jdoFileName2ClassName(jdoFileName);
172         if (className == null) {
173             throw new Exception JavaDoc("Impossible to load a null class");
174         }
175         className = StringReplace.replaceChar('/', '.', className);
176         logger.log(BasicLevel.DEBUG, "Loading serialized object into the class '" + className + "'.");
177         Object2StringSerializer s = null;
178         try {
179             s = (Object2StringSerializer) cl.loadClass(className).newInstance();
180         } catch (Throwable JavaDoc e) {
181             ClassNotFoundException JavaDoc cnfe = new ClassNotFoundException JavaDoc("Impossible to load the jorm meta information: The class "
182                     + className + " is not availlable through the classloader (" + cl + ") of the persistent class", e);
183             logger.log(BasicLevel.ERROR, cnfe.getMessage(), cnfe);
184             throw cnfe;
185         }
186         return deserialize(s.getSerializedObject());
187     }
188
189     private static void writeJavaClass(final String JavaDoc name,
190                                        final ClassWriter jclass,
191                                        final String JavaDoc srcFiles) throws IOException JavaDoc {
192         int p = name.lastIndexOf(File.separatorChar);
193
194         String JavaDoc pkg;
195         String JavaDoc clas;
196         if (p == -1) {
197             pkg = "";
198             clas = name;
199         }
200         else {
201             pkg = name.substring(0, p);
202             clas = name.substring(p + 1);
203         }
204         File JavaDoc outputDir;
205         if (srcFiles == null) {
206             outputDir = new File JavaDoc(pkg);
207         }
208         else {
209             outputDir = new File JavaDoc(srcFiles + File.separatorChar + pkg);
210         }
211
212         outputDir.mkdirs();
213         File JavaDoc outputFile = new File JavaDoc(outputDir, clas + ".class");
214         outputFile.createNewFile();
215         FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(outputFile);
216         fos.write(jclass.toByteArray());
217         fos.close();
218     }
219
220     public static Object JavaDoc getObject(String JavaDoc jdoFileName, ClassLoader JavaDoc cl, Logger logger) throws Exception JavaDoc {
221         String JavaDoc className = jdoFileName2ClassName(jdoFileName);
222
223         logger.log(BasicLevel.DEBUG, "Loading serialized object into the class '" + className + "'.");
224         Object2StringSerializer s = null;
225         try {
226             s = (Object2StringSerializer) cl.loadClass(className).newInstance();
227         }
228         catch (Throwable JavaDoc e) {
229             ClassNotFoundException JavaDoc cnfe =
230                 new ClassNotFoundException JavaDoc(
231                     "Impossible to load the jorm meta information: The class "
232                         + className
233                         + " is not availlable through the classloader of the persistent class",
234                     e);
235             logger.log(BasicLevel.ERROR, cnfe.getMessage(), cnfe);
236             throw cnfe;
237         }
238         return deserialize(s.getSerializedObject());
239     }
240
241     public static String JavaDoc jdoFileName2ClassName(String JavaDoc jdoFileName) {
242         return jdoFileName.substring(0, jdoFileName.length() - 4) + "SpeedoJMI";
243     }
244
245     
246     /**
247      * @return the String containing a serialized java object
248      */

249     public abstract String JavaDoc getSerializedObject();
250
251 }
252
Popular Tags