List of usage examples for io.netty.buffer ByteBuf writerIndex
public abstract ByteBuf writerIndex(int writerIndex);
From source file:at.yawk.dbus.protocol.codec.MessageHeaderCodec.java
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf rawBuf, List<Object> out) throws Exception { if (toRead != 0) { if (rawBuf.readableBytes() < toRead) { return; }/*from w w w . ja v a 2 s. co m*/ ByteBuf slice = rawBuf.slice().order(byteOrder); slice.writerIndex(slice.readerIndex() + toRead); slice.retain(); AlignableByteBuf decoding = AlignableByteBuf.decoding(slice); log.trace("INBOUND {}", decoding); out.add(decoding); rawBuf.readerIndex(rawBuf.readerIndex() + toRead); toRead = 0; } if (rawBuf.readableBytes() < MIN_HEADER_LENGTH) { return; } rawBuf.markReaderIndex(); byte endianness = rawBuf.readByte(); ByteOrder order; switch (endianness) { case 'l': order = ByteOrder.LITTLE_ENDIAN; break; case 'B': order = ByteOrder.BIG_ENDIAN; break; default: throw new DecoderException("Unknown byte order byte " + endianness); } AlignableByteBuf buf = AlignableByteBuf.decoding(rawBuf.resetReaderIndex().order(order)); buf.getBuffer().markReaderIndex(); buf.readByte(); // skip endianness byte we read above @Nullable MessageType type = MessageType.byId(buf.readByte()); byte flags = buf.readByte(); byte majorProtocolVersion = buf.readByte(); if (majorProtocolVersion != PROTOCOL_VERSION) { throw new DecoderException("Unsupported major protocol version " + majorProtocolVersion); } long bodyLength = buf.readUnsignedInt(); int serial = buf.readInt(); MessageHeader header = new MessageHeader(); header.setByteOrder(order); header.setMessageType(type); header.setNoReplyExpected((flags & NO_REPLY_EXPECTED) != 0); header.setNoAutoStart((flags & NO_AUTO_START) != 0); header.setAllowInteractiveAuthorization((flags & ALLOW_INTERACTIVE_AUTHORIZATION) != 0); header.setMajorProtocolVersion(majorProtocolVersion); header.setMessageBodyLength(bodyLength); header.setSerial(serial); header.setHeaderFields(new EnumMap<>(HeaderField.class)); ArrayObject headers = (ArrayObject) tryDecode(HEADER_FIELD_LIST_TYPE, buf); if (headers == null) { // not enough data buf.getBuffer().resetReaderIndex(); return; } for (DbusObject struct : headers.getValues()) { HeaderField field = HeaderField.byId(struct.get(0).byteValue()); if (field != null) { DbusObject value = struct.get(1).getValue(); if (!value.getType().equals(field.getType())) { throw new DecoderException("Invalid header type on " + field + ": got " + value.getType() + " but expected " + field.getType()); } header.getHeaderFields().put(field, value); } } if (type != null) { checkRequiredHeaderFieldsPresent(header); } if (!buf.canAlignRead(8)) { buf.getBuffer().resetReaderIndex(); return; } buf.alignRead(8); toRead = Math.toIntExact(header.getMessageBodyLength()); byteOrder = order; out.add(header); }
From source file:com.digitalpetri.opcua.stack.core.channel.ChunkDecoder.java
License:Apache License
private void decryptChunk(Delegate delegate, SecureChannel channel, ByteBuf chunkBuffer) throws UaException { int cipherTextBlockSize = delegate.getCipherTextBlockSize(channel); int blockCount = chunkBuffer.readableBytes() / cipherTextBlockSize; int plainTextBufferSize = cipherTextBlockSize * blockCount; ByteBuf plainTextBuffer = BufferUtil.buffer(plainTextBufferSize); ByteBuffer plainTextNioBuffer = plainTextBuffer.writerIndex(plainTextBufferSize).nioBuffer(); ByteBuffer chunkNioBuffer = chunkBuffer.nioBuffer(); try {//from w w w .j a va 2s.com Cipher cipher = delegate.getCipher(channel); assert (chunkBuffer.readableBytes() % cipherTextBlockSize == 0); if (delegate instanceof AsymmetricDelegate) { for (int blockNumber = 0; blockNumber < blockCount; blockNumber++) { chunkNioBuffer.limit(chunkNioBuffer.position() + cipherTextBlockSize); cipher.doFinal(chunkNioBuffer, plainTextNioBuffer); } } else { cipher.doFinal(chunkNioBuffer, plainTextNioBuffer); } } catch (GeneralSecurityException e) { throw new UaException(StatusCodes.Bad_SecurityChecksFailed, e); } /* Write plainTextBuffer back into the chunk buffer we decrypted from. */ plainTextNioBuffer.flip(); // limit = pos, pos = 0 chunkBuffer.writerIndex(chunkBuffer.readerIndex()); chunkBuffer.writeBytes(plainTextNioBuffer); plainTextBuffer.release(); }
From source file:com.digitalpetri.opcua.stack.core.channel.ChunkEncoder.java
License:Apache License
private void writePadding(int cipherTextBlockSize, int paddingSize, ByteBuf buffer) { if (cipherTextBlockSize > 256) { buffer.writeShort(paddingSize);//from www . ja v a 2 s . c om } else { buffer.writeByte(paddingSize); } for (int i = 0; i < paddingSize; i++) { buffer.writeByte(paddingSize); } if (cipherTextBlockSize > 256) { // Replace the last byte with the MSB of the 2-byte padding length int paddingLengthMSB = paddingSize >> 8; buffer.writerIndex(buffer.writerIndex() - 1); buffer.writeByte(paddingLengthMSB); } }
From source file:com.heliosapm.streams.metrichub.HubManager.java
License:Apache License
protected ByteBuf updateJsonRequest(final List<TSMeta> tsMetas, final ByteBuf header) { try {//from www.j a v a2s . c o m final ByteBuf request = BufferManager.getInstance().buffer(header.readableBytes() + 1024); request.writeBytes(header); header.resetReaderIndex(); request.writerIndex(request.writerIndex() - REQUEST_CLOSER.length()); for (TSMeta ts : tsMetas) { request.writeCharSequence(new StringBuilder("\"").append(ts.getTSUID()).append("\","), UTF8); } request.writerIndex(request.writerIndex() - 1); request.writeCharSequence(REQUEST_CLOSER, UTF8); return request; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.lambdaworks.redis.codec.StringCodec.java
License:Apache License
public void encode(String str, ByteBuf target) { if (str == null) { return;//from w ww .j a v a 2 s .c o m } if (utf8) { ByteBufUtil.writeUtf8(target, str); return; } if (ascii) { ByteBufUtil.writeAscii(target, str); return; } CharsetEncoder encoder = CharsetUtil.encoder(charset); int length = (int) ((double) str.length() * encoder.maxBytesPerChar()); target.ensureWritable(length); try { final ByteBuffer dstBuf = target.nioBuffer(0, length); final int pos = dstBuf.position(); CoderResult cr = encoder.encode(CharBuffer.wrap(str), dstBuf, true); if (!cr.isUnderflow()) { cr.throwException(); } cr = encoder.flush(dstBuf); if (!cr.isUnderflow()) { cr.throwException(); } target.writerIndex(target.writerIndex() + dstBuf.position() - pos); } catch (CharacterCodingException x) { throw new IllegalStateException(x); } }
From source file:com.linecorp.armeria.internal.grpc.GrpcMessageMarshaller.java
License:Apache License
private ByteBuf serializeProto(Message message) throws IOException { if (GrpcSerializationFormats.isProto(serializationFormat)) { final ByteBuf buf = alloc.buffer(message.getSerializedSize()); boolean success = false; try {/*from w ww . ja va2 s. co m*/ message.writeTo(CodedOutputStream.newInstance(buf.nioBuffer(0, buf.writableBytes()))); buf.writerIndex(buf.capacity()); success = true; } finally { if (!success) { buf.release(); } } return buf; } if (GrpcSerializationFormats.isJson(serializationFormat)) { final ByteBuf buf = alloc.buffer(); boolean success = false; try (ByteBufOutputStream os = new ByteBufOutputStream(buf)) { jsonMarshaller.writeValue(message, os); success = true; } finally { if (!success) { buf.release(); } } return buf; } throw new IllegalStateException("Unknown serialization format: " + serializationFormat); }
From source file:com.mastfrog.scamper.codec.RawMessageCodec.java
License:Open Source License
@Override public ByteBuf encode(MessageType type, ByteBuf outbound, Channel channel) { ByteBuf buf = channel.alloc().buffer(type.headerLength() + 1).writeByte(magicNumber()); type.writeHeader(buf);// w w w . j av a 2 s.com ByteBuf result = channel.alloc().compositeBuffer(2).addComponent(buf).addComponent(outbound); result.writerIndex(buf.readableBytes() + outbound.readableBytes()); return result; }
From source file:com.mastfrog.scamper.compression.CompressingCodec.java
License:Open Source License
@Override public ByteBuf encode(MessageType type, ByteBuf outbound, Channel channel) { try {//from w w w .jav a 2 s .com ByteBuf head = channel.alloc().buffer(type.headerLength() + 1); head.writeByte(magicNumber()); type.writeHeader(head); ByteBuf compressed = channel.alloc().buffer(); compress(outbound, compressed); ByteBuf result = channel.alloc().compositeBuffer(2).addComponent(head).addComponent(compressed); result.writerIndex(head.readableBytes() + compressed.readableBytes()); return result; } catch (Exception ex) { return Exceptions.chuck(ex); } }
From source file:com.minetats.mw.NamedPipe.java
License:Apache License
@Override public ByteBuf readChunk(ByteBufAllocator bba) throws Exception { chunks++;//from ww w . j ava 2 s.c o m ByteBuf buf = bba.heapBuffer(chunkSize); boolean release = false; int read = 0; try { do { buf.writerIndex(buf.writerIndex() + read); read = file.read(buf.array(), buf.arrayOffset() + read, chunkSize - read); } while (read > 0); int index = buf.writerIndex() - 1; if (buf.getByte(index) == '\n' && buf.getByte(index - 1) == '\n') { endOfInput = true; System.out.println("endOfInput=" + endOfInput + ", read " + chunks + " chunks"); } return buf; } finally { if (release) { buf.release(); } } }
From source file:com.spotify.netty.handler.codec.zmtp.ZMTPMessageParserTest.java
License:Apache License
private void testParse(final boolean enveloped, final Limit limit, final List<String> input, final ZMTPParsedMessage expected, int version) throws Exception { out.println(format("enveloped=%s limit=%s input=%s expected=%s", enveloped, limit, input, expected)); final ByteBuf serialized = serialize(input, version); final int serializedLength = serialized.readableBytes(); // Test parsing the whole message {/* ww w . java2 s. c o m*/ final ZMTPMessageParser parser = new ZMTPMessageParser(enveloped, limit.value, 1); final ZMTPParsedMessage parsed = parser.parse(serialized); serialized.setIndex(0, serializedLength); assertEquals(expected, parsed); } // Prepare for trivial message parsing test final int contentSize = min(limit.value - 1, 10); final List<String> envelope = asList("e", ""); final List<String> content = nCopies(contentSize, "."); final List<String> frames = newArrayList(concat(envelope, content)); final ZMTPMessage trivialMessage = ZMTPMessage.fromStringsUTF8(enveloped, frames); final ByteBuf trivialSerialized = serialize(frames, version); final int trivialLength = trivialSerialized.readableBytes(); // Test parsing fragmented input new Fragmenter(serialized.readableBytes()).fragment(new Fragmenter.Consumer() { @Override public void fragments(final int[] limits, final int count) throws Exception { serialized.setIndex(0, serializedLength); ZMTPParsedMessage parsed = null; final ZMTPMessageParser parser = new ZMTPMessageParser(enveloped, limit.value, 1); for (int i = 0; i < count; i++) { final int limit = limits[i]; serialized.writerIndex(limit); parsed = parser.parse(serialized); // Verify that the parser did not return a message for incomplete input if (limit < serializedLength) { assertNull(parsed); } } assertEquals(expected, parsed); // Verify that the parser can be reused to parse the same message serialized.setIndex(0, serializedLength); final ZMTPParsedMessage reparsed = parser.parse(serialized); assertEquals(expected, reparsed); // Verify that the parser can be reused to parse a well-behaved message trivialSerialized.setIndex(0, trivialLength); final ZMTPParsedMessage parsedTrivial = parser.parse(trivialSerialized); assertFalse(parsedTrivial.isTruncated()); assertEquals(trivialMessage, parsedTrivial.getMessage()); } }); }