/** * Serializes an object into a byte buffer. The object has to implement interface Serializable * or Externalizable. **/ public static byte[] objectToByteBuffer(Object obj) throws Exception { byte[] result = null; synchronized (outStream) { outStream.reset(); ObjectOutputStream out = new ObjectOutputStream(outStream); out.writeObject(obj); out.flush(); result = outStream.toByteArray(); out.close(); } return result; }
PacketSerializer(int initBufferSize, IPacketStreamSerializer<T> packetStreamSerializer) { _packetStreamSerializer = packetStreamSerializer; _buffer = new byte[initBufferSize]; _gsByteOutputStream = new GSByteArrayOutputStream(); _gsByteOutputStream.setBuffer(_buffer); _byteBuffer = ByteBuffer.wrap(_buffer); try { _oss = new ByteBufferObjectOutputStream(_gsByteOutputStream); } catch (IOException e) { throw new RuntimeException("Internal error creating PacketSerializer", e); } }
/** * Writes the specified byte to this byte array output stream. * * @param b the byte to be written. */ @Override public void write(int b) { ensureCapacity(1); _buffer[_count++] = (byte) b; }
} else // build a temporal buffer and streams bos = new GSByteArrayOutputStream(); bos.setSize(LENGTH_SIZE); // for the stream size mos = new MarshalOutputStream(bos, false); byteBuffer = wrap(bos); bos.setBuffer(DUMMY_BUFFER); // set DUMMY_BUFFER to release the strong reference to the byte[] bos.reset(); mos.reset(); if (buffer != byteBuffer) // replace the buffer in soft reference if needed
/** * Convert the desired object into the new object instance assignable from provided ClassLoader. * NOTE: This method is very expensive and provided object to convert must be {@link * java.io.Serializable}. * * @param obj the object to convert. Can be array as well. * @param classLoader the desired ClassLoader to convert the passed object. * @return the new instance of object derived from passed ClassLoader. * @throws IOException failed to convert **/ static public Object convertToAssignableClassLoader(Object obj, ClassLoader classLoader) throws IOException, ClassNotFoundException { GSByteArrayOutputStream oos = new GSByteArrayOutputStream(); MarshalOutputStream mos = new MarshalOutputStream(oos); mos.writeObject(obj); oos.flush(); GSByteArrayInputStream bais = new GSByteArrayInputStream(oos.toByteArray()); ClassLoader origCL = Thread.currentThread().getContextClassLoader(); try { ClassLoaderHelper.setContextClassLoader(classLoader, true); MarshalInputStream mis = new MarshalInputStream(bais); return mis.readObject(); } finally { ClassLoaderHelper.setContextClassLoader(origCL, true); } }
public ByteBuffer serializePacket(T packet) throws IOException { _packetStreamSerializer.writePacketToStream(_oss, packet); _oss.flush(); _oss.reset(); byte[] actualBuffer = _gsByteOutputStream.getBuffer(); //Need to rewrap the buffer because it was changed if (actualBuffer != _buffer) { _buffer = actualBuffer; _byteBuffer = ByteBuffer.wrap(_buffer); } //Remove reset indicator _byteBuffer.limit(_gsByteOutputStream.size() - 1); _byteBuffer.position(0); _gsByteOutputStream.setSize(0); return _byteBuffer; }
private MarshObject getMarshObjectInternal(Object o, boolean init) throws IOException { byte[] bc; if (init) { bc = serializeToByteArray(o); } else { _bao.setBuffer(_byteArrayCache.get()); _bao.reset(); // check for next time if (++zipEntryCounter < MAX_ENTRIES) { _zo.putNextEntry(new ZipEntry(Integer.toString(zipEntryCounter))); _oo.reset(); } else // open new zip OutputStream for next time { zipEntryCounter = 0; _zo = new ZipOutputStream(_bao); _zo.setLevel(_level); _zo.putNextEntry(new ZipEntry(Integer.toString(zipEntryCounter))); _oo = getObjectOutputStream(_zo); // remove ObjectOutputStream header from zip stream _zo.closeEntry(); _bao.reset(); _zo.putNextEntry(new ZipEntry(Integer.toString(++zipEntryCounter))); _oo.reset(); } bc = serializeToByteArray(o); _byteArrayCache.notifyUsedSize(bc.length); _bao.setBuffer(DUMMY_BUFFER); } return new CompressedMarshObject(bc); }
@Override public Object cloneValue(Object originalValue, boolean isCloneable, Class<?> clzz, String uid, String entryClassName) { if (isCloneable && clzz != null) { try { return clzz.getMethod("clone", new Class[0]).invoke(originalValue, new Object[0]); } catch (Exception ex) { } } try { if (_mis == null) {//create _os = new GSByteArrayOutputStream(INITIAL_SIZE); _is = new GSByteArrayInputStream(_os.getBuffer()); _mos = new MarshalOutputStream(_os); _mis = new MarshalInputStream(_is); } _mos.writeUnshared(originalValue); _is.setBuffer(_os.getBuffer(), _os.getCount()); Object res = _mis.readUnshared(); return res; } catch (Exception ex) { if (clzz == null) clzz = originalValue.getClass(); throw new FieldValueCloningErrorException(uid, entryClassName, clzz.getName(), originalValue, ex); } finally { reset(); } }
public Writer(SocketChannel sockChannel, int slowConsumerThroughput, int slowConsumerLatency, int slowConsumerRetries, IWriteInterestManager writeInterestManager) { _sockChannel = sockChannel; _slowConsumerThroughput = slowConsumerThroughput; _slowConsumerLatency = slowConsumerLatency; _slowConsumerRetries = slowConsumerRetries; _slowConsumer = _slowConsumerThroughput > 0; _slowConsumerSleepTime = _slowConsumerLatency / _slowConsumerRetries + 1; _slowConsumerBytes = (_slowConsumerThroughput * _slowConsumerLatency) / 1000; _contexts = new LinkedList<Context>(); _writeInterestManager = writeInterestManager; try { _baos = new GSByteArrayOutputStream(); _baos.setSize(LENGTH_SIZE); // mark the buffer to start writing only after the length place _oos = new MarshalOutputStream(_baos, true); // add a TC_RESET using the MarshalOutputStream.writeStreamHeader() initBuffer(_baos); } catch (Exception e) { if (_logger.isLoggable(Level.SEVERE)) { _logger.log(Level.SEVERE, e.getMessage(), e); } throw new RuntimeException("Failed to initialize LRMI Writer stream: ", e); } }
protected byte[] serializeToByteArray(Object o) throws IOException { _oo.writeObject(o); _oo.flush(); return _bao.toByteArray(); }
private ByteBuffer prepareBuffer(MarshalOutputStream mos, GSByteArrayOutputStream bos, ByteBuffer byteBuffer) throws IOException { mos.flush(); int length = bos.size(); if (byteBuffer.array() != bos.getBuffer()) // the buffer was changed { byteBuffer = wrap(bos); } else { byteBuffer.clear(); } byteBuffer.putInt(length - 4); byteBuffer.position(length); byteBuffer.flip(); return byteBuffer; } }
public void reset() { try { if (_mos != null) { _is.reset(); _os.reset(); _mos.reset(); //this is the only way to do reset on ObjetInputStream: // add reset flag and let the ObjectInputStream to read it // so all the handles in the ObjectInputStream will be cleared byte[] buffer = _is.getBuffer(); _is.setBuffer(_resetBuffer); _mis.readObject(); _is.setBuffer(buffer); } } catch (Exception ex) { throw new RuntimeException(ex); } }
/** * Set stream buffer, and reset the counter. * * @param buf new buffer * @return old buffer */ public void setBuffer(byte[] buf) { setBuffer(buf, 0); }
private ByteBuffer wrap(GSByteArrayOutputStream bos) { ByteBuffer byteBuffer = ByteBuffer.wrap(bos.getBuffer()); byteBuffer.order(ByteOrder.BIG_ENDIAN); return byteBuffer; }
/** * */ public MarshObjectConvertor(ISmartLengthBasedCacheCallback cacheCallback) { _byteArrayCache = createSerializationByteArrayCache(cacheCallback); try { _bao = new GSByteArrayOutputStream(); _oo = getObjectOutputStream(_bao); _bai = new GSByteArrayInputStream(new byte[0]); try { getObject(getMarshObjectInternal("", true)); } catch (ClassNotFoundException e) { if (_logger.isLoggable(Level.SEVERE)) { _logger.log(Level.SEVERE, e.getMessage(), e); } } } catch (IOException e) { if (_logger.isLoggable(Level.SEVERE)) { _logger.log(Level.SEVERE, e.getMessage(), e); } } }
/** * Gets the underlying buffer if its size is at most two times more than the actual data written * on the buffer. * * If this is not the case, creates a newly allocated byte array. Its size is the current size * of the actual content of this output stream and the valid contents of the buffer have been * copied into it. If the last 3 consecutive calls have resulted in new buffer creation, the * underlying buffer is replaced with the last created buffer while keeping the same count * position. */ public byte[] getCompactBuffer() { //If count is less then half of the capacity we return a compacted buffer if (_count <= getCapacity() >> 1) { byte newbuf[] = new byte[_count]; System.arraycopy(_buffer, 0, newbuf, 0, _count); if (++_compactionNeededTimes >= 3) { _compactionNeededTimes = 0; _buffer = newbuf; } return newbuf; } _compactionNeededTimes = 0; return _buffer; } }
public LRMIChat(RequestPacket packet) throws IOException { MarshalOutputStream mos; GSByteArrayOutputStream bos = new GSByteArrayOutputStream(); bos.setSize(4); mos = new MarshalOutputStream(bos, false); ByteBuffer buffer = wrap(bos); packet.writeExternal(mos); msg = prepareBuffer(mos, bos, buffer); mode = Mode.WRITE; headerBuffer = ByteBuffer.allocate(4); headerBuffer.order(ByteOrder.BIG_ENDIAN); }
protected byte[] serializeToByteArray(Object o) throws IOException { _oo.writeObject(o); _oo.flush(); _zo.closeEntry(); return _bao.toByteArray(); }
/** * @param byteBuffer buffer that might be used by the GSByteArrayOutputStream * @return prepared buffer. */ private ByteBuffer prepareBuffer(MarshalOutputStream mos, GSByteArrayOutputStream bos, ByteBuffer byteBuffer) throws IOException { mos.flush(); int length = bos.size(); if (byteBuffer.array() != bos.getBuffer()) // the buffer was changed { byteBuffer = wrap(bos); } else { byteBuffer.clear(); } byteBuffer.putInt(length - LENGTH_SIZE); byteBuffer.position(length); byteBuffer.flip(); return byteBuffer; }
/** * @return buffer that might be used by the GSByteArrayOutputStream */ private ByteBuffer prepareStream() throws IOException { ByteBuffer byteBuffer = _bufferCache.get(); byte[] streamBuffer = byteBuffer.array(); _baos.setBuffer(streamBuffer, LENGTH_SIZE); // 4 bytes for size return byteBuffer; }