List of usage examples for io.netty.buffer ByteBuf setInt
public abstract ByteBuf setInt(int index, int value);
From source file:com.yahoo.pulsar.common.api.Commands.java
License:Apache License
private static ByteBuf serializeCommandSendWithSize(BaseCommand.Builder cmdBuilder, ChecksumType checksumType, MessageMetadata msgMetadata, ByteBuf payload) { // / Wire format // [TOTAL_SIZE] [CMD_SIZE][CMD] [MAGIC_NUMBER][CHECKSUM] [METADATA_SIZE][METADATA] [PAYLOAD] BaseCommand cmd = cmdBuilder.build(); int cmdSize = cmd.getSerializedSize(); int msgMetadataSize = msgMetadata.getSerializedSize(); int payloadSize = payload.readableBytes(); int magicAndChecksumLength = ChecksumType.Crc32c.equals(checksumType) ? (2 + 4 /* magic + checksumLength*/) : 0;//from w ww. ja v a2s . co m boolean includeChecksum = magicAndChecksumLength > 0; int headerContentSize = 4 + cmdSize + magicAndChecksumLength + 4 + msgMetadataSize; // cmdLength + cmdSize + magicLength + // checksumSize + msgMetadataLength + // msgMetadataSize int totalSize = headerContentSize + payloadSize; int headersSize = 4 + headerContentSize; // totalSize + headerLength int checksumReaderIndex = -1; ByteBuf headers = PooledByteBufAllocator.DEFAULT.buffer(headersSize, headersSize); headers.writeInt(totalSize); // External frame try { // Write cmd headers.writeInt(cmdSize); ByteBufCodedOutputStream outStream = ByteBufCodedOutputStream.get(headers); cmd.writeTo(outStream); cmd.recycle(); cmdBuilder.recycle(); //Create checksum placeholder if (includeChecksum) { headers.writeShort(magicCrc32c); checksumReaderIndex = headers.writerIndex(); headers.writerIndex(headers.writerIndex() + checksumSize); //skip 4 bytes of checksum } // Write metadata headers.writeInt(msgMetadataSize); msgMetadata.writeTo(outStream); outStream.recycle(); } catch (IOException e) { // This is in-memory serialization, should not fail throw new RuntimeException(e); } ByteBuf command = DoubleByteBuf.get(headers, payload); // write checksum at created checksum-placeholder if (includeChecksum) { headers.markReaderIndex(); headers.readerIndex(checksumReaderIndex + checksumSize); int metadataChecksum = computeChecksum(headers); int computedChecksum = resumeChecksum(metadataChecksum, payload); // set computed checksum headers.setInt(checksumReaderIndex, computedChecksum); headers.resetReaderIndex(); } return command; }
From source file:com.yea.remote.netty.codec.NettyMessageEncoder.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf sendBuf) throws Exception { if (msg == null || msg.getHeader() == null) { throw new Exception("The encode message is null"); }/*from w ww . ja v a 2s .c o m*/ ISerializer serializer = serializePool.borrow(); try { long basedate = new Date().getTime(); sendBuf.writeInt((msg.getHeader().getCrcCode()));// 4 sendBuf.writeInt((msg.getHeader().getLength()));// 4Header+BodyHeader18 sendBuf.writeBytes((msg.getHeader().getSessionID()));// 16 sendBuf.writeByte((msg.getHeader().getType()));// 1 sendBuf.writeByte((msg.getHeader().getPriority()));// 1 sendBuf.writeByte((msg.getHeader().getResult()));// 1 if (compressionAlgorithm != null && compressionAlgorithm.code() > 0) { // serializer.setCompress(new Compress().setCompressionAlgorithm(compressionAlgorithm.algorithm())); sendBuf.writeByte(compressionAlgorithm.ordinal()); } else { sendBuf.writeByte(RemoteConstants.CompressionAlgorithm.NONE.ordinal()); } sendBuf.writeLong(basedate);// 8?? if (msg.getHeader().getAttachment() != null && !msg.getHeader().getAttachment().isEmpty()) { sendBuf.writeByte(msg.getHeader().getAttachment().size()); Map<String, Number> mapDateType = new HashMap<String, Number>();// Date Map<String, String> mapStringType = new HashMap<String, String>();// String int lengthPos = sendBuf.writerIndex(); sendBuf.writeBytes(new byte[1]);// 1?Date? byte[] keyArray = null; byte[] valueArray = null; for (Map.Entry<String, Object> param : msg.getHeader().getAttachment().entrySet()) { if (param.getValue() instanceof Date) { //Date???byte long time = basedate - ((Date) param.getValue()).getTime(); if (time > Integer.MAX_VALUE) { mapDateType.put(param.getKey(), new Long(time)); } else if (time > Short.MAX_VALUE) { mapDateType.put(param.getKey(), new Integer((int) time)); } else if (time > Byte.MAX_VALUE) { mapDateType.put(param.getKey(), new Short((short) time)); } else { mapDateType.put(param.getKey(), new Byte((byte) time)); } } else if (param.getValue() instanceof String) { //??getBytes()? mapStringType.put(param.getKey(), (String) param.getValue()); } else { keyArray = param.getKey().getBytes("ISO-8859-1"); sendBuf.writeShort(keyArray.length); sendBuf.writeBytes(keyArray); valueArray = serializer.serialize(param.getValue()); sendBuf.writeShort(valueArray.length); sendBuf.writeBytes(valueArray); } } sendBuf.setByte(lengthPos, msg.getHeader().getAttachment().size() - mapDateType.size() - mapStringType.size()); if (mapDateType.isEmpty()) { sendBuf.writeByte(0);// 1Date?0 } else { sendBuf.writeByte(mapDateType.size());// 1Date? for (Map.Entry<String, Number> param : mapDateType.entrySet()) { keyArray = param.getKey().getBytes("ISO-8859-1"); sendBuf.writeShort(keyArray.length); sendBuf.writeBytes(keyArray); if (param.getValue() instanceof Long) { sendBuf.writeByte(8); sendBuf.writeLong((Long) param.getValue()); } else if (param.getValue() instanceof Integer) { sendBuf.writeByte(4); sendBuf.writeInt((Integer) param.getValue()); } else if (param.getValue() instanceof Short) { sendBuf.writeByte(2); sendBuf.writeShort((Short) param.getValue()); } else { sendBuf.writeByte(1); sendBuf.writeByte((Byte) param.getValue()); } } } if (mapStringType.isEmpty()) { sendBuf.writeByte(0);// 1String?0 } else { sendBuf.writeByte(mapStringType.size());// 1String? for (Map.Entry<String, String> param : mapStringType.entrySet()) { keyArray = param.getKey().getBytes("ISO-8859-1"); sendBuf.writeShort(keyArray.length); sendBuf.writeBytes(keyArray); valueArray = param.getValue().getBytes("ISO-8859-1"); sendBuf.writeShort(valueArray.length); sendBuf.writeBytes(valueArray); } } } else { sendBuf.writeByte(0);// 20 } if (msg.getBody() != null) { byte[] objArray = serializer.serialize(msg.getBody()); int lengthPos = sendBuf.writerIndex(); sendBuf.writeBytes(LENGTH_PLACEHOLDER);// 4Body sendBuf.writeBytes(objArray); sendBuf.setInt(lengthPos, sendBuf.writerIndex() - lengthPos - 4);// Body } else { sendBuf.writeInt(0); } sendBuf.setInt(4, sendBuf.readableBytes() - 8);// Header+Body } finally { serializePool.restore(serializer); } }
From source file:com.zaradai.distributor.messaging.netty.handler.MessageEncoder.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception { int index = out.writerIndex(); // reserve space for length out.writeInt(0);// ww w .j a v a2 s. com // get the slot start for the message bytes int start = out.writerIndex(); // write the message writeHeader(out); writeSource(msg, out); writeEvent(msg, out); // get slot end index; int end = out.writerIndex(); // write out the bytes length out.setInt(index, (end - start)); }
From source file:com.zaradai.distributor.messaging.netty.handler.MessagingHandshake.java
License:Apache License
@Override protected void clientWrite(ByteBuf out) { int idx = out.writerIndex(); // reserve space for length out.writeInt(0);//from w ww .j a va 2s.c om // get slot for the bytes int start = out.writerIndex(); // write protocol header writeProtocolHeader(out); writeAddress(out); // note end of the object slot int end = out.writerIndex(); // write length out.setInt(idx, (end - start)); }
From source file:com.zz.learning.netty5.chap12.codec.MarshallingEncoder.java
License:Apache License
/** * ?/* w w w . ja v a 2 s .co m*/ * @param msg * @param out * @throws Exception */ protected void encode(Object msg, ByteBuf out) throws Exception { try { int lengthPos = out.writerIndex(); //?? out.writeBytes(LENGTH_PLACEHOLDER); // msg?? ChannelBufferByteOutput output = new ChannelBufferByteOutput(out); marshaller.start(output); marshaller.writeObject(msg); marshaller.finish(); out.setInt(lengthPos, out.writerIndex() - lengthPos - 4); //msg } finally { marshaller.close(); } }
From source file:com.zz.learning.netty5.chap12.codec.NettyMessageEncoder.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, NettyMessage msg, ByteBuf sendBuf) throws Exception { if (msg == null || msg.getHeader() == null) { throw new Exception("The encode message is null"); }// w w w . ja v a 2s . c o m sendBuf.writeInt((msg.getHeader().getCrcCode())); sendBuf.writeInt((msg.getHeader().getLength())); sendBuf.writeLong((msg.getHeader().getSessionID())); sendBuf.writeByte((msg.getHeader().getType())); sendBuf.writeByte((msg.getHeader().getPriority())); sendBuf.writeInt((msg.getHeader().getAttachment().size())); String key = null; byte[] keyArray = null; Object value = null; for (Map.Entry<String, Object> param : msg.getHeader().getAttachment().entrySet()) { key = param.getKey(); keyArray = key.getBytes("UTF-8"); sendBuf.writeInt(keyArray.length); sendBuf.writeBytes(keyArray); value = param.getValue(); marshallingEncoder.encode(value, sendBuf); } key = null; keyArray = null; value = null; if (msg.getBody() != null) { marshallingEncoder.encode(msg.getBody(), sendBuf); } else { sendBuf.writeInt(0); //? } //? sendBuf.setInt(4, //? crcCode,length sendBuf.readableBytes() - 8); }
From source file:common.xandayn.personalizedrecipes_old.common.network.packet.client.ClientRemoveRecipeFromServer.java
License:Open Source License
@Override public void fromBytes(ByteBuf buf) { buf.setInt(0, position); buf.setBoolean(1, removeAll); }
From source file:common.xandayn.personalizedrecipes_old.common.network.packet.server.ServerRemoveRecipePacket.java
License:Open Source License
@Override public void fromBytes(ByteBuf buf) { buf.setInt(0, position); }
From source file:hivemall.mix.MixMessageEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext ctx, MixMessage msg, ByteBuf out) throws Exception { int startIdx = out.writerIndex(); out.writeBytes(LENGTH_PLACEHOLDER);//from ww w . ja v a2 s. c o m MixEventName event = msg.getEvent(); byte b = event.getID(); out.writeByte(b); Object feature = msg.getFeature(); encodeObject(feature, out); float weight = msg.getWeight(); out.writeFloat(weight); float covariance = msg.getCovariance(); out.writeFloat(covariance); short clock = msg.getClock(); out.writeShort(clock); int deltaUpdates = msg.getDeltaUpdates(); out.writeInt(deltaUpdates); boolean cancelRequest = msg.isCancelRequest(); out.writeBoolean(cancelRequest); String groupId = msg.getGroupID(); writeString(groupId, out); int endIdx = out.writerIndex(); out.setInt(startIdx, endIdx - startIdx - 4); }
From source file:io.crate.protocols.postgres.ClientMessages.java
License:Apache License
static void sendBindMessage(ByteBuf buffer, String portalName, String statementName, List<Object> params) { buffer.writeByte('B'); byte[] portalBytes = portalName.getBytes(StandardCharsets.UTF_8); byte[] statementBytes = statementName.getBytes(StandardCharsets.UTF_8); int beforeLengthWriterIndex = buffer.writerIndex(); buffer.writeInt(0);//from w w w . j av a2 s .com writeCString(buffer, portalBytes); writeCString(buffer, statementBytes); buffer.writeShort(0); // formatCode use 0 to default to text for all buffer.writeShort(params.size()); int paramsLength = 0; for (Object param : params) { BytesRef value = DataTypes.STRING.value(param); buffer.writeInt(value.length); // the strings here are _not_ zero-padded because we specify the length upfront buffer.writeBytes(value.bytes, value.offset, value.length); paramsLength += 4 + value.length; } buffer.writeShort(0); // numResultFormatCodes - 0 to default to text for all buffer.setInt(beforeLengthWriterIndex, 4 + portalBytes.length + 1 + statementBytes.length + 1 + 2 + // numFormatCodes 2 + // numParams paramsLength + 2); // numResultColumnFormatCodes }