Example usage for java.io DataOutput writeByte

List of usage examples for java.io DataOutput writeByte

Introduction

In this page you can find the example usage for java.io DataOutput writeByte.

Prototype

void writeByte(int v) throws IOException;

Source Link

Document

Writes to the output stream the eight low- order bits of the argument v.

Usage

From source file:org.apache.geode.internal.InternalDataSerializer.java

public static void writeDSFID(DataSerializableFixedID o, DataOutput out) throws IOException {
    int dsfid = o.getDSFID();
    if (dsfidToClassMap != null && logger.isTraceEnabled(LogMarker.DEBUG_DSFID)) {
        logger.trace(LogMarker.DEBUG_DSFID, "writeDSFID {} class={}", dsfid, o.getClass());
        if (dsfid != DataSerializableFixedID.NO_FIXED_ID && dsfid != DataSerializableFixedID.ILLEGAL) {
            // consistency check to make sure that the same DSFID is not used
            // for two different classes
            String newClassName = o.getClass().getName();
            String existingClassName = (String) dsfidToClassMap.putIfAbsent(dsfid, newClassName);
            if (existingClassName != null && !existingClassName.equals(newClassName)) {
                logger.trace(LogMarker.DEBUG_DSFID, "dsfid={} is used for class {} and class {}", dsfid,
                        existingClassName, newClassName);
            }//w w w .java  2  s.  c o m
        }
    }
    if (dsfid == DataSerializableFixedID.NO_FIXED_ID) {
        out.writeByte(DS_NO_FIXED_ID);
        DataSerializer.writeClass(o.getClass(), out);
    } else {
        writeDSFIDHeader(dsfid, out);
    }
    try {
        invokeToData(o, out);
    } catch (IOException | CancelException | ToDataException | GemFireRethrowable io) {
        // Note: this is not a user code toData but one from our
        // internal code since only GemFire product code implements DSFID

        // Serializing a PDX can result in a cache closed exception. Just rethrow

        throw io;
    } catch (VirtualMachineError err) {
        SystemFailure.initiateFailure(err);
        // If this ever returns, rethrow the error. We're poisoned
        // now, so don't let this thread continue.
        throw err;
    } catch (Throwable t) {
        // Whenever you catch Error or Throwable, you must also
        // catch VirtualMachineError (see above). However, there is
        // _still_ a possibility that you are dealing with a cascading
        // error condition, so you also need to check to see if the JVM
        // is still usable:
        SystemFailure.checkFailure();
        throw new ToDataException("toData failed on dsfid=" + dsfid + " msg:" + t.getMessage(), t);
    }
}

From source file:org.apache.geode.internal.InternalDataSerializer.java

/**
 * Data serializes an instance of a "user class" (that is, a class that can be handled by a
 * registered {@code DataSerializer}) to the given {@code DataOutput}.
 *
 * @return {@code true} if {@code o} was written to {@code out}.
 *///from w w  w  . j av a2s . com
private static boolean writeUserObject(Object o, DataOutput out, boolean ensurePdxCompatibility)
        throws IOException {

    final Class<?> c = o.getClass();
    final DataSerializer serializer = InternalDataSerializer.getSerializer(c);
    if (serializer != null) {
        int id = serializer.getId();
        if (id != 0) {
            checkPdxCompatible(o, ensurePdxCompatibility);
            // id will be 0 if it is a WellKnowDS
            if (id <= Byte.MAX_VALUE && id >= Byte.MIN_VALUE) {
                out.writeByte(USER_CLASS);
                out.writeByte((byte) id);
            } else if (id <= Short.MAX_VALUE && id >= Short.MIN_VALUE) {
                out.writeByte(USER_CLASS_2);
                out.writeShort(id);
            } else {
                out.writeByte(USER_CLASS_4);
                out.writeInt(id);
            }
        } else {
            if (ensurePdxCompatibility) {
                if (!(serializer instanceof WellKnownPdxDS)) {
                    checkPdxCompatible(o, ensurePdxCompatibility);
                }
            }
        }
        boolean toDataResult;
        try {
            toDataResult = serializer.toData(o, out);
        } catch (IOException io) {
            if (serializer instanceof WellKnownDS) {
                // this is not user code so throw IOException
                throw io; // see bug 44659
            } else {
                // We no longer rethrow IOException here
                // because if user code throws an IOException we want
                // to create a ToDataException to report it as a problem
                // with the plugin code.
                throw new ToDataException("toData failed on DataSerializer with id=" + id + " for class " + c,
                        io);
            }
        } catch (CancelException | ToDataException | GemFireRethrowable ex) {
            // Serializing a PDX can result in a cache closed exception. Just rethrow
            throw ex;
        } catch (VirtualMachineError err) {
            SystemFailure.initiateFailure(err);
            // If this ever returns, rethrow the error. We're poisoned
            // now, so don't let this thread continue.
            throw err;
        } catch (Throwable t) {
            // Whenever you catch Error or Throwable, you must also
            // catch VirtualMachineError (see above). However, there is
            // _still_ a possibility that you are dealing with a cascading
            // error condition, so you also need to check to see if the JVM
            // is still usable:
            SystemFailure.checkFailure();
            throw new ToDataException("toData failed on DataSerializer with id=" + id + " for class " + c, t);
        }
        if (toDataResult) {
            return true;
        } else {
            throw new ToDataException(
                    LocalizedStrings.DataSerializer_SERIALIZER_0_A_1_SAID_THAT_IT_COULD_SERIALIZE_AN_INSTANCE_OF_2_BUT_ITS_TODATA_METHOD_RETURNED_FALSE
                            .toLocalizedString(serializer.getId(), serializer.getClass().getName(),
                                    o.getClass().getName()));
        }
        // Do byte[][] and Object[] here to fix bug 44060
    } else if (o instanceof byte[][]) {
        byte[][] byteArrays = (byte[][]) o;
        out.writeByte(ARRAY_OF_BYTE_ARRAYS);
        writeArrayOfByteArrays(byteArrays, out);
        return true;
    } else if (o instanceof Object[]) {
        Object[] array = (Object[]) o;
        out.writeByte(OBJECT_ARRAY);
        writeObjectArray(array, out, ensurePdxCompatibility);
        return true;
    } else if (is662SerializationEnabled()
            && (o.getClass().isEnum()/* for bug 52271 */ || (o.getClass().getSuperclass() != null
                    && o.getClass().getSuperclass().isEnum()))) {
        if (isPdxSerializationInProgress()) {
            writePdxEnum((Enum<?>) o, out);
        } else {
            checkPdxCompatible(o, ensurePdxCompatibility);
            writeGemFireEnum((Enum<?>) o, out);
        }
        return true;
    } else {
        PdxSerializer pdxSerializer = TypeRegistry.getPdxSerializer();
        return pdxSerializer != null && writePdx(out, null, o, pdxSerializer);
    }
}

From source file:org.apache.geode.internal.InternalDataSerializer.java

/**
 * Writes the type code for a primitive type Class to {@code DataOutput}.
 *///from ww w. j  av a2 s . c om
public static void writePrimitiveClass(Class c, DataOutput out) throws IOException {
    if (c == Boolean.TYPE) {
        out.writeByte(BOOLEAN_TYPE);
    } else if (c == Character.TYPE) {
        out.writeByte(CHARACTER_TYPE);
    } else if (c == Byte.TYPE) {
        out.writeByte(BYTE_TYPE);
    } else if (c == Short.TYPE) {
        out.writeByte(SHORT_TYPE);
    } else if (c == Integer.TYPE) {
        out.writeByte(INTEGER_TYPE);
    } else if (c == Long.TYPE) {
        out.writeByte(LONG_TYPE);
    } else if (c == Float.TYPE) {
        out.writeByte(FLOAT_TYPE);
    } else if (c == Double.TYPE) {
        out.writeByte(DOUBLE_TYPE);
    } else if (c == Void.TYPE) {
        out.writeByte(VOID_TYPE);
    } else if (c == null) {
        out.writeByte(NULL);
    } else {
        throw new InternalGemFireError(LocalizedStrings.InternalDataSerializer_UNKNOWN_PRIMITIVE_TYPE_0
                .toLocalizedString(c.getName()));
    }
}

From source file:org.apache.geode.internal.InternalDataSerializer.java

public static void writeUserDataSerializableHeader(int classId, DataOutput out) throws IOException {
    if (classId <= Byte.MAX_VALUE && classId >= Byte.MIN_VALUE) {
        out.writeByte(USER_DATA_SERIALIZABLE);
        out.writeByte(classId);/*w  w  w . java  2  s  .  c  o m*/
    } else if (classId <= Short.MAX_VALUE && classId >= Short.MIN_VALUE) {
        out.writeByte(USER_DATA_SERIALIZABLE_2);
        out.writeShort(classId);
    } else {
        out.writeByte(USER_DATA_SERIALIZABLE_4);
        out.writeInt(classId);
    }
}

From source file:org.apache.geode.internal.InternalDataSerializer.java

public static void basicWriteObject(Object o, DataOutput out, boolean ensurePdxCompatibility)
        throws IOException {
    checkOut(out);/*from   w  w w  .  j a v  a  2s .c  om*/

    final boolean isDebugEnabled_SERIALIZER = logger.isTraceEnabled(LogMarker.SERIALIZER);
    if (isDebugEnabled_SERIALIZER) {
        logger.trace(LogMarker.SERIALIZER, "basicWriteObject: {}", o);
    }

    // Handle special objects first
    if (o == null) {
        out.writeByte(NULL);

    } else if (o instanceof DataSerializableFixedID) {
        checkPdxCompatible(o, ensurePdxCompatibility);
        DataSerializableFixedID dsfid = (DataSerializableFixedID) o;
        writeDSFID(dsfid, out);
    } else if (autoSerialized(o, out)) {
        // all done
    } else if (o instanceof DataSerializable.Replaceable) {
        // do this first to fix bug 31609
        // do this before DataSerializable
        Object replacement = ((DataSerializable.Replaceable) o).replace();
        basicWriteObject(replacement, out, ensurePdxCompatibility);

    } else if (o instanceof PdxSerializable) {
        writePdx(out,
                GemFireCacheImpl.getForPdx("PDX registry is unavailable because the Cache has been closed."), o,
                null);
    } else if (o instanceof DataSerializable) {
        if (isDebugEnabled_SERIALIZER) {
            logger.trace(LogMarker.SERIALIZER, "Writing DataSerializable: {}", o);
        }
        checkPdxCompatible(o, ensurePdxCompatibility);

        Class c = o.getClass();
        // Is "c" a user class registered with an Instantiator?
        int classId = InternalInstantiator.getClassId(c);
        if (classId != 0) {
            writeUserDataSerializableHeader(classId, out);
        } else {
            out.writeByte(DATA_SERIALIZABLE);
            DataSerializer.writeClass(c, out);
        }
        DataSerializable ds = (DataSerializable) o;
        invokeToData(ds, out);

    } else if (o instanceof Sendable) {
        if (!(o instanceof PdxInstance) || o instanceof PdxInstanceEnum) {
            checkPdxCompatible(o, ensurePdxCompatibility);
        }
        ((Sendable) o).sendTo(out);
    } else if (writeWellKnownObject(o, out, ensurePdxCompatibility)) {
        // Nothing more to do...
    } else {
        checkPdxCompatible(o, ensurePdxCompatibility);
        if (logger.isTraceEnabled(LogMarker.DUMP_SERIALIZED)) {
            logger.trace(LogMarker.DUMP_SERIALIZED, "DataSerializer Serializing an instance of {}",
                    o.getClass().getName());
        }

        /*
         * If the (internally known) ThreadLocal named "DataSerializer.DISALLOW_JAVA_SERIALIZATION" is
         * set, then an exception will be thrown if we try to do standard Java Serialization. This is
         * used to catch Java serialization early for the case where the data is being sent to a
         * non-Java client
         */
        if (disallowJavaSerialization() && o instanceof Serializable) {
            throw new NotSerializableException(
                    LocalizedStrings.DataSerializer_0_IS_NOT_DATASERIALIZABLE_AND_JAVA_SERIALIZATION_IS_DISALLOWED
                            .toLocalizedString(o.getClass().getName()));
        }

        writeSerializableObject(o, out);
    }
}

From source file:org.apache.geode.internal.InternalDataSerializer.java

public static void writePdxEnumId(int eId, DataOutput out) throws IOException {
    out.writeByte(PDX_ENUM);
    out.writeByte(eId >> 24);/* ww w.  j a  va2 s .com*/
    writeArrayLength(eId & 0xFFFFFF, out);
}

From source file:org.apache.geode.internal.InternalDataSerializer.java

/**
 * write an object in java Serializable form with a SERIALIZABLE DSCODE so that it can be
 * deserialized with DataSerializer.readObject()
 * //from www.ja va2  s  . c  o  m
 * @param o the object to serialize
 * @param out the data output to serialize to
 */
public static void writeSerializableObject(Object o, DataOutput out) throws IOException {
    out.writeByte(SERIALIZABLE);
    if (out instanceof ObjectOutputStream) {
        ((ObjectOutputStream) out).writeObject(o);
    } else {
        OutputStream stream;
        if (out instanceof OutputStream) {
            stream = (OutputStream) out;

        } else {
            final DataOutput out2 = out;
            stream = new OutputStream() {
                @Override
                public void write(int b) throws IOException {
                    out2.write(b);
                }
            };
        }
        boolean wasDoNotCopy = false;
        if (out instanceof HeapDataOutputStream) {
            // To fix bug 52197 disable doNotCopy mode
            // while serialize with an ObjectOutputStream.
            // The problem is that ObjectOutputStream keeps
            // an internal byte array that it reuses while serializing.
            wasDoNotCopy = ((HeapDataOutputStream) out).setDoNotCopy(false);
        }
        try {
            ObjectOutput oos = new ObjectOutputStream(stream);
            if (stream instanceof VersionedDataStream) {
                Version v = ((VersionedDataStream) stream).getVersion();
                if (v != null && v != Version.CURRENT) {
                    oos = new VersionedObjectOutput(oos, v);
                }
            }
            oos.writeObject(o);
            // To fix bug 35568 just call flush. We can't call close because
            // it calls close on the wrapped OutputStream.
            oos.flush();
        } finally {
            if (wasDoNotCopy) {
                ((HeapDataOutputStream) out).setDoNotCopy(true);
            }
        }
    }
}

From source file:org.apache.geode.internal.InternalDataSerializer.java

public static void writeArrayLength(int len, DataOutput out) throws IOException {
    if (len == -1) {
        out.writeByte(NULL_ARRAY);
    } else if (len <= MAX_BYTE_ARRAY_LEN) {
        out.writeByte(len);//from   ww  w . j a  v  a2 s.  com
    } else if (len <= 0xFFFF) {
        out.writeByte(SHORT_ARRAY_LEN);
        out.writeShort(len);
    } else {
        out.writeByte(INT_ARRAY_LEN);
        out.writeInt(len);
    }
}

From source file:org.apache.geode.internal.InternalDataSerializer.java

/**
 * Write a variable length long the old way (pre 7.0). Use this only in contexts where you might
 * need to communicate with pre 7.0 members or files.
 *///  ww w .  j  a v  a  2s .  co m
public static void writeVLOld(long data, DataOutput out) throws IOException {
    if (data < 0) {
        Assert.fail("Data expected to be >=0 is " + data);
    }
    if (data <= MAX_BYTE_VL) {
        out.writeByte((byte) data);
    } else if (data <= 0x7FFF) {
        // set the sign bit to indicate a short
        out.write(((int) data >>> 8 | 0x80) & 0xFF);
        out.write((int) data >>> 0 & 0xFF);
    } else if (data <= Integer.MAX_VALUE) {
        out.writeByte(INT_VL);
        out.writeInt((int) data);
    } else {
        out.writeByte(LONG_VL);
        out.writeLong(data);
    }
}

From source file:org.apache.geode.internal.InternalDataSerializer.java

/**
 * Encode a long as a variable length array.
 * /*from w ww .ja va 2s  .  com*/
 * This method is appropriate for unsigned integers. For signed integers, negative values will
 * always consume 10 bytes, so it is recommended to use writeSignedVL instead.
 * 
 * This is taken from the varint encoding in protobufs (BSD licensed). See
 * https://developers.google.com/protocol-buffers/docs/encoding
 */
public static void writeUnsignedVL(long data, DataOutput out) throws IOException {
    while (true) {
        if ((data & ~0x7FL) == 0) {
            out.writeByte((int) data);
            return;
        } else {
            out.writeByte((int) data & 0x7F | 0x80);
            data >>>= 7;
        }
    }
}