List of usage examples for io.netty.buffer ByteBuf writeShort
public abstract ByteBuf writeShort(int value);
From source file:cn.academy.energy.msg.node.MsgNodeLoadList.java
License:Open Source License
@Override public void toBytes(ByteBuf buf) { buf.writeShort(cns.size()); for (int i = 0; i < cns.size(); ++i) { ByteBufUtils.writeUTF8String(buf, cns.get(i)); }//from w ww .ja v a2 s. c o m }
From source file:cn.lambdalib.s11n.network.NetworkS11n.java
License:MIT License
private static void writeTypeIndex(ByteBuf buf, Class type) { if (type.isArray()) { buf.writeShort(IDX_ARRAY); writeTypeIndex(buf, type.getComponentType()); } else {/*from w w w . j ava 2s .c o m*/ short idx = (short) typeIndex(type); if (idx == -1) { throw new RuntimeException("Type " + type + " not registered for net serialization"); } buf.writeShort(idx); } }
From source file:cn.lambdalib.s11n.network.NetworkS11n.java
License:MIT License
/** * Serializes a object./*from ww w .ja v a 2 s. c o m*/ * @param buf The buffer to serialize the object into * @param obj The object to be serialized, whose type MUST be previously registered using {@link #register(Class)} * @param nullable if paramterer is allowed to be <code>null</code> * @throws RuntimeException if serialization failed */ @SuppressWarnings("unchecked") public static void serialize(ByteBuf buf, Object obj, boolean nullable) { if (obj == null) { if (nullable) { buf.writeShort(IDX_NULL); } else { throw new NullPointerException("Trying to serialize a null object where it's not accepted"); } } else { Class type = obj.getClass(); writeTypeIndex(buf, type); serializeWithHint(buf, obj, type); } }
From source file:cn.lambdalib.s11n.network.NetworkS11n.java
License:MIT License
/** * serialize an object without writing the object type index into the buffer. Used to reduce data redundancy. * Use {@link #deserializeWithHint} with the same signature to recover the object. * * @param buf The buffer to serialize the object into * @param obj The object to be serialized, must not be null * @param type the top-level type used during serialization. When deserialization from the buf, same class should * be used.//from w ww. j av a 2 s .co m */ @SuppressWarnings("unchecked") public static <T> void serializeWithHint(ByteBuf buf, T obj, Class<? super T> type) { _check(obj != null, "Hintted serialization doesn't take null"); NetS11nAdaptor<? super T> adaptor = (NetS11nAdaptor) _adaptor(type); if (adaptor != null) { // Serialize direct types adaptor.write(buf, obj); } else if (type.isEnum()) { // Serialize enum buf.writeByte(((Enum) obj).ordinal()); } else if (type.isArray()) { // Serialize array int length = Array.getLength(obj); Preconditions.checkArgument(length < Short.MAX_VALUE, "Array too large"); buf.writeShort(length); for (int i = 0; i < length; ++i) { serialize(buf, Array.get(obj, i), true); } } else { // Serialize recursive types serializeRecursively(buf, obj, type); } }
From source file:com.addthis.muxy.MuxStreamDirectory.java
License:Apache License
protected long writeStreamsToBlock() throws IOException { long writtenBytes = 0; openWritesLock.lock();// ww w . j a v a 2 s . c o m try { /* yes, this could be optimized for concurrency by writing after lock is released, etc */ if (openWriteBytes.get() == 0) { return 0; } List<TempData> streamsWithData = new ArrayList<>(openStreamWrites.size()); for (StreamOut out : openStreamWrites.values()) { synchronized (out) { StreamOut pendingOut = pendingStreamCloses.get(out.meta.streamId); if (pendingOut != null) { pendingOut.outputBuffer.writeBytes(out.outputBuffer); assert out.outputBuffer.readableBytes() == 0; out.outputBuffer.discardSomeReadBytes(); } else if (out.output.buffer().readableBytes() > 0) { streamsWithData.add(new TempData(out)); out.outputBuffer.retain(); } } } for (StreamOut out : pendingStreamCloses.values()) { // guarded by openStreamWrites streamsWithData.add(new TempData(out)); } pendingStreamCloses.clear(); if (streamsWithData.isEmpty()) { return 0; } for (TempData td : streamsWithData) { writtenBytes += td.snapshotLength; } int streams = streamsWithData.size(); publishEvent(MuxyStreamEvent.BLOCK_FILE_WRITE, streams); int currentFileOffset = (int) openWriteFile.size(); /* write out IDs in this block */ ByteBuf metaBuffer = PooledByteBufAllocator.DEFAULT.directBuffer(2 + 4 * streams + 4 + 8 * streams); metaBuffer.writeShort(streams); int bodyOutputSize = 0; for (TempData out : streamsWithData) { metaBuffer.writeInt(out.meta.streamId); /* (4) chunk body offset (4) chunk length (n) chunk bytes */ bodyOutputSize += 8 + out.snapshotLength; } /* write remainder size for rest of block data so that readers can skip if desired ID isn't present */ metaBuffer.writeInt(bodyOutputSize); /* write offsets and lengths for each stream id */ int bodyOffset = streamsWithData.size() * 8; for (TempData out : streamsWithData) { metaBuffer.writeInt(bodyOffset); //TODO - reconsider how frequently this shortcut is placed on disk metaBuffer.writeInt(out.snapshotLength); bodyOffset += out.snapshotLength; } while (metaBuffer.readableBytes() > 0) { metaBuffer.readBytes(openWriteFile, metaBuffer.readableBytes()); } metaBuffer.release(); /* write bytes for each stream id */ for (TempData out : streamsWithData) { synchronized (out.stream) { // need less confusing variable names for concurrency int toWrite = out.snapshotLength; while (toWrite > 0) { int numBytesRead = out.data.readBytes(openWriteFile, toWrite); assert numBytesRead > 0; toWrite -= numBytesRead; } openWriteBytes.addAndGet((long) -out.snapshotLength); eventListener.reportWrite((long) -out.snapshotLength); out.meta.endFile = streamDirectoryConfig.currentFile.get(); out.meta.endFileBlockOffset = currentFileOffset; if (out.meta.startFile == 0) { out.meta.startFile = out.meta.endFile; out.meta.startFileBlockOffset = out.meta.endFileBlockOffset; } if (!out.data.release()) { // release the pending writes that did not get an extra retain out.data.discardSomeReadBytes(); } } } /* check for rolling current file on size threshold */ if (openWriteFile.size() > streamDirectoryConfig.maxFileSize) { openWriteFile.close(); openWriteFile = FileChannel.open(getFileByID(bumpCurrentFile()), APPEND, CREATE); publishEvent(MuxyStreamEvent.BLOCK_FILE_WRITE_ROLL, streamDirectoryConfig.currentFile); } } finally { openWritesLock.unlock(); } return writtenBytes; }
From source file:com.builtbroken.atomic.network.packet.PacketBase.java
/** * Called to write data without manually defining the write * * @param object - object to write//from w ww . j a v a2 s. c o m * @param buffer - location to write to */ protected void writeData(Object object, ByteBuf buffer) { if (object.getClass().isArray()) { for (int i = 0; i < Array.getLength(object); i++) { writeData(Array.get(object, i), buffer); } } else if (object instanceof Collection) { for (Object o : (Collection) object) { writeData(o, buffer); } } else if (object instanceof Byte) { buffer.writeByte((Byte) object); } else if (object instanceof Integer) { buffer.writeInt((Integer) object); } else if (object instanceof Short) { buffer.writeShort((Short) object); } else if (object instanceof Long) { buffer.writeLong((Long) object); } else if (object instanceof Float) { buffer.writeFloat((Float) object); } else if (object instanceof Double) { buffer.writeDouble((Double) object); } else if (object instanceof Boolean) { buffer.writeBoolean((Boolean) object); } else if (object instanceof String) { ByteBufUtils.writeUTF8String(buffer, (String) object); } else if (object instanceof NBTTagCompound) { ByteBufUtils.writeTag(buffer, (NBTTagCompound) object); } else if (object instanceof ItemStack) { ByteBufUtils.writeItemStack(buffer, (ItemStack) object); } else if (object instanceof FluidTank) { ByteBufUtils.writeTag(buffer, ((FluidTank) object).writeToNBT(new NBTTagCompound())); } else if (object instanceof Pos) { ((Pos) object).writeByteBuf(buffer); } else if (object instanceof IByteBufWriter) { ((IByteBufWriter) object).writeBytes(buffer); } else if (object instanceof Enum) { buffer.writeInt(((Enum) object).ordinal()); } else { throw new IllegalArgumentException("PacketBase: Unsupported write data type " + object); } }
From source file:com.builtbroken.icbm.content.missile.tile.TileCrashedMissile.java
@Override public void writeDescPacket(ByteBuf buf) { if (missile != null) { ByteBufUtils.writeItemStack(buf, missile.toStack()); } else {// w w w . j a va 2s.c om ByteBufUtils.writeItemStack(buf, new ItemStack(Items.stone_axe)); //random sync data, set the missile to null } buf.writeFloat(yaw); buf.writeFloat(pitch); posOffset.writeByteBuf(buf); buf.writeBoolean(block != null); if (block != null) { ByteBufUtils.writeUTF8String(buf, Block.blockRegistry.getNameForObject(block)); buf.writeShort(meta); } }
From source file:com.cc.nettytest.proxy.encoder.CCLengthFieldPrepender.java
License:Apache License
@Override public void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception { int length = lengthIncludesLengthFieldLength ? msg.readableBytes() + lengthFieldLength : msg.readableBytes();/*from w w w. j a v a2s .c om*/ switch (lengthFieldLength) { case 1: if (length >= 256) { throw new IllegalArgumentException("length does not fit into a byte: " + length); } out.writeByte((byte) length); break; case 2: if (length >= 65536) { throw new IllegalArgumentException("length does not fit into a short integer: " + length); } out.writeShort((short) length); break; case 3: if (length >= 16777216) { throw new IllegalArgumentException("length does not fit into a medium integer: " + length); } out.writeMedium(length); break; case 4: out.writeInt(ByteBufUtil.swapInt((int) length)); //SWAP FOR UIMANAGER break; case 8: out.writeLong(length); break; default: throw new Error("should not reach here"); } out.writeBytes(msg, msg.readerIndex(), msg.readableBytes()); }
From source file:com.cloudhopper.smpp.util.ChannelBufferUtil.java
License:Apache License
static public void writeTlv(ByteBuf buffer, Tlv tlv) throws NotEnoughDataInBufferException { // a null is a noop if (tlv == null) { return;// w w w .j a va2 s . co m } buffer.writeShort(tlv.getTag()); buffer.writeShort(tlv.getLength()); if (tlv.getValue() != null) { buffer.writeBytes(tlv.getValue()); } }
From source file:com.couchbase.client.core.endpoint.binary.BinaryHandler.java
License:Open Source License
/** * Encodes a {@link ObserveRequest} into its lower level representation. * * @return a ready {@link BinaryMemcacheRequest}. *//*w w w . j a va 2s . com*/ private static BinaryMemcacheRequest handleObserveRequest(final ChannelHandlerContext ctx, final ObserveRequest msg) { String key = msg.key(); ByteBuf content = ctx.alloc().buffer(); content.writeShort(msg.partition()); content.writeShort(key.length()); content.writeBytes(key.getBytes(CHARSET)); BinaryMemcacheRequest request = new DefaultFullBinaryMemcacheRequest("", Unpooled.EMPTY_BUFFER, content); request.setOpcode(OP_OBSERVE); request.setTotalBodyLength(content.readableBytes()); return request; }