KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > geronimo > interop > util > JavaObject


1 /**
2  *
3  * Copyright 2004-2005 The Apache Software Foundation
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18 package org.apache.geronimo.interop.util;
19
20 import java.io.ByteArrayInputStream JavaDoc;
21 import java.io.ByteArrayOutputStream JavaDoc;
22 import java.io.ObjectInputStream JavaDoc;
23 import java.io.ObjectOutputStream JavaDoc;
24
25 import org.apache.geronimo.interop.SystemException;
26
27
28 public abstract class JavaObject {
29     public static byte[] toByteArray(Object JavaDoc object) {
30         if (object == null) {
31             return null;
32         }
33         try {
34             ByteArrayOutputStream JavaDoc bs = new ByteArrayOutputStream JavaDoc();
35             ObjectOutputStream JavaDoc os = new ObjectOutputStream JavaDoc(bs);
36             os.writeObject(object);
37             // Ensure last byte is not NUL. Avoids truncation of values when
38
// stored in Sybase ASE databases.
39
os.writeByte((byte) '.');
40             os.flush();
41             byte[] buffer = bs.toByteArray();
42             os.close();
43             bs.close();
44             return buffer;
45         } catch (Exception JavaDoc ex) {
46             throw new SystemException("JavaObject.toByteArray", ex);
47         }
48     }
49
50     public static java.lang.Object JavaDoc fromByteArray(byte[] buffer) {
51         if (buffer == null) {
52             return null;
53         }
54         try {
55             ByteArrayInputStream JavaDoc bs = new ByteArrayInputStream JavaDoc(buffer);
56             ObjectInputStream JavaDoc is = new ObjectInputStream JavaDoc(bs);
57             Object JavaDoc object = is.readObject();
58             is.close();
59             bs.close();
60             return object;
61         } catch (Exception JavaDoc ex) {
62             throw new SystemException("JavaObject.fromByteArray", ex);
63         }
64     }
65 }
66
Popular Tags