jboss-marshalling-1.1.3.GA/0000755000175000017500000000000011253762303015361 5ustar twernertwernerjboss-marshalling-1.1.3.GA/serial/0000755000175000017500000000000011253762275016650 5ustar twernertwernerjboss-marshalling-1.1.3.GA/serial/src/0000755000175000017500000000000011253762274017436 5ustar twernertwernerjboss-marshalling-1.1.3.GA/serial/src/main/0000755000175000017500000000000011253762274020362 5ustar twernertwernerjboss-marshalling-1.1.3.GA/serial/src/main/java/0000755000175000017500000000000011253762274021303 5ustar twernertwernerjboss-marshalling-1.1.3.GA/serial/src/main/java/org/0000755000175000017500000000000011253762274022072 5ustar twernertwernerjboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/0000755000175000017500000000000011253762274023212 5ustar twernertwernerjboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/0000755000175000017500000000000011253762274025513 5ustar twernertwernerjboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/0000755000175000017500000000000011253762275026773 5ustar twernertwerner././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootjboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/SerialMarshallerFactory.javajboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/SerialMarshallerFactory0000644000175000017500000000530711144611037033471 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.serial; import org.jboss.marshalling.MarshallerFactory; import org.jboss.marshalling.AbstractMarshallerFactory; import org.jboss.marshalling.Unmarshaller; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.Marshaller; import org.jboss.marshalling.StreamHeader; import org.jboss.marshalling.Marshalling; import org.jboss.marshalling.reflect.SerializableClassRegistry; import java.io.IOException; import java.security.AccessController; import java.security.PrivilegedAction; /** * */ public final class SerialMarshallerFactory extends AbstractMarshallerFactory implements MarshallerFactory { private final SerializableClassRegistry registry; private static final StreamHeader defaultHeader = Marshalling.streamHeader(new byte[] { (byte) 0xac, (byte) 0xed }); /** * Construct a new instance of a River marshaller factory. */ public SerialMarshallerFactory() { registry = AccessController.doPrivileged(new PrivilegedAction() { public SerializableClassRegistry run() { return SerializableClassRegistry.getInstance(); } }); } protected StreamHeader getDefaultStreamHeader() { return defaultHeader; } protected int getDefaultVersion() { return 5; } public Unmarshaller createUnmarshaller(final MarshallingConfiguration configuration) throws IOException { return new SerialUnmarshaller(this, registry, configuration); } public Marshaller createMarshaller(final MarshallingConfiguration configuration) throws IOException { return new SerialMarshaller(this, registry, configuration); } } jboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/Serial.java0000644000175000017500000004646211143151160031050 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.serial; import java.io.InputStream; import java.io.Writer; import java.io.IOException; import java.io.DataInputStream; import java.io.BufferedWriter; import java.util.concurrent.atomic.AtomicInteger; import java.util.Map; import java.util.List; import java.util.HashMap; import java.util.Arrays; import java.util.Collections; import org.jboss.marshalling.UTFUtils; import org.jboss.marshalling.Marshalling; /** * */ public final class Serial implements ExtendedObjectStreamConstants { private Serial() {} private enum FieldType { BOOLEAN(false) { public Object getValueString(final DataInputStream dis) throws IOException { return " " + Boolean.toString(dis.readBoolean()); } }, BYTE(false) { public Object getValueString(final DataInputStream dis) throws IOException { return " " + Byte.toString(dis.readByte()); } }, CHAR(false) { public Object getValueString(final DataInputStream dis) throws IOException { return " " + Character.toString(dis.readChar()); } }, DOUBLE(false) { public Object getValueString(final DataInputStream dis) throws IOException { return " " + Double.toString(dis.readDouble()); } }, FLOAT(false) { public Object getValueString(final DataInputStream dis) throws IOException { return " " + Float.toString(dis.readFloat()); } }, INTEGER(false) { public Object getValueString(final DataInputStream dis) throws IOException { return " " + Integer.toString(dis.readInt()); } }, LONG(false) { public Object getValueString(final DataInputStream dis) throws IOException { return " " + Long.toString(dis.readLong()); } }, SHORT(false) { public Object getValueString(final DataInputStream dis) throws IOException { return " " + Short.toString(dis.readShort()); } }, OBJECT(true) { public Object getValueString(final DataInputStream dis) { return ""; } } ; private final boolean obj; FieldType(final boolean obj) { this.obj = obj; } public abstract Object getValueString(final DataInputStream dis) throws IOException; public boolean isObject() { return obj; } public static FieldType fromTypeCode(int typeCode) { switch (typeCode) { case 'B': return FieldType.BYTE; case 'C': return FieldType.CHAR; case 'D': return FieldType.DOUBLE; case 'F': return FieldType.FLOAT; case 'I': return FieldType.INTEGER; case 'J': return FieldType.LONG; case 'S': return FieldType.SHORT; case 'Z': return FieldType.BOOLEAN; default: return FieldType.OBJECT; } } } private static final class FieldInfo { private FieldType type; private String name; } private static final class ClassInfo { private List info; private int flags; private long svu; private String name; private ClassInfo parent; } public static void dumpStream(InputStream serializedData, Writer destination) throws IOException { final DataInputStream dis = serializedData instanceof DataInputStream ? (DataInputStream) serializedData : new DataInputStream(serializedData); final BufferedWriter bw = destination instanceof BufferedWriter ? (BufferedWriter) destination : new BufferedWriter(destination); try { dumpStream(dis, bw); } finally { bw.flush(); destination.flush(); } } private static void dumpStream(DataInputStream serializedData, BufferedWriter destination) throws IOException { final AtomicInteger seq = new AtomicInteger(baseWireHandle); final Map descrs = new HashMap(); if (serializedData.readShort() != STREAM_MAGIC) { printf(destination, 0, "Stream magic INVALID"); return; } else { printf(destination, 0, "[%04x] Stream magic", Integer.valueOf(STREAM_MAGIC & 0xffff)); } destination.write(String.format("[%04x] Stream version\n", Integer.valueOf(serializedData.readUnsignedShort()))); // read contents for (;;) { int i = serializedData.read(); if (i == -1) { destination.write("--- End of stream ---\n"); return; } else { dumpContent(descrs, seq, serializedData, destination, 0, i); } } } private static void dumpContent(Map descrMap, final AtomicInteger seq, final DataInputStream dis, final BufferedWriter w, final int depth, final int leadByte) throws IOException { switch (leadByte) { case TC_BLOCKDATA: { final int len = dis.readUnsignedByte(); printf(w, depth, "[%02x] TC_BLOCKDATA - Data block of %d bytes", Integer.valueOf(TC_BLOCKDATA), Integer.valueOf(len)); for (int i = 0; i < len; i += dis.skipBytes(len - i)); return; } case TC_BLOCKDATALONG: { final int len = dis.readInt(); printf(w, depth, "[%02x] TC_BLOCKDATA - Data block of %d bytes", Integer.valueOf(TC_BLOCKDATA), Integer.valueOf(len)); for (int i = 0; i < len; i += dis.skipBytes(len - i)); return; } default: { dumpObject(descrMap, seq, dis, w, depth, leadByte); return; } } } private static void dumpObject(Map descrMap, final AtomicInteger seq, final DataInputStream dis, final BufferedWriter w, final int depth, final int leadByte) throws IOException { switch (leadByte) { // newObject case TC_OBJECT: { printf(w, depth, "[%02x] TC_OBJECT - New object", Integer.valueOf(TC_OBJECT)); final ClassInfo classInfo = dumpDescriptor(descrMap, seq, dis, w, depth + 1, dis.readUnsignedByte()); final int handle = seq.getAndIncrement(); printf(w, depth + 1, "[--] New object handle is [%08x]", Integer.valueOf(handle)); dumpFields(classInfo, descrMap, seq, dis, w, depth + 1); return; } case TC_OBJECTTABLE: { final int handle = seq.getAndIncrement(); printf(w, depth, "[%02x] TC_OBJECTTABLE - New object from table, handle is [%08x]", Integer.valueOf(TC_OBJECTTABLE), Integer.valueOf(handle)); dumpBlockData(descrMap, seq, dis, w, depth + 1); } // newClass case TC_CLASS: { printf(w, depth, "[%02x] TC_CLASS - New class", Integer.valueOf(TC_CLASS)); dumpDescriptor(descrMap, seq, dis, w, depth + 1, dis.readUnsignedByte()); final int handle = seq.getAndIncrement(); printf(w, depth + 1, "[--] New class handle is [%08x]", Integer.valueOf(handle)); return; } // newArray case TC_ARRAY: { printf(w, depth, "[%02x] TC_ARRAY - New array", Integer.valueOf(TC_ARRAY)); final ClassInfo classInfo = dumpDescriptor(descrMap, seq, dis, w, depth + 1, dis.readUnsignedByte()); final int handle = seq.getAndIncrement(); printf(w, depth + 1, "[--] New array handle is [%08x]", Integer.valueOf(handle)); final int len = dis.readInt(); printf(w, depth + 1, "[%x08] Array of length %d", Integer.valueOf(len), Integer.valueOf(len)); for (int i = 0; i < len; i ++) { final FieldType fieldType = FieldType.fromTypeCode(classInfo.name.charAt(1)); printf(w, depth + 2, "[%d] = %s", Integer.valueOf(i), fieldType.getValueString(dis)); if (fieldType.isObject()) { dumpObject(descrMap, seq, dis, w, depth + 3, dis.readUnsignedByte()); } } return; } // newString case TC_STRING: case TC_LONGSTRING: { dumpString(descrMap, seq, dis, w, depth, leadByte); return; } // newEnum case TC_ENUM: { printf(w, depth, "[%02x] TC_ENUM - New enum", Integer.valueOf(TC_ENUM)); dumpDescriptor(descrMap, seq, dis, w, depth + 1, dis.readUnsignedByte()); final int handle = seq.getAndIncrement(); printf(w, depth + 1, "[--] New enum handle is [%08x], constant name follows", Integer.valueOf(handle)); dumpString(descrMap, seq, dis, w, depth + 2, dis.readUnsignedByte()); return; } // newClassDesc case TC_CLASSTABLEDESC: case TC_PROXYCLASSDESC: case TC_CLASSDESC: { dumpDescriptor(descrMap, seq, dis, w, depth, leadByte); return; } // prevObject case TC_REFERENCE: { printf(w, depth, "[%02x] TC_REFERENCE - Backreference [%08x]", Integer.valueOf(TC_REFERENCE), Integer.valueOf(dis.readInt())); return; } // nullReference case TC_NULL: { printf(w, depth, "[%02x] TC_NULL - Null value", Integer.valueOf(TC_NULL)); return; } // exception default: { throw new IllegalStateException("Wrong lead byte: " + leadByte); } } } private static void dumpString(Map descrMap, final AtomicInteger seq, final DataInputStream dis, final BufferedWriter w, final int depth, final int leadByte) throws IOException { switch (leadByte) { case TC_STRING: { final int handle = seq.getAndIncrement(); final String str = dis.readUTF(); printf(w, depth, "[%02x] TC_STRING - New string, handle [%08x] = \"%s\"", Integer.valueOf(TC_STRING), Integer.valueOf(handle), str); return; } case TC_LONGSTRING: { final int handle = seq.getAndIncrement(); final String str = UTFUtils.readUTFBytesByByteCount(Marshalling.createByteInput(dis), dis.readLong()); printf(w, depth, "[%02x] TC_LONGSTRING - New string, handle [%08x] = \"%s\"", Integer.valueOf(TC_LONGSTRING), Integer.valueOf(handle), str); return; } case TC_REFERENCE: { printf(w, depth, "[%02x] TC_REFERENCE - Backreference [%08x]", Integer.valueOf(TC_REFERENCE), Integer.valueOf(dis.readInt())); return; } case TC_NULL: { printf(w, depth, "[%02x] TC_NULL - Null value", Integer.valueOf(TC_NULL)); return; } default: { throw new IllegalStateException("Wrong lead byte: " + leadByte); } } } private static void dumpFields(final ClassInfo info, final Map map, final AtomicInteger seq, final DataInputStream dis, final BufferedWriter w, final int depth) throws IOException { if ((info.flags & SC_EXTERNALIZABLE) != 0) { printf(w, depth, "[--] Externalizable data block:"); dumpBlockData(map, seq, dis, w, depth + 1); } else if ((info.flags & SC_SERIALIZABLE) != 0) { if (info.parent != null) { dumpFields(info.parent, map, seq, dis, w, depth); } printf(w, depth, "[--] Fields for class %s:", info.name); for (FieldInfo fieldInfo : info.info) { printf(w, depth + 1, "[--] Field %s = %s", fieldInfo.name, fieldInfo.type.getValueString(dis)); if (fieldInfo.type.isObject()) { dumpObject(map, seq, dis, w, depth + 2, dis.readUnsignedByte()); } } if ((info.flags & SC_WRITE_METHOD) != 0) { printf(w, depth, "[--] Custom data for class %s:", info.name); dumpBlockData(map, seq, dis, w, depth + 1); } } else { if (info.parent != null) { dumpFields(info.parent, map, seq, dis, w, depth); } printf(w, depth, "[--] No info for class %s", info.name); } } private static void dumpBlockData(final Map map, final AtomicInteger seq, final DataInputStream dis, final BufferedWriter w, final int depth) throws IOException { for (;;) { final int leadByte = dis.readUnsignedByte(); if (leadByte == TC_ENDBLOCKDATA) { printf(w, depth, "[%02x] TC_ENDBLOCKDATA - End block data", Byte.valueOf(TC_ENDBLOCKDATA)); return; } else { dumpContent(map, seq, dis, w, depth, leadByte); } } } private static ClassInfo dumpDescriptor(Map descrMap, final AtomicInteger seq, final DataInputStream dis, final BufferedWriter w, final int depth, final int leadByte) throws IOException { switch (leadByte) { // prevObject case TC_REFERENCE: { final int h = dis.readInt(); printf(w, depth, "[%02x] TC_REFERENCE - Backreference [%08x]", Integer.valueOf(TC_REFERENCE), Integer.valueOf(h)); return descrMap.get(Integer.valueOf(h)); } // nullReference case TC_NULL: { printf(w, depth, "[%02x] TC_NULL - Null value", Integer.valueOf(TC_NULL)); return null; } case TC_CLASSTABLEDESC: { final int handle = seq.getAndIncrement(); printf(w, depth, "[%02x] TC_CLASSTABLEDESC - New class descriptor from table, handle [%08x] - stream is indeterminate from this point on", Integer.valueOf(TC_CLASSTABLEDESC), Integer.valueOf(handle)); dumpBlockData(descrMap, seq, dis, w, depth); return null; } case TC_CLASSDESC: { final String name = dis.readUTF(); final long svu = dis.readLong(); final int handle = seq.getAndIncrement(); printf(w, depth, "[%02x] TC_CLASSDESC - New class descriptor, class = \"%s\", uid = %d, handle [%08x]", Integer.valueOf(TC_CLASSDESC), name, Long.valueOf(svu), Integer.valueOf(handle)); final int flags = dis.readUnsignedByte(); final int fieldCount = dis.readUnsignedShort(); FieldInfo[] info = new FieldInfo[fieldCount]; printf(w, depth + 1, "[--] Flags: (" + (((flags & SC_BLOCK_DATA) != 0) ? " SC_BLOCK_DATA" : "") + (((flags & SC_ENUM) != 0) ? " SC_ENUM" : "") + (((flags & SC_EXTERNALIZABLE) != 0) ? " SC_EXTERNALIZABLE" : "") + (((flags & SC_SERIALIZABLE) != 0) ? " SC_SERIALIZABLE" : "") + (((flags & SC_WRITE_METHOD) != 0) ? " SC_WRITE_METHOD" : "") + ")"); printf(w, depth + 1, "[--] %d fields", Integer.valueOf(fieldCount)); for (int i = 0; i < fieldCount; i++) { final int typeCode = dis.readUnsignedByte(); final String fieldName = dis.readUTF(); printf(w, depth + 2, "[--] Field \"%s\" type code '%s'%s", fieldName, Character.toString((char)typeCode), (typeCode == '[' || typeCode == 'L' ? ", type name follows" : "")); if (typeCode == '[' || typeCode == 'L') { dumpString(descrMap, seq, dis, w, depth + 3, dis.readUnsignedByte()); } info[i] = new FieldInfo(); info[i].name = fieldName; info[i].type = FieldType.fromTypeCode(typeCode); } printf(w, depth + 1, "[--] Class desc data block:"); dumpBlockData(descrMap, seq, dis, w, depth + 2); final ClassInfo classInfo = new ClassInfo(); descrMap.put(Integer.valueOf(handle), classInfo); classInfo.info = Arrays.asList(info); classInfo.name = name; classInfo.flags = flags; classInfo.svu = svu; printf(w, depth + 1, "[--] Superclass descriptor follows"); classInfo.parent = dumpDescriptor(descrMap, seq, dis, w, depth + 3, dis.readUnsignedByte()); return classInfo; } case TC_PROXYCLASSDESC: { final int handle = seq.getAndIncrement(); final int count = dis.readInt(); printf(w, depth, "[%02x] TC_PROXYCLASSDESC - New proxy class descriptor, %d interfaces", Integer.valueOf(TC_PROXYCLASSDESC), Integer.valueOf(count)); for (int i = 0; i < count; i ++) { printf(w, depth + 1, "[--] Interface: \"%s\"", dis.readUTF()); } printf(w, depth + 1, "[--] Class desc data block:"); dumpBlockData(descrMap, seq, dis, w, depth + 2); final ClassInfo classInfo = new ClassInfo(); descrMap.put(Integer.valueOf(handle), classInfo); classInfo.info = Collections.emptyList(); classInfo.name = String.format("proxy class %08x", Integer.valueOf(handle)); printf(w, depth + 2, "[--] Superclass descriptor follows"); classInfo.parent = dumpDescriptor(descrMap, seq, dis, w, depth + 3, dis.readUnsignedByte()); return classInfo; } default: { throw new IllegalStateException("Wrong lead byte: " + leadByte); } } } private static void printf(BufferedWriter w, int depth, String format, Object... args) throws IOException { for (int i = 0; i < depth; i++) { w.write(" "); } w.write(String.format(format + "\n", args)); w.flush(); } } jboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/BlockUnmarshaller.java0000644000175000017500000002507611143152362033244 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.serial; import org.jboss.marshalling.Unmarshaller; import org.jboss.marshalling.ByteInput; import org.jboss.marshalling.Marshalling; import org.jboss.marshalling.UTFUtils; import static org.jboss.marshalling.Marshalling.createOptionalDataException; import java.io.IOException; import java.io.StreamCorruptedException; import java.io.EOFException; /** * */ public final class BlockUnmarshaller implements Unmarshaller, ExtendedObjectStreamConstants { private final SerialUnmarshaller serialUnmarshaller; private int remaining; BlockUnmarshaller(final SerialUnmarshaller serialUnmarshaller) { this.serialUnmarshaller = serialUnmarshaller; } boolean inBlock() { return remaining > 0; } int remaining() { return remaining; } void endOfStream() { if (remaining == 0) { remaining = -1; } else { throw new IllegalStateException("Not at end of block"); } } void unblock() { if (remaining == -1) { remaining = 0; } } void readBlockHeader(int leadByte) throws IOException { switch (leadByte) { case TC_BLOCKDATA: remaining = serialUnmarshaller.readUnsignedByte(); return; case TC_BLOCKDATALONG: final int len = serialUnmarshaller.readInt(); if (len < 0) { throw new StreamCorruptedException("Invalid block length"); } remaining = len; return; case TC_ENDBLOCKDATA: remaining = -1; return; default: throw badLeadByte(leadByte); } } void readToEndBlockData() throws IOException, ClassNotFoundException { for (;;) { while (remaining > 0) { skipBytes(remaining); } final int b = serialUnmarshaller.read(); switch (b) { case -1: remaining = -1; return; case TC_ENDBLOCKDATA: remaining = -1; return; case TC_BLOCKDATA: case TC_BLOCKDATALONG: readBlockHeader(b); break; default: // consume object... or whatever serialUnmarshaller.doReadObject(b, false); break; } } } private StreamCorruptedException badLeadByte(final int leadByte) { return new StreamCorruptedException("Unexpected lead byte " + leadByte); } public Object readObjectUnshared() throws ClassNotFoundException, IOException { return readObject(true); } public Object readObject() throws ClassNotFoundException, IOException { return readObject(false); } private Object readObject(boolean unshared) throws ClassNotFoundException, IOException { if (remaining > 0) { throw createOptionalDataException(remaining); } else if (remaining == -1) { throw createOptionalDataException(true); } final int leadByte = serialUnmarshaller.read(); if (leadByte == -1 || leadByte == TC_ENDBLOCKDATA) { remaining = -1; throw createOptionalDataException(true); } return serialUnmarshaller.doReadObject(leadByte, unshared); } public int read() throws IOException { while (remaining == 0) { final int v = serialUnmarshaller.read(); if (v == -1) { return -1; } readBlockHeader(v); } if (remaining == -1) { return -1; } remaining--; return serialUnmarshaller.read(); } public int read(final byte[] b) throws IOException { return read(b, 0, b.length); } public int read(final byte[] b, final int off, final int len) throws IOException { while (remaining == 0) { final int v = serialUnmarshaller.read(); if (v == -1) { return -1; } readBlockHeader(v); } final int remaining = this.remaining; if (remaining == -1) { return -1; } final int cnt = serialUnmarshaller.read(b, off, Math.min(remaining, len)); this.remaining = remaining - cnt; return cnt; } public long skip(final long n) throws IOException { while (remaining == 0) { final int v = serialUnmarshaller.read(); if (v == -1) { return -1; } readBlockHeader(v); } final int remaining = this.remaining; if (remaining == -1) { return -1; } final int cnt = serialUnmarshaller.skipBytes((int)Math.min((long)remaining, n)); this.remaining = remaining - cnt; return cnt; } public int available() throws IOException { return Math.min(remaining, serialUnmarshaller.available()); } public void readFully(final byte[] b) throws IOException { Marshalling.readFully(this, b); } public void readFully(final byte[] b, final int off, final int len) throws IOException { Marshalling.readFully(this, b, off, len); } public int skipBytes(final int n) throws IOException { while (remaining == 0) { final int v = serialUnmarshaller.read(); if (v == -1) { return -1; } readBlockHeader(v); } final int remaining = this.remaining; if (remaining == -1) { return -1; } final int cnt = serialUnmarshaller.skipBytes(Math.min(remaining, n)); this.remaining = remaining - cnt; return cnt; } public boolean readBoolean() throws IOException { while (remaining == 0) { readBlockHeader(serialUnmarshaller.readUnsignedByte()); } if (remaining == -1) { throw new EOFException(); } remaining--; return serialUnmarshaller.readBoolean(); } public byte readByte() throws IOException { while (remaining == 0) { readBlockHeader(serialUnmarshaller.readUnsignedByte()); } if (remaining == -1) { throw new EOFException(); } remaining--; return serialUnmarshaller.readByte(); } public int readUnsignedByte() throws IOException { while (remaining == 0) { readBlockHeader(serialUnmarshaller.readUnsignedByte()); } if (remaining == -1) { throw new EOFException(); } remaining--; return serialUnmarshaller.readUnsignedByte(); } public short readShort() throws IOException { if (remaining < 2) { return (short) (readUnsignedByte() << 8 | readUnsignedByte()); } else { remaining -= 2; return serialUnmarshaller.readShort(); } } public int readUnsignedShort() throws IOException { if (remaining < 2) { return readUnsignedByte() << 8 | readUnsignedByte(); } else { remaining -= 2; return serialUnmarshaller.readUnsignedShort(); } } public char readChar() throws IOException { if (remaining < 2) { return (char) (readUnsignedByte() << 8 | readUnsignedByte()); } else { remaining -= 2; return serialUnmarshaller.readChar(); } } public int readInt() throws IOException { if (remaining < 4) { return readUnsignedByte() << 24 | readUnsignedByte() << 16 | readUnsignedByte() << 8 | readUnsignedByte(); } else { remaining -= 4; return serialUnmarshaller.readInt(); } } public long readLong() throws IOException { if (remaining < 8) { return (long) readUnsignedByte() << 56L | (long) readUnsignedByte() << 48L | (long) readUnsignedByte() << 40L | (long) readUnsignedByte() << 32L | (long) readUnsignedByte() << 24L | (long) readUnsignedByte() << 16L | (long) readUnsignedByte() << 8L | (long) readUnsignedByte(); } else { remaining -= 8; return serialUnmarshaller.readLong(); } } public float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } public double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } public String readLine() throws IOException { throw new UnsupportedOperationException("readLine() is deprecated anyway!"); } public String readUTF() throws IOException { final int len = readUnsignedShort(); return UTFUtils.readUTFBytesByByteCount(this, len); } public void clearInstanceCache() throws IOException { throw new IllegalStateException("clearInstanceCache() may not be called in this context"); } public void clearClassCache() throws IOException { throw new IllegalStateException("clearClassCache() may not be called in this context"); } public void start(final ByteInput newInput) throws IOException { throw new IllegalStateException("start() may not be called in this context"); } public void finish() throws IOException { throw new IllegalStateException("finish() may not be called in this context"); } public void close() throws IOException { throw new IllegalStateException("close() may not be called in this context"); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootjboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/ExternalizedObject.javajboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/ExternalizedObject.java0000644000175000017500000000636311143101064033410 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.serial; import java.io.Externalizable; import java.io.ObjectOutput; import java.io.IOException; import java.io.ObjectInput; import java.io.InvalidClassException; import java.io.ObjectStreamException; import org.jboss.marshalling.Externalizer; import org.jboss.marshalling.Creator; /** * An externalized object. This wrapper allows an object that was written with an {@code Externalizer} to be * read by standard Java serialization. Note that if an externalized object's child object graph ever refers * to the original object, there will be an error in the reconstructed object graph such that those references * will refer to this wrapper object rather than the properly externalized object. */ public final class ExternalizedObject implements Externalizable, Creator { private static final long serialVersionUID = -7764783599281227099L; private Externalizer externalizer; private transient Object obj; public ExternalizedObject() { } public ExternalizedObject(final Externalizer externalizer, final Object obj) { this.externalizer = externalizer; this.obj = obj; } /** {@inheritDoc} */ public void writeExternal(final ObjectOutput out) throws IOException { out.writeObject(externalizer); externalizer.writeExternal(obj, out); } /** {@inheritDoc} */ public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { externalizer = (Externalizer) in.readObject(); final Object o = externalizer.createExternal(getClass(), in, this); externalizer.readExternal(o, in); obj = o; } /** * Return the externalized object after {@code readExternal()} completes. * * @return the externalized object * @throws ObjectStreamException never */ public Object readResolve() throws ObjectStreamException { return obj; } /** {@inheritDoc} */ public T create(final Class clazz) throws InvalidClassException { try { return clazz.newInstance(); } catch (Exception e) { final InvalidClassException ee = new InvalidClassException(clazz.getName(), e.getMessage()); ee.initCause(e); throw ee; } } } jboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/SerialMarshaller.java0000644000175000017500000005454011153266555033077 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.serial; import org.jboss.marshalling.AbstractMarshaller; import org.jboss.marshalling.Marshaller; import org.jboss.marshalling.AbstractMarshallerFactory; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.ByteOutput; import org.jboss.marshalling.Externalizer; import org.jboss.marshalling.UTFUtils; import org.jboss.marshalling.ObjectTable; import org.jboss.marshalling.ClassTable; import org.jboss.marshalling.util.IdentityIntMap; import org.jboss.marshalling.util.FieldPutter; import org.jboss.marshalling.util.Kind; import org.jboss.marshalling.reflect.SerializableClassRegistry; import org.jboss.marshalling.reflect.SerializableClass; import org.jboss.marshalling.reflect.SerializableField; import java.io.IOException; import java.io.ObjectStreamClass; import java.io.Serializable; import java.io.Externalizable; import java.io.NotSerializableException; import java.io.InvalidClassException; import java.io.InvalidObjectException; import java.util.IdentityHashMap; import java.util.Map; import java.lang.reflect.Proxy; import java.lang.reflect.Field; import java.security.PrivilegedExceptionAction; import java.security.AccessController; import java.security.PrivilegedActionException; /** * */ public final class SerialMarshaller extends AbstractMarshaller implements Marshaller, ExtendedObjectStreamConstants { private static final int MIN_BUFFER_SIZE = 16; private final SerializableClassRegistry registry; private final IdentityIntMap instanceCache; private final IdentityIntMap> descriptorCache; private final IdentityHashMap replacementCache; private final IdentityHashMap, Externalizer> externalizers; private final int bufferSize; private SerialObjectOutputStream oos; private BlockMarshaller blockMarshaller; private int instanceSeq; SerialMarshaller(final AbstractMarshallerFactory marshallerFactory, final SerializableClassRegistry registry, final MarshallingConfiguration configuration) throws IOException { super(marshallerFactory, configuration); if (configuredVersion != 5) { throw new IOException("Only protocol version 5 is supported for writing"); } this.registry = registry; instanceCache = new IdentityIntMap(configuration.getInstanceCount()); descriptorCache = new IdentityIntMap>(configuration.getClassCount()); replacementCache = new IdentityHashMap(configuration.getInstanceCount()); externalizers = new IdentityHashMap, Externalizer>(configuration.getClassCount()); bufferSize = configuration.getBufferSize(); } protected void doWriteObject(final Object orig, final boolean unshared) throws IOException { if (orig == null) { write(TC_NULL); return; } final IdentityHashMap replacementCache = this.replacementCache; Object obj; if (replacementCache.containsKey(orig)) { obj = replacementCache.get(orig); } else { obj = orig; } final IdentityIntMap instanceCache = this.instanceCache; int v; final ObjectTable.Writer writer; // - first check for cached objects, Classes, or ObjectStreamClass if (! unshared && (v = instanceCache.get(obj, -1)) != -1) { write(TC_REFERENCE); writeInt(v + baseWireHandle); return; } else if ((writer = objectTable.getObjectWriter(obj)) != null) { write(TC_OBJECTTABLE); final int id = instanceSeq++; if (! unshared) instanceCache.put(obj, id); writer.writeObject(blockMarshaller, obj); doEndBlock(); return; } else if (obj instanceof Class) { write(TC_CLASS); writeNewClassDescFor((Class)obj); final int id = instanceSeq++; if (! unshared) instanceCache.put(obj, id); return; } else if (obj instanceof ObjectStreamClass) { throw new NotSerializableException(ObjectStreamClass.class.getName()); } // - next check for replacements // - first, check for implemented writeReplace method on the object final SerializableClassRegistry registry = this.registry; for (;;) { final Class objClass = obj.getClass(); final SerializableClass sc = registry.lookup(objClass); if (!sc.hasWriteReplace()) { break; } final Object replacement = sc.callWriteReplace(obj); try { if (replacement == null || replacement == obj || obj.getClass() == objClass) { break; } } finally { obj = replacement; } } obj = objectResolver.writeReplace(obj); // - next, if the object was replaced we do our original checks again... if (obj != orig) { // cache the replacement replacementCache.put(orig, obj); if (obj == null) { write(TC_NULL); return; } else if (! unshared && (v = instanceCache.get(obj, -1)) != -1) { write(TC_REFERENCE); writeInt(v); return; } else if (obj instanceof Class) { write(TC_CLASS); writeNewClassDescFor((Class)obj); final int id = instanceSeq++; if (! unshared) instanceCache.put(obj, id); return; } else if (obj instanceof ObjectStreamClass) { throw new NotSerializableException(ObjectStreamClass.class.getName()); } } // - next check for other special types if (obj instanceof String) { final String string = (String) obj; final long len = UTFUtils.getLongUTFLength(string); if (len < 65536L) { write(TC_STRING); final int id = instanceSeq++; if (! unshared) instanceCache.put(obj, id); writeShort((int) len); UTFUtils.writeUTFBytes(this, string); return; } else { write(TC_LONGSTRING); final int id = instanceSeq++; if (! unshared) instanceCache.put(obj, id); writeLong(len); UTFUtils.writeUTFBytes(this, string); return; } } final Class objClass = obj.getClass(); if (obj instanceof Enum) { write(TC_ENUM); writeClassDescFor(objClass); final int id = instanceSeq++; if (! unshared) instanceCache.put(obj, id); doWriteObject(((Enum)obj).name(), false); return; } else if (objClass.isArray()) { write(TC_ARRAY); writeClassDescFor(objClass); final int id = instanceSeq++; if (! unshared) instanceCache.put(obj, id); if (obj instanceof byte[]) { final byte[] bytes = (byte[]) obj; writeInt(bytes.length); write(bytes); } else if (obj instanceof short[]) { final short[] shorts = (short[]) obj; writeInt(shorts.length); for (short s : shorts) { writeShort(s); } } else if (obj instanceof int[]) { final int[] ints = (int[]) obj; writeInt(ints.length); for (int s : ints) { writeInt(s); } } else if (obj instanceof long[]) { final long[] longs = (long[]) obj; writeInt(longs.length); for (long s : longs) { writeLong(s); } } else if (obj instanceof float[]) { final float[] floats = (float[]) obj; writeInt(floats.length); for (float s : floats) { writeFloat(s); } } else if (obj instanceof double[]) { final double[] doubles = (double[]) obj; writeInt(doubles.length); for (double s : doubles) { writeDouble(s); } } else if (obj instanceof boolean[]) { final boolean[] booleans = (boolean[]) obj; writeInt(booleans.length); for (boolean s : booleans) { writeBoolean(s); } } else if (obj instanceof char[]) { final char[] chars = (char[]) obj; writeInt(chars.length); for (char s : chars) { writeChar(s); } } else { final Object[] objs = (Object[]) obj; writeInt(objs.length); for (Object o : objs) { doWriteObject(o, false); } } return; } Externalizer externalizer; if (externalizers.containsKey(objClass)) { externalizer = externalizers.get(objClass); } else { externalizer = classExternalizerFactory.getExternalizer(objClass); if (externalizer == null) { externalizer = externalizerFactory.getExternalizer(obj); } externalizers.put(objClass, externalizer); } if (externalizer != null) { final ExternalizedObject eo = new ExternalizedObject(externalizer, obj); doWriteObject(eo, unshared); replacementCache.put(obj, eo); return; } else if (obj instanceof Externalizable) { write(TC_OBJECT); writeClassDescFor(objClass); final int id = instanceSeq++; if (! unshared) instanceCache.put(obj, id); final Externalizable externalizable = (Externalizable) obj; externalizable.writeExternal(blockMarshaller); doEndBlock(); return; } else if (obj instanceof Serializable) { write(TC_OBJECT); writeClassDescFor(objClass); final int id = instanceSeq++; if (! unshared) instanceCache.put(obj, id); writeSerialData(objClass, obj); return; } else { throw new NotSerializableException(objClass.getName()); } } private void writeSerialData(Class objClass, Object obj) throws IOException { final Class superClass = objClass.getSuperclass(); if (superClass != null && Serializable.class.isAssignableFrom(objClass)) { writeSerialData(superClass, obj); } final SerializableClass sc = registry.lookup(objClass); if (sc.hasWriteObject()) { final SerialObjectOutputStream oos = getObjectOutputStream(); final Object oldObj = oos.saveCurrentObject(obj); final SerializableClass oldSc = oos.saveCurrentSerializableClass(sc); final Map map = oos.saveCurrentFieldMap(); final SerialObjectOutputStream.State oldState = oos.saveState(); try { sc.callWriteObject(obj, oos); } finally { oos.setCurrentObject(oldObj); oos.setCurrentSerializableClass(oldSc); oos.setCurrentFieldMap(map); oos.restoreState(oldState); } doEndBlock(); } else { doWriteFields(sc, obj); } } private final PrivilegedExceptionAction createObjectOutputStreamAction = new PrivilegedExceptionAction() { public SerialObjectOutputStream run() throws IOException { return new SerialObjectOutputStream(SerialMarshaller.this, blockMarshaller); } }; private SerialObjectOutputStream createObjectOutputStream() throws IOException { try { return AccessController.doPrivileged(createObjectOutputStreamAction); } catch (PrivilegedActionException e) { throw (IOException) e.getCause(); } } private SerialObjectOutputStream getObjectOutputStream() throws IOException { if (oos == null) { oos = createObjectOutputStream(); } return oos; } protected void doWriteFields(final SerializableClass info, final Object obj) throws IOException { final SerializableField[] serializableFields = info.getFields(); for (SerializableField serializableField : serializableFields) { try { final Field field = serializableField.getField(); switch (serializableField.getKind()) { case BOOLEAN: { writeBoolean(field.getBoolean(obj)); break; } case BYTE: { writeByte(field.getByte(obj)); break; } case SHORT: { writeShort(field.getShort(obj)); break; } case INT: { writeInt(field.getInt(obj)); break; } case CHAR: { writeChar(field.getChar(obj)); break; } case LONG: { writeLong(field.getLong(obj)); break; } case DOUBLE: { writeDouble(field.getDouble(obj)); break; } case FLOAT: { writeFloat(field.getFloat(obj)); break; } } } catch (IllegalAccessException e) { final InvalidObjectException ioe = new InvalidObjectException("Unexpected illegal access exception"); ioe.initCause(e); throw ioe; } } for (SerializableField serializableField : serializableFields) { try { final Field field = serializableField.getField(); Kind i = serializableField.getKind(); if (i == Kind.OBJECT) { doWriteObject(field.get(obj), serializableField.isUnshared()); } } catch (IllegalAccessException e) { final InvalidObjectException ioe = new InvalidObjectException("Unexpected illegal access exception"); ioe.initCause(e); throw ioe; } } } private void writeClassDescFor(final Class forClass) throws IOException { if (forClass == null) { write(TC_NULL); } else { final int id = descriptorCache.get(forClass, -1); if (id == -1) { writeNewClassDescFor(forClass); } else { write(TC_REFERENCE); writeInt(id + baseWireHandle); } } } private void writeNewClassDescFor(final Class forClass) throws IOException { if (Proxy.isProxyClass(forClass)) { writeNewProxyClassDesc(forClass); } else { writeNewPlainClassDesc(forClass); } } private void writeNewProxyClassDesc(final Class forClass) throws IOException { write(TC_PROXYCLASSDESC); descriptorCache.put(forClass, instanceSeq++); final String[] names = classResolver.getProxyInterfaces(forClass); writeInt(names.length); for (String name : names) { writeUTF(name); } classResolver.annotateProxyClass(blockMarshaller, forClass); doEndBlock(); writeClassDescFor(forClass.getSuperclass()); } private void writeNewPlainClassDesc(final Class forClass) throws IOException { final ClassTable.Writer writer = classTable.getClassWriter(forClass); if (writer != null) { write(TC_CLASSTABLEDESC); descriptorCache.put(forClass, instanceSeq++); writer.writeClass(blockMarshaller, forClass); doEndBlock(); return; } write(TC_CLASSDESC); writeUTF(classResolver.getClassName(forClass)); descriptorCache.put(forClass, instanceSeq++); if (forClass.isEnum()) { writeLong(0L); write(SC_SERIALIZABLE | SC_ENUM); writeShort(0); } else if (Serializable.class.isAssignableFrom(forClass)) { final SerializableClass sc = registry.lookup(forClass); final long svu = sc.getEffectiveSerialVersionUID(); writeLong(svu); if (Externalizable.class.isAssignableFrom(forClass)) { // todo: add a protocol_1 option? write(SC_EXTERNALIZABLE + SC_BLOCK_DATA); writeShort(0); } else { if (sc.hasWriteObject()) { write(SC_WRITE_METHOD + SC_SERIALIZABLE); } else { write(SC_SERIALIZABLE); } final SerializableField[] fields = sc.getFields(); writeShort(fields.length); // first write primitive fields, then object fields for (SerializableField field : fields) { final Kind kind = field.getKind(); final String name = field.getName(); final Class type; try { type = field.getType(); } catch (ClassNotFoundException e) { // not possible throw new InvalidClassException(forClass.getName(), "Field " + name + "'s class was not found"); } if (kind != Kind.OBJECT) { write(primitives.get(type, -1)); writeUTF(name); } } for (SerializableField field : fields) { final Kind kind = field.getKind(); final String name = field.getName(); final Class type; try { type = field.getType(); } catch (ClassNotFoundException e) { // not possible throw new InvalidClassException(forClass.getName(), "Field " + name + "'s class was not found"); } if (kind == Kind.OBJECT) { final String signature = getSignature(type); write(signature.charAt(0)); writeUTF(name); writeObject(signature); } } } } else { writeLong(0L); write(0); writeShort(0); } classResolver.annotateClass(blockMarshaller, forClass); doEndBlock(); final Class sc = forClass.getSuperclass(); if (Serializable.class.isAssignableFrom(sc) && ! forClass.isEnum()) { writeClassDescFor(sc); } else { write(TC_NULL); } } private void doEndBlock() throws IOException { blockMarshaller.flush(); write(TC_ENDBLOCKDATA); } private static final IdentityIntMap> primitives; static { primitives = new IdentityIntMap>(32); primitives.put(byte.class, 'B'); primitives.put(char.class, 'C'); primitives.put(double.class, 'D'); primitives.put(float.class, 'F'); primitives.put(int.class, 'I'); primitives.put(long.class, 'J'); primitives.put(short.class, 'S'); primitives.put(boolean.class, 'Z'); primitives.put(void.class, 'V'); } private static String getSignature(final Class type) { final int id; if ((id = primitives.get(type, -1)) != -1) { return Character.toString((char)id); } else if (type.isArray()) { return "[" + getSignature(type.getComponentType()); } else { return "L" + type.getName().replace('.', '/') + ";"; } } public void clearInstanceCache() throws IOException { instanceCache.clear(); descriptorCache.clear(); replacementCache.clear(); externalizers.clear(); instanceSeq = 0; if (byteOutput != null) { write(TC_RESET); } } public void clearClassCache() throws IOException { clearInstanceCache(); } public void start(final ByteOutput byteOutput) throws IOException { blockMarshaller = new BlockMarshaller(this, bufferSize < MIN_BUFFER_SIZE ? MIN_BUFFER_SIZE : bufferSize); super.start(byteOutput); } protected void doStart() throws IOException { super.doStart(); writeShort(configuredVersion); } public void finish() throws IOException { super.finish(); blockMarshaller = null; oos = null; } public void flush() throws IOException { final BlockMarshaller blockMarshaller = this.blockMarshaller; if (blockMarshaller != null) { blockMarshaller.flush(); } super.flush(); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootjboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/SerialObjectInputStream.javajboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/SerialObjectInputStream0000644000175000017500000001007411143101064033437 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.serial; import org.jboss.marshalling.MarshallerObjectInputStream; import org.jboss.marshalling.reflect.SerializableClass; import java.io.IOException; import java.io.ObjectInputValidation; import java.io.NotActiveException; import java.io.InvalidObjectException; /** * */ public final class SerialObjectInputStream extends MarshallerObjectInputStream { private final SerialUnmarshaller serialUnmarshaller; private PlainDescriptor currentDescriptor; private SerializableClass currentSerializableClass; private Object currentSubject; private State state = State.OFF; enum State { OFF, NEW, ON, ; } SerialObjectInputStream(final SerialUnmarshaller serialUnmarshaller) throws IOException, SecurityException { super(serialUnmarshaller.getBlockUnmarshaller()); this.serialUnmarshaller = serialUnmarshaller; } PlainDescriptor saveCurrentDescriptor(PlainDescriptor currentDescriptor) { try { return this.currentDescriptor; } finally { this.currentDescriptor = currentDescriptor; } } void setCurrentDescriptor(final PlainDescriptor currentDescriptor) { this.currentDescriptor = currentDescriptor; } Object saveCurrentSubject(Object currentSubject) { try { return this.currentSubject; } finally { this.currentSubject = currentSubject; } } void setCurrentSubject(final Object currentSubject) { this.currentSubject = currentSubject; } SerializableClass saveCurrentSerializableClass(SerializableClass currentSerializableClass) { try { return this.currentSerializableClass; } finally { this.currentSerializableClass = currentSerializableClass; } } void setCurrentSerializableClass(final SerializableClass currentSerializableClass) { this.currentSerializableClass = currentSerializableClass; } State saveState() { try { return state; } finally { state = State.NEW; } } State restoreState(final State state) { try { return this.state; } finally { this.state = state; } } public void defaultReadObject() throws IOException, ClassNotFoundException { if (state != State.NEW) { throw new IllegalStateException("Fields may not be read now"); } state = State.ON; currentDescriptor.defaultReadFields(serialUnmarshaller, currentSubject); } public GetField readFields() throws IOException, ClassNotFoundException { if (state != State.NEW) { throw new IllegalStateException("Fields may not be read now"); } state = State.ON; return currentDescriptor.getField(serialUnmarshaller, currentSerializableClass); } public void registerValidation(final ObjectInputValidation obj, final int prio) throws NotActiveException, InvalidObjectException { serialUnmarshaller.addValidation(obj, prio); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootjboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/ExtendedObjectStreamConstants.javajboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/ExtendedObjectStreamCon0000644000175000017500000000247711143151160033412 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.serial; import java.io.ObjectStreamConstants; /** * Protocol extensions used locally for JBoss Marshalling extensions to Class/Object Resolvers. */ public interface ExtendedObjectStreamConstants extends ObjectStreamConstants { int TC_CLASSTABLEDESC = 0xF0; int TC_OBJECTTABLE = 0xF1; } jboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/NoDataDescriptor.java0000644000175000017500000000304611143101064033023 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.serial; import org.jboss.marshalling.reflect.SerializableClass; import java.io.IOException; /** * */ class NoDataDescriptor extends Descriptor { NoDataDescriptor(final Class type, final Descriptor parent) { super(parent, type); } protected void readSerial(final SerialUnmarshaller serialUnmarshaller, final SerializableClass sc, final Object subject) throws IOException, ClassNotFoundException { if (sc.hasReadObjectNoData()) { sc.callReadObjectNoData(subject); } } } jboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/Descriptor.java0000644000175000017500000000360411143151275031745 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.serial; import org.jboss.marshalling.reflect.SerializableClass; import org.jboss.marshalling.reflect.SerializableField; import java.io.IOException; /** * */ abstract class Descriptor implements ExtendedObjectStreamConstants { private final Descriptor parent; private final Class type; protected Descriptor(final Descriptor parent, final Class type) { this.parent = parent; this.type = type; } protected Descriptor getParent() { return parent; } protected Class getType() { return type; } protected abstract void readSerial(SerialUnmarshaller serialUnmarshaller, SerializableClass sc, Object subject) throws IOException, ClassNotFoundException; public int getFlags() { return 0; } public SerializableField[] getFields() { return SerializableClass.NOFIELDS; } } jboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/ProxyDescriptor.java0000644000175000017500000000276411143101064033004 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.serial; import java.io.ObjectStreamConstants; /** * */ class ProxyDescriptor extends NoDataDescriptor { private final String[] interfaces; ProxyDescriptor(final Class type, final Descriptor parent, final String[] interfaces) { super(type, parent); this.interfaces = interfaces; } public String[] getInterfaces() { return interfaces; } public int getFlags() { return ObjectStreamConstants.SC_SERIALIZABLE; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootjboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/SerialObjectOutputStream.javajboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/SerialObjectOutputStrea0000644000175000017500000002062711143125530033474 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.serial; import org.jboss.marshalling.MarshallerObjectOutputStream; import org.jboss.marshalling.reflect.SerializableClass; import org.jboss.marshalling.reflect.SerializableField; import org.jboss.marshalling.util.FieldPutter; import org.jboss.marshalling.util.BooleanFieldPutter; import org.jboss.marshalling.util.ByteFieldPutter; import org.jboss.marshalling.util.CharFieldPutter; import org.jboss.marshalling.util.DoubleFieldPutter; import org.jboss.marshalling.util.FloatFieldPutter; import org.jboss.marshalling.util.IntFieldPutter; import org.jboss.marshalling.util.LongFieldPutter; import org.jboss.marshalling.util.ObjectFieldPutter; import org.jboss.marshalling.util.ShortFieldPutter; import org.jboss.marshalling.util.Kind; import java.io.IOException; import java.io.ObjectOutput; import java.util.Map; import java.util.TreeMap; /** * */ public final class SerialObjectOutputStream extends MarshallerObjectOutputStream { protected enum State { OFF, NEW, FIELDS, ON, ; } private final SerialMarshaller serialMarshaller; private State state = State.OFF; private Object currentObject; private SerializableClass currentSerializableClass; private Map currentFieldMap; protected SerialObjectOutputStream(final SerialMarshaller serialMarshaller, final BlockMarshaller blockMarshaller) throws IOException, SecurityException { super(blockMarshaller); this.serialMarshaller = serialMarshaller; } State saveState() { try { return state; } finally { state = State.NEW; } } State restoreState(final State state) { try { return this.state; } finally { this.state = state; } } Object saveCurrentObject(final Object currentObject) { try { return this.currentObject; } finally { this.currentObject = currentObject; } } void setCurrentObject(final Object currentObject) { this.currentObject = currentObject; } Map saveCurrentFieldMap() { return currentFieldMap; } void setCurrentFieldMap(Map map) { currentFieldMap = map; } SerializableClass saveCurrentSerializableClass(final SerializableClass currentSerializableClass) { try { return this.currentSerializableClass; } finally { this.currentSerializableClass = currentSerializableClass; } } void setCurrentSerializableClass(final SerializableClass currentSerializableClass) { this.currentSerializableClass = currentSerializableClass; } public void writeFields() throws IOException { if (state == State.FIELDS) { for (FieldPutter putter : currentFieldMap.values()) { if (putter.getKind() != Kind.OBJECT) { putter.write(serialMarshaller); } } for (FieldPutter putter : currentFieldMap.values()) { if (putter.getKind() == Kind.OBJECT) { putter.write(serialMarshaller); } } } else { throw new IllegalStateException("fields may not be written now"); } state = State.ON; } public PutField putFields() throws IOException { if (state == State.NEW) { final Map map = new TreeMap(); currentFieldMap = map; for (SerializableField serializableField : currentSerializableClass.getFields()) { final FieldPutter putter; switch (serializableField.getKind()) { case BOOLEAN: { putter = new BooleanFieldPutter(); break; } case BYTE: { putter = new ByteFieldPutter(); break; } case CHAR: { putter = new CharFieldPutter(); break; } case DOUBLE: { putter = new DoubleFieldPutter(); break; } case FLOAT: { putter = new FloatFieldPutter(); break; } case INT: { putter = new IntFieldPutter(); break; } case LONG: { putter = new LongFieldPutter(); break; } case OBJECT: { putter = new ObjectFieldPutter(serializableField.isUnshared()); break; } case SHORT: { putter = new ShortFieldPutter(); break; } default: { continue; } } map.put(serializableField.getName(), putter); } state = State.FIELDS; return new PutField() { public void put(final String name, final boolean val) { find(name).setBoolean(val); } public void put(final String name, final byte val) { find(name).setByte(val); } public void put(final String name, final char val) { find(name).setChar(val); } public void put(final String name, final short val) { find(name).setShort(val); } public void put(final String name, final int val) { find(name).setInt(val); } public void put(final String name, final long val) { find(name).setLong(val); } public void put(final String name, final float val) { find(name).setFloat(val); } public void put(final String name, final double val) { find(name).setDouble(val); } public void put(final String name, final Object val) { find(name).setObject(val); } public void write(final ObjectOutput out) throws IOException { throw new UnsupportedOperationException("write(ObjectOutput)"); } private FieldPutter find(final String name) { final FieldPutter putter = map.get(name); if (putter == null) { throw new IllegalArgumentException("No field named '" + name + "' found"); } return putter; } }; } else { throw new IllegalStateException("putFields() may not be called now"); } } public void defaultWriteObject() throws IOException { if (state == State.NEW || state == State.FIELDS) { serialMarshaller.doWriteFields(currentSerializableClass, currentObject); } else { throw new IllegalStateException("fields may not be written now"); } state = State.ON; } } jboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/PlainDescriptor.java0000644000175000017500000003450211143127472032734 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.serial; import org.jboss.marshalling.reflect.SerializableField; import org.jboss.marshalling.reflect.SerializableClass; import org.jboss.marshalling.util.ReadField; import org.jboss.marshalling.util.BooleanReadField; import org.jboss.marshalling.util.ByteReadField; import org.jboss.marshalling.util.CharReadField; import org.jboss.marshalling.util.DoubleReadField; import org.jboss.marshalling.util.FloatReadField; import org.jboss.marshalling.util.IntReadField; import org.jboss.marshalling.util.LongReadField; import org.jboss.marshalling.util.ObjectReadField; import org.jboss.marshalling.util.ShortReadField; import org.jboss.marshalling.util.Kind; import java.io.IOException; import java.io.ObjectStreamConstants; import java.io.InvalidClassException; import java.io.ObjectInputStream; import java.io.ObjectStreamClass; import java.io.StreamCorruptedException; import java.util.Map; import java.util.HashMap; /** * */ class PlainDescriptor extends Descriptor implements ObjectStreamConstants { private final SerializableField[] fields; private final int flags; protected PlainDescriptor(final Class type, final Descriptor parent, final SerializableField[] fields, final int flags) { super(parent, type); this.fields = fields; this.flags = flags; } public SerializableField[] getFields() { return fields; } public int getFlags() { return flags; } protected void readSerial(final SerialUnmarshaller serialUnmarshaller, final SerializableClass sc, final Object subject) throws IOException, ClassNotFoundException { if ((flags & SC_WRITE_METHOD) != 0) { if (sc.hasReadObject()) { doReadObject(serialUnmarshaller, sc, subject); } else { defaultReadFields(serialUnmarshaller, subject); } final BlockUnmarshaller blockUnmarshaller = serialUnmarshaller.getBlockUnmarshaller(); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); } else { if (sc.hasReadObject()) { final BlockUnmarshaller blockUnmarshaller = serialUnmarshaller.getBlockUnmarshaller(); blockUnmarshaller.endOfStream(); doReadObject(serialUnmarshaller, sc, subject); blockUnmarshaller.unblock(); } else { defaultReadFields(serialUnmarshaller, subject); } } } private void doReadObject(final SerialUnmarshaller serialUnmarshaller, final SerializableClass sc, final Object subject) throws ClassNotFoundException, IOException { final SerialObjectInputStream ois = serialUnmarshaller.getObjectInputStream(); final SerialObjectInputStream.State oldState = ois.saveState(); final PlainDescriptor oldDescriptor = ois.saveCurrentDescriptor(this); final SerializableClass oldSerializableClass = ois.saveCurrentSerializableClass(sc); final Object oldSubject = ois.saveCurrentSubject(subject); try { sc.callReadObject(subject, ois); if (ois.restoreState(oldState) != SerialObjectInputStream.State.ON) { throw new StreamCorruptedException("readObject() did not read fields"); } } finally { ois.restoreState(oldState); ois.setCurrentDescriptor(oldDescriptor); ois.setCurrentSerializableClass(oldSerializableClass); ois.setCurrentSubject(oldSubject); } } void defaultReadFields(final SerialUnmarshaller serialUnmarshaller, final Object subject) throws IOException, ClassNotFoundException { try { // first primitive fields for (SerializableField serializableField : fields) { switch (serializableField.getKind()) { case BOOLEAN: { serializableField.getField().setBoolean(subject, serialUnmarshaller.readBoolean()); break; } case BYTE: { serializableField.getField().setByte(subject, serialUnmarshaller.readByte()); break; } case CHAR: { serializableField.getField().setChar(subject, serialUnmarshaller.readChar()); break; } case DOUBLE: { serializableField.getField().setDouble(subject, serialUnmarshaller.readDouble()); break; } case FLOAT: { serializableField.getField().setFloat(subject, serialUnmarshaller.readFloat()); break; } case INT: { serializableField.getField().setInt(subject, serialUnmarshaller.readInt()); break; } case LONG: { serializableField.getField().setLong(subject, serialUnmarshaller.readLong()); break; } case SHORT: { serializableField.getField().setShort(subject, serialUnmarshaller.readShort()); break; } } } // next object fields for (SerializableField serializableField : fields) { if (serializableField.getKind() == Kind.OBJECT) { serializableField.getField().set(subject, serialUnmarshaller.readObject()); } } } catch (IllegalAccessException e) { final InvalidClassException ice = new InvalidClassException("Unexpected illegal access"); ice.initCause(e); throw ice; } } ObjectInputStream.GetField getField(final SerialUnmarshaller serialUnmarshaller, final SerializableClass sc) throws IOException, ClassNotFoundException { final Map readFields = new HashMap(); for (SerializableField serializableField : sc.getFields()) { final ReadField readField; switch (serializableField.getKind()) { case BOOLEAN: { readField = new BooleanReadField(serializableField); break; } case BYTE: { readField = new ByteReadField(serializableField); break; } case CHAR: { readField = new CharReadField(serializableField); break; } case DOUBLE: { readField = new DoubleReadField(serializableField); break; } case FLOAT: { readField = new FloatReadField(serializableField); break; } case INT: { readField = new IntReadField(serializableField); break; } case LONG: { readField = new LongReadField(serializableField); break; } case OBJECT: { readField = new ObjectReadField(serializableField); break; } case SHORT: { readField = new ShortReadField(serializableField); break; } default: { continue; } } readFields.put(serializableField.getName(), readField); } // read primitive fields for (SerializableField serializableField : fields) { final ReadField readField; switch (serializableField.getKind()) { case BOOLEAN: { readField = new BooleanReadField(serializableField, serialUnmarshaller.readBoolean()); break; } case BYTE: { readField = new ByteReadField(serializableField, serialUnmarshaller.readByte()); break; } case CHAR: { readField = new CharReadField(serializableField, serialUnmarshaller.readChar()); break; } case DOUBLE: { readField = new DoubleReadField(serializableField, serialUnmarshaller.readDouble()); break; } case FLOAT: { readField = new FloatReadField(serializableField, serialUnmarshaller.readFloat()); break; } case INT: { readField = new IntReadField(serializableField, serialUnmarshaller.readInt()); break; } case LONG: { readField = new LongReadField(serializableField, serialUnmarshaller.readLong()); break; } case SHORT: { readField = new ShortReadField(serializableField, serialUnmarshaller.readShort()); break; } default: { continue; } } readFields.put(serializableField.getName(), readField); } // read object fields for (SerializableField serializableField : fields) { final ReadField readField; switch (serializableField.getKind()) { case OBJECT: { readField = new ObjectReadField(serializableField, serialUnmarshaller.readObject()); break; } default: { continue; } } readFields.put(serializableField.getName(), readField); } return new ObjectInputStream.GetField() { public ObjectStreamClass getObjectStreamClass() { throw new UnsupportedOperationException("getObjectStreamClass()"); } public boolean defaulted(final String name) throws IOException { final ReadField field = readFields.get(name); if (field == null) throw new IllegalArgumentException("No such field named " + name); return field.isDefaulted(); } public boolean get(final String name, final boolean val) throws IOException { final ReadField field = readFields.get(name); if (field == null) throw new IllegalArgumentException("No such field named " + name); return field.isDefaulted() ? val : field.getBoolean(); } public byte get(final String name, final byte val) throws IOException { final ReadField field = readFields.get(name); if (field == null) throw new IllegalArgumentException("No such field named " + name); return field.isDefaulted() ? val : field.getByte(); } public char get(final String name, final char val) throws IOException { final ReadField field = readFields.get(name); if (field == null) throw new IllegalArgumentException("No such field named " + name); return field.isDefaulted() ? val : field.getChar(); } public short get(final String name, final short val) throws IOException { final ReadField field = readFields.get(name); if (field == null) throw new IllegalArgumentException("No such field named " + name); return field.isDefaulted() ? val : field.getShort(); } public int get(final String name, final int val) throws IOException { final ReadField field = readFields.get(name); if (field == null) throw new IllegalArgumentException("No such field named " + name); return field.isDefaulted() ? val : field.getInt(); } public long get(final String name, final long val) throws IOException { final ReadField field = readFields.get(name); if (field == null) throw new IllegalArgumentException("No such field named " + name); return field.isDefaulted() ? val : field.getLong(); } public float get(final String name, final float val) throws IOException { final ReadField field = readFields.get(name); if (field == null) throw new IllegalArgumentException("No such field named " + name); return field.isDefaulted() ? val : field.getFloat(); } public double get(final String name, final double val) throws IOException { final ReadField field = readFields.get(name); if (field == null) throw new IllegalArgumentException("No such field named " + name); return field.isDefaulted() ? val : field.getDouble(); } public Object get(final String name, final Object val) throws IOException { final ReadField field = readFields.get(name); if (field == null) throw new IllegalArgumentException("No such field named " + name); return field.isDefaulted() ? val : field.getObject(); } }; } } jboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/BlockMarshaller.java0000644000175000017500000002563711143151160032677 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.serial; import org.jboss.marshalling.Marshaller; import org.jboss.marshalling.ByteOutput; import org.jboss.marshalling.UTFUtils; import java.io.IOException; /** * */ public final class BlockMarshaller implements Marshaller, ExtendedObjectStreamConstants { private final SerialMarshaller serialMarshaller; private final byte[] buffer; private int position; BlockMarshaller(final SerialMarshaller marshaller, final int bufferSize) { serialMarshaller = marshaller; buffer = new byte[bufferSize]; } public void start(final ByteOutput newOutput) throws IOException { throw new IllegalStateException("start() not allowed in this context"); } public void clearInstanceCache() throws IOException { throw new IllegalStateException("clearInstanceCache() not allowed in this context"); } public void clearClassCache() throws IOException { throw new IllegalStateException("clearClassCache() not allowed in this context"); } public void finish() throws IOException { throw new IllegalStateException("finish() not allowed in this context"); } public void writeObject(final Object obj) throws IOException { doWriteObject(obj, false); } public void writeObjectUnshared(final Object obj) throws IOException { doWriteObject(obj, true); } private void doWriteObject(final Object obj, final boolean unshared) throws IOException { flush(); serialMarshaller.doWriteObject(obj, unshared); flush(); } public void write(final int v) throws IOException { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining == 0) { flush(); buffer[0] = (byte) v; position = 1; } else { buffer[position++] = (byte) v; } } public void write(final byte[] b) throws IOException { write(b, 0, b.length); } public void write(final byte[] bytes, final int off, final int len) throws IOException { final int bl = buffer.length; final int position = this.position; if (len > bl - position || len > bl >> 1) { flush(); if (len > 256) { serialMarshaller.write(TC_BLOCKDATALONG); serialMarshaller.writeInt(len); serialMarshaller.write(bytes, off, len); } else if (len > 0) { serialMarshaller.write(TC_BLOCKDATA); serialMarshaller.write(len); serialMarshaller.write(bytes, off, len); } } else { System.arraycopy(bytes, off, buffer, position, len); this.position = position + len; } } public void writeBoolean(final boolean v) throws IOException { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining == 0) { flush(); buffer[0] = (byte) (v ? 1 : 0); position = 1; } else { buffer[position++] = (byte) (v ? 1 : 0); } } public void writeByte(final int v) throws IOException { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining == 0) { flush(); buffer[0] = (byte) v; position = 1; } else { buffer[position++] = (byte) v; } } public void writeShort(final int v) throws IOException { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 2) { flush(); buffer[0] = (byte) (v >> 8); buffer[1] = (byte) v; position = 2; } else { final int s = position; position = s + 2; buffer[s] = (byte) (v >> 8); buffer[s+1] = (byte) v; } } public void writeChar(final int v) throws IOException { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 2) { flush(); buffer[0] = (byte) (v >> 8); buffer[1] = (byte) v; position = 2; } else { final int s = position; position = s + 2; buffer[s] = (byte) (v >> 8); buffer[s+1] = (byte) v; } } public void writeInt(final int v) throws IOException { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 4) { flush(); buffer[0] = (byte) (v >> 24); buffer[1] = (byte) (v >> 16); buffer[2] = (byte) (v >> 8); buffer[3] = (byte) v; position = 4; } else { final int s = position; position = s + 4; buffer[s] = (byte) (v >> 24); buffer[s+1] = (byte) (v >> 16); buffer[s+2] = (byte) (v >> 8); buffer[s+3] = (byte) v; } } public void writeLong(final long v) throws IOException { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 8) { flush(); buffer[0] = (byte) (v >> 56L); buffer[1] = (byte) (v >> 48L); buffer[2] = (byte) (v >> 40L); buffer[3] = (byte) (v >> 32L); buffer[4] = (byte) (v >> 24L); buffer[5] = (byte) (v >> 16L); buffer[6] = (byte) (v >> 8L); buffer[7] = (byte) v; position = 8; } else { final int s = position; position = s + 8; buffer[s] = (byte) (v >> 56L); buffer[s+1] = (byte) (v >> 48L); buffer[s+2] = (byte) (v >> 40L); buffer[s+3] = (byte) (v >> 32L); buffer[s+4] = (byte) (v >> 24L); buffer[s+5] = (byte) (v >> 16L); buffer[s+6] = (byte) (v >> 8L); buffer[s+7] = (byte) v; } } public void writeFloat(final float v) throws IOException { final int bits = Float.floatToIntBits(v); final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 4) { flush(); buffer[0] = (byte) (bits >> 24); buffer[1] = (byte) (bits >> 16); buffer[2] = (byte) (bits >> 8); buffer[3] = (byte) bits; position = 4; } else { final int s = position; position = s + 4; buffer[s] = (byte) (bits >> 24); buffer[s+1] = (byte) (bits >> 16); buffer[s+2] = (byte) (bits >> 8); buffer[s+3] = (byte) bits; } } public void writeDouble(final double v) throws IOException { final long bits = Double.doubleToLongBits(v); final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 8) { flush(); buffer[0] = (byte) (bits >> 56L); buffer[1] = (byte) (bits >> 48L); buffer[2] = (byte) (bits >> 40L); buffer[3] = (byte) (bits >> 32L); buffer[4] = (byte) (bits >> 24L); buffer[5] = (byte) (bits >> 16L); buffer[6] = (byte) (bits >> 8L); buffer[7] = (byte) bits; position = 8; } else { final int s = position; position = s + 8; buffer[s] = (byte) (bits >> 56L); buffer[s+1] = (byte) (bits >> 48L); buffer[s+2] = (byte) (bits >> 40L); buffer[s+3] = (byte) (bits >> 32L); buffer[s+4] = (byte) (bits >> 24L); buffer[s+5] = (byte) (bits >> 16L); buffer[s+6] = (byte) (bits >> 8L); buffer[s+7] = (byte) bits; } } public void writeBytes(final String s) throws IOException { final int len = s.length(); for (int i = 0; i < len; i ++) { write(s.charAt(i)); } } public void writeChars(final String s) throws IOException { final int len = s.length(); for (int i = 0; i < len; i ++) { writeChar(s.charAt(i)); } } public void writeUTF(final String s) throws IOException { final int len = UTFUtils.getShortUTFLength(s); final int position = this.position; final int bufsize = buffer.length; int remaining = bufsize - position; if (len > bufsize >> 1 || len + 2 > remaining) { // the string will take up more than half the buffer or it is bigger than the remaining space // so don't bother double-buffering this block flush(); if (len < 253) { serialMarshaller.write(TC_BLOCKDATA); serialMarshaller.write(len + 2); serialMarshaller.writeShort(len); UTFUtils.writeUTFBytes(serialMarshaller, s); } else { serialMarshaller.write(TC_BLOCKDATALONG); serialMarshaller.writeInt(len + 2); serialMarshaller.writeShort(len); UTFUtils.writeUTFBytes(serialMarshaller, s); } } else { // the string will fit in this buffer writeShort(len); UTFUtils.writeUTFBytes(this, s); } } public void flush() throws IOException { final int position = this.position; if (position > 256) { serialMarshaller.write(TC_BLOCKDATALONG); serialMarshaller.writeInt(position); serialMarshaller.write(buffer, 0, position); } else if (position > 0) { serialMarshaller.write(TC_BLOCKDATA); serialMarshaller.write(position); serialMarshaller.write(buffer, 0, position); } this.position = 0; } public void close() throws IOException { } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootjboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/SerialUnmarshaller.javajboss-marshalling-1.1.3.GA/serial/src/main/java/org/jboss/marshalling/serial/SerialUnmarshaller.java0000644000175000017500000006273211174432764033444 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.serial; import org.jboss.marshalling.Unmarshaller; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.AbstractUnmarshaller; import org.jboss.marshalling.UTFUtils; import org.jboss.marshalling.ByteInput; import static org.jboss.marshalling.Marshalling.createOptionalDataException; import org.jboss.marshalling.reflect.SerializableClassRegistry; import org.jboss.marshalling.reflect.SerializableClass; import org.jboss.marshalling.reflect.SerializableField; import java.io.IOException; import java.io.StreamCorruptedException; import java.io.ObjectStreamClass; import java.io.InvalidClassException; import java.io.WriteAbortedException; import java.io.InvalidObjectException; import java.io.Externalizable; import java.io.NotSerializableException; import java.io.ObjectInputValidation; import java.io.Serializable; import java.util.ArrayList; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.HashSet; import java.util.Collections; import java.lang.reflect.Array; import java.security.PrivilegedExceptionAction; import java.security.AccessController; import java.security.PrivilegedActionException; /** * */ public final class SerialUnmarshaller extends AbstractUnmarshaller implements Unmarshaller, ExtendedObjectStreamConstants { private static final Object UNSHARED = new Object(); private static final Object UNRESOLVED = new Object(); private final ArrayList instanceCache; private final SerializableClassRegistry registry; private int depth = 0; private SerialObjectInputStream ois; private BlockUnmarshaller blockUnmarshaller; private int version; SerialUnmarshaller(final SerialMarshallerFactory factory, final SerializableClassRegistry registry, final MarshallingConfiguration configuration) { super(factory, configuration); this.registry = registry; instanceCache = new ArrayList(configuration.getInstanceCount()); } protected Object doReadObject(final boolean unshared) throws ClassNotFoundException, IOException { final Object obj = doReadObject(readUnsignedByte(), unshared); if (depth == 0) try { for (Set validations : validationMap.values()) { for (ObjectInputValidation validation : validations) { validation.validateObject(); } } } finally { validationMap.clear(); } return obj; } String doReadString() throws IOException, ClassNotFoundException { final int leadByte = readUnsignedByte(); switch (leadByte) { case TC_NULL: return null; case TC_REFERENCE: try { return (String) readBackReference(readInt()); } catch (ClassCastException e) { throw new StreamCorruptedException("Expected a string backreference"); } case TC_STRING: return (String) doReadObject(leadByte, false); default: throw new StreamCorruptedException("Expected a string object"); } } Object readBackReference(int handle) throws IOException { final int idx = handle - baseWireHandle; if (idx < 0 || idx >= instanceCache.size()) { throw new StreamCorruptedException(String.format("Invalid backreference: %08x", Integer.valueOf(handle))); } final Object obj = instanceCache.get(idx); if (obj == UNSHARED) { throw new StreamCorruptedException(String.format("Invalid backreference to unshared instance: %08x", Integer.valueOf(handle))); } if (obj == UNRESOLVED) { throw new StreamCorruptedException(String.format("Invalid backreference to unresolved instance: %08x", Integer.valueOf(handle))); } return obj; } Object doReadObject(int leadByte, final boolean unshared) throws IOException, ClassNotFoundException { depth ++; try { final BlockUnmarshaller blockUnmarshaller = this.blockUnmarshaller; for (;;) switch (leadByte) { case TC_NULL: { return null; } case TC_REFERENCE: { final Object prevObj = readBackReference(readInt()); if (prevObj instanceof Descriptor) { throw objectStreamClassException(); } return prevObj; } case TC_CLASS: { final Descriptor descriptor = readNonNullClassDescriptor(); final Class obj = descriptor.getType(); instanceCache.add(obj); return obj; } case TC_CLASSDESC: { throw objectStreamClassException(); } case TC_PROXYCLASSDESC: { throw objectStreamClassException(); } case TC_STRING: { final int len = readUnsignedShort(); final String str = UTFUtils.readUTFBytesByByteCount(this, len); instanceCache.add(unshared ? UNSHARED : str); return str; } case TC_LONGSTRING: { final long len = super.readLong(); final String str = UTFUtils.readUTFBytesByByteCount(this, len); instanceCache.add(unshared ? UNSHARED : str); return str; } case TC_ARRAY: { final Descriptor descriptor = readNonNullClassDescriptor(); final int idx = instanceCache.size(); instanceCache.add(UNRESOLVED); final int size = readInt(); final Class type = descriptor.getType(); if (! type.isArray()) { throw new InvalidClassException(type.getName(), "Expected array type"); } final Class ct = type.getComponentType(); if (ct.isPrimitive()) { if (ct == byte.class) { final byte[] bytes = new byte[size]; readFully(bytes); instanceCache.set(idx, bytes); return bytes; } else if (ct == short.class) { final short[] shorts = new short[size]; for (int i = 0; i < shorts.length; i++) { shorts[i] = readShort(); } instanceCache.set(idx, shorts); return shorts; } else if (ct == int.class) { final int[] ints = new int[size]; for (int i = 0; i < ints.length; i++) { ints[i] = readInt(); } instanceCache.set(idx, ints); return ints; } else if (ct == long.class) { final long[] longs = new long[size]; for (int i = 0; i < longs.length; i++) { longs[i] = readLong(); } instanceCache.set(idx, longs); return longs; } else if (ct == float.class) { final float[] floats = new float[size]; for (int i = 0; i < floats.length; i++) { floats[i] = readFloat(); } instanceCache.set(idx, floats); return floats; } else if (ct == double.class) { final double[] doubles = new double[size]; for (int i = 0; i < doubles.length; i++) { doubles[i] = readDouble(); } instanceCache.set(idx, doubles); return doubles; } else if (ct == boolean.class) { final boolean[] booleans = new boolean[size]; for (int i = 0; i < booleans.length; i++) { booleans[i] = readBoolean(); } instanceCache.set(idx, booleans); return booleans; } else if (ct == char.class) { final char[] chars = new char[size]; for (int i = 0; i < chars.length; i++) { chars[i] = readChar(); } instanceCache.set(idx, chars); return chars; } else { throw new InvalidClassException(type.getName(), "Invalid component type"); } } else { final Object[] objects = (Object[]) Array.newInstance(ct, size); instanceCache.set(idx, objects); for (int i = 0; i < objects.length; i++) { objects[i] = doReadObject(false); } return objects; } } case TC_ENUM: { final Descriptor descriptor = readNonNullClassDescriptor(); final Class enumType; try { enumType = descriptor.getType().asSubclass(Enum.class); } catch (ClassCastException e) { throw new InvalidClassException("Expected an enum class descriptor"); } final int idx = instanceCache.size(); instanceCache.add(UNRESOLVED); final String constName = (String) doReadObject(false); final Enum obj = Enum.valueOf(enumType, constName); instanceCache.set(idx, obj); return obj; } case TC_OBJECT: { final Descriptor descriptor = readNonNullClassDescriptor(); if ((descriptor.getFlags() & (SC_SERIALIZABLE | SC_EXTERNALIZABLE)) == 0) { throw new NotSerializableException(descriptor.getClass().getName()); } final Object obj = creator.create(descriptor.getType()); final int idx = instanceCache.size(); instanceCache.add(unshared ? UNSHARED : obj); if ((descriptor.getFlags() & SC_EXTERNALIZABLE) != 0) { if (obj instanceof Externalizable) { final Externalizable externalizable = (Externalizable) obj; if ((descriptor.getFlags() & SC_BLOCK_DATA) != 0) { externalizable.readExternal(blockUnmarshaller); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); } else { // data is not in block format! externalizable.readExternal(this); } } else { throw new InvalidObjectException("Created object should be Externalizable but it is not"); } } else if (obj instanceof Externalizable) { throw new InvalidObjectException("Created object should not be Externalizable but it is"); } else { doReadSerialObject(descriptor, obj); } final SerializableClass sc = registry.lookup(obj.getClass()); if (sc.hasReadResolve()) { final Object replacement = sc.callReadResolve(obj); if (! unshared) instanceCache.set(idx, replacement); return replacement; } return obj; } case TC_OBJECTTABLE: { final int idx = instanceCache.size(); instanceCache.add(unshared ? UNSHARED : UNRESOLVED); final Object obj = objectTable.readObject(blockUnmarshaller); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); if (! unshared) instanceCache.set(idx, obj); return obj; } case TC_EXCEPTION: { clearInstanceCache(); final IOException ex = (IOException) doReadObject(false); throw new WriteAbortedException("Write aborted", ex); } case TC_BLOCKDATA: case TC_BLOCKDATALONG: { blockUnmarshaller.readBlockHeader(leadByte); throw createOptionalDataException(blockUnmarshaller.remaining()); } case TC_ENDBLOCKDATA: { throw createOptionalDataException(0); } case TC_RESET: { if (depth > 1) { throw new StreamCorruptedException("Reset token in the middle of stream processing"); } clearInstanceCache(); leadByte = readByte() & 0xff; continue; } default: { throw badLeadByte(leadByte); } } } finally { depth --; } } private void doReadSerialObject(final Descriptor descriptor, final Object obj) throws ClassNotFoundException, IOException { final Descriptor parent = descriptor.getParent(); if (parent != null) { doReadSerialObject(parent, obj); } descriptor.readSerial(this, registry.lookup(descriptor.getType()), obj); } private static InvalidClassException objectStreamClassException() { return new InvalidClassException(ObjectStreamClass.class.getName(), "Cannot read ObjectStreamClass instances"); } private Descriptor readNonNullClassDescriptor() throws ClassNotFoundException, IOException { final Descriptor desc = readClassDescriptor(); if (desc == null) { throw new StreamCorruptedException("Unexpected null class descriptor"); } return desc; } private Descriptor readClassDescriptor() throws ClassNotFoundException, IOException { return readClassDescriptor(readUnsignedByte()); } private Descriptor readClassDescriptor(int leadByte) throws IOException, ClassNotFoundException { final BlockUnmarshaller blockUnmarshaller = this.blockUnmarshaller; switch (leadByte) { case TC_CLASSTABLEDESC: { final Class clazz = classTable.readClass(blockUnmarshaller); final int idx = instanceCache.size(); instanceCache.add(UNRESOLVED); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); Descriptor descriptor = descriptorForClass(clazz); instanceCache.set(idx, descriptor); return descriptor; } case TC_CLASSDESC: { final String className = readUTF(); final long svu = readLong(); final int idx = instanceCache.size(); instanceCache.add(UNRESOLVED); final int descFlags = readUnsignedByte(); final int fieldCount = readUnsignedShort(); final int[] typecodes = new int[fieldCount]; final String[] names = new String[fieldCount]; final String[] fieldSignatures = new String[fieldCount]; for (int i = 0; i < fieldCount; i ++) { typecodes[i] = readUnsignedByte(); names[i] = readUTF(); if (typecodes[i] == '[' || typecodes[i] == 'L') { fieldSignatures[i] = doReadString(); } } final Class clazz = classResolver.resolveClass(blockUnmarshaller, className, svu); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); final SerializableClass sc = registry.lookup(clazz); final SerializableField[] fields = new SerializableField[fieldCount]; for (int i = 0; i < fieldCount; i ++) { final Class fieldType; switch (typecodes[i]) { case 'B': { fieldType = byte.class; break; } case 'C': { fieldType = char.class; break; } case 'D': { fieldType = double.class; break; } case 'F': { fieldType = float.class; break; } case 'I': { fieldType = int.class; break; } case 'J': { fieldType = long.class; break; } case 'S': { fieldType = short.class; break; } case 'Z': { fieldType = boolean.class; break; } case 'L': case '[': { fieldType = Object.class; break; } default: { throw new StreamCorruptedException("Invalid field typecode " + typecodes[i]); } } fields[i] = sc.getSerializableField(names[i], fieldType, false); } final Descriptor superDescr = readClassDescriptor(); final Class superClazz = clazz.getSuperclass(); final Descriptor descriptor; if (superDescr == null || superDescr.getType().isAssignableFrom(superClazz)) { descriptor = descFlags == 0 ? new NoDataDescriptor(clazz, bridge(superDescr, superClazz)) : new PlainDescriptor(clazz, bridge(superDescr, superClazz), fields, descFlags); } else { throw new InvalidClassException(clazz.getName(), "Class hierarchy mismatch"); } instanceCache.set(idx, descriptor); return descriptor; } case TC_PROXYCLASSDESC: { final int idx = instanceCache.size(); instanceCache.add(UNRESOLVED); final int cnt = readInt(); final String[] interfaces = new String[cnt]; for (int i = 0; i < interfaces.length; i++) { interfaces[i] = readUTF(); } final Class clazz = classResolver.resolveProxyClass(blockUnmarshaller, interfaces); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); final Descriptor superDescr = readClassDescriptor(); final ProxyDescriptor descr = new ProxyDescriptor(clazz, superDescr, interfaces); instanceCache.set(idx, descr); return descr; } case TC_NULL: { return null; } case TC_REFERENCE: { try { return (Descriptor) readBackReference(readInt()); } catch (ClassCastException e) { throw new StreamCorruptedException("Backreference was not a resolved class descriptor"); } } default: throw badLeadByte(leadByte); } } private Descriptor bridge(final Descriptor descriptor, final Class type) { final Class superDescrClazz = descriptor == null ? null : descriptor.getType(); final Class typeSuperclass = type.getSuperclass(); if (type == superDescrClazz || descriptor == null && (typeSuperclass == null || Serializable.class.isAssignableFrom(typeSuperclass))) { return descriptor; } else { return new NoDataDescriptor(type, bridge(descriptor, typeSuperclass)); } } private StreamCorruptedException badLeadByte(final int leadByte) { return new StreamCorruptedException("Unexpected lead byte " + leadByte); } public void clearInstanceCache() throws IOException { instanceCache.clear(); } public void clearClassCache() throws IOException { instanceCache.clear(); } public void start(final ByteInput byteInput) throws IOException { depth = 0; blockUnmarshaller = new BlockUnmarshaller(this); super.start(byteInput); } protected void doStart() throws IOException { super.doStart(); int version = readUnsignedShort(); if (version > 5) { throw new IOException("Unsupported protocol version " + version); } this.version = version; } public void finish() throws IOException { super.finish(); blockUnmarshaller = null; depth = 0; } public void close() throws IOException { finish(); } BlockUnmarshaller getBlockUnmarshaller() { return blockUnmarshaller; } private final PrivilegedExceptionAction createObjectOutputStreamAction = new PrivilegedExceptionAction() { public SerialObjectInputStream run() throws IOException { return new SerialObjectInputStream(SerialUnmarshaller.this); } }; private SerialObjectInputStream createObjectInputStream() throws IOException { try { return AccessController.doPrivileged(createObjectOutputStreamAction); } catch (PrivilegedActionException e) { throw (IOException) e.getCause(); } } SerialObjectInputStream getObjectInputStream() throws IOException { return ois == null ? (ois = createObjectInputStream()) : ois; } private final SortedMap> validationMap = new TreeMap>(Collections.reverseOrder()); void addValidation(final ObjectInputValidation validation, final int prio) { final Set validations; final Integer prioKey = Integer.valueOf(prio); if (validationMap.containsKey(prioKey)) { validations = validationMap.get(prioKey); } else { validations = new HashSet(); validationMap.put(prioKey, validations); } validations.add(validation); } public Descriptor descriptorForClass(final Class clazz) { if (Externalizable.class.isAssignableFrom(clazz)) { // todo - make WRITE_METHOD depend on block mode return new PlainDescriptor(clazz, null, SerializableClass.NOFIELDS, SC_EXTERNALIZABLE | SC_BLOCK_DATA); } else if (Serializable.class.isAssignableFrom(clazz)) { final Class superclass = clazz.getSuperclass(); final Descriptor parent; if (superclass != null && Serializable.class.isAssignableFrom(superclass)) { parent = descriptorForClass(superclass); } else { parent = null; } final SerializableClass serializableClass = registry.lookup(clazz); return new PlainDescriptor(clazz, parent, serializableClass.getFields(), SC_SERIALIZABLE | (serializableClass.hasWriteObject() ? SC_WRITE_METHOD : 0)); } else { return new NoDataDescriptor(clazz, null); } } } jboss-marshalling-1.1.3.GA/serial/pom.xml0000644000175000017500000000246711200351743020160 0ustar twernertwerner 4.0.0 org.jboss.marshalling serial jar 1.1.3.GA org.jboss.marshalling marshalling-api 1.1.3.GA org.apache.maven.plugins maven-compiler-plugin 2.0.2 1.5 1.5 serial repository.jboss.org JBoss Maven2 Repository ${repository.url} jboss-marshalling-1.1.3.GA/river/0000755000175000017500000000000011253762300016505 5ustar twernertwernerjboss-marshalling-1.1.3.GA/river/src/0000755000175000017500000000000011253762277017311 5ustar twernertwernerjboss-marshalling-1.1.3.GA/river/src/test/0000755000175000017500000000000011253762277020270 5ustar twernertwernerjboss-marshalling-1.1.3.GA/river/src/test/java/0000755000175000017500000000000011253762277021211 5ustar twernertwernerjboss-marshalling-1.1.3.GA/river/src/test/java/org/0000755000175000017500000000000011253762277022000 5ustar twernertwernerjboss-marshalling-1.1.3.GA/river/src/test/java/org/jboss/0000755000175000017500000000000011253762277023120 5ustar twernertwernerjboss-marshalling-1.1.3.GA/river/src/test/java/org/jboss/marshalling/0000755000175000017500000000000011253762277025421 5ustar twernertwernerjboss-marshalling-1.1.3.GA/river/src/test/java/org/jboss/marshalling/river/0000755000175000017500000000000011253762277026550 5ustar twernertwernerjboss-marshalling-1.1.3.GA/river/src/test/java/org/jboss/marshalling/river/ReadWriteTest.java0000644000175000017500000000500311140106724032117 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; import org.jboss.marshalling.MarshallerFactory; import org.jboss.marshalling.Marshaller; import org.jboss.marshalling.Marshalling; import org.jboss.marshalling.Unmarshaller; import org.jboss.marshalling.reflect.SunReflectiveCreator; import org.jboss.marshalling.MarshallingConfiguration; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; /** * */ public abstract class ReadWriteTest { public void run() throws Throwable { final MarshallerFactory factory = new RiverMarshallerFactory(); final MarshallingConfiguration configuration = new MarshallingConfiguration(); configuration.setCreator(new SunReflectiveCreator()); configure(configuration); final Marshaller marshaller = factory.createMarshaller(configuration); final ByteArrayOutputStream baos = new ByteArrayOutputStream(10240); marshaller.start(Marshalling.createByteOutput(baos)); runWrite(marshaller); marshaller.finish(); final byte[] bytes = baos.toByteArray(); final Unmarshaller unmarshaller = factory.createUnmarshaller(configuration); unmarshaller.start(Marshalling.createByteInput(new ByteArrayInputStream(bytes))); runRead(unmarshaller); unmarshaller.finish(); } public void configure(MarshallingConfiguration configuration) throws Throwable {} public void runWrite(Marshaller marshaller) throws Throwable {}; public void runRead(Unmarshaller unmarshaller) throws Throwable {}; } jboss-marshalling-1.1.3.GA/river/src/main/0000755000175000017500000000000011253762300020220 5ustar twernertwernerjboss-marshalling-1.1.3.GA/river/src/main/resources/0000755000175000017500000000000011253762300022232 5ustar twernertwernerjboss-marshalling-1.1.3.GA/river/src/main/resources/META-INF/0000755000175000017500000000000011253762300023372 5ustar twernertwernerjboss-marshalling-1.1.3.GA/river/src/main/resources/META-INF/jboss-classloading.xml0000644000175000017500000000052311140107601027665 0ustar twernertwerner jboss-marshalling-1.1.3.GA/river/src/main/java/0000755000175000017500000000000011253762277021156 5ustar twernertwernerjboss-marshalling-1.1.3.GA/river/src/main/java/org/0000755000175000017500000000000011253762277021745 5ustar twernertwernerjboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/0000755000175000017500000000000011253762277023065 5ustar twernertwernerjboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/0000755000175000017500000000000011253762277025366 5ustar twernertwernerjboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/0000755000175000017500000000000011253762300026500 5ustar twernertwernerjboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/Protocol.java0000644000175000017500000001236111145414170031146 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; /** * */ public final class Protocol { public static final int MAX_VERSION = 1; public static final int ID_NULL_OBJECT = 0x01; public static final int ID_REPEAT_OBJECT = 0x02; public static final int ID_PREDEFINED_OBJECT = 0x03; public static final int ID_NEW_OBJECT = 0x04; public static final int ID_NEW_OBJECT_UNSHARED = 0x05; public static final int ID_REPEAT_CLASS = 0x06; public static final int ID_PLAIN_CLASS = 0x07; public static final int ID_PROXY_CLASS = 0x08; // Proxy.isProxy(?) == true public static final int ID_SERIALIZABLE_CLASS = 0x09; // ? extends Serializable.class public static final int ID_EXTERNALIZABLE_CLASS = 0x0a; // ? extends Externalizable.class public static final int ID_EXTERNALIZER_CLASS = 0x0b; public static final int ID_ENUM_TYPE_CLASS = 0x0c; // ? extends Enum.class public static final int ID_OBJECT_ARRAY_TYPE_CLASS = 0x0d; // ? extends Object[].class public static final int ID_PREDEFINED_PLAIN_CLASS = 0x0e; public static final int ID_PREDEFINED_PROXY_CLASS = 0x0f; public static final int ID_PREDEFINED_SERIALIZABLE_CLASS = 0x10; public static final int ID_PREDEFINED_EXTERNALIZABLE_CLASS = 0x11; public static final int ID_PREDEFINED_EXTERNALIZER_CLASS = 0x12; public static final int ID_PREDEFINED_ENUM_TYPE_CLASS = 0x13; // the following are never cached public static final int ID_STRING_CLASS = 0x14; // String.class public static final int ID_CLASS_CLASS = 0x15; // Class.class public static final int ID_OBJECT_CLASS = 0x16; // Object.class public static final int ID_ENUM_CLASS = 0x17; // Enum.class public static final int ID_BOOLEAN_ARRAY_CLASS = 0x18; // boolean[].class public static final int ID_BYTE_ARRAY_CLASS = 0x19; // ..etc.. public static final int ID_SHORT_ARRAY_CLASS = 0x1a; public static final int ID_INT_ARRAY_CLASS = 0x1b; public static final int ID_LONG_ARRAY_CLASS = 0x1c; public static final int ID_CHAR_ARRAY_CLASS = 0x1d; public static final int ID_FLOAT_ARRAY_CLASS = 0x1e; public static final int ID_DOUBLE_ARRAY_CLASS = 0x1f; public static final int ID_PRIM_BOOLEAN = 0x20; // boolean.class public static final int ID_PRIM_BYTE = 0x21; // ..etc.. public static final int ID_PRIM_SHORT = 0x22; public static final int ID_PRIM_INT = 0x23; public static final int ID_PRIM_LONG = 0x24; public static final int ID_PRIM_CHAR = 0x25; public static final int ID_PRIM_FLOAT = 0x26; public static final int ID_PRIM_DOUBLE = 0x27; public static final int ID_VOID = 0x28; // void.class public static final int ID_BOOLEAN_CLASS = 0x29; // Boolean.class public static final int ID_BYTE_CLASS = 0x2a; // ..etc.. public static final int ID_SHORT_CLASS = 0x2b; public static final int ID_INTEGER_CLASS = 0x2c; public static final int ID_LONG_CLASS = 0x2d; public static final int ID_CHARACTER_CLASS = 0x2e; public static final int ID_FLOAT_CLASS = 0x2f; public static final int ID_DOUBLE_CLASS = 0x30; public static final int ID_VOID_CLASS = 0x31; // Void.class // protocol version >= 1 public static final int ID_START_BLOCK_SMALL = 0x32; // 8 bit size public static final int ID_START_BLOCK_MEDIUM = 0x33; // 16 bit size public static final int ID_START_BLOCK_LARGE = 0x34; // 32 bit size public static final int ID_END_BLOCK_DATA = 0x35; public static final int ID_CLEAR_CLASS_CACHE = 0x36; // implies CLEAR_ISNTANCE_CACHE public static final int ID_CLEAR_INSTANCE_CACHE = 0x37; public static final int ID_WRITE_OBJECT_CLASS = 0x38; // ? extends Serializable.class, plus writeObject method private Protocol() { } } jboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/RiverUnmarshaller.java0000644000175000017500000012535711201063575033026 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; import org.jboss.marshalling.AbstractUnmarshaller; import org.jboss.marshalling.UTFUtils; import org.jboss.marshalling.reflect.SerializableClass; import org.jboss.marshalling.reflect.SerializableClassRegistry; import org.jboss.marshalling.reflect.SerializableField; import org.jboss.marshalling.Externalizer; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.Creator; import org.jboss.marshalling.MarshallerObjectInput; import java.util.ArrayList; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.Collections; import java.util.HashSet; import java.io.IOException; import java.io.StreamCorruptedException; import java.io.InvalidObjectException; import java.io.InvalidClassException; import java.io.Externalizable; import java.io.NotSerializableException; import java.io.ObjectInput; import java.io.ObjectInputValidation; import java.io.Serializable; import java.lang.reflect.Proxy; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; import java.security.PrivilegedActionException; /** * */ public class RiverUnmarshaller extends AbstractUnmarshaller { private final ArrayList instanceCache; private final ArrayList classCache; private final SerializableClassRegistry registry; private ObjectInput objectInput; private int version; private int depth; private BlockUnmarshaller blockUnmarshaller; private RiverObjectInputStream objectInputStream; private final SortedMap> validationMap = new TreeMap>(Collections.reverseOrder()); private static final Field proxyInvocationHandler; static { proxyInvocationHandler = AccessController.doPrivileged(new PrivilegedAction() { public Field run() { try { final Field field = Proxy.class.getDeclaredField("h"); field.setAccessible(true); return field; } catch (NoSuchFieldException e) { throw new NoSuchFieldError(e.getMessage()); } } }); } protected RiverUnmarshaller(final RiverMarshallerFactory marshallerFactory, final SerializableClassRegistry registry, final MarshallingConfiguration configuration) { super(marshallerFactory, configuration); this.registry = registry; instanceCache = new ArrayList(configuration.getInstanceCount()); classCache = new ArrayList(configuration.getClassCount()); } public void clearInstanceCache() throws IOException { instanceCache.clear(); } public void clearClassCache() throws IOException { clearInstanceCache(); classCache.clear(); } public void close() throws IOException { finish(); } public void finish() throws IOException { super.finish(); blockUnmarshaller = null; objectInput = null; objectInputStream = null; } private ObjectInput getObjectInput() { final ObjectInput objectInput = this.objectInput; return objectInput == null ? (this.objectInput = (version > 0 ? getBlockUnmarshaller() : new MarshallerObjectInput(this))) : objectInput; } private BlockUnmarshaller getBlockUnmarshaller() { final BlockUnmarshaller blockUnmarshaller = this.blockUnmarshaller; return blockUnmarshaller == null ? this.blockUnmarshaller = new BlockUnmarshaller(this) : blockUnmarshaller; } private final PrivilegedExceptionAction createObjectInputStreamAction = new PrivilegedExceptionAction() { public RiverObjectInputStream run() throws IOException { return new RiverObjectInputStream(RiverUnmarshaller.this, version > 0 ? getBlockUnmarshaller() : RiverUnmarshaller.this); } }; private RiverObjectInputStream getObjectInputStream() throws IOException { final RiverObjectInputStream objectInputStream = this.objectInputStream; return objectInputStream == null ? this.objectInputStream = createObjectInputStream() : objectInputStream; } private RiverObjectInputStream createObjectInputStream() throws IOException { try { return AccessController.doPrivileged(createObjectInputStreamAction); } catch (PrivilegedActionException e) { throw (IOException) e.getCause(); } } protected Object doReadObject(final boolean unshared) throws ClassNotFoundException, IOException { final Object obj = doReadObject(readUnsignedByte(), unshared); if (depth == 0) try { for (Set validations : validationMap.values()) { for (ObjectInputValidation validation : validations) { validation.validateObject(); } } } finally { validationMap.clear(); } return obj; } Object doReadObject(int leadByte, final boolean unshared) throws IOException, ClassNotFoundException { depth ++; try { for (;;) switch (leadByte) { case Protocol.ID_NULL_OBJECT: { return null; } case Protocol.ID_REPEAT_OBJECT: { if (unshared) { throw new InvalidObjectException("Attempt to read a backreference as unshared"); } try { final Object obj = instanceCache.get(readInt()); if (obj != null) return obj; } catch (IndexOutOfBoundsException e) { } throw new InvalidObjectException("Attempt to read a backreference with an invalid ID"); } case Protocol.ID_NEW_OBJECT: case Protocol.ID_NEW_OBJECT_UNSHARED: { if (unshared != (leadByte == Protocol.ID_NEW_OBJECT_UNSHARED)) { throw new InvalidObjectException("Shared/unshared object mismatch"); } return doReadNewObject(readUnsignedByte(), unshared); } case Protocol.ID_PREDEFINED_OBJECT: { if (unshared) { throw new InvalidObjectException("Attempt to read a predefined object as unshared"); } if (version == 1) { final BlockUnmarshaller blockUnmarshaller = getBlockUnmarshaller(); final Object obj = objectTable.readObject(blockUnmarshaller); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); return obj; } else { return objectTable.readObject(this); } } case Protocol.ID_CLEAR_CLASS_CACHE: { if (depth > 1) { throw new StreamCorruptedException("ID_CLEAR_CLASS_CACHE token in the middle of stream processing"); } classCache.clear(); instanceCache.clear(); leadByte = readUnsignedByte(); continue; } case Protocol.ID_CLEAR_INSTANCE_CACHE: { if (depth > 1) { throw new StreamCorruptedException("ID_CLEAR_INSTANCE_CACHE token in the middle of stream processing"); } instanceCache.clear(); continue; } default: { throw new StreamCorruptedException("Unexpected byte found when reading an object: " + leadByte); } } } finally { depth --; } } ClassDescriptor doReadClassDescriptor(final int classType) throws IOException, ClassNotFoundException { final ArrayList classCache = this.classCache; switch (classType) { case Protocol.ID_REPEAT_CLASS: { return classCache.get(readInt()); } case Protocol.ID_PREDEFINED_ENUM_TYPE_CLASS: { final int idx = classCache.size(); classCache.add(null); final Class type = readClassTableClass(); final ClassDescriptor descriptor = new ClassDescriptor(type, Protocol.ID_ENUM_TYPE_CLASS); classCache.set(idx, descriptor); return descriptor; } case Protocol.ID_PREDEFINED_EXTERNALIZABLE_CLASS: { final int idx = classCache.size(); classCache.add(null); final Class type = readClassTableClass(); final ClassDescriptor descriptor = new ClassDescriptor(type, Protocol.ID_EXTERNALIZABLE_CLASS); classCache.set(idx, descriptor); return descriptor; } case Protocol.ID_PREDEFINED_EXTERNALIZER_CLASS: { final int idx = classCache.size(); classCache.add(null); final Class type = readClassTableClass(); final Externalizer externalizer = (Externalizer) readObject(); final ClassDescriptor descriptor = new ExternalizerClassDescriptor(type, externalizer); classCache.set(idx, descriptor); return descriptor; } case Protocol.ID_PREDEFINED_PLAIN_CLASS: { final int idx = classCache.size(); classCache.add(null); final Class type = readClassTableClass(); final ClassDescriptor descriptor = new ClassDescriptor(type, Protocol.ID_PLAIN_CLASS); classCache.set(idx, descriptor); return descriptor; } case Protocol.ID_PREDEFINED_PROXY_CLASS: { final int idx = classCache.size(); classCache.add(null); final Class type = readClassTableClass(); final ClassDescriptor descriptor = new ClassDescriptor(type, Protocol.ID_PROXY_CLASS); classCache.set(idx, descriptor); return descriptor; } case Protocol.ID_PREDEFINED_SERIALIZABLE_CLASS: { final int idx = classCache.size(); classCache.add(null); final Class type = readClassTableClass(); final SerializableClass serializableClass = registry.lookup(type); int descType = version > 0 && serializableClass.hasWriteObject() ? Protocol.ID_WRITE_OBJECT_CLASS : Protocol.ID_SERIALIZABLE_CLASS; final ClassDescriptor descriptor = new SerializableClassDescriptor(serializableClass, doReadClassDescriptor(readUnsignedByte()), serializableClass.getFields(), descType); classCache.set(idx, descriptor); return descriptor; } case Protocol.ID_PLAIN_CLASS: { final String className = readString(); final Class clazz = doResolveClass(className, 0L); final ClassDescriptor descriptor = new ClassDescriptor(clazz, Protocol.ID_PLAIN_CLASS); classCache.add(descriptor); return descriptor; } case Protocol.ID_PROXY_CLASS: { String[] interfaces = new String[readInt()]; for (int i = 0; i < interfaces.length; i ++) { interfaces[i] = readString(); } final ClassDescriptor descriptor; if (version == 1) { final BlockUnmarshaller blockUnmarshaller = getBlockUnmarshaller(); descriptor = new ClassDescriptor(classResolver.resolveProxyClass(blockUnmarshaller, interfaces), Protocol.ID_PROXY_CLASS); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); } else { descriptor = new ClassDescriptor(classResolver.resolveProxyClass(this, interfaces), Protocol.ID_PROXY_CLASS); } classCache.add(descriptor); return descriptor; } case Protocol.ID_WRITE_OBJECT_CLASS: case Protocol.ID_SERIALIZABLE_CLASS: { int idx = classCache.size(); classCache.add(null); final String className = readString(); final long uid = readLong(); final Class clazz = doResolveClass(className, uid); final Class superClazz = clazz.getSuperclass(); classCache.set(idx, new IncompleteClassDescriptor(clazz, classType)); final int cnt = readInt(); final String[] names = new String[cnt]; final ClassDescriptor[] descriptors = new ClassDescriptor[cnt]; final boolean[] unshareds = new boolean[cnt]; for (int i = 0; i < cnt; i ++) { names[i] = readUTF(); descriptors[i] = doReadClassDescriptor(readUnsignedByte()); unshareds[i] = readBoolean(); } ClassDescriptor superDescriptor = doReadClassDescriptor(readUnsignedByte()); if (superDescriptor != null) { final Class superType = superDescriptor.getType(); if (! superType.isAssignableFrom(clazz)) { throw new InvalidClassException(clazz.getName(), "Class does not extend stream superclass"); } Class cl = superClazz; while (cl != superType) { superDescriptor = new SerializableClassDescriptor(registry.lookup(cl), superDescriptor); cl = cl.getSuperclass(); } } else if (superClazz != null) { Class cl = superClazz; while (Serializable.class.isAssignableFrom(cl)) { superDescriptor = new SerializableClassDescriptor(registry.lookup(cl), superDescriptor); cl = cl.getSuperclass(); } } final SerializableClass serializableClass = registry.lookup(clazz); final SerializableField[] fields = new SerializableField[cnt]; for (int i = 0; i < cnt; i ++) { fields[i] = serializableClass.getSerializableField(names[i], descriptors[i].getType(), unshareds[i]); } final ClassDescriptor descriptor = new SerializableClassDescriptor(serializableClass, superDescriptor, fields, classType); classCache.set(idx, descriptor); return descriptor; } case Protocol.ID_EXTERNALIZABLE_CLASS: { final String className = readString(); final long uid = readLong(); final Class clazz = doResolveClass(className, uid); final ClassDescriptor descriptor = new ClassDescriptor(clazz, Protocol.ID_EXTERNALIZABLE_CLASS); classCache.add(descriptor); return descriptor; } case Protocol.ID_EXTERNALIZER_CLASS: { final String className = readString(); int idx = classCache.size(); classCache.add(null); final Class clazz = doResolveClass(className, 0L); final Externalizer externalizer = (Externalizer) readObject(); final ClassDescriptor descriptor = new ExternalizerClassDescriptor(clazz, externalizer); classCache.set(idx, descriptor); return descriptor; } case Protocol.ID_ENUM_TYPE_CLASS: { final ClassDescriptor descriptor = new ClassDescriptor(doResolveClass(readString(), 0L), Protocol.ID_ENUM_TYPE_CLASS); classCache.add(descriptor); return descriptor; } case Protocol.ID_OBJECT_ARRAY_TYPE_CLASS: { final ClassDescriptor elementType = doReadClassDescriptor(readUnsignedByte()); final ClassDescriptor arrayDescriptor = new ClassDescriptor(Array.newInstance(elementType.getType(), 0).getClass(), Protocol.ID_OBJECT_ARRAY_TYPE_CLASS); classCache.add(arrayDescriptor); return arrayDescriptor; } case Protocol.ID_STRING_CLASS: { return ClassDescriptor.STRING_DESCRIPTOR; } case Protocol.ID_OBJECT_CLASS: { return ClassDescriptor.OBJECT_DESCRIPTOR; } case Protocol.ID_CLASS_CLASS: { return ClassDescriptor.CLASS_DESCRIPTOR; } case Protocol.ID_ENUM_CLASS: { return ClassDescriptor.ENUM_DESCRIPTOR; } case Protocol.ID_BOOLEAN_ARRAY_CLASS: { return ClassDescriptor.BOOLEAN_ARRAY; } case Protocol.ID_BYTE_ARRAY_CLASS: { return ClassDescriptor.BYTE_ARRAY; } case Protocol.ID_SHORT_ARRAY_CLASS: { return ClassDescriptor.SHORT_ARRAY; } case Protocol.ID_INT_ARRAY_CLASS: { return ClassDescriptor.INT_ARRAY; } case Protocol.ID_LONG_ARRAY_CLASS: { return ClassDescriptor.LONG_ARRAY; } case Protocol.ID_CHAR_ARRAY_CLASS: { return ClassDescriptor.CHAR_ARRAY; } case Protocol.ID_FLOAT_ARRAY_CLASS: { return ClassDescriptor.FLOAT_ARRAY; } case Protocol.ID_DOUBLE_ARRAY_CLASS: { return ClassDescriptor.DOUBLE_ARRAY; } case Protocol.ID_PRIM_BOOLEAN: { return ClassDescriptor.BOOLEAN; } case Protocol.ID_PRIM_BYTE: { return ClassDescriptor.BYTE; } case Protocol.ID_PRIM_CHAR: { return ClassDescriptor.CHAR; } case Protocol.ID_PRIM_DOUBLE: { return ClassDescriptor.DOUBLE; } case Protocol.ID_PRIM_FLOAT: { return ClassDescriptor.FLOAT; } case Protocol.ID_PRIM_INT: { return ClassDescriptor.INT; } case Protocol.ID_PRIM_LONG: { return ClassDescriptor.LONG; } case Protocol.ID_PRIM_SHORT: { return ClassDescriptor.SHORT; } case Protocol.ID_VOID: { return ClassDescriptor.VOID; } case Protocol.ID_BOOLEAN_CLASS: { return ClassDescriptor.BOOLEAN_OBJ; } case Protocol.ID_BYTE_CLASS: { return ClassDescriptor.BYTE_OBJ; } case Protocol.ID_SHORT_CLASS: { return ClassDescriptor.SHORT_OBJ; } case Protocol.ID_INTEGER_CLASS: { return ClassDescriptor.INTEGER_OBJ; } case Protocol.ID_LONG_CLASS: { return ClassDescriptor.LONG_OBJ; } case Protocol.ID_CHARACTER_CLASS: { return ClassDescriptor.CHARACTER_OBJ; } case Protocol.ID_FLOAT_CLASS: { return ClassDescriptor.FLOAT_OBJ; } case Protocol.ID_DOUBLE_CLASS: { return ClassDescriptor.DOUBLE_OBJ; } case Protocol.ID_VOID_CLASS: { return ClassDescriptor.VOID_OBJ; } default: { throw new InvalidClassException("Unexpected class ID " + classType); } } } private Class readClassTableClass() throws IOException, ClassNotFoundException { if (version == 1) { final BlockUnmarshaller blockUnmarshaller = getBlockUnmarshaller(); final Class type = classTable.readClass(blockUnmarshaller); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); return type; } else { return classTable.readClass(this); } } private Class doResolveClass(final String className, final long uid) throws IOException, ClassNotFoundException { if (version == 1) { final BlockUnmarshaller blockUnmarshaller = getBlockUnmarshaller(); final Class resolvedClass = classResolver.resolveClass(blockUnmarshaller, className, uid); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); return resolvedClass; } else { return classResolver.resolveClass(this, className, uid); } } protected String readString() throws IOException { final int length = readInt(); return UTFUtils.readUTFBytes(this, length); } private static final class DummyInvocationHandler implements InvocationHandler { public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { throw new NoSuchMethodError("Invocation handler not yet loaded"); } } protected void doStart() throws IOException { super.doStart(); if (configuredVersion > 0) { int version = readUnsignedByte(); if (version > Protocol.MAX_VERSION) { throw new IOException("Unsupported protocol version " + version); } this.version = version; } else { version = 0; } } private static final InvocationHandler DUMMY_HANDLER = new DummyInvocationHandler(); private static Object createProxyInstance(Creator creator, Class type) throws IOException { try { return creator.create(type); } catch (Exception e) { return Proxy.newProxyInstance(type.getClassLoader(), type.getInterfaces(), DUMMY_HANDLER); } } protected Object doReadNewObject(final int streamClassType, final boolean unshared) throws ClassNotFoundException, IOException { final ClassDescriptor descriptor = doReadClassDescriptor(streamClassType); final int classType = descriptor.getTypeID(); switch (classType) { case Protocol.ID_PROXY_CLASS: { final Class type = descriptor.getType(); final Object obj = createProxyInstance(creator, type); final int idx = instanceCache.size(); instanceCache.add(obj); try { proxyInvocationHandler.set(obj, doReadObject(unshared)); } catch (IllegalAccessException e) { throw new InvalidClassException(type.getName(), "Unable to set proxy invocation handler"); } final Object resolvedObject = objectResolver.readResolve(obj); if (unshared) { instanceCache.set(idx, null); } else if (obj != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case Protocol.ID_WRITE_OBJECT_CLASS: case Protocol.ID_SERIALIZABLE_CLASS: { final SerializableClassDescriptor serializableClassDescriptor = (SerializableClassDescriptor) descriptor; final Class type = descriptor.getType(); final SerializableClass serializableClass = serializableClassDescriptor.getSerializableClass(); final Object obj = creator.create(type); final int idx = instanceCache.size(); instanceCache.add(obj); doInitSerializable(obj, serializableClassDescriptor); final Object resolvedObject = objectResolver.readResolve(serializableClass.hasReadResolve() ? serializableClass.callReadResolve(obj) : obj); if (unshared) { instanceCache.set(idx, null); } else if (obj != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case Protocol.ID_EXTERNALIZABLE_CLASS: { final Class type = descriptor.getType(); final SerializableClass serializableClass = registry.lookup(type); final Externalizable obj = (Externalizable) creator.create(type); final int idx = instanceCache.size(); instanceCache.add(obj); if (version > 0) { final BlockUnmarshaller blockUnmarshaller = getBlockUnmarshaller(); obj.readExternal(blockUnmarshaller); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); } else { obj.readExternal(getObjectInput()); } final Object resolvedObject = objectResolver.readResolve(serializableClass.hasReadResolve() ? serializableClass.callReadResolve(obj) : obj); if (unshared) { instanceCache.set(idx, null); } else if (obj != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case Protocol.ID_EXTERNALIZER_CLASS: { final int idx = instanceCache.size(); instanceCache.add(null); Externalizer externalizer = ((ExternalizerClassDescriptor) descriptor).getExternalizer(); final Class type = descriptor.getType(); final SerializableClass serializableClass = registry.lookup(type); final Object obj; if (version > 0) { final BlockUnmarshaller blockUnmarshaller = getBlockUnmarshaller(); obj = externalizer.createExternal(type, blockUnmarshaller, creator); instanceCache.set(idx, obj); externalizer.readExternal(obj, blockUnmarshaller); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); } else { obj = externalizer.createExternal(type, this, creator); instanceCache.set(idx, obj); externalizer.readExternal(obj, getObjectInput()); } final Object resolvedObject = objectResolver.readResolve(serializableClass.hasReadResolve() ? serializableClass.callReadResolve(obj) : obj); if (unshared) { instanceCache.set(idx, null); } else if (obj != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case Protocol.ID_ENUM_TYPE_CLASS: { final String name = readString(); final Enum obj = resolveEnumConstant(descriptor, name); final int idx = instanceCache.size(); instanceCache.add(obj); final Object resolvedObject = objectResolver.readResolve(obj); if (unshared) { instanceCache.set(idx, null); } else if (obj != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case Protocol.ID_OBJECT_ARRAY_TYPE_CLASS: { final int cnt = readInt(); final Object[] array = (Object[]) Array.newInstance(descriptor.getType().getComponentType(), cnt); final int idx = instanceCache.size(); instanceCache.add(array); for (int i = 0; i < cnt; i ++) { array[i] = doReadObject(unshared); } final Object resolvedObject = objectResolver.readResolve(array); if (unshared) { instanceCache.set(idx, null); } else if (array != resolvedObject) { instanceCache.set(idx, resolvedObject); } return resolvedObject; } case Protocol.ID_STRING_CLASS: { final String obj = readString(); final Object resolvedObject = objectResolver.readResolve(obj); if (unshared) { instanceCache.add(null); } else { instanceCache.add(resolvedObject); } return resolvedObject; } case Protocol.ID_CLASS_CLASS: { final ClassDescriptor nestedDescriptor = doReadClassDescriptor(readUnsignedByte()); // Classes are not resolved and may not be unshared! final Class obj = nestedDescriptor.getType(); return obj; } case Protocol.ID_BOOLEAN_ARRAY_CLASS: { final int cnt = readInt(); final boolean[] array = new boolean[cnt]; int v = 0; int bc = cnt & ~7; for (int i = 0; i < bc; ) { v = readByte(); array[i++] = (v & 1) != 0; array[i++] = (v & 2) != 0; array[i++] = (v & 4) != 0; array[i++] = (v & 8) != 0; array[i++] = (v & 16) != 0; array[i++] = (v & 32) != 0; array[i++] = (v & 64) != 0; array[i++] = (v & 128) != 0; } if (bc < cnt) { v = readUnsignedByte(); int bit = 1; for (int i = bc; i < cnt; i ++) { array[i] = (v & bit) != 0; bit <<= 1; } } final Object resolvedObject = objectResolver.readResolve(array); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } case Protocol.ID_BYTE_ARRAY_CLASS: { final int cnt = readInt(); final byte[] array = new byte[cnt]; readFully(array, 0, array.length); final Object resolvedObject = objectResolver.readResolve(array); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } case Protocol.ID_SHORT_ARRAY_CLASS: { final int cnt = readInt(); final short[] array = new short[cnt]; for (int i = 0; i < cnt; i ++) { array[i] = readShort(); } final Object resolvedObject = objectResolver.readResolve(array); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } case Protocol.ID_INT_ARRAY_CLASS: { final int cnt = readInt(); final int[] array = new int[cnt]; for (int i = 0; i < cnt; i ++) { array[i] = readInt(); } final Object resolvedObject = objectResolver.readResolve(array); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } case Protocol.ID_LONG_ARRAY_CLASS: { final int cnt = readInt(); final long[] array = new long[cnt]; for (int i = 0; i < cnt; i ++) { array[i] = readLong(); } final Object resolvedObject = objectResolver.readResolve(array); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } case Protocol.ID_CHAR_ARRAY_CLASS: { final int cnt = readInt(); final char[] array = new char[cnt]; for (int i = 0; i < cnt; i ++) { array[i] = readChar(); } final Object resolvedObject = objectResolver.readResolve(array); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } case Protocol.ID_FLOAT_ARRAY_CLASS: { final int cnt = readInt(); final float[] array = new float[cnt]; for (int i = 0; i < cnt; i ++) { array[i] = readFloat(); } final Object resolvedObject = objectResolver.readResolve(array); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } case Protocol.ID_DOUBLE_ARRAY_CLASS: { final int cnt = readInt(); final double[] array = new double[cnt]; for (int i = 0; i < cnt; i ++) { array[i] = readDouble(); } final Object resolvedObject = objectResolver.readResolve(array); instanceCache.add(unshared ? null : resolvedObject); return resolvedObject; } case Protocol.ID_BOOLEAN_CLASS: { return objectResolver.readResolve(Boolean.valueOf(readBoolean())); } case Protocol.ID_BYTE_CLASS: { return objectResolver.readResolve(Byte.valueOf(readByte())); } case Protocol.ID_SHORT_CLASS: { return objectResolver.readResolve(Short.valueOf(readShort())); } case Protocol.ID_INTEGER_CLASS: { return objectResolver.readResolve(Integer.valueOf(readInt())); } case Protocol.ID_LONG_CLASS: { return objectResolver.readResolve(Long.valueOf(readLong())); } case Protocol.ID_CHARACTER_CLASS: { return objectResolver.readResolve(Character.valueOf(readChar())); } case Protocol.ID_FLOAT_CLASS: { return objectResolver.readResolve(Float.valueOf(readFloat())); } case Protocol.ID_DOUBLE_CLASS: { return objectResolver.readResolve(Double.valueOf(readDouble())); } case Protocol.ID_OBJECT_CLASS: case Protocol.ID_PLAIN_CLASS: { throw new NotSerializableException("(remote)" + descriptor.getType().getName()); } default: { throw new InvalidObjectException("Unexpected class type " + classType); } } } @SuppressWarnings({"unchecked"}) private static Enum resolveEnumConstant(final ClassDescriptor descriptor, final String name) { return Enum.valueOf((Class)descriptor.getType(), name); } private void doInitSerializable(final Object obj, final SerializableClassDescriptor descriptor) throws IOException, ClassNotFoundException { final Class type = descriptor.getType(); final SerializableClass info = registry.lookup(type); final ClassDescriptor superDescriptor = descriptor.getSuperClassDescriptor(); if (superDescriptor instanceof SerializableClassDescriptor) { final SerializableClassDescriptor serializableSuperDescriptor = (SerializableClassDescriptor) superDescriptor; doInitSerializable(obj, serializableSuperDescriptor); } final int typeId = descriptor.getTypeID(); if (descriptor.isGap()) { if (info.hasReadObjectNoData()) { info.callReadObjectNoData(obj); } } else if (info.hasReadObject()) { final RiverObjectInputStream objectInputStream = getObjectInputStream(); final SerializableClassDescriptor oldDescriptor = objectInputStream.swapClass(descriptor); final Object oldObj = objectInputStream.swapCurrent(obj); final RiverObjectInputStream.State restoreState = objectInputStream.start(); boolean ok = false; try { if (typeId == Protocol.ID_WRITE_OBJECT_CLASS) { // protocol version >= 1; read fields info.callReadObject(obj, objectInputStream); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); } else if (version >= 1) { // protocol version >= 1 but no fields to read blockUnmarshaller.endOfStream(); info.callReadObject(obj, objectInputStream); blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); } else { // protocol version 0 info.callReadObject(obj, objectInputStream); } objectInputStream.finish(restoreState); objectInputStream.swapCurrent(oldObj); objectInputStream.swapClass(oldDescriptor); ok = true; } finally { if (! ok) { objectInputStream.fullReset(); } } } else { readFields(obj, descriptor); if (typeId == Protocol.ID_WRITE_OBJECT_CLASS) { // protocol version >= 1 with useless user data blockUnmarshaller.readToEndBlockData(); blockUnmarshaller.unblock(); } } } protected void readFields(final Object obj, final SerializableClassDescriptor descriptor) throws IOException, ClassNotFoundException { for (SerializableField serializableField : descriptor.getFields()) { final Field field = serializableField.getField(); if (field == null) { // missing; consume stream data only switch (serializableField.getKind()) { case BOOLEAN: { readBoolean(); break; } case BYTE: { readByte(); break; } case CHAR: { readChar(); break; } case DOUBLE: { readDouble(); break; } case FLOAT: { readFloat(); break; } case INT: { readInt(); break; } case LONG: { readLong(); break; } case OBJECT: { if (serializableField.isUnshared()) { readObjectUnshared(); } else { readObject(); } break; } case SHORT: { readShort(); break; } } } else try { switch (serializableField.getKind()) { case BOOLEAN: { field.setBoolean(obj, readBoolean()); break; } case BYTE: { field.setByte(obj, readByte()); break; } case CHAR: { field.setChar(obj, readChar()); break; } case DOUBLE: { field.setDouble(obj, readDouble()); break; } case FLOAT: { field.setFloat(obj, readFloat()); break; } case INT: { field.setInt(obj, readInt()); break; } case LONG: { field.setLong(obj, readLong()); break; } case OBJECT: { final Object robj; if (serializableField.isUnshared()) { robj = readObjectUnshared(); } else { robj = readObject(); } field.set(obj, robj); break; } case SHORT: { field.setShort(obj, readShort()); break; } } } catch (IllegalAccessException e) { final InvalidObjectException ioe = new InvalidObjectException("Unable to set a field"); ioe.initCause(e); throw ioe; } } } void addValidation(final ObjectInputValidation validation, final int prio) { final Set validations; final Integer prioKey = Integer.valueOf(prio); if (validationMap.containsKey(prioKey)) { validations = validationMap.get(prioKey); } else { validations = new HashSet(); validationMap.put(prioKey, validations); } validations.add(validation); } public String readUTF() throws IOException { final int len = readInt(); return UTFUtils.readUTFBytes(this, len); } } jboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/BlockUnmarshaller.java0000644000175000017500000002556111145414170032763 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; import org.jboss.marshalling.Unmarshaller; import org.jboss.marshalling.ByteInput; import org.jboss.marshalling.Marshalling; import org.jboss.marshalling.UTFUtils; import static org.jboss.marshalling.Marshalling.createOptionalDataException; import java.io.IOException; import java.io.StreamCorruptedException; import java.io.EOFException; /** * */ public final class BlockUnmarshaller implements Unmarshaller { private final RiverUnmarshaller riverUnmarshaller; private int remaining; BlockUnmarshaller(final RiverUnmarshaller riverUnmarshaller) { this.riverUnmarshaller = riverUnmarshaller; } boolean inBlock() { return remaining > 0; } int remaining() { return remaining; } void endOfStream() { if (remaining == 0) { remaining = -1; } else { throw new IllegalStateException("Not at end of block"); } } void unblock() { if (remaining == -1) { remaining = 0; } } void readBlockHeader(int leadByte) throws IOException { switch (leadByte) { case Protocol.ID_START_BLOCK_SMALL: remaining = riverUnmarshaller.readUnsignedByte(); return; case Protocol.ID_START_BLOCK_MEDIUM: remaining = riverUnmarshaller.readUnsignedShort(); return; case Protocol.ID_START_BLOCK_LARGE: final int len = riverUnmarshaller.readInt(); if (len < 0) { throw new StreamCorruptedException("Invalid block length"); } remaining = len; return; case Protocol.ID_END_BLOCK_DATA: remaining = -1; return; default: throw badLeadByte(leadByte); } } void readToEndBlockData() throws IOException, ClassNotFoundException { for (;;) { while (remaining > 0) { skipBytes(remaining); } final int b = riverUnmarshaller.read(); switch (b) { case -1: remaining = -1; return; case Protocol.ID_END_BLOCK_DATA: remaining = -1; return; case Protocol.ID_START_BLOCK_SMALL: case Protocol.ID_START_BLOCK_MEDIUM: case Protocol.ID_START_BLOCK_LARGE: readBlockHeader(b); break; default: // consume object... or whatever riverUnmarshaller.doReadObject(b, false); break; } } } private StreamCorruptedException badLeadByte(final int leadByte) { return new StreamCorruptedException("Unexpected lead byte " + leadByte); } public Object readObjectUnshared() throws ClassNotFoundException, IOException { return readObject(true); } public Object readObject() throws ClassNotFoundException, IOException { return readObject(false); } private Object readObject(boolean unshared) throws ClassNotFoundException, IOException { if (remaining > 0) { throw createOptionalDataException(remaining); } else if (remaining == -1) { throw createOptionalDataException(true); } final int leadByte = riverUnmarshaller.read(); if (leadByte == -1 || leadByte == Protocol.ID_END_BLOCK_DATA) { remaining = -1; throw createOptionalDataException(true); } return riverUnmarshaller.doReadObject(leadByte, unshared); } public int read() throws IOException { while (remaining == 0) { final int v = riverUnmarshaller.read(); if (v == -1) { return -1; } readBlockHeader(v); } if (remaining == -1) { return -1; } remaining--; return riverUnmarshaller.read(); } public int read(final byte[] b) throws IOException { return read(b, 0, b.length); } public int read(final byte[] b, final int off, final int len) throws IOException { while (remaining == 0) { final int v = riverUnmarshaller.read(); if (v == -1) { return -1; } readBlockHeader(v); } final int remaining = this.remaining; if (remaining == -1) { return -1; } final int cnt = riverUnmarshaller.read(b, off, Math.min(remaining, len)); this.remaining = remaining - cnt; return cnt; } public long skip(final long n) throws IOException { while (remaining == 0) { final int v = riverUnmarshaller.read(); if (v == -1) { return -1; } readBlockHeader(v); } final int remaining = this.remaining; if (remaining == -1) { return -1; } final int cnt = riverUnmarshaller.skipBytes((int)Math.min((long)remaining, n)); this.remaining = remaining - cnt; return cnt; } public int available() throws IOException { return Math.min(remaining, riverUnmarshaller.available()); } public void readFully(final byte[] b) throws IOException { Marshalling.readFully(this, b); } public void readFully(final byte[] b, final int off, final int len) throws IOException { Marshalling.readFully(this, b, off, len); } public int skipBytes(final int n) throws IOException { while (remaining == 0) { final int v = riverUnmarshaller.read(); if (v == -1) { return -1; } readBlockHeader(v); } final int remaining = this.remaining; if (remaining == -1) { return -1; } final int cnt = riverUnmarshaller.skipBytes(Math.min(remaining, n)); this.remaining = remaining - cnt; return cnt; } public boolean readBoolean() throws IOException { while (remaining == 0) { readBlockHeader(riverUnmarshaller.readUnsignedByte()); } if (remaining == -1) { throw new EOFException(); } remaining--; return riverUnmarshaller.readBoolean(); } public byte readByte() throws IOException { while (remaining == 0) { readBlockHeader(riverUnmarshaller.readUnsignedByte()); } if (remaining == -1) { throw new EOFException(); } remaining--; return riverUnmarshaller.readByte(); } public int readUnsignedByte() throws IOException { while (remaining == 0) { readBlockHeader(riverUnmarshaller.readUnsignedByte()); } if (remaining == -1) { throw new EOFException(); } remaining--; return riverUnmarshaller.readUnsignedByte(); } public short readShort() throws IOException { if (remaining < 2) { return (short) (readUnsignedByte() << 8 | readUnsignedByte()); } else { remaining -= 2; return riverUnmarshaller.readShort(); } } public int readUnsignedShort() throws IOException { if (remaining < 2) { return readUnsignedByte() << 8 | readUnsignedByte(); } else { remaining -= 2; return riverUnmarshaller.readUnsignedShort(); } } public char readChar() throws IOException { if (remaining < 2) { return (char) (readUnsignedByte() << 8 | readUnsignedByte()); } else { remaining -= 2; return riverUnmarshaller.readChar(); } } public int readInt() throws IOException { if (remaining < 4) { return readUnsignedByte() << 24 | readUnsignedByte() << 16 | readUnsignedByte() << 8 | readUnsignedByte(); } else { remaining -= 4; return riverUnmarshaller.readInt(); } } public long readLong() throws IOException { if (remaining < 8) { return (long) readUnsignedByte() << 56L | (long) readUnsignedByte() << 48L | (long) readUnsignedByte() << 40L | (long) readUnsignedByte() << 32L | (long) readUnsignedByte() << 24L | (long) readUnsignedByte() << 16L | (long) readUnsignedByte() << 8L | (long) readUnsignedByte(); } else { remaining -= 8; return riverUnmarshaller.readLong(); } } public float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } public double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } public String readLine() throws IOException { throw new UnsupportedOperationException("readLine() is deprecated anyway!"); } public String readUTF() throws IOException { final int len = readInt(); if (len < 0) { throw new StreamCorruptedException("Invalid string length"); } return UTFUtils.readUTFBytes(this, len); } public void clearInstanceCache() throws IOException { throw new IllegalStateException("clearInstanceCache() may not be called in this context"); } public void clearClassCache() throws IOException { throw new IllegalStateException("clearClassCache() may not be called in this context"); } public void start(final ByteInput newInput) throws IOException { throw new IllegalStateException("start() may not be called in this context"); } public void finish() throws IOException { throw new IllegalStateException("finish() may not be called in this context"); } public void close() throws IOException { throw new IllegalStateException("close() may not be called in this context"); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootjboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/RiverMarshallerFactory.javajboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/RiverMarshallerFactory.ja0000644000175000017500000000462411145414170033453 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; import org.jboss.marshalling.AbstractMarshallerFactory; import org.jboss.marshalling.Unmarshaller; import org.jboss.marshalling.Marshaller; import org.jboss.marshalling.reflect.SerializableClassRegistry; import org.jboss.marshalling.MarshallingConfiguration; import java.io.IOException; import java.security.AccessController; import java.security.PrivilegedAction; /** * The River marshaller factory implementation. */ public class RiverMarshallerFactory extends AbstractMarshallerFactory { private final SerializableClassRegistry registry; /** * Construct a new instance of a River marshaller factory. */ public RiverMarshallerFactory() { registry = AccessController.doPrivileged(new PrivilegedAction() { public SerializableClassRegistry run() { return SerializableClassRegistry.getInstance(); } }); } /** {@inheritDoc} */ public Unmarshaller createUnmarshaller(final MarshallingConfiguration configuration) throws IOException { return new RiverUnmarshaller(this, registry, configuration); } /** {@inheritDoc} */ public Marshaller createMarshaller(final MarshallingConfiguration configuration) throws IOException { return new RiverMarshaller(this, registry, configuration); } protected int getDefaultVersion() { return 1; } } jboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/ClassDescriptor.java0000644000175000017500000001130211142217125032441 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; /** * */ public class ClassDescriptor { private final Class type; private int typeID; public static final ClassDescriptor STRING_DESCRIPTOR = new ClassDescriptor(String.class, Protocol.ID_STRING_CLASS); public static final ClassDescriptor CLASS_DESCRIPTOR = new ClassDescriptor(Class.class, Protocol.ID_CLASS_CLASS); public static final ClassDescriptor OBJECT_DESCRIPTOR = new ClassDescriptor(Object.class, Protocol.ID_OBJECT_CLASS); public static final ClassDescriptor ENUM_DESCRIPTOR = new ClassDescriptor(Enum.class, Protocol.ID_ENUM_CLASS); public static final ClassDescriptor BOOLEAN = new ClassDescriptor(boolean.class, Protocol.ID_PRIM_BOOLEAN); public static final ClassDescriptor BYTE = new ClassDescriptor(byte.class, Protocol.ID_PRIM_BYTE); public static final ClassDescriptor SHORT = new ClassDescriptor(short.class, Protocol.ID_PRIM_SHORT); public static final ClassDescriptor INT = new ClassDescriptor(int.class, Protocol.ID_PRIM_INT); public static final ClassDescriptor LONG = new ClassDescriptor(long.class, Protocol.ID_PRIM_LONG); public static final ClassDescriptor CHAR = new ClassDescriptor(char.class, Protocol.ID_PRIM_CHAR); public static final ClassDescriptor FLOAT = new ClassDescriptor(float.class, Protocol.ID_PRIM_FLOAT); public static final ClassDescriptor DOUBLE = new ClassDescriptor(double.class, Protocol.ID_PRIM_DOUBLE); public static final ClassDescriptor VOID = new ClassDescriptor(void.class, Protocol.ID_VOID); public static final ClassDescriptor BOOLEAN_OBJ = new ClassDescriptor(Boolean.class, Protocol.ID_BOOLEAN_CLASS); public static final ClassDescriptor BYTE_OBJ = new ClassDescriptor(Byte.class, Protocol.ID_BYTE_CLASS); public static final ClassDescriptor SHORT_OBJ = new ClassDescriptor(Short.class, Protocol.ID_SHORT_CLASS); public static final ClassDescriptor INTEGER_OBJ = new ClassDescriptor(Integer.class, Protocol.ID_INTEGER_CLASS); public static final ClassDescriptor LONG_OBJ = new ClassDescriptor(Long.class, Protocol.ID_LONG_CLASS); public static final ClassDescriptor CHARACTER_OBJ = new ClassDescriptor(Character.class, Protocol.ID_CHARACTER_CLASS); public static final ClassDescriptor FLOAT_OBJ = new ClassDescriptor(Float.class, Protocol.ID_FLOAT_CLASS); public static final ClassDescriptor DOUBLE_OBJ = new ClassDescriptor(Double.class, Protocol.ID_DOUBLE_CLASS); public static final ClassDescriptor VOID_OBJ = new ClassDescriptor(Void.class, Protocol.ID_VOID_CLASS); public static final ClassDescriptor BOOLEAN_ARRAY = new ClassDescriptor(boolean[].class, Protocol.ID_BOOLEAN_ARRAY_CLASS); public static final ClassDescriptor BYTE_ARRAY = new ClassDescriptor(byte[].class, Protocol.ID_BYTE_ARRAY_CLASS); public static final ClassDescriptor SHORT_ARRAY = new ClassDescriptor(short[].class, Protocol.ID_SHORT_ARRAY_CLASS); public static final ClassDescriptor INT_ARRAY = new ClassDescriptor(int[].class, Protocol.ID_INT_ARRAY_CLASS); public static final ClassDescriptor LONG_ARRAY = new ClassDescriptor(long[].class, Protocol.ID_LONG_ARRAY_CLASS); public static final ClassDescriptor CHAR_ARRAY = new ClassDescriptor(char[].class, Protocol.ID_CHAR_ARRAY_CLASS); public static final ClassDescriptor FLOAT_ARRAY = new ClassDescriptor(float[].class, Protocol.ID_FLOAT_ARRAY_CLASS); public static final ClassDescriptor DOUBLE_ARRAY = new ClassDescriptor(double[].class, Protocol.ID_DOUBLE_ARRAY_CLASS); public ClassDescriptor(final Class type, final int typeID) { this.type = type; this.typeID = typeID; } public Class getType() { return type; } public int getTypeID() { return typeID; } } jboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/RiverPutField.java0000644000175000017500000000576711143062353032105 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; import java.io.ObjectOutputStream; import java.io.ObjectOutput; import java.io.IOException; import java.util.Arrays; import org.jboss.marshalling.Marshaller; import org.jboss.marshalling.util.FieldPutter; /** * */ public class RiverPutField extends ObjectOutputStream.PutField { private final FieldPutter[] fields; private final String[] names; public RiverPutField(final FieldPutter[] fields, final String[] names) { this.fields = fields; this.names = names; } private FieldPutter find(final String name) { final int pos = Arrays.binarySearch(names, name); if (pos < 0) { throw new IllegalArgumentException("No field named '" + name + "' could be found"); } return fields[pos]; } public void put(final String name, final boolean val) { find(name).setBoolean(val); } public void put(final String name, final byte val) { find(name).setByte(val); } public void put(final String name, final char val) { find(name).setChar(val); } public void put(final String name, final short val) { find(name).setShort(val); } public void put(final String name, final int val) { find(name).setInt(val); } public void put(final String name, final long val) { find(name).setLong(val); } public void put(final String name, final float val) { find(name).setFloat(val); } public void put(final String name, final double val) { find(name).setDouble(val); } public void put(final String name, final Object val) { find(name).setObject(val); } @Deprecated public final void write(final ObjectOutput out) throws IOException { throw new UnsupportedOperationException("write(ObjectOutput)"); } protected final void write(final Marshaller marshaller) throws IOException { for (FieldPutter putter : fields) { putter.write(marshaller); } } } jboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/package-info.java0000644000175000017500000000037311140106724031667 0ustar twernertwerner/** * The River protocol implementation package. Construct an instance of the {@link org.jboss.marshalling.river.RiverMarshallerFactory RiverMarshallerFactory} * class to use the River marshalling protocol. */ package org.jboss.marshalling.river; ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootjboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/RiverObjectOutputStream.javajboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/RiverObjectOutputStream.j0000644000175000017500000001577211145414170033501 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; import org.jboss.marshalling.MarshallerObjectOutputStream; import org.jboss.marshalling.Marshaller; import org.jboss.marshalling.util.BooleanFieldPutter; import org.jboss.marshalling.util.ByteFieldPutter; import org.jboss.marshalling.util.CharFieldPutter; import org.jboss.marshalling.util.DoubleFieldPutter; import org.jboss.marshalling.util.FloatFieldPutter; import org.jboss.marshalling.util.IntFieldPutter; import org.jboss.marshalling.util.LongFieldPutter; import org.jboss.marshalling.util.ShortFieldPutter; import org.jboss.marshalling.util.ObjectFieldPutter; import org.jboss.marshalling.util.FieldPutter; import org.jboss.marshalling.reflect.SerializableField; import org.jboss.marshalling.reflect.SerializableClass; import java.io.IOException; import java.io.NotActiveException; import java.util.concurrent.atomic.AtomicReference; /** * */ public class RiverObjectOutputStream extends MarshallerObjectOutputStream { protected enum State { OFF, UNWRITTEN_FIELDS, ON, ; } private final AtomicReference state = new AtomicReference(State.OFF); private final RiverMarshaller marshaller; private final Marshaller delegateMarshaller; private RiverPutField putField; private SerializableClass serializableClass; private Object current; protected RiverObjectOutputStream(final Marshaller delegateMarshaller, final RiverMarshaller marshaller) throws IOException, SecurityException { super(delegateMarshaller); this.marshaller = marshaller; this.delegateMarshaller = delegateMarshaller; } public void writeFields() throws IOException { final RiverPutField putField = this.putField; if (putField == null) { throw new NotActiveException("no current PutField object"); } if (! state.compareAndSet(State.UNWRITTEN_FIELDS, State.ON)) { throw new NotActiveException("writeFields() may only be called when the fields have not yet been written"); } this.putField = null; putField.write(marshaller); } public PutField putFields() throws IOException { if (state.get() == State.OFF) { throw new NotActiveException("No object is currently being serialized"); } if (putField == null) { final SerializableField[] serializableFields = serializableClass.getFields(); final FieldPutter[] fields; final String[] names; final int cnt = serializableFields.length; fields = new FieldPutter[cnt]; names = new String[cnt]; for (int i = 0; i < cnt; i ++) { final SerializableField field = serializableFields[i]; names[i] = field.getName(); switch (field.getKind()) { case BOOLEAN: { fields[i] = new BooleanFieldPutter(); break; } case BYTE: { fields[i] = new ByteFieldPutter(); break; } case CHAR: { fields[i] = new CharFieldPutter(); break; } case DOUBLE: { fields[i] = new DoubleFieldPutter(); break; } case FLOAT: { fields[i] = new FloatFieldPutter(); break; } case INT: { fields[i] = new IntFieldPutter(); break; } case LONG: { fields[i] = new LongFieldPutter(); break; } case OBJECT: { fields[i] = new ObjectFieldPutter(field.isUnshared()); break; } case SHORT: { fields[i] = new ShortFieldPutter(); break; } } } putField = new RiverPutField(fields, names); } return putField; } protected SerializableClass swapClass(SerializableClass newSerializableClass) { try { return serializableClass; } finally { serializableClass = newSerializableClass; } } protected Object swapCurrent(Object current) { try { return this.current; } finally { this.current = current; } } public void defaultWriteObject() throws IOException { if (! state.compareAndSet(State.UNWRITTEN_FIELDS, State.ON)) { throw new NotActiveException("writeFields() may only be called when the fields have not yet been written"); } try { marshaller.doWriteFields(serializableClass, current); } finally { putField = null; serializableClass = null; current = null; } } protected State start() throws IOException { return state.getAndSet(State.UNWRITTEN_FIELDS); } protected void finish(State restoreState) throws IOException { switch (state.getAndSet(restoreState)) { case UNWRITTEN_FIELDS: throw new NotActiveException("Fields were never written"); } } protected void fullReset() { state.set(State.OFF); putField = null; serializableClass = null; current = null; } private void checkState() throws NotActiveException { switch (state.get()) { case OFF: throw new NotActiveException("Object stream not active"); case ON: return; case UNWRITTEN_FIELDS: throw new NotActiveException("Fields not yet written"); default: throw new IllegalStateException("Unknown state"); } } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootjboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/SerializableClassDescriptor.javajboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/SerializableClassDescript0000644000175000017500000000511111150654311033511 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; import org.jboss.marshalling.reflect.SerializableField; import org.jboss.marshalling.reflect.SerializableClass; /** * */ public final class SerializableClassDescriptor extends ClassDescriptor { private final SerializableClass serializableClass; private final ClassDescriptor superClassDescriptor; private final SerializableField[] fields; private final boolean gap; public SerializableClassDescriptor(final SerializableClass serializableClass, final ClassDescriptor superClassDescriptor, final SerializableField[] fields, final int classType) throws ClassNotFoundException { super(serializableClass.getSubjectClass(), classType); this.serializableClass = serializableClass; this.superClassDescriptor = superClassDescriptor; this.fields = fields; gap = false; } public SerializableClassDescriptor(final SerializableClass serializableClass, final ClassDescriptor superClassDescriptor) throws ClassNotFoundException { super(serializableClass.getSubjectClass(), Protocol.ID_SERIALIZABLE_CLASS); this.serializableClass = serializableClass; this.superClassDescriptor = superClassDescriptor; fields = SerializableClass.NOFIELDS; gap = true; } public ClassDescriptor getSuperClassDescriptor() { return superClassDescriptor; } public SerializableField[] getFields() { return fields; } public SerializableClass getSerializableClass() { return serializableClass; } public boolean isGap() { return gap; } } jboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/RiverMarshaller.java0000644000175000017500000011030611201063312032434 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; import org.jboss.marshalling.AbstractMarshaller; import org.jboss.marshalling.UTFUtils; import org.jboss.marshalling.reflect.SerializableClass; import org.jboss.marshalling.Externalizer; import org.jboss.marshalling.ObjectResolver; import org.jboss.marshalling.ExternalizerFactory; import org.jboss.marshalling.reflect.SerializableClassRegistry; import org.jboss.marshalling.reflect.SerializableField; import org.jboss.marshalling.ObjectTable; import org.jboss.marshalling.ClassTable; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.ClassExternalizerFactory; import org.jboss.marshalling.MarshallerObjectOutput; import org.jboss.marshalling.util.IdentityIntMap; import java.io.IOException; import java.io.Serializable; import java.io.Externalizable; import java.io.NotSerializableException; import java.io.InvalidObjectException; import java.io.InvalidClassException; import java.io.ObjectOutput; import java.lang.reflect.Proxy; import java.lang.reflect.Field; import java.util.IdentityHashMap; import java.security.AccessController; import java.security.PrivilegedExceptionAction; import java.security.PrivilegedActionException; /** * */ public class RiverMarshaller extends AbstractMarshaller { private final IdentityIntMap instanceCache; private final IdentityIntMap> classCache; private final IdentityHashMap, Externalizer> externalizers; private int instanceSeq; private int classSeq; private final SerializableClassRegistry registry; private RiverObjectOutputStream objectOutputStream; private ObjectOutput objectOutput; private BlockMarshaller blockMarshaller; protected RiverMarshaller(final RiverMarshallerFactory marshallerFactory, final SerializableClassRegistry registry, final MarshallingConfiguration configuration) throws IOException { super(marshallerFactory, configuration); if (configuredVersion > Protocol.MAX_VERSION) { throw new IOException("Protocol version not supported"); } this.registry = registry; final float loadFactor = 0x0.5p0f; instanceCache = new IdentityIntMap((int) ((double)configuration.getInstanceCount() / (double)loadFactor), loadFactor); classCache = new IdentityIntMap>((int) ((double)configuration.getClassCount() / (double)loadFactor), loadFactor); externalizers = new IdentityHashMap, Externalizer>(configuration.getClassCount()); } protected void doWriteObject(final Object original, final boolean unshared) throws IOException { final ClassExternalizerFactory classExternalizerFactory = this.classExternalizerFactory; final ExternalizerFactory externalizerFactory = this.externalizerFactory; final ObjectResolver objectResolver = this.objectResolver; Object obj = original; Class objClass; int id; boolean isArray, isEnum; SerializableClass info; boolean unreplaced = true; try { for (;;) { if (obj == null) { write(Protocol.ID_NULL_OBJECT); return; } final int rid; if (! unshared && (rid = instanceCache.get(obj, -1)) != -1) { write(Protocol.ID_REPEAT_OBJECT); writeInt(rid); return; } final ObjectTable.Writer objectTableWriter; if (! unshared && (objectTableWriter = objectTable.getObjectWriter(obj)) != null) { write(Protocol.ID_PREDEFINED_OBJECT); if (configuredVersion == 1) { objectTableWriter.writeObject(getBlockMarshaller(), obj); writeEndBlock(); } else { objectTableWriter.writeObject(this, obj); } return; } objClass = obj.getClass(); id = BASIC_CLASSES.get(objClass, -1); // First, non-replaceable classes if (id == Protocol.ID_CLASS_CLASS) { final Class classObj = (Class) obj; write(Protocol.ID_NEW_OBJECT); write(Protocol.ID_CLASS_CLASS); writeClassClass(classObj); instanceCache.put(classObj, instanceSeq++); return; } isEnum = obj instanceof Enum; isArray = objClass.isArray(); info = isArray || isEnum ? null : registry.lookup(objClass); // replace once if (unreplaced) { if (info != null) { // check for a user replacement if (info.hasWriteReplace()) { obj = info.callWriteReplace(obj); } } // Check for a global replacement obj = objectResolver.writeReplace(obj); unreplaced = false; continue; } else { break; } } if (isEnum) { // objClass cannot equal Enum.class because it is abstract final Enum theEnum = (Enum) obj; // enums are always shared write(Protocol.ID_NEW_OBJECT); writeEnumClass(theEnum.getDeclaringClass()); writeString(theEnum.name()); instanceCache.put(obj, instanceSeq++); return; } // Now replaceable classes switch (id) { case Protocol.ID_BYTE_CLASS: { write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_BYTE_CLASS); writeByte(((Byte) obj).byteValue()); return; } case Protocol.ID_BOOLEAN_CLASS: { write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_BOOLEAN_CLASS); writeBoolean(((Boolean) obj).booleanValue()); return; } case Protocol.ID_CHARACTER_CLASS: { write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_CHARACTER_CLASS); writeChar(((Character) obj).charValue()); return; } case Protocol.ID_DOUBLE_CLASS: { write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_DOUBLE_CLASS); writeDouble(((Double) obj).doubleValue()); return; } case Protocol.ID_FLOAT_CLASS: { write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_FLOAT_CLASS); writeFloat(((Float) obj).floatValue()); return; } case Protocol.ID_INTEGER_CLASS: { write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_INTEGER_CLASS); writeInt(((Integer) obj).intValue()); return; } case Protocol.ID_LONG_CLASS: { write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_LONG_CLASS); writeLong(((Long) obj).longValue()); return; } case Protocol.ID_SHORT_CLASS: { write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_SHORT_CLASS); writeShort(((Short) obj).shortValue()); return; } case Protocol.ID_STRING_CLASS: { final String string = (String) obj; write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_STRING_CLASS); writeString(string); if (unshared) { instanceCache.put(obj, -1); instanceSeq++; } else { instanceCache.put(obj, instanceSeq++); } return; } case Protocol.ID_BYTE_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_BYTE_ARRAY_CLASS); final byte[] bytes = (byte[]) obj; final int len = bytes.length; writeInt(len); write(bytes, 0, len); if (unshared) { instanceCache.put(obj, -1); } return; } case Protocol.ID_BOOLEAN_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_BOOLEAN_ARRAY_CLASS); final boolean[] booleans = (boolean[]) obj; final int len = booleans.length; writeInt(len); final int bc = len & ~7; for (int i = 0; i < bc;) { write( (booleans[i++] ? 1 : 0) | (booleans[i++] ? 2 : 0) | (booleans[i++] ? 4 : 0) | (booleans[i++] ? 8 : 0) | (booleans[i++] ? 16 : 0) | (booleans[i++] ? 32 : 0) | (booleans[i++] ? 64 : 0) | (booleans[i++] ? 128 : 0) ); } if (bc < len) { int out = 0; int bit = 1; for (int i = bc; i < len; i++) { if (booleans[i]) out |= bit; bit <<= 1; } write(out); } if (unshared) { instanceCache.put(obj, -1); } return; } case Protocol.ID_CHAR_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_CHAR_ARRAY_CLASS); final char[] chars = (char[]) obj; final int len = chars.length; writeInt(len); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } if (unshared) { instanceCache.put(obj, -1); } return; } case Protocol.ID_SHORT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_SHORT_ARRAY_CLASS); final short[] shorts = (short[]) obj; final int len = shorts.length; writeInt(len); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } if (unshared) { instanceCache.put(obj, -1); } return; } case Protocol.ID_INT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_INT_ARRAY_CLASS); final int[] ints = (int[]) obj; final int len = ints.length; writeInt(len); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } if (unshared) { instanceCache.put(obj, -1); } return; } case Protocol.ID_LONG_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_LONG_ARRAY_CLASS); final long[] longs = (long[]) obj; final int len = longs.length; writeInt(len); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } if (unshared) { instanceCache.put(obj, -1); } return; } case Protocol.ID_FLOAT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_FLOAT_ARRAY_CLASS); final float[] floats = (float[]) obj; final int len = floats.length; writeInt(len); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } if (unshared) { instanceCache.put(obj, -1); } return; } case Protocol.ID_DOUBLE_ARRAY_CLASS: { instanceCache.put(obj, instanceSeq++); write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); write(Protocol.ID_DOUBLE_ARRAY_CLASS); final double[] doubles = (double[]) obj; final int len = doubles.length; writeInt(len); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } if (unshared) { instanceCache.put(obj, -1); } return; } case -1: break; default: throw new NotSerializableException(objClass.getName()); } if (isArray) { write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); writeObjectArrayClass(objClass); instanceCache.put(obj, instanceSeq++); final Object[] objects = (Object[]) obj; final int len = objects.length; writeInt(len); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } if (unshared) { instanceCache.put(obj, -1); } return; } // serialize proxies efficiently if (Proxy.isProxyClass(objClass)) { write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); instanceCache.put(obj, instanceSeq++); writeProxyClass(objClass); doWriteObject(Proxy.getInvocationHandler(obj), false); if (unshared) { instanceCache.put(obj, -1); } return; } // it's a user type // user type #1: externalizer Externalizer externalizer; if (externalizers.containsKey(objClass)) { externalizer = externalizers.get(objClass); } else { externalizer = classExternalizerFactory.getExternalizer(objClass); if (externalizer == null) { externalizer = externalizerFactory.getExternalizer(obj); } externalizers.put(objClass, externalizer); } if (externalizer != null) { write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); writeExternalizerClass(objClass, externalizer); instanceCache.put(obj, instanceSeq++); final ObjectOutput objectOutput; objectOutput = getObjectOutput(); externalizer.writeExternal(obj, objectOutput); writeEndBlock(); if (unshared) { instanceCache.put(obj, -1); } return; } // user type #2: externalizable if (obj instanceof Externalizable) { write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); instanceCache.put(obj, instanceSeq++); final Externalizable ext = (Externalizable) obj; final ObjectOutput objectOutput = getObjectOutput(); writeExternalizableClass(objClass); ext.writeExternal(objectOutput); writeEndBlock(); if (unshared) { instanceCache.put(obj, -1); } return; } // user type #3: serializable if (obj instanceof Serializable) { write(unshared ? Protocol.ID_NEW_OBJECT_UNSHARED : Protocol.ID_NEW_OBJECT); writeSerializableClass(objClass); instanceCache.put(obj, instanceSeq++); doWriteSerializableObject(info, obj, objClass); if (unshared) { instanceCache.put(obj, -1); } return; } throw new NotSerializableException(objClass.getName()); } finally { if (! unreplaced && obj != original) { final int replId = instanceCache.get(obj, -1); if (replId != -1) { instanceCache.put(original, replId); } } } } private void writeEndBlock() throws IOException { final BlockMarshaller blockMarshaller = this.blockMarshaller; if (blockMarshaller != null) { blockMarshaller.flush(); writeByte(Protocol.ID_END_BLOCK_DATA); } } protected ObjectOutput getObjectOutput() { final ObjectOutput output = objectOutput; return output == null ? configuredVersion == 0 ? (objectOutput = new MarshallerObjectOutput(this)) : (objectOutput = getBlockMarshaller()) : output; } protected BlockMarshaller getBlockMarshaller() { final BlockMarshaller blockMarshaller = this.blockMarshaller; return blockMarshaller == null ? (this.blockMarshaller = new BlockMarshaller(this, bufferSize)) : blockMarshaller; } private RiverObjectOutputStream getObjectOutputStream() throws IOException { final RiverObjectOutputStream objectOutputStream = this.objectOutputStream; return objectOutputStream == null ? this.objectOutputStream = createObjectOutputStream() : objectOutputStream; } private final PrivilegedExceptionAction createObjectOutputStreamAction = new PrivilegedExceptionAction() { public RiverObjectOutputStream run() throws IOException { return new RiverObjectOutputStream(configuredVersion == 0 ? RiverMarshaller.this : getBlockMarshaller(), RiverMarshaller.this); } }; private RiverObjectOutputStream createObjectOutputStream() throws IOException { try { return AccessController.doPrivileged(createObjectOutputStreamAction); } catch (PrivilegedActionException e) { throw (IOException) e.getCause(); } } protected void doWriteSerializableObject(final SerializableClass info, final Object obj, final Class objClass) throws IOException { final Class superclass = objClass.getSuperclass(); if (Serializable.class.isAssignableFrom(superclass)) { doWriteSerializableObject(registry.lookup(superclass), obj, superclass); } if (info.hasWriteObject()) { final RiverObjectOutputStream objectOutputStream = getObjectOutputStream(); final SerializableClass oldInfo = objectOutputStream.swapClass(info); final Object oldObj = objectOutputStream.swapCurrent(obj); final RiverObjectOutputStream.State restoreState = objectOutputStream.start(); boolean ok = false; try { info.callWriteObject(obj, objectOutputStream); writeEndBlock(); objectOutputStream.finish(restoreState); objectOutputStream.swapCurrent(oldObj); objectOutputStream.swapClass(oldInfo); ok = true; } finally { if (! ok) { objectOutputStream.fullReset(); } } } else { doWriteFields(info, obj); } } protected void doWriteFields(final SerializableClass info, final Object obj) throws IOException { final SerializableField[] serializableFields = info.getFields(); for (SerializableField serializableField : serializableFields) { try { final Field field = serializableField.getField(); switch (serializableField.getKind()) { case BOOLEAN: { writeBoolean(field.getBoolean(obj)); break; } case BYTE: { writeByte(field.getByte(obj)); break; } case SHORT: { writeShort(field.getShort(obj)); break; } case INT: { writeInt(field.getInt(obj)); break; } case CHAR: { writeChar(field.getChar(obj)); break; } case LONG: { writeLong(field.getLong(obj)); break; } case DOUBLE: { writeDouble(field.getDouble(obj)); break; } case FLOAT: { writeFloat(field.getFloat(obj)); break; } case OBJECT: { doWriteObject(field.get(obj), serializableField.isUnshared()); break; } } } catch (IllegalAccessException e) { final InvalidObjectException ioe = new InvalidObjectException("Unexpected illegal access exception"); ioe.initCause(e); throw ioe; } } } protected void writeProxyClass(final Class objClass) throws IOException { if (! writeKnownClass(objClass)) { writeNewProxyClass(objClass); } } protected void writeNewProxyClass(final Class objClass) throws IOException { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(Protocol.ID_PREDEFINED_PROXY_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { write(Protocol.ID_PROXY_CLASS); final String[] names = classResolver.getProxyInterfaces(objClass); writeInt(names.length); for (String name : names) { writeString(name); } classCache.put(objClass, classSeq++); if (configuredVersion == 1) { final BlockMarshaller blockMarshaller = getBlockMarshaller(); classResolver.annotateProxyClass(blockMarshaller, objClass); writeEndBlock(); } else { classResolver.annotateProxyClass(this, objClass); } } } protected void writeEnumClass(final Class objClass) throws IOException { if (! writeKnownClass(objClass)) { writeNewEnumClass(objClass); } } protected void writeNewEnumClass(final Class objClass) throws IOException { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(Protocol.ID_PREDEFINED_ENUM_TYPE_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { write(Protocol.ID_ENUM_TYPE_CLASS); writeString(classResolver.getClassName(objClass)); classCache.put(objClass, classSeq++); doAnnotateClass(objClass); } } protected void writeClassClass(final Class classObj) throws IOException { write(Protocol.ID_CLASS_CLASS); writeClass(classObj); // not cached } protected void writeObjectArrayClass(final Class objClass) throws IOException { write(Protocol.ID_OBJECT_ARRAY_TYPE_CLASS); writeClass(objClass.getComponentType()); classCache.put(objClass, classSeq++); } protected void writeClass(final Class objClass) throws IOException { if (! writeKnownClass(objClass)) { writeNewClass(objClass); } } private static final IdentityIntMap> BASIC_CLASSES; static { final IdentityIntMap> map = new IdentityIntMap>(0x0.6p0f); map.put(byte.class, Protocol.ID_PRIM_BYTE); map.put(boolean.class, Protocol.ID_PRIM_BOOLEAN); map.put(char.class, Protocol.ID_PRIM_CHAR); map.put(double.class, Protocol.ID_PRIM_DOUBLE); map.put(float.class, Protocol.ID_PRIM_FLOAT); map.put(int.class, Protocol.ID_PRIM_INT); map.put(long.class, Protocol.ID_PRIM_LONG); map.put(short.class, Protocol.ID_PRIM_SHORT); map.put(void.class, Protocol.ID_VOID); map.put(Byte.class, Protocol.ID_BYTE_CLASS); map.put(Boolean.class, Protocol.ID_BOOLEAN_CLASS); map.put(Character.class, Protocol.ID_CHARACTER_CLASS); map.put(Double.class, Protocol.ID_DOUBLE_CLASS); map.put(Float.class, Protocol.ID_FLOAT_CLASS); map.put(Integer.class, Protocol.ID_INTEGER_CLASS); map.put(Long.class, Protocol.ID_LONG_CLASS); map.put(Short.class, Protocol.ID_SHORT_CLASS); map.put(Void.class, Protocol.ID_VOID_CLASS); map.put(Object.class, Protocol.ID_OBJECT_CLASS); map.put(Class.class, Protocol.ID_CLASS_CLASS); map.put(String.class, Protocol.ID_STRING_CLASS); map.put(Enum.class, Protocol.ID_ENUM_CLASS); map.put(byte[].class, Protocol.ID_BYTE_ARRAY_CLASS); map.put(boolean[].class, Protocol.ID_BOOLEAN_ARRAY_CLASS); map.put(char[].class, Protocol.ID_CHAR_ARRAY_CLASS); map.put(double[].class, Protocol.ID_DOUBLE_ARRAY_CLASS); map.put(float[].class, Protocol.ID_FLOAT_ARRAY_CLASS); map.put(int[].class, Protocol.ID_INT_ARRAY_CLASS); map.put(long[].class, Protocol.ID_LONG_ARRAY_CLASS); map.put(short[].class, Protocol.ID_SHORT_ARRAY_CLASS); BASIC_CLASSES = map; } protected void writeNewClass(final Class objClass) throws IOException { if (objClass.isEnum()) { writeNewEnumClass(objClass.asSubclass(Enum.class)); } else if (Proxy.isProxyClass(objClass)) { writeNewProxyClass(objClass); } else if (objClass.isArray()) { writeObjectArrayClass(objClass); } else if (! objClass.isInterface() && Serializable.class.isAssignableFrom(objClass)) { if (Externalizable.class.isAssignableFrom(objClass)) { writeNewExternalizableClass(objClass); } else { writeNewSerializableClass(objClass); } } else { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(Protocol.ID_PREDEFINED_PLAIN_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { write(Protocol.ID_PLAIN_CLASS); writeString(classResolver.getClassName(objClass)); doAnnotateClass(objClass); classCache.put(objClass, classSeq++); } } } private void writeClassTableData(final Class objClass, final ClassTable.Writer classTableWriter) throws IOException { if (configuredVersion == 1) { classTableWriter.writeClass(getBlockMarshaller(), objClass); writeEndBlock(); } else { classTableWriter.writeClass(this, objClass); } } protected boolean writeKnownClass(final Class objClass) throws IOException { int i = BASIC_CLASSES.get(objClass, -1); if (i != -1) { write(i); return true; } i = classCache.get(objClass, -1); if (i != -1) { write(Protocol.ID_REPEAT_CLASS); writeInt(i); return true; } return false; } protected void writeSerializableClass(final Class objClass) throws IOException { if (! writeKnownClass(objClass)) { writeNewSerializableClass(objClass); } } protected void writeNewSerializableClass(final Class objClass) throws IOException { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(Protocol.ID_PREDEFINED_SERIALIZABLE_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { final SerializableClass info = registry.lookup(objClass); if (configuredVersion > 0 && info.hasWriteObject()) { write(Protocol.ID_WRITE_OBJECT_CLASS); } else { write(Protocol.ID_SERIALIZABLE_CLASS); } writeString(classResolver.getClassName(objClass)); writeLong(info.getEffectiveSerialVersionUID()); classCache.put(objClass, classSeq++); doAnnotateClass(objClass); final SerializableField[] fields = info.getFields(); final int cnt = fields.length; writeInt(cnt); for (int i = 0; i < cnt; i++) { SerializableField field = fields[i]; writeUTF(field.getName()); try { writeClass(field.getType()); } catch (ClassNotFoundException e) { throw new InvalidClassException("Class of field was unloaded"); } writeBoolean(field.isUnshared()); } } writeClass(objClass.getSuperclass()); } protected void writeExternalizableClass(final Class objClass) throws IOException { if (! writeKnownClass(objClass)) { writeNewExternalizableClass(objClass); } } protected void writeNewExternalizableClass(final Class objClass) throws IOException { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(Protocol.ID_PREDEFINED_EXTERNALIZABLE_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { write(Protocol.ID_EXTERNALIZABLE_CLASS); writeString(classResolver.getClassName(objClass)); writeLong(registry.lookup(objClass).getEffectiveSerialVersionUID()); classCache.put(objClass, classSeq++); doAnnotateClass(objClass); } } protected void writeExternalizerClass(final Class objClass, final Externalizer externalizer) throws IOException { if (! writeKnownClass(objClass)) { writeNewExternalizerClass(objClass, externalizer); } } protected void writeNewExternalizerClass(final Class objClass, final Externalizer externalizer) throws IOException { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(Protocol.ID_PREDEFINED_EXTERNALIZER_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { write(Protocol.ID_EXTERNALIZER_CLASS); writeString(classResolver.getClassName(objClass)); classCache.put(objClass, classSeq++); doAnnotateClass(objClass); } writeObject(externalizer); } protected void doAnnotateClass(final Class objClass) throws IOException { if (configuredVersion == 1) { classResolver.annotateClass(getBlockMarshaller(), objClass); writeEndBlock(); } else { classResolver.annotateClass(this, objClass); } } public void clearInstanceCache() throws IOException { instanceCache.clear(); instanceSeq = 0; if (byteOutput != null) { write(Protocol.ID_CLEAR_INSTANCE_CACHE); } } public void clearClassCache() throws IOException { classCache.clear(); externalizers.clear(); classSeq = 0; instanceCache.clear(); instanceSeq = 0; if (byteOutput != null) { write(Protocol.ID_CLEAR_CLASS_CACHE); } } protected void doStart() throws IOException { super.doStart(); final int configuredVersion = this.configuredVersion; if (configuredVersion > 0) { writeByte(configuredVersion); } } private void writeString(String string) throws IOException { writeInt(string.length()); flush(); UTFUtils.writeUTFBytes(byteOutput, string); } // Replace writeUTF with a faster, non-scanning version public void writeUTF(final String string) throws IOException { writeInt(string.length()); flush(); UTFUtils.writeUTFBytes(byteOutput, string); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootjboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/IncompleteClassDescriptor.javajboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/IncompleteClassDescriptor0000644000175000017500000000234211140106724033545 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; /** * */ public final class IncompleteClassDescriptor extends ClassDescriptor { public IncompleteClassDescriptor(final Class type, final int typeID) { super(type, typeID); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootjboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/ExternalizerClassDescriptor.javajboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/ExternalizerClassDescript0000644000175000017500000000274311140106724033566 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; import org.jboss.marshalling.Externalizer; /** * */ public final class ExternalizerClassDescriptor extends ClassDescriptor { private final Externalizer externalizer; public ExternalizerClassDescriptor(final Class clazz, final Externalizer externalizer) { super(clazz, Protocol.ID_EXTERNALIZER_CLASS); this.externalizer = externalizer; } public Externalizer getExternalizer() { return externalizer; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootjboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/RiverObjectInputStream.javajboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/RiverObjectInputStream.ja0000644000175000017500000002217111150613301033421 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; import org.jboss.marshalling.MarshallerObjectInputStream; import org.jboss.marshalling.Unmarshaller; import org.jboss.marshalling.util.ReadField; import org.jboss.marshalling.util.ShortReadField; import org.jboss.marshalling.util.ObjectReadField; import org.jboss.marshalling.util.LongReadField; import org.jboss.marshalling.util.IntReadField; import org.jboss.marshalling.util.FloatReadField; import org.jboss.marshalling.util.DoubleReadField; import org.jboss.marshalling.util.CharReadField; import org.jboss.marshalling.util.ByteReadField; import org.jboss.marshalling.util.BooleanReadField; import org.jboss.marshalling.reflect.SerializableField; import java.io.IOException; import java.io.ObjectInputValidation; import java.io.NotActiveException; import java.io.InvalidObjectException; import java.io.ObjectStreamClass; import java.util.concurrent.atomic.AtomicReference; /** * */ public class RiverObjectInputStream extends MarshallerObjectInputStream { private AtomicReference state = new AtomicReference(State.OFF); private final RiverUnmarshaller unmarshaller; protected RiverObjectInputStream(final RiverUnmarshaller riverUnmarshaller, final Unmarshaller delegateUnmarshaller) throws IOException, SecurityException { super(delegateUnmarshaller); unmarshaller = riverUnmarshaller; } private SerializableClassDescriptor serializableClassDescriptor; private Object current; public void defaultReadObject() throws IOException, ClassNotFoundException { if (! state.compareAndSet(State.UNREAD_FIELDS, State.ON)) { throw new NotActiveException("defaultReadObject() may only be called when the fields have not yet been read"); } try { unmarshaller.readFields(current, serializableClassDescriptor); } finally { serializableClassDescriptor = null; current = null; } } public GetField readFields() throws IOException, ClassNotFoundException { if (! state.compareAndSet(State.UNREAD_FIELDS, State.ON)) { throw new NotActiveException("readFields() may only be called when the fields have not yet been read"); } final SerializableField[] streamFields = serializableClassDescriptor.getFields(); final int cnt = streamFields.length; final ReadField[] readFields = new ReadField[cnt]; // todo - find defaulted fields for (int i = 0; i < cnt; i++) { SerializableField field = streamFields[i]; switch (field.getKind()) { case BOOLEAN: { readFields[i] = new BooleanReadField(field, unmarshaller.readBoolean()); break; } case BYTE: { readFields[i] = new ByteReadField(field, unmarshaller.readByte()); break; } case CHAR: { readFields[i] = new CharReadField(field, unmarshaller.readChar()); break; } case DOUBLE: { readFields[i] = new DoubleReadField(field, unmarshaller.readDouble()); break; } case FLOAT: { readFields[i] = new FloatReadField(field, unmarshaller.readFloat()); break; } case INT: { readFields[i] = new IntReadField(field, unmarshaller.readInt()); break; } case LONG: { readFields[i] = new LongReadField(field, unmarshaller.readLong()); break; } case OBJECT: { readFields[i] = new ObjectReadField(field, unmarshaller.readObject()); break; } case SHORT: { readFields[i] = new ShortReadField(field, unmarshaller.readShort()); break; } default: throw new IllegalStateException("Wrong field type"); } } return new GetField() { public ObjectStreamClass getObjectStreamClass() { throw new UnsupportedOperationException("TODO..."); } private ReadField find(final String name) { if (name == null) { throw new NullPointerException("name is null"); } for (ReadField field : readFields) { if (name.equals(field.getName())) { return field; } } throw new IllegalArgumentException("No field named '" + name + "'"); } public boolean defaulted(final String name) throws IOException { return find(name).isDefaulted(); } public boolean get(final String name, final boolean val) throws IOException { final ReadField field = find(name); return field.isDefaulted() ? val : field.getBoolean(); } public byte get(final String name, final byte val) throws IOException { final ReadField field = find(name); return field.isDefaulted() ? val : field.getByte(); } public char get(final String name, final char val) throws IOException { final ReadField field = find(name); return field.isDefaulted() ? val : field.getChar(); } public short get(final String name, final short val) throws IOException { final ReadField field = find(name); return field.isDefaulted() ? val : field.getShort(); } public int get(final String name, final int val) throws IOException { final ReadField field = find(name); return field.isDefaulted() ? val : field.getInt(); } public long get(final String name, final long val) throws IOException { final ReadField field = find(name); return field.isDefaulted() ? val : field.getLong(); } public float get(final String name, final float val) throws IOException { final ReadField field = find(name); return field.isDefaulted() ? val : field.getFloat(); } public double get(final String name, final double val) throws IOException { final ReadField field = find(name); return field.isDefaulted() ? val : field.getDouble(); } public Object get(final String name, final Object val) throws IOException { final ReadField field = find(name); return field.isDefaulted() ? val : field.getObject(); } }; } public void registerValidation(final ObjectInputValidation obj, final int prio) throws NotActiveException, InvalidObjectException { unmarshaller.addValidation(obj, prio); } protected SerializableClassDescriptor swapClass(final SerializableClassDescriptor descriptor) { try { return serializableClassDescriptor; } finally { serializableClassDescriptor = descriptor; } } protected Object swapCurrent(final Object obj) { try { return current; } finally { current = obj; } } protected State start() { return state.getAndSet(State.UNREAD_FIELDS); } protected void finish(final State restoreState) throws IOException { switch (state.getAndSet(restoreState)) { case OFF: // ?? break; case ON: // todo if blockmode, flush... break; case UNREAD_FIELDS: throw new NotActiveException("Fields were never read"); } } protected void fullReset() { state.set(State.OFF); serializableClassDescriptor = null; current = null; } protected enum State { OFF, UNREAD_FIELDS, ON, ; } } jboss-marshalling-1.1.3.GA/river/src/main/java/org/jboss/marshalling/river/BlockMarshaller.java0000644000175000017500000002465311200745514032422 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; import org.jboss.marshalling.Marshaller; import org.jboss.marshalling.ByteOutput; import org.jboss.marshalling.UTFUtils; import java.io.IOException; /** * */ public final class BlockMarshaller implements Marshaller { private final RiverMarshaller riverMarshaller; private final byte[] buffer; private int position; BlockMarshaller(RiverMarshaller riverMarshaller, int blockSize) { this.riverMarshaller = riverMarshaller; buffer = new byte[blockSize]; } public void start(final ByteOutput newOutput) throws IOException { throw new IllegalStateException("start() not allowed in this context"); } public void clearInstanceCache() throws IOException { throw new IllegalStateException("clearInstanceCache() not allowed in this context"); } public void clearClassCache() throws IOException { throw new IllegalStateException("clearClassCache() not allowed in this context"); } public void finish() throws IOException { throw new IllegalStateException("finish() not allowed in this context"); } public void writeObject(final Object obj) throws IOException { doWriteObject(obj, false); } public void writeObjectUnshared(final Object obj) throws IOException { doWriteObject(obj, true); } private void doWriteObject(final Object obj, final boolean unshared) throws IOException { flush(); riverMarshaller.doWriteObject(obj, unshared); flush(); } public void write(final int v) throws IOException { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining == 0) { flush(); buffer[0] = (byte) v; position = 1; } else { buffer[position++] = (byte) v; } } public void write(final byte[] b) throws IOException { write(b, 0, b.length); } public void write(final byte[] bytes, final int off, final int len) throws IOException { if (len < 1) { return; } final int bl = buffer.length; final int position = this.position; if (len > bl - position || len > bl >> 1) { flush(); if (len < 256) { riverMarshaller.write(Protocol.ID_START_BLOCK_SMALL); riverMarshaller.writeByte(len); riverMarshaller.write(bytes, off, len); } else if (len < 65536) { riverMarshaller.write(Protocol.ID_START_BLOCK_MEDIUM); riverMarshaller.writeShort(len); riverMarshaller.write(bytes, off, len); } else { riverMarshaller.write(Protocol.ID_START_BLOCK_LARGE); riverMarshaller.writeInt(len); riverMarshaller.write(bytes, off, len); } } else { System.arraycopy(bytes, off, buffer, position, len); this.position = position + len; } } public void writeBoolean(final boolean v) throws IOException { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining == 0) { flush(); buffer[0] = (byte) (v ? 1 : 0); position = 1; } else { buffer[position++] = (byte) (v ? 1 : 0); } } public void writeByte(final int v) throws IOException { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining == 0) { flush(); buffer[0] = (byte) v; position = 1; } else { buffer[position++] = (byte) v; } } public void writeShort(final int v) throws IOException { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 2) { flush(); buffer[0] = (byte) (v >> 8); buffer[1] = (byte) v; position = 2; } else { final int s = position; position = s + 2; buffer[s] = (byte) (v >> 8); buffer[s+1] = (byte) v; } } public void writeChar(final int v) throws IOException { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 2) { flush(); buffer[0] = (byte) (v >> 8); buffer[1] = (byte) v; position = 2; } else { final int s = position; position = s + 2; buffer[s] = (byte) (v >> 8); buffer[s+1] = (byte) v; } } public void writeInt(final int v) throws IOException { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 4) { flush(); buffer[0] = (byte) (v >> 24); buffer[1] = (byte) (v >> 16); buffer[2] = (byte) (v >> 8); buffer[3] = (byte) v; position = 4; } else { final int s = position; position = s + 4; buffer[s] = (byte) (v >> 24); buffer[s+1] = (byte) (v >> 16); buffer[s+2] = (byte) (v >> 8); buffer[s+3] = (byte) v; } } public void writeLong(final long v) throws IOException { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 8) { flush(); buffer[0] = (byte) (v >> 56L); buffer[1] = (byte) (v >> 48L); buffer[2] = (byte) (v >> 40L); buffer[3] = (byte) (v >> 32L); buffer[4] = (byte) (v >> 24L); buffer[5] = (byte) (v >> 16L); buffer[6] = (byte) (v >> 8L); buffer[7] = (byte) v; position = 8; } else { final int s = position; position = s + 8; buffer[s] = (byte) (v >> 56L); buffer[s+1] = (byte) (v >> 48L); buffer[s+2] = (byte) (v >> 40L); buffer[s+3] = (byte) (v >> 32L); buffer[s+4] = (byte) (v >> 24L); buffer[s+5] = (byte) (v >> 16L); buffer[s+6] = (byte) (v >> 8L); buffer[s+7] = (byte) v; } } public void writeFloat(final float v) throws IOException { final int bits = Float.floatToIntBits(v); final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 4) { flush(); buffer[0] = (byte) (bits >> 24); buffer[1] = (byte) (bits >> 16); buffer[2] = (byte) (bits >> 8); buffer[3] = (byte) bits; position = 4; } else { final int s = position; position = s + 4; buffer[s] = (byte) (bits >> 24); buffer[s+1] = (byte) (bits >> 16); buffer[s+2] = (byte) (bits >> 8); buffer[s+3] = (byte) bits; } } public void writeDouble(final double v) throws IOException { final long bits = Double.doubleToLongBits(v); final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 8) { flush(); buffer[0] = (byte) (bits >> 56L); buffer[1] = (byte) (bits >> 48L); buffer[2] = (byte) (bits >> 40L); buffer[3] = (byte) (bits >> 32L); buffer[4] = (byte) (bits >> 24L); buffer[5] = (byte) (bits >> 16L); buffer[6] = (byte) (bits >> 8L); buffer[7] = (byte) bits; position = 8; } else { final int s = position; position = s + 8; buffer[s] = (byte) (bits >> 56L); buffer[s+1] = (byte) (bits >> 48L); buffer[s+2] = (byte) (bits >> 40L); buffer[s+3] = (byte) (bits >> 32L); buffer[s+4] = (byte) (bits >> 24L); buffer[s+5] = (byte) (bits >> 16L); buffer[s+6] = (byte) (bits >> 8L); buffer[s+7] = (byte) bits; } } public void writeBytes(final String s) throws IOException { final int len = s.length(); for (int i = 0; i < len; i ++) { write(s.charAt(i)); } } public void writeChars(final String s) throws IOException { final int len = s.length(); for (int i = 0; i < len; i ++) { writeChar(s.charAt(i)); } } public void writeUTF(final String s) throws IOException { // span multiple blocks, no doubt, but should be reasonably fast writeInt(s.length()); UTFUtils.writeUTFBytes(this, s); } public void flush() throws IOException { final int position = this.position; if (position == 0) { return; } final RiverMarshaller marshaller = riverMarshaller; if (position < 256) { marshaller.write(Protocol.ID_START_BLOCK_SMALL); marshaller.writeByte(position); } else if (position < 65536) { marshaller.write(Protocol.ID_START_BLOCK_MEDIUM); marshaller.writeShort(position); } else { marshaller.write(Protocol.ID_START_BLOCK_LARGE); marshaller.writeInt(position); } marshaller.write(buffer, 0, position); this.position = 0; } public void close() throws IOException { } } jboss-marshalling-1.1.3.GA/river/pom.xml0000644000175000017500000000246511200351743020026 0ustar twernertwerner 4.0.0 org.jboss.marshalling river jar 1.1.3.GA org.jboss.marshalling marshalling-api 1.1.3.GA org.apache.maven.plugins maven-compiler-plugin 2.0.2 1.5 1.5 river repository.jboss.org JBoss Maven2 Repository ${repository.url} jboss-marshalling-1.1.3.GA/COPYING.txt0000644000175000017500000005750411122550145017237 0ustar twernertwerner GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS jboss-marshalling-1.1.3.GA/testing-support/0000755000175000017500000000000011253762300020545 5ustar twernertwernerjboss-marshalling-1.1.3.GA/testing-support/src/0000755000175000017500000000000011253762300021334 5ustar twernertwernerjboss-marshalling-1.1.3.GA/testing-support/src/main/0000755000175000017500000000000011253762300022260 5ustar twernertwernerjboss-marshalling-1.1.3.GA/testing-support/src/main/resources/0000755000175000017500000000000011253762300024272 5ustar twernertwernerjboss-marshalling-1.1.3.GA/testing-support/src/main/java/0000755000175000017500000000000011253762300023201 5ustar twernertwernerjboss-marshalling-1.1.3.GA/testing-support/src/main/java/org/0000755000175000017500000000000011253762300023770 5ustar twernertwernerjboss-marshalling-1.1.3.GA/testing-support/src/main/java/org/jboss/0000755000175000017500000000000011253762300025110 5ustar twernertwernerjboss-marshalling-1.1.3.GA/testing-support/src/main/java/org/jboss/testsupport/0000755000175000017500000000000011253762300027524 5ustar twernertwerner././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootjboss-marshalling-1.1.3.GA/testing-support/src/main/java/org/jboss/testsupport/LoggingSecurityManager.javajboss-marshalling-1.1.3.GA/testing-support/src/main/java/org/jboss/testsupport/LoggingSecurityManage0000644000175000017500000001554111122550145033701 0ustar twernertwernerpackage org.jboss.testsupport; import java.security.Permission; import java.io.FileDescriptor; import java.net.InetAddress; import java.util.logging.Logger; import java.util.logging.Level; /** * */ public final class LoggingSecurityManager extends SecurityManager { private static final Logger log = Logger.getLogger("ACCESS_EXCEPTION"); public LoggingSecurityManager() { } private ThreadLocal in = new ThreadLocal(); private T logged(T se) { final Boolean inb = in.get(); if (inb != Boolean.TRUE) { in.set(Boolean.TRUE); try { log.log(Level.SEVERE, "Access violation!", se); return se; } finally { in.set(null); } } return se; } public void checkPermission(final Permission perm) { try { super.checkPermission(perm); } catch (SecurityException se) { throw logged(se); } } public void checkPermission(final Permission perm, final Object context) { try { super.checkPermission(perm, context); } catch (SecurityException se) { throw logged(se); } } public void checkCreateClassLoader() { try { super.checkCreateClassLoader(); } catch (SecurityException se) { throw logged(se); } } public void checkAccess(final Thread t) { try { super.checkAccess(t); } catch (SecurityException se) { throw logged(se); } } public void checkAccess(final ThreadGroup g) { try { super.checkAccess(g); } catch (SecurityException se) { throw logged(se); } } public void checkExit(final int status) { try { super.checkExit(status); } catch (SecurityException se) { throw logged(se); } } public void checkExec(final String cmd) { try { super.checkExec(cmd); } catch (SecurityException se) { throw logged(se); } } public void checkLink(final String lib) { try { super.checkLink(lib); } catch (SecurityException se) { throw logged(se); } } public void checkRead(final FileDescriptor fd) { try { super.checkRead(fd); } catch (SecurityException se) { throw logged(se); } } public void checkRead(final String file) { try { super.checkRead(file); } catch (SecurityException se) { throw logged(se); } } public void checkRead(final String file, final Object context) { try { super.checkRead(file, context); } catch (SecurityException se) { throw logged(se); } } public void checkWrite(final FileDescriptor fd) { try { super.checkWrite(fd); } catch (SecurityException se) { throw logged(se); } } public void checkWrite(final String file) { try { super.checkWrite(file); } catch (SecurityException se) { throw logged(se); } } public void checkDelete(final String file) { try { super.checkDelete(file); } catch (SecurityException se) { throw logged(se); } } public void checkConnect(final String host, final int port) { try { super.checkConnect(host, port); } catch (SecurityException se) { throw logged(se); } } public void checkConnect(final String host, final int port, final Object context) { try { super.checkConnect(host, port, context); } catch (SecurityException se) { throw logged(se); } } public void checkListen(final int port) { try { super.checkListen(port); } catch (SecurityException se) { throw logged(se); } } public void checkAccept(final String host, final int port) { try { super.checkAccept(host, port); } catch (SecurityException se) { throw logged(se); } } public void checkMulticast(final InetAddress maddr) { try { super.checkMulticast(maddr); } catch (SecurityException se) { throw logged(se); } } @Deprecated public void checkMulticast(final InetAddress maddr, final byte ttl) { try { super.checkMulticast(maddr, ttl); } catch (SecurityException se) { throw logged(se); } } public void checkPropertiesAccess() { try { super.checkPropertiesAccess(); } catch (SecurityException se) { throw logged(se); } } public void checkPropertyAccess(final String key) { try { super.checkPropertyAccess(key); } catch (SecurityException se) { throw logged(se); } } public boolean checkTopLevelWindow(final Object window) { try { return super.checkTopLevelWindow(window); } catch (SecurityException se) { throw logged(se); } } public void checkPrintJobAccess() { try { super.checkPrintJobAccess(); } catch (SecurityException se) { throw logged(se); } } public void checkSystemClipboardAccess() { try { super.checkSystemClipboardAccess(); } catch (SecurityException se) { throw logged(se); } } public void checkAwtEventQueueAccess() { try { super.checkAwtEventQueueAccess(); } catch (SecurityException se) { throw logged(se); } } public void checkPackageAccess(final String pkg) { try { super.checkPackageAccess(pkg); } catch (SecurityException se) { throw logged(se); } } public void checkPackageDefinition(final String pkg) { try { super.checkPackageDefinition(pkg); } catch (SecurityException se) { throw logged(se); } } public void checkSetFactory() { try { super.checkSetFactory(); } catch (SecurityException se) { throw logged(se); } } public void checkMemberAccess(final Class clazz, final int which) { try { super.checkMemberAccess(clazz, which); } catch (SecurityException se) { throw logged(se); } } public void checkSecurityAccess(final String target) { try { super.checkSecurityAccess(target); } catch (SecurityException se) { throw logged(se); } } } jboss-marshalling-1.1.3.GA/testing-support/src/main/java/org/jboss/testsupport/LoggingHelper.java0000644000175000017500000001000311122550145033104 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.testsupport; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.logging.Logger; import java.util.logging.Level; import java.util.logging.Handler; import java.util.logging.Formatter; import java.util.logging.LogRecord; /** * */ public final class LoggingHelper { private static final class Once { private static final long startTime = System.currentTimeMillis(); static { AccessController.doPrivileged(new PrivilegedAction() { public Void run() { final Logger rootLogger = Logger.getLogger(""); rootLogger.setLevel(Level.ALL); final Handler[] handlers = rootLogger.getHandlers(); for (Handler handler : handlers) { handler.setLevel(Level.ALL); handler.setFormatter(new Formatter() { public String format(final LogRecord record) { StringBuilder builder = new StringBuilder(); long offs = record.getMillis() - startTime; final String sign = offs < 0 ? "-" : "+"; offs = Math.abs(offs); int ms = (int) (offs % 1000L); long s = offs / 1000L; builder.append(String.format("%s%04d.%03d ", sign, Long.valueOf(s), Long.valueOf(ms))); builder.append(String.format("tid:%d ", Integer.valueOf(record.getThreadID()))); builder.append(record.getLevel().toString()); builder.append(" [").append(record.getLoggerName()).append("] "); builder.append(String.format(record.getMessage(), record.getParameters())); Throwable t = record.getThrown(); while (t != null) { builder.append("\n Caused by: "); builder.append(t.toString()); for (StackTraceElement e : t.getStackTrace()) { builder.append("\n at "); builder.append(e.getClassName()).append('.').append(e.getMethodName()); builder.append("(").append(e.getFileName()).append(':').append(e.getLineNumber()).append(')'); } t = t.getCause(); } builder.append('\n'); return builder.toString(); } }); } return null; } }); } } private LoggingHelper() { } public static void init() { new Once(); } } jboss-marshalling-1.1.3.GA/api/0000755000175000017500000000000011253762303016132 5ustar twernertwernerjboss-marshalling-1.1.3.GA/api/src/0000755000175000017500000000000011253762300016716 5ustar twernertwernerjboss-marshalling-1.1.3.GA/api/src/test/0000755000175000017500000000000011253762300017675 5ustar twernertwernerjboss-marshalling-1.1.3.GA/api/src/test/java/0000755000175000017500000000000011253762300020616 5ustar twernertwernerjboss-marshalling-1.1.3.GA/api/src/main/0000755000175000017500000000000011253762303017645 5ustar twernertwernerjboss-marshalling-1.1.3.GA/api/src/main/resources/0000755000175000017500000000000011253762303021657 5ustar twernertwernerjboss-marshalling-1.1.3.GA/api/src/main/resources/META-INF/0000755000175000017500000000000011253762303023017 5ustar twernertwernerjboss-marshalling-1.1.3.GA/api/src/main/resources/META-INF/jboss-classloading.xml0000644000175000017500000000053711140107601027314 0ustar twernertwerner jboss-marshalling-1.1.3.GA/api/src/main/java/0000755000175000017500000000000011253762300020563 5ustar twernertwernerjboss-marshalling-1.1.3.GA/api/src/main/java/org/0000755000175000017500000000000011253762300021352 5ustar twernertwernerjboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/0000755000175000017500000000000011253762300022472 5ustar twernertwernerjboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/0000755000175000017500000000000011253762302024775 5ustar twernertwerner././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootjboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/MarshallingObjectInputStream.javajboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/MarshallingObjectInputStream.java0000644000175000017500000001721011140107533033417 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.io.IOException; import java.io.ObjectInputValidation; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectStreamClass; /** * An object input stream which wraps an {@code Unmarshaller}, which may be used by legacy {@link java.io.ObjectInputStream ObjectInputStream}-based * applications that wish to use the marshalling framework. */ public final class MarshallingObjectInputStream extends ObjectInputStream { private Unmarshaller unmarshaller; /** * Construct a new instance which delegates to the given unmarshaller, reading from the given input. The unmarshaller * will read from the input stream until it is closed. * * @param unmarshaller the delegate unmarshaller * @param stream the input stream to read from * * @throws java.io.IOException if an I/O error occurs * @throws SecurityException if the caller does not have permission to construct an instance of this class */ public MarshallingObjectInputStream(final Unmarshaller unmarshaller, final InputStream stream) throws IOException, SecurityException { this(unmarshaller, Marshalling.createByteInput(stream)); } /** * Construct a new instance which delegates to the given unmarshaller, reading from the given input. The unmarshaller * will read from the input stream until it is closed. * * @param unmarshaller the delegate unmarshaller * @param byteInput the input stream to read from * * @throws java.io.IOException if an I/O error occurs * @throws SecurityException if the caller does not have permission to construct an instance of this class */ public MarshallingObjectInputStream(final Unmarshaller unmarshaller, final ByteInput byteInput) throws IOException, SecurityException { unmarshaller.start(byteInput); this.unmarshaller = unmarshaller; } public Object readUnshared() throws IOException, ClassNotFoundException { return unmarshaller.readObjectUnshared(); } protected Object readObjectOverride() throws ClassNotFoundException, IOException { return unmarshaller.readObject(); } public int read() throws IOException { return unmarshaller.read(); } public int read(final byte[] b) throws IOException { return unmarshaller.read(b); } public int read(final byte[] b, final int off, final int len) throws IOException { return unmarshaller.read(b, off, len); } public long skip(final long n) throws IOException { return unmarshaller.skip(n); } public int available() throws IOException { return unmarshaller.available(); } public void close() throws IOException, IllegalStateException { unmarshaller.finish(); unmarshaller = null; } public void readFully(final byte[] b) throws IOException { unmarshaller.readFully(b); } public void readFully(final byte[] b, final int off, final int len) throws IOException { unmarshaller.readFully(b, off, len); } public int skipBytes(final int n) throws IOException { return unmarshaller.skipBytes(n); } public boolean readBoolean() throws IOException { return unmarshaller.readBoolean(); } public byte readByte() throws IOException { return unmarshaller.readByte(); } public int readUnsignedByte() throws IOException { return unmarshaller.readUnsignedByte(); } public short readShort() throws IOException { return unmarshaller.readShort(); } public int readUnsignedShort() throws IOException { return unmarshaller.readUnsignedShort(); } public char readChar() throws IOException { return unmarshaller.readChar(); } public int readInt() throws IOException { return unmarshaller.readInt(); } public long readLong() throws IOException { return unmarshaller.readLong(); } public float readFloat() throws IOException { return unmarshaller.readFloat(); } public double readDouble() throws IOException { return unmarshaller.readDouble(); } @Deprecated public String readLine() throws IOException { return unmarshaller.readLine(); } public String readUTF() throws IOException { return unmarshaller.readUTF(); } public Object readObjectUnshared() throws ClassNotFoundException, IOException { return unmarshaller.readObjectUnshared(); } /** {@inheritDoc} */ protected final Class resolveClass(final ObjectStreamClass desc) throws IllegalStateException { throw new IllegalStateException("Class may not be resolved in this context"); } /** {@inheritDoc} */ protected final Class resolveProxyClass(final String[] interfaces) throws IllegalStateException { throw new IllegalStateException("Class may not be resolved in this context"); } /** {@inheritDoc} */ protected final Object resolveObject(final Object obj) throws IllegalStateException { throw new IllegalStateException("Object may not be resolved in this context"); } /** {@inheritDoc} */ protected final boolean enableResolveObject(final boolean enable) throws IllegalStateException { throw new IllegalStateException("Object resolution may not be enabled in this context"); } /** {@inheritDoc} */ protected final void readStreamHeader() throws IllegalStateException { throw new IllegalStateException("Stream header may not be read in this context"); } /** {@inheritDoc} */ protected final ObjectStreamClass readClassDescriptor() throws IllegalStateException { throw new IllegalStateException("Class descriptor may not be read in this context"); } /** * May not be invoked in this context. * * @throws IllegalStateException always */ public void defaultReadObject() throws IllegalStateException { throw new IllegalStateException("This method may not be invoked in this context"); } /** * May not be invoked in this context. * * @throws IllegalStateException always */ public GetField readFields() throws IllegalStateException { throw new IllegalStateException("Fields may not be read in this context"); } /** * May not be invoked in this context. * * @param obj ignored * @param prio ignored * @throws IllegalStateException always */ public void registerValidation(final ObjectInputValidation obj, final int prio) throws IllegalStateException { throw new IllegalStateException("Validation objects may not be registered in this context"); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootjboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/MarshallerObjectOutputStream.javajboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/MarshallerObjectOutputStream.java0000644000175000017500000001475511122550145033465 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.io.ObjectOutputStream; import java.io.IOException; import java.io.ObjectStreamClass; /** * A marshaller's object output stream. Used by marshallers for compatibility with Java serialization. Instances of * this class may be passed in to the overriden serialization methods for a class implementing {@link java.io.Serializable}. *

* This class is not part of the marshalling API; rather it is intended for marshaller implementors to make it easier * to develop Java serialization-compatible marshallers. */ public abstract class MarshallerObjectOutputStream extends ObjectOutputStream { private final Marshaller output; /** * Construct a new instance that delegates to the given marshaller. * * @param output the delegate marshaller * @throws IOException if an I/O error occurs * @throws SecurityException if the caller does not have permission to construct an instance of this class */ protected MarshallerObjectOutputStream(final Marshaller output) throws IOException, SecurityException { this.output = output; } // Delegated methods /** {@inheritDoc} */ protected void writeObjectOverride(final Object obj) throws IOException { output.writeObject(obj); } /** {@inheritDoc} */ public void writeUnshared(final Object obj) throws IOException { output.writeObjectUnshared(obj); } /** {@inheritDoc} */ public void write(final int val) throws IOException { output.write(val); } /** {@inheritDoc} */ public void write(final byte[] buf) throws IOException { output.write(buf, 0, buf.length); } /** {@inheritDoc} */ public void write(final byte[] buf, final int off, final int len) throws IOException { output.write(buf, off, len); } /** {@inheritDoc} */ public void flush() throws IOException { output.flush(); } /** {@inheritDoc} */ public void writeBoolean(final boolean val) throws IOException { output.writeBoolean(val); } /** {@inheritDoc} */ public void writeByte(final int val) throws IOException { output.writeByte(val); } /** {@inheritDoc} */ public void writeShort(final int val) throws IOException { output.writeShort(val); } /** {@inheritDoc} */ public void writeChar(final int val) throws IOException { output.writeChar(val); } /** {@inheritDoc} */ public void writeInt(final int val) throws IOException { output.writeInt(val); } /** {@inheritDoc} */ public void writeLong(final long val) throws IOException { output.writeLong(val); } /** {@inheritDoc} */ public void writeFloat(final float val) throws IOException { output.writeFloat(val); } /** {@inheritDoc} */ public void writeDouble(final double val) throws IOException { output.writeDouble(val); } /** {@inheritDoc} */ public void writeBytes(final String str) throws IOException { output.writeBytes(str); } /** {@inheritDoc} */ public void writeChars(final String str) throws IOException { output.writeChars(str); } /** {@inheritDoc} */ public void writeUTF(final String str) throws IOException { output.writeUTF(str); } // Unsupported methods /** {@inheritDoc} */ public final void reset() throws IOException { throw new IOException("reset() may not be invoked on this stream"); } /** {@inheritDoc} */ public final void close() throws IOException { throw new IllegalStateException("Stream may not be closed in this context"); } /** {@inheritDoc} */ public final void useProtocolVersion(final int version) throws IOException { throw new IllegalStateException("Protocol version may not be changed"); } /** {@inheritDoc} */ protected final void annotateClass(final Class cl) throws IOException { throw new IllegalStateException("Class may not be annotated in this context"); } /** {@inheritDoc} */ protected final void annotateProxyClass(final Class cl) throws IOException { throw new IllegalStateException("Class may not be annotated in this context"); } /** {@inheritDoc} */ protected final Object replaceObject(final Object obj) throws IOException { throw new IllegalStateException("Object may not be replaced in this context"); } /** {@inheritDoc} */ protected final boolean enableReplaceObject(final boolean enable) throws SecurityException { throw new SecurityException("Object replacement may not be controlled in this context"); } /** {@inheritDoc} */ protected final void writeStreamHeader() throws IOException { throw new IllegalStateException("Stream header may not be written in this context"); } /** {@inheritDoc} */ protected final void writeClassDescriptor(final ObjectStreamClass desc) throws IOException { throw new IllegalStateException("Class descriptor may not be written in this context"); } /** {@inheritDoc} */ protected final void drain() throws IOException { throw new IllegalStateException("Output may not be drained in this context"); } // User-implementation methods /** {@inheritDoc} */ public abstract void writeFields() throws IOException; /** {@inheritDoc} */ public abstract PutField putFields() throws IOException; /** {@inheritDoc} */ public abstract void defaultWriteObject() throws IOException; } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootjboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/ChainingClassExternalizerFactory.javajboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/ChainingClassExternalizerFactory.0000644000175000017500000000652511140355243033436 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.util.Collection; import java.util.Iterator; /** * A class externalizer factory that tries each delegate externalizer factory in sequence, returning the first match. */ public class ChainingClassExternalizerFactory implements ClassExternalizerFactory { private final ClassExternalizerFactory[] externalizerFactories; /** * Construct a new instance. * * @param factories a collection of factories to use */ public ChainingClassExternalizerFactory(final Collection factories) { externalizerFactories = factories.toArray(new ClassExternalizerFactory[factories.size()]); } /** * Construct a new instance. * * @param factories a collection of factories to use */ public ChainingClassExternalizerFactory(final Iterable factories) { this(factories.iterator()); } /** * Construct a new instance. * * @param factories a sequence of factories to use */ public ChainingClassExternalizerFactory(final Iterator factories) { externalizerFactories = unroll(factories, 0); } /** * Construct a new instance. * * @param factories an array of factories to use */ public ChainingClassExternalizerFactory(final ClassExternalizerFactory[] factories) { externalizerFactories = factories.clone(); } private static ClassExternalizerFactory[] unroll(final Iterator iterator, final int i) { if (iterator.hasNext()) { final ClassExternalizerFactory factory = iterator.next(); final ClassExternalizerFactory[] array = unroll(iterator, i + 1); array[i] = factory; return array; } else { return new ClassExternalizerFactory[i]; } } /** {@inheritDoc} This implementation tries each nested externalizer factory in order until a match is found. */ public Externalizer getExternalizer(final Class type) { for (ClassExternalizerFactory externalizerFactory : externalizerFactories) { final Externalizer externalizer = externalizerFactory.getExternalizer(type); if (externalizer != null) { return externalizer; } } return null; } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/AbstractExternalizer.java0000644000175000017500000000357511122550145032005 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.io.ObjectInput; import java.io.IOException; /** * An externalizer base class which handles object creation in a default fashion. */ public abstract class AbstractExternalizer implements Externalizer { private static final long serialVersionUID = -584504194617263431L; /** * Create an instance of a type using the provided creator. * * @param subjectType the type to create * @param input the object input * @param defaultCreator the creator * @return a new instance * @throws IOException if an I/O error occurs * @throws ClassNotFoundException if the class could not be located */ public Object createExternal(final Class subjectType, final ObjectInput input, final Creator defaultCreator) throws IOException, ClassNotFoundException { return defaultCreator.create(subjectType); } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/MarshallerObjectInput.java0000644000175000017500000001122411142471673032106 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.io.ObjectInput; import java.io.IOException; /** * A marshaller's object input. This implementation delegates to an {@code Unmarshaller} implementation while throwing * an exception if {@code close()} is called. *

* This class is not part of the marshalling API; rather it is intended for marshaller implementors to make it easier * to develop Java serialization-compatible marshallers. */ public class MarshallerObjectInput implements ObjectInput { private final Unmarshaller unmarshaller; /** * Construct a new instance. * * @param unmarshaller the unmarshaller to delegate to */ public MarshallerObjectInput(final Unmarshaller unmarshaller) { this.unmarshaller = unmarshaller; } /** {@inheritDoc} */ public Object readObject() throws ClassNotFoundException, IOException { return unmarshaller.readObject(); } /** {@inheritDoc} */ public int read() throws IOException { return unmarshaller.read(); } /** {@inheritDoc} */ public int read(final byte[] b) throws IOException { return unmarshaller.read(b); } /** {@inheritDoc} */ public int read(final byte[] b, final int off, final int len) throws IOException { return unmarshaller.read(b, off, len); } /** {@inheritDoc} */ public long skip(final long n) throws IOException { return unmarshaller.skip(n); } /** {@inheritDoc} */ public int available() throws IOException { return unmarshaller.available(); } /** {@inheritDoc} This implementation always throws an {@link IllegalStateException}. */ public void close() throws IOException { throw new IllegalStateException("close() may not be called in this context"); } /** {@inheritDoc} */ public void readFully(final byte[] b) throws IOException { unmarshaller.readFully(b); } /** {@inheritDoc} */ public void readFully(final byte[] b, final int off, final int len) throws IOException { unmarshaller.readFully(b, off, len); } /** {@inheritDoc} */ public int skipBytes(final int n) throws IOException { return unmarshaller.skipBytes(n); } /** {@inheritDoc} */ public boolean readBoolean() throws IOException { return unmarshaller.readBoolean(); } /** {@inheritDoc} */ public byte readByte() throws IOException { return unmarshaller.readByte(); } /** {@inheritDoc} */ public int readUnsignedByte() throws IOException { return unmarshaller.readUnsignedByte(); } /** {@inheritDoc} */ public short readShort() throws IOException { return unmarshaller.readShort(); } /** {@inheritDoc} */ public int readUnsignedShort() throws IOException { return unmarshaller.readUnsignedShort(); } /** {@inheritDoc} */ public char readChar() throws IOException { return unmarshaller.readChar(); } /** {@inheritDoc} */ public int readInt() throws IOException { return unmarshaller.readInt(); } /** {@inheritDoc} */ public long readLong() throws IOException { return unmarshaller.readLong(); } /** {@inheritDoc} */ public float readFloat() throws IOException { return unmarshaller.readFloat(); } /** {@inheritDoc} */ public double readDouble() throws IOException { return unmarshaller.readDouble(); } /** {@inheritDoc} */ public String readLine() throws IOException { return unmarshaller.readLine(); } /** {@inheritDoc} */ public String readUTF() throws IOException { return unmarshaller.readUTF(); } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/Marshaller.java0000644000175000017500000000507711122550145027736 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.io.ObjectOutput; import java.io.IOException; /** * An object marshaller for writing objects to byte streams. */ public interface Marshaller extends ObjectOutput, ByteOutput { /** * Write an object to the underlying storage or stream as a new instance. The class that implements this interface * defines how the object is written. * * @param obj the object to be written * @throws IOException if an error occurs */ void writeObjectUnshared(Object obj) throws IOException; /** * Begin marshalling to a stream. * * @param newOutput the new stream * @throws IOException if an error occurs during setup, such as an error writing the header */ void start(ByteOutput newOutput) throws IOException; /** * Discard the instance cache. May also discard the class cache in implementations that do not support separated * class and instance caches. * * @throws IOException if an error occurs */ void clearInstanceCache() throws IOException; /** * Discard the class cache. Implicitly also discards the instance cache. * * @throws IOException if an error occurs */ void clearClassCache() throws IOException; /** * Finish marshalling to a stream. Any transient class or instance cache is discarded. The stream is released. * No further marshalling may be done until the {@link #start(ByteOutput)} method is again invoked. * * @throws IOException if an error occurs */ void finish() throws IOException; } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/StreamHeader.java0000644000175000017500000000310211142200542030166 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.io.IOException; /** * A producer of stream headers. */ public interface StreamHeader { /** * Read the stream header from the stream. * * @param input the stream header * @throws IOException if the header is invalid or an error occurs */ void readHeader(ByteInput input) throws IOException; /** * Write the stream header to the stream. * * @param output the stream header * @throws IOException if an error occurs */ void writeHeader(ByteOutput output) throws IOException; } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/Externalizer.java0000644000175000017500000000565711122550145030324 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.io.IOException; import java.io.ObjectOutput; import java.io.ObjectInput; import java.io.Serializable; /** * A replacement serializer for an object class. */ public interface Externalizer extends Serializable { /** * Write the external representation of an object. The object's class and the externalizer's class will * already have been written. * * @param subject the object to externalize * @param output the output * @throws IOException if an error occurs */ void writeExternal(Object subject, ObjectOutput output) throws IOException; /** * Create an instance of a type. The object may then be initialized from {@code input}, or that may be deferred * to the {@code readExternal()} method. Instances may simply delegate the task to the given {@code Creator}. * Note that this method is called only on the leaf class, so externalizers for non-final classes that initialize * the instance from the stream need to be aware of this. * * @param subjectType the type of object to create * @param input the input * @param defaultCreator the configured creator * @return the new instance * @throws IOException if an error occurs * @throws ClassNotFoundException if a class could not be found during read */ Object createExternal(Class subjectType, ObjectInput input, Creator defaultCreator) throws IOException, ClassNotFoundException; /** * Read the external representation of an object. The object will already be instantiated, but may be uninitialized, when * this method is called. * * @param subject the object to read * @param input the input * @throws IOException if an error occurs * @throws ClassNotFoundException if a class could not be found during read */ void readExternal(Object subject, ObjectInput input) throws IOException, ClassNotFoundException; } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/AbstractMarshaller.java0000644000175000017500000003535511145414170031426 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.io.IOException; import java.io.NotActiveException; /** * An abstract implementation of the {@code Marshaller} interface. Most of the * write methods delegate directly to the current data output. */ public abstract class AbstractMarshaller implements Marshaller { /** The configured externalizer factory. */ protected final ExternalizerFactory externalizerFactory; /** The configured class externalizer factory. */ protected final ClassExternalizerFactory classExternalizerFactory; /** The configured stream header. */ protected final StreamHeader streamHeader; /** The configured class resolver. */ protected final ClassResolver classResolver; /** The configured object resolver. */ protected final ObjectResolver objectResolver; /** The configured object creator. */ protected final Creator creator; /** The configured class table. */ protected final ClassTable classTable; /** The configured object table. */ protected final ObjectTable objectTable; /** The configured version to write. */ protected final int configuredVersion; /** The current byte output. */ protected ByteOutput byteOutput; /** * Construct a new marshaller instance. * * @param marshallerFactory the marshaller factory * @param configuration */ protected AbstractMarshaller(final AbstractMarshallerFactory marshallerFactory, final MarshallingConfiguration configuration) { final ExternalizerFactory externalizerFactory = configuration.getExternalizerFactory(); this.externalizerFactory = externalizerFactory == null ? marshallerFactory.getDefaultExternalizerFactory() : externalizerFactory; final ClassExternalizerFactory classExternalizerFactory = configuration.getClassExternalizerFactory(); this.classExternalizerFactory = classExternalizerFactory == null ? marshallerFactory.getDefaultClassExternalizerFactory() : classExternalizerFactory; final StreamHeader streamHeader = configuration.getStreamHeader(); this.streamHeader = streamHeader == null ? marshallerFactory.getDefaultStreamHeader() : streamHeader; final ClassResolver classResolver = configuration.getClassResolver(); this.classResolver = classResolver == null ? marshallerFactory.getDefaultClassResolver() : classResolver; final ObjectResolver objectResolver = configuration.getObjectResolver(); this.objectResolver = objectResolver == null ? marshallerFactory.getDefaultObjectResolver() : objectResolver; final Creator creator = configuration.getCreator(); this.creator = creator == null ? marshallerFactory.getDefaultCreator() : creator; final ClassTable classTable = configuration.getClassTable(); this.classTable = classTable == null ? marshallerFactory.getDefaultClassTable() : classTable; final ObjectTable objectTable = configuration.getObjectTable(); this.objectTable = objectTable == null ? marshallerFactory.getDefaultObjectTable() : objectTable; final int configuredVersion = configuration.getVersion(); this.configuredVersion = configuredVersion == -1 ? marshallerFactory.getDefaultVersion() : configuredVersion; final int minBufSize = marshallerFactory.getMinimumBufferSize(); final int bufferSize = configuration.getBufferSize(); this.bufferSize = bufferSize == -1 ? marshallerFactory.getDefaultBufferSize() : bufferSize < minBufSize ? minBufSize : bufferSize; } private static NotActiveException notActiveException() { return new NotActiveException("Output not started"); } protected final int bufferSize; private byte[] buffer; private int position; /** {@inheritDoc} */ public void write(final int v) throws IOException { try { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining == 0) { flush(); buffer[0] = (byte) v; position = 1; } else { buffer[position++] = (byte) v; } } catch (NullPointerException e) { throw notActiveException(); } } /** {@inheritDoc} */ public void write(final byte[] bytes) throws IOException { write(bytes, 0, bytes.length); } /** {@inheritDoc} */ public void write(final byte[] bytes, final int off, int len) throws IOException { final int bl = buffer.length; final int position = this.position; if (len > bl - position || len > bl >> 3) { flush(); byteOutput.write(bytes, off, len); } else { System.arraycopy(bytes, off, buffer, position, len); this.position = position + len; } } /** {@inheritDoc} */ public void writeBoolean(final boolean v) throws IOException { try { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining == 0) { flush(); buffer[0] = (byte) (v ? 1 : 0); position = 1; } else { buffer[position++] = (byte) (v ? 1 : 0); } } catch (NullPointerException e) { throw notActiveException(); } } /** {@inheritDoc} */ public void writeByte(final int v) throws IOException { try { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining == 0) { flush(); buffer[0] = (byte) v; position = 1; } else { buffer[position++] = (byte) v; } } catch (NullPointerException e) { throw notActiveException(); } } /** {@inheritDoc} */ public void writeShort(final int v) throws IOException { try { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 2) { flush(); buffer[0] = (byte) (v >> 8); buffer[1] = (byte) v; position = 2; } else { final int s = position; position = s + 2; buffer[s] = (byte) (v >> 8); buffer[s+1] = (byte) v; } } catch (NullPointerException e) { throw notActiveException(); } } /** {@inheritDoc} */ public void writeChar(final int v) throws IOException { try { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 2) { flush(); buffer[0] = (byte) (v >> 8); buffer[1] = (byte) v; position = 2; } else { final int s = position; position = s + 2; buffer[s] = (byte) (v >> 8); buffer[s+1] = (byte) v; } } catch (NullPointerException e) { throw notActiveException(); } } /** {@inheritDoc} */ public void writeInt(final int v) throws IOException { try { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 4) { flush(); buffer[0] = (byte) (v >> 24); buffer[1] = (byte) (v >> 16); buffer[2] = (byte) (v >> 8); buffer[3] = (byte) v; position = 4; } else { final int s = position; position = s + 4; buffer[s] = (byte) (v >> 24); buffer[s+1] = (byte) (v >> 16); buffer[s+2] = (byte) (v >> 8); buffer[s+3] = (byte) v; } } catch (NullPointerException e) { throw notActiveException(); } } /** {@inheritDoc} */ public void writeLong(final long v) throws IOException { try { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 8) { flush(); buffer[0] = (byte) (v >> 56L); buffer[1] = (byte) (v >> 48L); buffer[2] = (byte) (v >> 40L); buffer[3] = (byte) (v >> 32L); buffer[4] = (byte) (v >> 24L); buffer[5] = (byte) (v >> 16L); buffer[6] = (byte) (v >> 8L); buffer[7] = (byte) v; position = 8; } else { final int s = position; position = s + 8; buffer[s] = (byte) (v >> 56L); buffer[s+1] = (byte) (v >> 48L); buffer[s+2] = (byte) (v >> 40L); buffer[s+3] = (byte) (v >> 32L); buffer[s+4] = (byte) (v >> 24L); buffer[s+5] = (byte) (v >> 16L); buffer[s+6] = (byte) (v >> 8L); buffer[s+7] = (byte) v; } } catch (NullPointerException e) { throw notActiveException(); } } /** {@inheritDoc} */ public void writeFloat(final float v) throws IOException { final int bits = Float.floatToIntBits(v); try { final byte[] buffer = this.buffer; final int remaining = buffer.length - position; if (remaining < 4) { flush(); buffer[0] = (byte) (bits >> 24); buffer[1] = (byte) (bits >> 16); buffer[2] = (byte) (bits >> 8); buffer[3] = (byte) bits; position = 4; } else { final int s = position; position = s + 4; buffer[s] = (byte) (bits >> 24); buffer[s+1] = (byte) (bits >> 16); buffer[s+2] = (byte) (bits >> 8); buffer[s+3] = (byte) bits; } } catch (NullPointerException e) { throw notActiveException(); } } /** {@inheritDoc} */ public void writeDouble(final double v) throws IOException { final long bits = Double.doubleToLongBits(v); try { final int remaining = buffer.length - position; if (remaining < 8) { flush(); buffer[0] = (byte) (bits >> 56L); buffer[1] = (byte) (bits >> 48L); buffer[2] = (byte) (bits >> 40L); buffer[3] = (byte) (bits >> 32L); buffer[4] = (byte) (bits >> 24L); buffer[5] = (byte) (bits >> 16L); buffer[6] = (byte) (bits >> 8L); buffer[7] = (byte) bits; position = 8; } else { final int s = position; position = s + 8; buffer[s] = (byte) (bits >> 56L); buffer[s+1] = (byte) (bits >> 48L); buffer[s+2] = (byte) (bits >> 40L); buffer[s+3] = (byte) (bits >> 32L); buffer[s+4] = (byte) (bits >> 24L); buffer[s+5] = (byte) (bits >> 16L); buffer[s+6] = (byte) (bits >> 8L); buffer[s+7] = (byte) bits; } } catch (NullPointerException e) { throw notActiveException(); } } /** {@inheritDoc} */ public void writeBytes(final String s) throws IOException { final int len = s.length(); for (int i = 0; i < len; i ++) { write(s.charAt(i)); } } /** {@inheritDoc} */ public void writeChars(final String s) throws IOException { final int len = s.length(); for (int i = 0; i < len; i ++) { writeChar(s.charAt(i)); } } /** {@inheritDoc} */ public void writeUTF(final String s) throws IOException { writeShort(UTFUtils.getShortUTFLength(s)); UTFUtils.writeUTFBytes(this, s); } /** {@inheritDoc} */ public void flush() throws IOException { final int pos = position; final ByteOutput byteOutput = this.byteOutput; if (byteOutput != null) { if (pos > 0) { byteOutput.write(buffer, 0, pos); } position = 0; byteOutput.flush(); } } /** {@inheritDoc} */ public void close() throws IOException { finish(); } /** {@inheritDoc} */ public void start(final ByteOutput byteOutput) throws IOException { this.byteOutput = byteOutput; buffer = new byte[bufferSize]; doStart(); } /** {@inheritDoc} */ public void finish() throws IOException { try { flush(); } finally { buffer = null; byteOutput = null; clearClassCache(); } } /** * Implementation of the actual object-writing method. * * @param obj the object to write * @param unshared {@code true} if the instance is unshared, {@code false} if it is shared * @throws IOException if an I/O error occurs */ protected abstract void doWriteObject(Object obj, boolean unshared) throws IOException; /** {@inheritDoc} */ public final void writeObjectUnshared(final Object obj) throws IOException { doWriteObject(obj, true); } /** {@inheritDoc} */ public final void writeObject(final Object obj) throws IOException { doWriteObject(obj, false); } /** * Perform any marshaller-specific start activity. This implementation simply writes the stream header. * * @throws IOException if I/O exception occurs */ protected void doStart() throws IOException { streamHeader.writeHeader(this); } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/UTFUtils.java0000644000175000017500000002754211202552614027326 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.io.IOException; import java.io.UTFDataFormatException; import java.io.EOFException; /** * Handy utility methods for dealing with strings in the modified UTF-8 format. */ public final class UTFUtils { private static final String INVALID_BYTE = "Invalid byte"; private static final String MALFORMED = "Malformed UTF-8 sequence"; private UTFUtils() { } private static final int UTF_BUFS_CHAR_CNT = 256; private static final int UTF_BUFS_BYTE_CNT = UTF_BUFS_CHAR_CNT * 3; private static final class BytesHolder extends ThreadLocal { protected byte[] initialValue() { return new byte[UTF_BUFS_BYTE_CNT]; } } private static final BytesHolder BYTES_HOLDER = new BytesHolder(); /** * Get the number of bytes used by the modified UTF-8 encoded form of the given string. If the length is * greater than {@code 65536}, an exception is thrown. * * @param s the string * @return the length * @throws UTFDataFormatException if the string is longer than {@code 65536} characters */ public static int getShortUTFLength(final String s) throws UTFDataFormatException { final int length = s.length(); int l = 0; for (int i = 0; i < length; i ++) { final char c = s.charAt(i); if (c > 0 && c <= 0x7f) { l ++; } else if (c <= 0x07ff) { l += 2; } else { l += 3; } if (l > 65535) { throw new UTFDataFormatException("String is too long for writeUTF"); } } return l; } /** * Get the number of bytes used by the modified UTF-8 encoded form of the given string. * * @param s the string * @return the length */ public static long getLongUTFLength(final String s) { final int length = s.length(); long l = 0; for (int i = 0; i < length; i ++) { final char c = s.charAt(i); if (c > 0 && c <= 0x7f) { l ++; } else if (c <= 0x07ff) { l += 2L; } else { l += 3L; } } return l; } /** * Write the modified UTF-8 form of the given string to the given output. * * @param output the output to write to * @param s the string * @throws IOException if an I/O error occurs */ public static void writeUTFBytes(final ByteOutput output, final String s) throws IOException { final byte[] byteBuf = BYTES_HOLDER.get(); final int length = s.length(); int strIdx = 0; int byteIdx = 0; while (strIdx < length) { final char c = s.charAt(strIdx ++); if (c > 0 && c <= 0x7f) { byteBuf[byteIdx ++] = (byte) c; } else if (c <= 0x07ff) { byteBuf[byteIdx ++] = (byte)(0xc0 | 0x1f & c >> 6); byteBuf[byteIdx ++] = (byte)(0x80 | 0x3f & c); } else { byteBuf[byteIdx ++] = (byte)(0xe0 | 0x0f & c >> 12); byteBuf[byteIdx ++] = (byte)(0x80 | 0x3f & c >> 6); byteBuf[byteIdx ++] = (byte)(0x80 | 0x3f & c); } if (byteIdx > UTF_BUFS_BYTE_CNT - 4) { output.write(byteBuf, 0, byteIdx); byteIdx = 0; } } if (byteIdx > 0) { output.write(byteBuf, 0, byteIdx); } } /** * Read the given number of characters from the given byte input. The length given is in characters, * NOT in bytes. * * @param input the byte source * @param len the number of characters to read * @return the string * @throws IOException if an I/O error occurs */ public static String readUTFBytes(final ByteInput input, final int len) throws IOException { final byte[] byteBuf = BYTES_HOLDER.get(); final char[] chars = new char[len]; int i = 0, cnt = 0, charIdx = 0; while (charIdx < len) { if (i == cnt) { cnt = input.read(byteBuf, 0, Math.min(UTF_BUFS_BYTE_CNT, len - charIdx)); if (cnt < 0) { throw new EOFException(); } i = 0; } final int a = byteBuf[i++] & 0xff; if (a < 0x80) { // low bit clear chars[charIdx ++] = (char) a; } else if (a < 0xc0) { throw new UTFDataFormatException(INVALID_BYTE); } else if (a < 0xe0) { if (i == cnt) { cnt = input.read(byteBuf, 0, Math.min(UTF_BUFS_BYTE_CNT, len - charIdx)); if (cnt < 0) { throw new EOFException(); } i = 0; } final int b = byteBuf[i ++] & 0xff; if ((b & 0xc0) != 0x80) { throw new UTFDataFormatException(INVALID_BYTE); } chars[charIdx ++] = (char) ((a & 0x1f) << 6 | b & 0x3f); } else if (a < 0xf0) { if (i == cnt) { cnt = input.read(byteBuf, 0, Math.min(UTF_BUFS_BYTE_CNT, len - charIdx)); if (cnt < 0) { throw new EOFException(); } i = 0; } final int b = byteBuf[i ++] & 0xff; if ((b & 0xc0) != 0x80) { throw new UTFDataFormatException(INVALID_BYTE); } if (i == cnt) { cnt = input.read(byteBuf, 0, Math.min(UTF_BUFS_BYTE_CNT, len - charIdx)); if (cnt < 0) { throw new EOFException(); } i = 0; } final int c = byteBuf[i ++] & 0xff; if ((c & 0xc0) != 0x80) { throw new UTFDataFormatException(INVALID_BYTE); } chars[charIdx ++] = (char) ((a & 0x0f) << 12 | (b & 0x3f) << 6 | c & 0x3f); } else { throw new UTFDataFormatException(INVALID_BYTE); } } return String.valueOf(chars); } /** * Read the given number of characters from the given byte input. The length given is in bytes. * * @param input the byte source * @param len the number of bytes to read * @return the string * @throws IOException if an I/O error occurs */ public static String readUTFBytesByByteCount(final ByteInput input, final long len) throws IOException { final StringBuilder builder = new StringBuilder(); for (long i = 0; i < len; i ++) { final int a = input.read(); if (a < 0) { throw new EOFException("Expected " + (len - i) + " more bytes"); } else if (a == 0) { builder.append('\0'); } else if (a < 0x80) { builder.append((char) a); } else if (a < 0xc0) { throw new UTFDataFormatException(INVALID_BYTE); } else if (a < 0xe0) { if (++i < len) { final int b = input.read(); if (b == -1) { throw new EOFException("Expected " + (len - i) + " more bytes"); } else if ((b & 0xc0) != 0x80) { throw new UTFDataFormatException(INVALID_BYTE); } builder.append((char) ((a & 0x1f) << 6 | b & 0x3f)); } else { throw new UTFDataFormatException(MALFORMED); } } else if (a < 0xf0) { if (++i < len) { final int b = input.read(); if (b == -1) { throw new EOFException("Expected " + (len - i) + " more bytes"); } else if ((b & 0xc0) != 0x80) { throw new UTFDataFormatException(INVALID_BYTE); } if (++i < len) { final int c1 = input.read(); if (c1 == -1) { throw new EOFException("Expected " + (len - i) + " more bytes"); } else if ((c1 & 0xc0) != 0x80) { throw new UTFDataFormatException(INVALID_BYTE); } builder.append((char) ((a & 0x0f) << 12 | (b & 0x3f) << 6 | c1 & 0x3f)); } else { throw new UTFDataFormatException(MALFORMED); } } else { throw new UTFDataFormatException(MALFORMED); } } else { throw new UTFDataFormatException(INVALID_BYTE); } } return builder.toString(); } /** * Read a null-terminated modified UTF-8 string from the given byte input. Bytes are read until a 0 is found or * until the end of the stream, whichever comes first. * * @param input the input * @return the string * @throws IOException if an I/O error occurs */ public static String readUTFZBytes(final ByteInput input) throws IOException { final StringBuilder builder = new StringBuilder(); for (;;) { final int c = readUTFChar(input); if (c == -1) { return builder.toString(); } builder.append((char) c); } } private static int readUTFChar(final ByteInput input) throws IOException { final int a = input.read(); if (a < 0) { throw new EOFException(); } else if (a == 0) { return -1; } else if (a < 0x80) { return (char)a; } else if (a < 0xc0) { throw new UTFDataFormatException(INVALID_BYTE); } else if (a < 0xe0) { final int b = input.read(); if (b == -1) { throw new EOFException(); } else if ((b & 0xc0) != 0x80) { throw new UTFDataFormatException(INVALID_BYTE); } return (a & 0x1f) << 6 | b & 0x3f; } else if (a < 0xf0) { final int b = input.read(); if (b == -1) { throw new EOFException(); } else if ((b & 0xc0) != 0x80) { throw new UTFDataFormatException(INVALID_BYTE); } final int c = input.read(); if (c == -1) { throw new EOFException(); } else if ((c & 0xc0) != 0x80) { throw new UTFDataFormatException(INVALID_BYTE); } return (a & 0x0f) << 12 | (b & 0x3f) << 6 | c & 0x3f; } else { throw new UTFDataFormatException(INVALID_BYTE); } } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/ClassTable.java0000644000175000017500000000471611122550145027660 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.io.IOException; /** * A lookup mechanism for predefined classes. Some marshallers can use this to * avoid sending lengthy class descriptor information. */ public interface ClassTable { /** * Determine whether the given class reference is a valid predefined reference. * * @param clazz the candidate class * @return the class writer, or {@code null} to use the default mechanism * @throws IOException if an I/O error occurs */ Writer getClassWriter(Class clazz) throws IOException; /** * Read a class from the stream. The class will have been written by the * {@link #getClassWriter(Class)} method's {@code Writer} instance, as defined above. * * @param unmarshaller the unmarshaller to read from * @return the class * @throws IOException if an I/O error occurs * @throws ClassNotFoundException if a class could not be found */ Class readClass(Unmarshaller unmarshaller) throws IOException, ClassNotFoundException; /** * The class writer for a specific class. */ interface Writer { /** * Write the predefined class reference to the stream. * * @param marshaller the marshaller to write to * @param clazz the class reference to write * @throws IOException if an I/O error occurs */ void writeClass(Marshaller marshaller, Class clazz) throws IOException; } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/ClassResolver.java0000644000175000017500000001052311140107201030412 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.io.IOException; /** * A class annotater and resolver. Instances of this interface have the opportunity * to append information (such as classloader information, or class bytes) to a written * class descriptor. This information can then be used on unmarshalling to aid in the * selection (or creation) of the proper {@code Class} based on the class descriptor and * the annotation data. */ public interface ClassResolver { /** * Add optional information about a class to a stream. The class descriptor will * already have been written. * * @see java.io.ObjectOutputStream#annotateClass(Class) * * @param marshaller the marshaller to write to * @param clazz the class that was written * @throws IOException if an error occurs */ void annotateClass(Marshaller marshaller, Class clazz) throws IOException; /** * Add optional information about a proxy class to a stream. The class descriptor will * already have been written. * * @see java.io.ObjectOutputStream#annotateProxyClass(Class) * * @param marshaller the marshaller to write to * @param proxyClass the chass that was written * @throws IOException if an error occurs */ void annotateProxyClass(Marshaller marshaller, Class proxyClass) throws IOException; /** * Get the class name to write for a given class. The class name will be written as part of the * class descriptor. * * @param clazz the class * @return the class name * @throws IOException if an error occurs */ String getClassName(Class clazz) throws IOException; /** * Get the interface names to write for a given proxy class. The interface names will be written as part * of the class descriptor. * * @param proxyClass the proxy class * @return the proxy class interface names * @throws IOException if an error occurs */ String[] getProxyInterfaces(Class proxyClass) throws IOException; /** * Load the local class for a class descriptor. The class descriptor has already been read, * but any data written by {@link #annotateClass(Marshaller, Class)} should be read by this method. * * @see java.io.ObjectInputStream#resolveClass(java.io.ObjectStreamClass) * * @param unmarshaller the unmarshaller from which to read annotation data, if any * @param name the class name * @param serialVersionUID the serial version UID * @return the corresponding class * @throws IOException if an I/O error occurs * @throws ClassNotFoundException if the class could not be loaded */ Class resolveClass(Unmarshaller unmarshaller, String name, long serialVersionUID) throws IOException, ClassNotFoundException; /** * Load a proxy class that implements the given interfaces. * * @see java.io.ObjectInputStream#resolveProxyClass(String[]) * * @param unmarshaller the unmarshaller from which to read annotation data, if any * @param interfaces the class descriptor * @return the proxy class * @throws IOException if an I/O error occurs * @throws ClassNotFoundException if the proxy class could not be loaded */ Class resolveProxyClass(Unmarshaller unmarshaller, String[] interfaces) throws IOException, ClassNotFoundException; } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/package-info.java0000644000175000017500000000100511140107071030147 0ustar twernertwerner/** * The marshalling API. Marshalling is done by use of {@link org.jboss.marshalling.Marshaller Marshaller} and {@link org.jboss.marshalling.Unmarshaller Unmarshaller} instances. These * instances are acquired from a {@link org.jboss.marshalling.MarshallerFactory MarshallerFactory} using a {@link MarshallingConfiguration Configuration} to configure them. The * default implementation is the River protocol, usable by way of the {@link org.jboss.marshalling.river} package. */ package org.jboss.marshalling; jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/Externalize.java0000644000175000017500000000365011140105560030126 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Documented; /** * Indicate that this class should be externalized by an instance of the given externalizer class. Any externalizer * provided by a {@link org.jboss.marshalling.ClassExternalizerFactory ClassExternalizerFactory} or a * {@link org.jboss.marshalling.ExternalizerFactory ExternalizerFactory} will take precedence over the externalizer * specified by this annotation. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Inherited @Documented public @interface Externalize { /** * Specify the externalizer class to be used by the annotated class. * * @return the externalizer type */ Class value(); } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/ExternalizerFactory.java0000644000175000017500000000305611140105112031631 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; /** * A factory for locating custom externalizers. * * @deprecated Please see {@link org.jboss.marshalling.ClassExternalizerFactory ClassExternalizerFactory}. */ @Deprecated public interface ExternalizerFactory { /** * Look up a custom externalizer for a given object instance. If no such externalizer exists, returns {@code null}. * * @param instance the instance to be externalized * @return the externalizer, or {@code null} if there is none */ Externalizer getExternalizer(Object instance); } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/ChainingObjectTable.java0000644000175000017500000000766211140360720031463 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.util.List; import java.util.ArrayList; import java.io.IOException; import java.io.StreamCorruptedException; /** * An object table that multiplexes up to 256 class tables. The protocol works by prepending the custom object table * with an identifier byte. */ public class ChainingObjectTable implements ObjectTable { private interface Pair { X getX(); Y getY(); } private static Pair pair(final ObjectTable objectTable, final Writer writer) { return new Pair() { public ObjectTable getX() { return objectTable; } public Writer getY() { return writer; } }; } private final List> writers; private final ObjectTable[] readers; /** * Construct a new instance. The given array may be sparse, but it may not be more than * 256 elements in length. Object tables are checked in order of increasing array index. * * @param objectTables the object tables to delegate to */ public ChainingObjectTable(final ObjectTable[] objectTables) { if (objectTables == null) { throw new NullPointerException("objectTables is null"); } readers = objectTables.clone(); if (readers.length > 256) { throw new IllegalArgumentException("Object table array is too long (limit is 256 elements)"); } writers = new ArrayList>(); for (int i = 0; i < readers.length; i++) { final ObjectTable objectTable = readers[i]; if (objectTable != null) { final int idx = i; writers.add(pair(objectTable, new Writer() { public void writeObject(final Marshaller marshaller, final Object obj) throws IOException { marshaller.writeByte(idx); objectTable.getObjectWriter(obj).writeObject(marshaller, obj); } })); } } } /** {@inheritDoc} */ public Writer getObjectWriter(final Object obj) throws IOException { for (Pair entry : writers) { final ObjectTable table = entry.getX(); final Writer writer = entry.getY(); if (table.getObjectWriter(obj) != null) { return writer; } } return null; } /** {@inheritDoc} */ public Object readObject(final Unmarshaller unmarshaller) throws IOException, ClassNotFoundException { final int v = unmarshaller.readByte() & 0xff; final ObjectTable table = readers[v]; if (table == null) { throw new StreamCorruptedException(String.format("Unknown object table ID %02x encountered", Integer.valueOf(v))); } return table.readObject(unmarshaller); } }jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/Version.java0000644000175000017500000000262711204556030027267 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; /** * The version of the Marshalling API. */ public final class Version { private Version() { } /** * The version. */ public static final String VERSION = "1.1.3.GA"; /** * Print the version to {@code System.out}. * * @param args ignored */ public static void main(String[] args) { System.out.print(VERSION); } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/ByteInput.java0000644000175000017500000000636511122550145027570 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.io.Closeable; import java.io.IOException; /** * An input stream of bytes. */ public interface ByteInput extends Closeable { /** * Reads the next byte of data from the input stream. If no byte is available because the end of the stream has * been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream * is detected, or an exception is thrown. * * @return the next byte, or -1 if the end of stream has been reached * @throws IOException if an error occurs */ int read() throws IOException; /** * Read some bytes from the input stream into the given array. Returns the number of bytes actually read (possibly * zero), or -1 if the end of stream has been reached. * * @param b the destination array * @return the number of bytes read (possibly zero), or -1 if the end of stream has been reached * @throws IOException if an error occurs */ int read(byte[] b) throws IOException; /** * Read some bytes from the input stream into the given array. Returns the number of bytes actually read (possibly * zero), or -1 if the end of stream has been reached. * * @param b the destination array * @param off the offset into the array into which data should be read * @param len the number of bytes to attempt to fill in the destination array * @return the number of bytes read (possibly zero), or -1 if the end of stream has been reached * @throws IOException if an error occurs */ int read(byte[] b, int off, int len) throws IOException; /** * Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without * blocking by the next invocation of a method for this input stream. * * @return the number of bytes * @throws IOException if an error occurs */ int available() throws IOException; /** * Skips over and discards up to {@code n} bytes of data from this input stream. * * @param n the number of bytes to attempt to skip * @return the number of bytes skipped * @throws IOException if an error occurs */ long skip(long n) throws IOException; } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/SimpleClassResolver.java0000644000175000017500000000405111153270554031603 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; /** * A class resolver which uses a predefined classloader. */ public class SimpleClassResolver extends AbstractClassResolver { private final ClassLoader classLoader; /** * Construct a new instance, specifying a classloader. * * @param classLoader the classloader to use */ public SimpleClassResolver(final ClassLoader classLoader) { this(false, classLoader); } /** * Construct a new instance, specifying a classloader and a flag which determines whether {@code serialVersionUID} * matching will be enforced. * * @param enforceSerialVersionUid {@code true} to throw an exception on unmatched {@code serialVersionUID} * @param classLoader the classloader to use */ public SimpleClassResolver(final boolean enforceSerialVersionUid, final ClassLoader classLoader) { super(enforceSerialVersionUid); this.classLoader = classLoader; } /** {@inheritDoc} */ protected ClassLoader getClassLoader() { return classLoader; } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/Unmarshaller.java0000644000175000017500000000431411122550145030272 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.io.ObjectInput; import java.io.IOException; /** * An unmarshaller which reads objects from a stream. */ public interface Unmarshaller extends ObjectInput, ByteInput { /** * Read and return an unshared object. * * @return an unshared object * @throws IOException if an error occurs */ Object readObjectUnshared() throws ClassNotFoundException, IOException; /** * Begin unmarshalling from a stream. * * @param newInput the new stream * @throws IOException if an error occurs during setup, such as an invalid header */ void start(ByteInput newInput) throws IOException; /** * Discard the instance cache. * * @throws IOException if an error occurs */ void clearInstanceCache() throws IOException; /** * Discard the class cache. Implicitly also discards the instance cache. * * @throws IOException if an error occurs */ void clearClassCache() throws IOException; /** * Finish unmarshalling from a stream. Any transient class or instance cache is discarded. * * @throws IOException if an error occurs */ void finish() throws IOException; } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/0000755000175000017500000000000011253762303025753 5ustar twernertwernerjboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/CharReadField.java0000644000175000017500000000314511143125530031227 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.reflect.SerializableField; import java.io.IOException; /** * */ public class CharReadField extends ReadField { private final char value; public CharReadField(final SerializableField field, final char value) { super(field.getName(), false); this.value = value; } public CharReadField(final SerializableField field) { super(field.getName(), true); value = 0; } public Kind getKind() { return Kind.CHAR; } public char getChar() throws IOException { return value; } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/ByteFieldPutter.java0000644000175000017500000000276311143125530031672 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.Marshaller; import java.io.IOException; /** * */ public class ByteFieldPutter extends FieldPutter { private byte value; public void write(final Marshaller marshaller) throws IOException { marshaller.writeByte(value); } public Kind getKind() { return Kind.BYTE; } public byte getByte() { return value; } public void setByte(final byte value) { this.value = value; } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/ShortReadField.java0000644000175000017500000000315511143125530031452 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.reflect.SerializableField; import java.io.IOException; /** * */ public class ShortReadField extends ReadField { private final short value; public ShortReadField(final SerializableField field, final short value) { super(field.getName(), false); this.value = value; } public ShortReadField(final SerializableField field) { super(field.getName(), true); value = 0; } public Kind getKind() { return Kind.SHORT; } public short getShort() throws IOException { return value; } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/CharFieldPutter.java0000644000175000017500000000276211143125530031643 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.Marshaller; import java.io.IOException; /** * */ public class CharFieldPutter extends FieldPutter { private char value; public void write(final Marshaller marshaller) throws IOException { marshaller.writeChar(value); } public Kind getKind() { return Kind.CHAR; } public char getChar() { return value; } public void setChar(final char value) { this.value = value; } }jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/BooleanReadField.java0000644000175000017500000000320111143125530031722 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.reflect.SerializableField; import java.io.IOException; /** * */ public class BooleanReadField extends ReadField { private final boolean value; public BooleanReadField(final SerializableField field, final boolean value) { super(field.getName(), false); this.value = value; } public BooleanReadField(final SerializableField field) { super(field.getName(), true); value = false; } public Kind getKind() { return Kind.BOOLEAN; } public boolean getBoolean() throws IOException { return value; } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/Kind.java0000644000175000017500000000225111143125530027474 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; /** * */ public enum Kind { BOOLEAN, BYTE, CHAR, DOUBLE, FLOAT, INT, LONG, OBJECT, SHORT, ; } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/LongReadField.java0000644000175000017500000000314511143125530031251 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.reflect.SerializableField; import java.io.IOException; /** * */ public class LongReadField extends ReadField { private final long value; public LongReadField(final SerializableField field, final long value) { super(field.getName(), false); this.value = value; } public LongReadField(final SerializableField field) { super(field.getName(), true); value = 0; } public Kind getKind() { return Kind.LONG; } public long getLong() throws IOException { return value; } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/ShortFieldPutter.java0000644000175000017500000000277211143125530032066 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.Marshaller; import java.io.IOException; /** * */ public class ShortFieldPutter extends FieldPutter { private short value; public void write(final Marshaller marshaller) throws IOException { marshaller.writeShort(value); } public Kind getKind() { return Kind.SHORT; } public short getShort() { return value; } public void setShort(final short value) { this.value = value; } }jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/BooleanFieldPutter.java0000644000175000017500000000300611143125530032335 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import java.io.IOException; import org.jboss.marshalling.Marshaller; /** * */ public class BooleanFieldPutter extends FieldPutter { private boolean value; public void write(final Marshaller marshaller) throws IOException { marshaller.writeBoolean(value); } public Kind getKind() { return Kind.BOOLEAN; } public void setBoolean(boolean value) { this.value = value; } public boolean getBoolean() { return value; } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/ObjectFieldPutter.java0000644000175000017500000000336011143125530032167 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.Marshaller; import java.io.IOException; /** * */ public class ObjectFieldPutter extends FieldPutter { private Object value; private final boolean unshared; public ObjectFieldPutter(final boolean unshared) { this.unshared = unshared; } public void write(final Marshaller marshaller) throws IOException { if (unshared) { marshaller.writeObjectUnshared(value); } else { marshaller.writeObject(value); } } public Kind getKind() { return Kind.OBJECT; } public Object getObject() { return value; } public void setObject(final Object value) { this.value = value; } }jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/IntReadField.java0000644000175000017500000000313511143125530031103 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.reflect.SerializableField; import java.io.IOException; /** * */ public class IntReadField extends ReadField { private final int value; public IntReadField(final SerializableField field, final int value) { super(field.getName(), false); this.value = value; } public IntReadField(final SerializableField field) { super(field.getName(), true); value = 0; } public Kind getKind() { return Kind.INT; } public int getInt() throws IOException { return value; } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/FieldPutter.java0000644000175000017500000000652411143125530031045 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import java.io.IOException; import org.jboss.marshalling.Marshaller; /** * */ public abstract class FieldPutter { protected FieldPutter() { } public abstract void write(final Marshaller marshaller) throws IOException; public abstract Kind getKind(); public void setBoolean(boolean value) { throw new IllegalArgumentException("Field is not a boolean field"); } public boolean getBoolean() { throw new IllegalArgumentException("Field is not a boolean field"); } public byte getByte() { throw new IllegalArgumentException("Field is not a byte field"); } public void setByte(byte value) { throw new IllegalArgumentException("Field is not a byte field"); } public char getChar() { throw new IllegalArgumentException("Field is not a char field"); } public void setChar(char value) { throw new IllegalArgumentException("Field is not a char field"); } public double getDouble() { throw new IllegalArgumentException("Field is not a double field"); } public void setDouble(double value) { throw new IllegalArgumentException("Field is not a double field"); } public float getFloat() { throw new IllegalArgumentException("Field is not a float field"); } public void setFloat(float value) { throw new IllegalArgumentException("Field is not a float field"); } public int getInt() { throw new IllegalArgumentException("Field is not an int field"); } public void setInt(int value) { throw new IllegalArgumentException("Field is not an int field"); } public long getLong() { throw new IllegalArgumentException("Field is not a long field"); } public void setLong(long value) { throw new IllegalArgumentException("Field is not a long field"); } public Object getObject() { throw new IllegalArgumentException("Field is not an Object field"); } public void setObject(Object value) { throw new IllegalArgumentException("Field is not an Object field"); } public short getShort() { throw new IllegalArgumentException("Field is not a short field"); } public void setShort(short value) { throw new IllegalArgumentException("Field is not a short field"); } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/DoubleReadField.java0000644000175000017500000000316511143125530031566 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.reflect.SerializableField; import java.io.IOException; /** * */ public class DoubleReadField extends ReadField { private final double value; public DoubleReadField(final SerializableField field, final double value) { super(field.getName(), false); this.value = value; } public DoubleReadField(final SerializableField field) { super(field.getName(), true); value = 0; } public Kind getKind() { return Kind.DOUBLE; } public double getDouble() throws IOException { return value; } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/ReadField.java0000644000175000017500000000476611143125530030443 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import java.io.IOException; /** * */ public abstract class ReadField implements Comparable { private final String name; private final boolean defaulted; protected ReadField(final String name, final boolean defaulted) { this.name = name; this.defaulted = defaulted; } public abstract Kind getKind(); public String getName() { return name; } public boolean isDefaulted() { return defaulted; } public boolean getBoolean() throws IOException { throw wrongFieldType(); } public char getChar() throws IOException { throw wrongFieldType(); } public float getFloat() throws IOException { throw wrongFieldType(); } public double getDouble() throws IOException { throw wrongFieldType(); } public byte getByte() throws IOException { throw wrongFieldType(); } public short getShort() throws IOException { throw wrongFieldType(); } public int getInt() throws IOException { throw wrongFieldType(); } public long getLong() throws IOException { throw wrongFieldType(); } public Object getObject() throws IOException { throw wrongFieldType(); } private static IllegalArgumentException wrongFieldType() { return new IllegalArgumentException("Invalid field type"); } public int compareTo(final ReadField o) { return name.compareTo(o.name); } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/ByteReadField.java0000644000175000017500000000314511143125530031255 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.reflect.SerializableField; import java.io.IOException; /** * */ public class ByteReadField extends ReadField { private final byte value; public ByteReadField(final SerializableField field, final byte value) { super(field.getName(), false); this.value = value; } public ByteReadField(final SerializableField field) { super(field.getName(), true); value = 0; } public Kind getKind() { return Kind.BYTE; } public byte getByte() throws IOException { return value; } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/IdentityIntMap.java0000644000175000017500000001533711200746720031526 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import java.util.Arrays; /** * An efficient identity object map whose keys are objects and whose values are {@code int}s. */ public final class IdentityIntMap { private int[] values; private Object[] keys; private int count; private int resizeCount; /** * Construct a new instance with the given initial capacity and load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor */ public IdentityIntMap(int initialCapacity, final float loadFactor) { if (initialCapacity < 1) { throw new IllegalArgumentException("initialCapacity must be > 0"); } if (loadFactor <= 0.0f || loadFactor >= 1.0f) { throw new IllegalArgumentException("loadFactor must be > 0.0 and < 1.0"); } if (initialCapacity < 16) { initialCapacity = 16; } else { // round up final int c = Integer.highestOneBit(initialCapacity) - 1; initialCapacity = Integer.highestOneBit(initialCapacity + c); } keys = new Object[initialCapacity]; values = new int[initialCapacity]; resizeCount = (int) ((double) initialCapacity * (double) loadFactor); } /** * Construct a new instance with the given load factor and an initial capacity of 64. * * @param loadFactor the load factor */ public IdentityIntMap(final float loadFactor) { this(64, loadFactor); } /** * Construct a new instance with the given initial capacity and a load factor of {@code 0.5}. * * @param initialCapacity the initial capacity */ public IdentityIntMap(final int initialCapacity) { this(initialCapacity, 0.5f); } /** * Construct a new instance with an initial capacity of 64 and a load factor of {@code 0.5}. */ public IdentityIntMap() { this(0.5f); } /** * Get a value from the map. * * @param key the key * @param defVal the value to return if the key is not found * @return the map value at the given key, or the value of {@code defVal} if it's not found */ public int get(T key, int defVal) { if (key == null) { throw new NullPointerException("key is null"); } final Object[] keys = this.keys; final int mask = keys.length - 1; int hc = System.identityHashCode(key) & mask; Object v; for (;;) { v = keys[hc]; if (v == key) { return values[hc]; } if (v == null) { // not found return defVal; } hc = (hc + 1) & mask; } } /** * Put a value into the map. Any previous mapping is discarded silently. * * @param key the key * @param value the value to store */ public void put(T key, int value) { if (key == null) { throw new NullPointerException("key is null"); } final Object[] keys = this.keys; final int mask = keys.length - 1; final int[] values = this.values; Object v; int hc = System.identityHashCode(key) & mask; for (int idx = hc;; idx = hc++ & mask) { v = keys[idx]; if (v == null) { keys[idx] = key; values[idx] = value; if (++count > resizeCount) { resize(); } return; } if (v == key) { values[idx] = value; return; } } } private void resize() { final Object[] oldKeys = keys; final int oldsize = oldKeys.length; final int[] oldValues = values; if (oldsize >= 0x40000000) { throw new IllegalStateException("Table full"); } final int newsize = oldsize << 1; final int mask = newsize - 1; final Object[] newKeys = new Object[newsize]; final int[] newValues = new int[newsize]; keys = newKeys; values = newValues; if ((resizeCount <<= 1) == 0) { resizeCount = Integer.MAX_VALUE; } for (int oi = 0; oi < oldsize; oi ++) { final Object key = oldKeys[oi]; if (key != null) { int ni = System.identityHashCode(key) & mask; for (;;) { final Object v = newKeys[ni]; if (v == null) { // found newKeys[ni] = key; newValues[ni] = oldValues[oi]; break; } ni = (ni + 1) & mask; } } } } public void clear() { Arrays.fill(keys, null); count = 0; } /** * Get a string summary representation of this map. * * @return a string representation */ public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Map length = ").append(keys.length).append(", count = ").append(count).append(", resize count = ").append(resizeCount).append('\n'); for (int i = 0; i < keys.length; i ++) { builder.append('[').append(i).append("] = "); if (keys[i] != null) { final int hc = System.identityHashCode(keys[i]); builder.append("{ ").append(keys[i]).append(" (hash ").append(hc).append(", modulus ").append(hc % keys.length).append(") => ").append(values[i]).append(" }"); } else { builder.append("(blank)"); } builder.append('\n'); } return builder.toString(); } }jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/DoubleFieldPutter.java0000644000175000017500000000300211143125530032164 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.Marshaller; import java.io.IOException; /** * */ public class DoubleFieldPutter extends FieldPutter { private double value; public void write(final Marshaller marshaller) throws IOException { marshaller.writeDouble(value); } public Kind getKind() { return Kind.DOUBLE; } public double getDouble() { return value; } public void setDouble(final double value) { this.value = value; } }jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/FloatFieldPutter.java0000644000175000017500000000277211143125530032034 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.Marshaller; import java.io.IOException; /** * */ public class FloatFieldPutter extends FieldPutter { private float value; public void write(final Marshaller marshaller) throws IOException { marshaller.writeFloat(value); } public Kind getKind() { return Kind.FLOAT; } public float getFloat() { return value; } public void setFloat(final float value) { this.value = value; } }jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/ObjectReadField.java0000644000175000017500000000317011143125530031556 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.reflect.SerializableField; import java.io.IOException; /** * */ public class ObjectReadField extends ReadField { private final Object value; public ObjectReadField(final SerializableField field, final Object value) { super(field.getName(), false); this.value = value; } public ObjectReadField(final SerializableField field) { super(field.getName(), true); value = null; } public Kind getKind() { return Kind.OBJECT; } public Object getObject() throws IOException { return value; } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/IntFieldPutter.java0000644000175000017500000000275211143125530031517 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.Marshaller; import java.io.IOException; /** * */ public class IntFieldPutter extends FieldPutter { private int value; public void write(final Marshaller marshaller) throws IOException { marshaller.writeInt(value); } public Kind getKind() { return Kind.INT; } public int getInt() { return value; } public void setInt(final int value) { this.value = value; } }jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/FloatReadField.java0000644000175000017500000000315511143125530031420 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.reflect.SerializableField; import java.io.IOException; /** * */ public class FloatReadField extends ReadField { private final float value; public FloatReadField(final SerializableField field, final float value) { super(field.getName(), false); this.value = value; } public FloatReadField(final SerializableField field) { super(field.getName(), true); value = 0; } public Kind getKind() { return Kind.FLOAT; } public float getFloat() throws IOException { return value; } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/util/LongFieldPutter.java0000644000175000017500000000276211143125530031665 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.util; import org.jboss.marshalling.Marshaller; import java.io.IOException; /** * */ public class LongFieldPutter extends FieldPutter { private long value; public void write(final Marshaller marshaller) throws IOException { marshaller.writeLong(value); } public Kind getKind() { return Kind.LONG; } public long getLong() { return value; } public void setLong(final long value) { this.value = value; } }jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/ContextClassResolver.java0000644000175000017500000000426111153270554032001 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.security.AccessController; import java.security.PrivilegedAction; /** * A class resolver which uses the context classloader to resolve classes. */ public class ContextClassResolver extends AbstractClassResolver { private static final PrivilegedAction classLoaderAction = new PrivilegedAction() { public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } }; /** * Construct a new instance. */ public ContextClassResolver() { } /** * Construct a new instance. * * @param enforceSerialVersionUid {@code true} if an exception should be thrown on an incorrect serialVersionUID */ public ContextClassResolver(final boolean enforceSerialVersionUid) { super(enforceSerialVersionUid); } /** {@inheritDoc} */ protected ClassLoader getClassLoader() { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { return AccessController.doPrivileged(classLoaderAction); } else { return Thread.currentThread().getContextClassLoader(); } } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootjboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/AnnotationClassExternalizerFactory.javajboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/AnnotationClassExternalizerFactor0000644000175000017500000000346311151425007033555 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; /** * An externalizer factory which looks for the presence of the {@link org.jboss.marshalling.Externalize Externalize} annotation. */ public class AnnotationClassExternalizerFactory implements ClassExternalizerFactory { /** * Construct a new instance. */ public AnnotationClassExternalizerFactory() { } /** {@inheritDoc} */ public Externalizer getExternalizer(final Class type) { final Externalize ann = type.getAnnotation(Externalize.class); if (ann == null) { return null; } else { try { return ann.value().newInstance(); } catch (Exception e) { throw new IllegalArgumentException("Cannot instantiate externalizer for " + type, e); } } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootjboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/MappingClassExternalizerFactory.javajboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/MappingClassExternalizerFactory.j0000644000175000017500000000354511151301665033463 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling; import java.util.Map; import java.util.HashMap; import java.util.Collections; /** * An externalizer factory which uses a fixed mapping from class to externalizer. */ public class MappingClassExternalizerFactory implements ClassExternalizerFactory { private final Map, Externalizer> externalizerMap; /** * Construct a new instance. A copy is made of the given map. * * @param map the mapping */ public MappingClassExternalizerFactory(final Map, Externalizer> map) { externalizerMap = Collections.unmodifiableMap(new HashMap, Externalizer>(map)); } /** {@inheritDoc} This implementation uses the fixed mapping that was specified in the constructor. */ public Externalizer getExternalizer(final Class type) { return externalizerMap.get(type); } } jboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/reflect/0000755000175000017500000000000011253762302026421 5ustar twernertwerner././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootjboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/reflect/SerializableClassRegistry.javajboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/reflect/SerializableClassRegistry0000644000175000017500000000667411122550145033501 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.reflect; import java.io.SerializablePermission; import java.util.concurrent.ConcurrentMap; import java.util.EnumSet; import java.security.AccessController; import java.security.PrivilegedAction; /** * A registry for reflection information usable by serialization implementations. Objects returned from this registry * can be used to invoke private methods without security checks, so it is important to be careful not to "leak" instances * out of secured implementations. */ public final class SerializableClassRegistry { private SerializableClassRegistry() { } private static final SerializableClassRegistry INSTANCE = new SerializableClassRegistry(); private static final SerializablePermission PERMISSION = new SerializablePermission("allowSerializationReflection"); /** * Get the serializable class registry instance, if allowed by the current security manager. The caller must have * the {@code java.io.SerializablePermission} {@code "allowSerializationReflection"} in order to invoke this method. * * @return the registry * @throws SecurityException if the caller does not have sufficient privileges */ public static SerializableClassRegistry getInstance() throws SecurityException { SecurityManager manager = System.getSecurityManager(); if (manager != null) { manager.checkPermission(PERMISSION); } return INSTANCE; } private final ConcurrentMap, SerializableClass> cache = new ConcurrentReferenceHashMap, SerializableClass>(512, 0.8f, 16, ConcurrentReferenceHashMap.ReferenceType.WEAK, ConcurrentReferenceHashMap.ReferenceType.STRONG, EnumSet.of(ConcurrentReferenceHashMap.Option.IDENTITY_COMPARISONS)); /** * Look up serialization information for a class. The resultant object will be cached. * * @param subject the class to look up * @return the serializable class informatio */ public SerializableClass lookup(final Class subject) { SerializableClass info = cache.get(subject); if (info != null) { return info; } info = AccessController.doPrivileged(new PrivilegedAction() { public SerializableClass run() { return new SerializableClass(subject); } }); final SerializableClass old = cache.putIfAbsent(subject, info); return old != null ? old : info; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootjboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/reflect/ConcurrentReferenceHashMap.javajboss-marshalling-1.1.3.GA/api/src/main/java/org/jboss/marshalling/reflect/ConcurrentReferenceHashMa0000644000175000017500000017365411122550145033402 0ustar twernertwerner/* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package org.jboss.marshalling.reflect; import java.io.IOException; import java.io.Serializable; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.EnumSet; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.locks.ReentrantLock; /** * An advanced hash table supporting configurable garbage collection semantics * of keys and values, optional referential-equality, full concurrency of * retrievals, and adjustable expected concurrency for updates. * * This table is designed around specific advanced use-cases. If there is any * doubt whether this table is for you, you most likely should be using * {@link java.util.concurrent.ConcurrentHashMap} instead. * * This table supports strong, weak, and soft keys and values. By default keys * are weak, and values are strong. Such a configuration offers similar behavior * to {@link java.util.WeakHashMap}, entries of this table are periodically * removed once their corresponding keys are no longer referenced outside of * this table. In other words, this table will not prevent a key from being * discarded by the garbage collector. Once a key has been discarded by the * collector, the corresponding entry is no longer visible to this table; * however, the entry may occupy space until a future table operation decides to * reclaim it. For this reason, summary functions such as size and * isEmpty might return a value greater than the observed number of * entries. In order to support a high level of concurrency, stale entries are * only reclaimed during blocking (usually mutating) operations. * * Enabling soft keys allows entries in this table to remain until their space * is absolutely needed by the garbage collector. This is unlike weak keys which * can be reclaimed as soon as they are no longer referenced by a normal strong * reference. The primary use case for soft keys is a cache, which ideally * occupies memory that is not in use for as long as possible. * * By default, values are held using a normal strong reference. This provides * the commonly desired guarantee that a value will always have at least the * same life-span as it's key. For this reason, care should be taken to ensure * that a value never refers, either directly or indirectly, to its key, thereby * preventing reclamation. If this is unavoidable, then it is recommended to use * the same reference type in use for the key. However, it should be noted that * non-strong values may disappear before their corresponding key. * * While this table does allow the use of both strong keys and values, it is * recommended to use {@link java.util.concurrent.ConcurrentHashMap} for such a * configuration, since it is optimized for that case. * * Just like {@link java.util.concurrent.ConcurrentHashMap}, this class obeys * the same functional specification as {@link java.util.Hashtable}, and * includes versions of methods corresponding to each method of * Hashtable. However, even though all operations are thread-safe, * retrieval operations do not entail locking, and there is * not any support for locking the entire table in a way that * prevents all access. This class is fully interoperable with * Hashtable in programs that rely on its thread safety but not on * its synchronization details. * *

* Retrieval operations (including get) generally do not block, so * may overlap with update operations (including put and * remove). Retrievals reflect the results of the most recently * completed update operations holding upon their onset. For * aggregate operations such as putAll and clear, * concurrent retrievals may reflect insertion or removal of only some entries. * Similarly, Iterators and Enumerations return elements reflecting the state of * the hash table at some point at or since the creation of the * iterator/enumeration. They do not throw * {@link ConcurrentModificationException}. However, iterators are designed to * be used by only one thread at a time. * *

* The allowed concurrency among update operations is guided by the optional * concurrencyLevel constructor argument (default 16), * which is used as a hint for internal sizing. The table is internally * partitioned to try to permit the indicated number of concurrent updates * without contention. Because placement in hash tables is essentially random, * the actual concurrency will vary. Ideally, you should choose a value to * accommodate as many threads as will ever concurrently modify the table. Using * a significantly higher value than you need can waste space and time, and a * significantly lower value can lead to thread contention. But overestimates * and underestimates within an order of magnitude do not usually have much * noticeable impact. A value of one is appropriate when it is known that only * one thread will modify and all others will only read. Also, resizing this or * any other kind of hash table is a relatively slow operation, so, when * possible, it is a good idea to provide estimates of expected table sizes in * constructors. * *

* This class and its views and iterators implement all of the optional * methods of the {@link Map} and {@link Iterator} interfaces. * *

* Like {@link Hashtable} but unlike {@link HashMap}, this class does * not allow null to be used as a key or value. * *

* This class is a member of the * Java Collections Framework. * * @author Doug Lea * @author Jason T. Greene * @param the type of keys maintained by this map * @param the type of mapped values */ class ConcurrentReferenceHashMap extends AbstractMap implements java.util.concurrent.ConcurrentMap, Serializable { private static final long serialVersionUID = 7249069246763182397L; /* * The basic strategy is to subdivide the table among Segments, * each of which itself is a concurrently readable hash table. */ /** * An option specifying which Java reference type should be used to refer * to a key and/or value. */ public static enum ReferenceType { /** Indicates a normal Java strong reference should be used */ STRONG, /** Indicates a {@link WeakReference} should be used */ WEAK, /** Indicates a {@link SoftReference} should be used */ SOFT }; public static enum Option { /** Indicates that referential-equality (== instead of .equals()) should * be used when locating keys. This offers similar behavior to {@link IdentityHashMap} */ IDENTITY_COMPARISONS }; /* ---------------- Constants -------------- */ static final ReferenceType DEFAULT_KEY_TYPE = ReferenceType.WEAK; static final ReferenceType DEFAULT_VALUE_TYPE = ReferenceType.STRONG; /** * The default initial capacity for this table, * used when not otherwise specified in a constructor. */ static final int DEFAULT_INITIAL_CAPACITY = 16; /** * The default load factor for this table, used when not * otherwise specified in a constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * The default concurrency level for this table, used when not * otherwise specified in a constructor. */ static final int DEFAULT_CONCURRENCY_LEVEL = 16; /** * The maximum capacity, used if a higher value is implicitly * specified by either of the constructors with arguments. MUST * be a power of two <= 1<<30 to ensure that entries are indexable * using ints. */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * The maximum number of segments to allow; used to bound * constructor arguments. */ static final int MAX_SEGMENTS = 1 << 16; // slightly conservative /** * Number of unsynchronized retries in size and containsValue * methods before resorting to locking. This is used to avoid * unbounded retries if tables undergo continuous modification * which would make it impossible to obtain an accurate result. */ static final int RETRIES_BEFORE_LOCK = 2; /* ---------------- Fields -------------- */ /** * Mask value for indexing into segments. The upper bits of a * key's hash code are used to choose the segment. */ final int segmentMask; /** * Shift value for indexing within segments. */ final int segmentShift; /** * The segments, each of which is a specialized hash table */ final Segment[] segments; boolean identityComparisons; transient Set keySet; transient Set> entrySet; transient Collection values; /* ---------------- Small Utilities -------------- */ /** * Applies a supplemental hash function to a given hashCode, which * defends against poor quality hash functions. This is critical * because ConcurrentReferenceHashMap uses power-of-two length hash tables, * that otherwise encounter collisions for hashCodes that do not * differ in lower or upper bits. */ private static int hash(int h) { // Spread bits to regularize both segment and index locations, // using variant of single-word Wang/Jenkins hash. h += (h << 15) ^ 0xffffcd7d; h ^= (h >>> 10); h += (h << 3); h ^= (h >>> 6); h += (h << 2) + (h << 14); return h ^ (h >>> 16); } /** * Returns the segment that should be used for key with given hash * @param hash the hash code for the key * @return the segment */ final Segment segmentFor(int hash) { return segments[(hash >>> segmentShift) & segmentMask]; } private int hashOf(Object key) { return hash(identityComparisons ? System.identityHashCode(key) : key.hashCode()); } /* ---------------- Inner Classes -------------- */ static interface KeyReference { int keyHash(); Object keyRef(); } /** * A weak-key reference which stores the key hash needed for reclamation. */ static final class WeakKeyReference extends WeakReference implements KeyReference { final int hash; WeakKeyReference(K key, int hash, ReferenceQueue refQueue) { super(key, refQueue); this.hash = hash; } public final int keyHash() { return hash; } public final Object keyRef() { return this; } } /** * A soft-key reference which stores the key hash needed for reclamation. */ static final class SoftKeyReference extends SoftReference implements KeyReference { final int hash; SoftKeyReference(K key, int hash, ReferenceQueue refQueue) { super(key, refQueue); this.hash = hash; } public final int keyHash() { return hash; } public final Object keyRef() { return this; } } static final class WeakValueReference extends WeakReference implements KeyReference { final Object keyRef; final int hash; WeakValueReference(V value, Object keyRef, int hash, ReferenceQueue refQueue) { super(value, refQueue); this.keyRef = keyRef; this.hash = hash; } public final int keyHash() { return hash; } public final Object keyRef() { return keyRef; } } static final class SoftValueReference extends SoftReference implements KeyReference { final Object keyRef; final int hash; SoftValueReference(V value, Object keyRef, int hash, ReferenceQueue refQueue) { super(value, refQueue); this.keyRef = keyRef; this.hash = hash; } public final int keyHash() { return hash; } public final Object keyRef() { return keyRef; } } /** * ConcurrentReferenceHashMap list entry. Note that this is never exported * out as a user-visible Map.Entry. * * Because the value field is volatile, not final, it is legal wrt * the Java Memory Model for an unsynchronized reader to see null * instead of initial value when read via a data race. Although a * reordering leading to this is not likely to ever actually * occur, the Segment.readValueUnderLock method is used as a * backup in case a null (pre-initialized) value is ever seen in * an unsynchronized access method. */ static final class HashEntry { final Object keyRef; final int hash; volatile Object valueRef; final HashEntry next; HashEntry(K key, int hash, HashEntry next, V value, ReferenceType keyType, ReferenceType valueType, ReferenceQueue refQueue) { this.hash = hash; this.next = next; this.keyRef = newKeyReference(key, keyType, refQueue); this.valueRef = newValueReference(value, valueType, refQueue); } final Object newKeyReference(K key, ReferenceType keyType, ReferenceQueue refQueue) { if (keyType == ReferenceType.WEAK) return new WeakKeyReference(key, hash, refQueue); if (keyType == ReferenceType.SOFT) return new SoftKeyReference(key, hash, refQueue); return key; } final Object newValueReference(V value, ReferenceType valueType, ReferenceQueue refQueue) { if (valueType == ReferenceType.WEAK) return new WeakValueReference(value, keyRef, hash, refQueue); if (valueType == ReferenceType.SOFT) return new SoftValueReference(value, keyRef, hash, refQueue); return value; } @SuppressWarnings("unchecked") final K key() { if (keyRef instanceof Reference) return ((Reference)keyRef).get(); return (K) keyRef; } final V value() { return dereferenceValue(valueRef); } @SuppressWarnings("unchecked") final V dereferenceValue(Object value) { if (value instanceof Reference) return ((Reference)value).get(); return (V) value; } final void setValue(V value, ReferenceType valueType, ReferenceQueue refQueue) { this.valueRef = newValueReference(value, valueType, refQueue); } @SuppressWarnings("unchecked") static final HashEntry[] newArray(int i) { return new HashEntry[i]; } } /** * Segments are specialized versions of hash tables. This * subclasses from ReentrantLock opportunistically, just to * simplify some locking and avoid separate construction. */ static final class Segment extends ReentrantLock implements Serializable { /* * Segments maintain a table of entry lists that are ALWAYS * kept in a consistent state, so can be read without locking. * Next fields of nodes are immutable (final). All list * additions are performed at the front of each bin. This * makes it easy to check changes, and also fast to traverse. * When nodes would otherwise be changed, new nodes are * created to replace them. This works well for hash tables * since the bin lists tend to be short. (The average length * is less than two for the default load factor threshold.) * * Read operations can thus proceed without locking, but rely * on selected uses of volatiles to ensure that completed * write operations performed by other threads are * noticed. For most purposes, the "count" field, tracking the * number of elements, serves as that volatile variable * ensuring visibility. This is convenient because this field * needs to be read in many read operations anyway: * * - All (unsynchronized) read operations must first read the * "count" field, and should not look at table entries if * it is 0. * * - All (synchronized) write operations should write to * the "count" field after structurally changing any bin. * The operations must not take any action that could even * momentarily cause a concurrent read operation to see * inconsistent data. This is made easier by the nature of * the read operations in Map. For example, no operation * can reveal that the table has grown but the threshold * has not yet been updated, so there are no atomicity * requirements for this with respect to reads. * * As a guide, all critical volatile reads and writes to the * count field are marked in code comments. */ private static final long serialVersionUID = 2249069246763182397L; /** * The number of elements in this segment's region. */ transient volatile int count; /** * Number of updates that alter the size of the table. This is * used during bulk-read methods to make sure they see a * consistent snapshot: If modCounts change during a traversal * of segments computing size or checking containsValue, then * we might have an inconsistent view of state so (usually) * must retry. */ transient int modCount; /** * The table is rehashed when its size exceeds this threshold. * (The value of this field is always (int)(capacity * * loadFactor).) */ transient int threshold; /** * The per-segment table. */ transient volatile HashEntry[] table; /** * The load factor for the hash table. Even though this value * is same for all segments, it is replicated to avoid needing * links to outer object. * @serial */ final float loadFactor; /** * The collected weak-key reference queue for this segment. * This should be (re)initialized whenever table is assigned, */ transient volatile ReferenceQueue refQueue; final ReferenceType keyType; final ReferenceType valueType; final boolean identityComparisons; Segment(int initialCapacity, float lf, ReferenceType keyType, ReferenceType valueType, boolean identityComparisons) { loadFactor = lf; this.keyType = keyType; this.valueType = valueType; this.identityComparisons = identityComparisons; setTable(HashEntry.newArray(initialCapacity)); } @SuppressWarnings("unchecked") static final Segment[] newArray(int i) { return new Segment[i]; } private boolean keyEq(Object src, Object dest) { return identityComparisons ? src == dest : src.equals(dest); } /** * Sets table to new HashEntry array. * Call only while holding lock or in constructor. */ void setTable(HashEntry[] newTable) { threshold = (int)(newTable.length * loadFactor); table = newTable; refQueue = new ReferenceQueue(); } /** * Returns properly casted first entry of bin for given hash. */ HashEntry getFirst(int hash) { HashEntry[] tab = table; return tab[hash & (tab.length - 1)]; } HashEntry newHashEntry(K key, int hash, HashEntry next, V value) { return new HashEntry(key, hash, next, value, keyType, valueType, refQueue); } /** * Reads value field of an entry under lock. Called if value * field ever appears to be null. This is possible only if a * compiler happens to reorder a HashEntry initialization with * its table assignment, which is legal under memory model * but is not known to ever occur. */ V readValueUnderLock(HashEntry e) { lock(); try { removeStale(); return e.value(); } finally { unlock(); } } /* Specialized implementations of map methods */ V get(Object key, int hash) { if (count != 0) { // read-volatile HashEntry e = getFirst(hash); while (e != null) { if (e.hash == hash && keyEq(key, e.key())) { Object opaque = e.valueRef; if (opaque != null) return e.dereferenceValue(opaque); return readValueUnderLock(e); // recheck } e = e.next; } } return null; } boolean containsKey(Object key, int hash) { if (count != 0) { // read-volatile HashEntry e = getFirst(hash); while (e != null) { if (e.hash == hash && keyEq(key, e.key())) return true; e = e.next; } } return false; } boolean containsValue(Object value) { if (count != 0) { // read-volatile HashEntry[] tab = table; int len = tab.length; for (int i = 0 ; i < len; i++) { for (HashEntry e = tab[i]; e != null; e = e.next) { Object opaque = e.valueRef; V v; if (opaque == null) v = readValueUnderLock(e); // recheck else v = e.dereferenceValue(opaque); if (value.equals(v)) return true; } } } return false; } boolean replace(K key, int hash, V oldValue, V newValue) { lock(); try { removeStale(); HashEntry e = getFirst(hash); while (e != null && (e.hash != hash || !keyEq(key, e.key()))) e = e.next; boolean replaced = false; if (e != null && oldValue.equals(e.value())) { replaced = true; e.setValue(newValue, valueType, refQueue); } return replaced; } finally { unlock(); } } V replace(K key, int hash, V newValue) { lock(); try { removeStale(); HashEntry e = getFirst(hash); while (e != null && (e.hash != hash || !keyEq(key, e.key()))) e = e.next; V oldValue = null; if (e != null) { oldValue = e.value(); e.setValue(newValue, valueType, refQueue); } return oldValue; } finally { unlock(); } } V put(K key, int hash, V value, boolean onlyIfAbsent) { lock(); try { removeStale(); int c = count; if (c++ > threshold) {// ensure capacity int reduced = rehash(); if (reduced > 0) // adjust from possible weak cleanups count = (c -= reduced) - 1; // write-volatile } HashEntry[] tab = table; int index = hash & (tab.length - 1); HashEntry first = tab[index]; HashEntry e = first; while (e != null && (e.hash != hash || !keyEq(key, e.key()))) e = e.next; V oldValue; if (e != null) { oldValue = e.value(); if (!onlyIfAbsent) e.setValue(value, valueType, refQueue); } else { oldValue = null; ++modCount; tab[index] = newHashEntry(key, hash, first, value); count = c; // write-volatile } return oldValue; } finally { unlock(); } } int rehash() { HashEntry[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity >= MAXIMUM_CAPACITY) return 0; /* * Reclassify nodes in each list to new Map. Because we are * using power-of-two expansion, the elements from each bin * must either stay at same index, or move with a power of two * offset. We eliminate unnecessary node creation by catching * cases where old nodes can be reused because their next * fields won't change. Statistically, at the default * threshold, only about one-sixth of them need cloning when * a table doubles. The nodes they replace will be garbage * collectable as soon as they are no longer referenced by any * reader thread that may be in the midst of traversing table * right now. */ HashEntry[] newTable = HashEntry.newArray(oldCapacity<<1); threshold = (int)(newTable.length * loadFactor); int sizeMask = newTable.length - 1; int reduce = 0; for (int i = 0; i < oldCapacity ; i++) { // We need to guarantee that any existing reads of old Map can // proceed. So we cannot yet null out each bin. HashEntry e = oldTable[i]; if (e != null) { HashEntry next = e.next; int idx = e.hash & sizeMask; // Single node on list if (next == null) newTable[idx] = e; else { // Reuse trailing consecutive sequence at same slot HashEntry lastRun = e; int lastIdx = idx; for (HashEntry last = next; last != null; last = last.next) { int k = last.hash & sizeMask; if (k != lastIdx) { lastIdx = k; lastRun = last; } } newTable[lastIdx] = lastRun; // Clone all remaining nodes for (HashEntry p = e; p != lastRun; p = p.next) { // Skip GC'd weak refs K key = p.key(); if (key == null) { reduce++; continue; } int k = p.hash & sizeMask; HashEntry n = newTable[k]; newTable[k] = newHashEntry(key, p.hash, n, p.value()); } } } } table = newTable; return reduce; } /** * Remove; match on key only if value null, else match both. */ V remove(Object key, int hash, Object value, boolean refRemove) { lock(); try { if (!refRemove) removeStale(); int c = count - 1; HashEntry[] tab = table; int index = hash & (tab.length - 1); HashEntry first = tab[index]; HashEntry e = first; // a ref remove operation compares the Reference instance while (e != null && key != e.keyRef && (refRemove || hash != e.hash || !keyEq(key, e.key()))) e = e.next; V oldValue = null; if (e != null) { V v = e.value(); if (value == null || value.equals(v)) { oldValue = v; // All entries following removed node can stay // in list, but all preceding ones need to be // cloned. ++modCount; HashEntry newFirst = e.next; for (HashEntry p = first; p != e; p = p.next) { K pKey = p.key(); if (pKey == null) { // Skip GC'd keys c--; continue; } newFirst = newHashEntry(pKey, p.hash, newFirst, p.value()); } tab[index] = newFirst; count = c; // write-volatile } } return oldValue; } finally { unlock(); } } final void removeStale() { KeyReference ref; while ((ref = (KeyReference) refQueue.poll()) != null) { remove(ref.keyRef(), ref.keyHash(), null, true); } } void clear() { if (count != 0) { lock(); try { HashEntry[] tab = table; for (int i = 0; i < tab.length ; i++) tab[i] = null; ++modCount; // replace the reference queue to avoid unnecessary stale cleanups refQueue = new ReferenceQueue(); count = 0; // write-volatile } finally { unlock(); } } } } /* ---------------- Public operations -------------- */ /** * Creates a new, empty map with the specified initial * capacity, reference types, load factor and concurrency level. * * Behavioral changing options such as {@link Option#IDENTITY_COMPARISONS} * can also be specified. * * @param initialCapacity the initial capacity. The implementation * performs internal sizing to accommodate this many elements. * @param loadFactor the load factor threshold, used to control resizing. * Resizing may be performed when the average number of elements per * bin exceeds this threshold. * @param concurrencyLevel the estimated number of concurrently * updating threads. The implementation performs internal sizing * to try to accommodate this many threads. * @param keyType the reference type to use for keys * @param valueType the reference type to use for values * @param options the behavioral options * @throws IllegalArgumentException if the initial capacity is * negative or the load factor or concurrencyLevel are * nonpositive. */ public ConcurrentReferenceHashMap(int initialCapacity, float loadFactor, int concurrencyLevel, ReferenceType keyType, ReferenceType valueType, EnumSet