/** * Decodes value from a given byte array to the object according to the flags given. * * @param flags Flags. * @param bytes Byte array to decode. * @return Decoded value. * @throws GridException If deserialization failed. */ private Object decodeObj(short flags, byte[] bytes) throws GridException { assert bytes != null; if ((flags & SERIALIZED_FLAG) != 0) return jdkMarshaller.unmarshal(new ByteArrayInputStream(bytes), null); int masked = flags & 0xff00; switch (masked) { case BOOLEAN_FLAG: return bytes[0] == '1'; case INT_FLAG: return U.bytesToInt(bytes, 0); case LONG_FLAG: return U.bytesToLong(bytes, 0); case DATE_FLAG: return new Date(U.bytesToLong(bytes, 0)); case BYTE_FLAG: return bytes[0]; case FLOAT_FLAG: return Float.intBitsToFloat(U.bytesToInt(bytes, 0)); case DOUBLE_FLAG: return Double.longBitsToDouble(U.bytesToLong(bytes, 0)); case BYTE_ARR_FLAG: return bytes; default: return new String(bytes); } }
/** * Encodes given object to a byte array and returns flags that describe the type of serialized * object. * * @param obj Object to serialize. * @param out Output stream to which object should be written. * @return Serialization flags. * @throws GridException If JDK serialization failed. */ private int encodeObj(Object obj, ByteArrayOutputStream out) throws GridException { int flags = 0; byte[] data = null; if (obj instanceof String) { data = ((String) obj).getBytes(); } else if (obj instanceof Boolean) { data = new byte[] {(byte) ((Boolean) obj ? '1' : '0')}; flags |= BOOLEAN_FLAG; } else if (obj instanceof Integer) { data = U.intToBytes((Integer) obj); flags |= INT_FLAG; } else if (obj instanceof Long) { data = U.longToBytes((Long) obj); flags |= LONG_FLAG; } else if (obj instanceof Date) { data = U.longToBytes(((Date) obj).getTime()); flags |= DATE_FLAG; } else if (obj instanceof Byte) { data = new byte[] {(Byte) obj}; flags |= BYTE_FLAG; } else if (obj instanceof Float) { data = U.intToBytes(Float.floatToIntBits((Float) obj)); flags |= FLOAT_FLAG; } else if (obj instanceof Double) { data = U.longToBytes(Double.doubleToLongBits((Double) obj)); flags |= DOUBLE_FLAG; } else if (obj instanceof byte[]) { data = (byte[]) obj; flags |= BYTE_ARR_FLAG; } else { jdkMarshaller.marshal(obj, out); flags |= SERIALIZED_FLAG; } if (data != null) out.write(data, 0, data.length); return flags; }
/** * Deserialize object from byte array using marshaller. * * @param bytes Bytes to deserialize. * @param <X> Result object type. * @return Deserialized object. * @throws GridException If failed. */ protected <X> X fromBytes(byte[] bytes) throws GridException { if (bytes == null || bytes.length == 0) return null; return marsh.unmarshal(bytes, getClass().getClassLoader()); }
/** * Serialize object to byte array using marshaller. * * @param obj Object to convert to byte array. * @return Byte array. * @throws GridException If failed to convert. */ protected byte[] toBytes(Object obj) throws GridException { return marsh.marshal(obj); }