001: /*
002: * @(#)PnutsObjectInputStream.java 1.2 04/12/06
003: *
004: * Copyright (c) 1997-2004 Sun Microsystems, Inc. All Rights Reserved.
005: *
006: * See the file "LICENSE.txt" for information on usage and redistribution
007: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
008: */
009: package pnuts.io;
010:
011: import java.io.InputStream;
012: import java.io.ObjectInputStream;
013: import java.io.ObjectStreamClass;
014: import java.io.IOException;
015: import java.io.StreamCorruptedException;
016: import java.util.Hashtable;
017: import java.lang.reflect.Array;
018: import pnuts.lang.Pnuts;
019: import pnuts.lang.Context;
020:
021: /**
022: * This class deserializes primitive date and objects. Classes are
023: * resolved using the classloader of the context passed to the constructor.
024: */
025: public class PnutsObjectInputStream extends ObjectInputStream {
026:
027: private Context context;
028: private static Hashtable primitives = new Hashtable();
029: static {
030: primitives.put("int", int.class);
031: primitives.put("short", short.class);
032: primitives.put("byte", byte.class);
033: primitives.put("char", char.class);
034: primitives.put("long", long.class);
035: primitives.put("float", float.class);
036: primitives.put("double", double.class);
037: primitives.put("boolean", boolean.class);
038: }
039:
040: public PnutsObjectInputStream(InputStream in, Context context)
041: throws IOException, StreamCorruptedException {
042: super (in);
043: this .context = context;
044: }
045:
046: public void setContext(Context context) {
047: this .context = context;
048: }
049:
050: protected Class resolveClass(ObjectStreamClass objectStreamClass)
051: throws IOException, ClassNotFoundException {
052: String name = objectStreamClass.getName();
053:
054: if (!name.startsWith("[")) {
055: Class type = (Class) primitives.get(name);
056: if (type != null) {
057: return type;
058: } else {
059: return Pnuts.loadClass(name, context);
060: }
061: }
062:
063: int i;
064: for (i = 1; name.charAt(i) == '['; i++) { /* just skip */
065: }
066:
067: Class clazz;
068: if (name.charAt(i) == 'L') {
069: clazz = Pnuts.loadClass(name.substring(i + 1,
070: name.length() - 1), context);
071: } else {
072: if (name.length() != i + 1) {
073: throw new ClassNotFoundException(name);
074: }
075: clazz = primitiveType(name.charAt(i));
076: }
077: int dim[] = new int[i];
078: for (int j = 0; j < i; j++) {
079: dim[j] = 0;
080: }
081: return Array.newInstance(clazz, dim).getClass();
082: }
083:
084: private Class primitiveType(char ch) {
085: switch (ch) {
086: case 'B':
087: return Byte.TYPE;
088: case 'C':
089: return Character.TYPE;
090: case 'D':
091: return Double.TYPE;
092: case 'F':
093: return Float.TYPE;
094: case 'I':
095: return Integer.TYPE;
096: case 'J':
097: return Long.TYPE;
098: case 'S':
099: return Short.TYPE;
100: case 'Z':
101: return Boolean.TYPE;
102: default:
103: return null;
104: }
105: }
106: }
|