List of usage examples for io.netty.buffer ByteBuf writerIndex
public abstract int writerIndex();
From source file:org.bgp4j.netty.protocol.open.OpenPacket.java
License:Apache License
@Override protected void encodePayload(ByteBuf buffer) { buffer.writeByte(getProtocolVersion()); buffer.writeShort(getAutonomousSystem()); buffer.writeShort(getHoldTime());/*from www . ja v a 2 s. c o m*/ buffer.writeInt((int) getBgpIdentifier()); if (!capabilities.isEmpty()) { int capabilityLengthIndex = buffer.writerIndex(); buffer.writeByte(0); // placeholder for capability length buffer.writeByte(BGPv4Constants.BGP_OPEN_PARAMETER_TYPE_CAPABILITY); // type byte int parameterLengthIndex = buffer.writerIndex(); buffer.writeByte(0); // placeholder for parameter length CapabilityCodec.encodeCapabilities(buffer, getCapabilities()); buffer.setByte(capabilityLengthIndex, buffer.writerIndex() - capabilityLengthIndex - 1); buffer.setByte(parameterLengthIndex, buffer.writerIndex() - parameterLengthIndex - 1); } else { buffer.writeByte(0); // no capabilites encoded --> optional parameter length equals 0 } }
From source file:org.bgp4j.netty.protocol.refresh.RouteRefreshPacket.java
License:Apache License
@Override protected void encodePayload(ByteBuf buffer) { buffer.writeShort(getAddressFamily().toCode()); buffer.writeByte(0);//from w ww .ja v a 2s . c om buffer.writeByte(getSubsequentAddressFamily().toCode()); if (outboundRouteFilter != null) { buffer.writeByte(outboundRouteFilter.getRefreshType().toCode()); for (ORFType type : outboundRouteFilter.getEntries().keySet()) { buffer.writeByte(type.toCode()); int entriesLengthIndex = buffer.writerIndex(); buffer.writeShort(0); // placeholder for entries length for (ORFEntry entry : outboundRouteFilter.getEntries().get(type)) { ORFEntryCodec.encodeORFEntry(buffer, entry); } buffer.setShort(entriesLengthIndex, buffer.writerIndex() - entriesLengthIndex - 2); } } }
From source file:org.bgp4j.netty.protocol.update.UpdatePacket.java
License:Apache License
@Override protected void encodePayload(ByteBuf buffer) { int withdrawnRoutesLengthIndex = buffer.writerIndex(); buffer.writeShort(0); // placeholder for withdrawn routes length encodeWithdrawnRoutes(buffer);/* w w w .j av a 2 s . c o m*/ buffer.setShort(withdrawnRoutesLengthIndex, buffer.writerIndex() - withdrawnRoutesLengthIndex - 2); int pathAttributesLengthIndex = buffer.writerIndex(); buffer.writeShort(0); // placeholder for path attributes length encodePathAttributes(buffer); buffer.setShort(pathAttributesLengthIndex, buffer.writerIndex() - pathAttributesLengthIndex - 2); encodeNlris(buffer); }
From source file:org.curioswitch.common.server.framework.redis.ProtobufRedisCodec.java
License:Open Source License
private static void encodeTo(Message message, ByteBuf target) { try {// w ww . ja va 2 s . com message.writeTo( CodedOutputStream.newInstance(target.nioBuffer(target.writerIndex(), target.writableBytes()))); } catch (IOException e) { throw new UncheckedIOException("Could not encode message.", e); } }
From source file:org.curioswitch.curiostack.gcloud.storage.FileWriter.java
License:Open Source License
private CompletableFuture<Void> doUploadChunk(ByteBuf chunk, boolean endOfFile) { int length = chunk.readableBytes(); long limit = filePosition + length; StringBuilder range = new StringBuilder("bytes "); if (length == 0) { range.append('*'); } else {// w w w. j a va2 s . c o m range.append(filePosition).append('-').append(limit - 1); } range.append('/'); if (endOfFile) { range.append(limit); } else { range.append('*'); } RequestHeaders headers = RequestHeaders.of(HttpMethod.PUT, uploadUrl, HttpHeaderNames.CONTENT_RANGE, range.toString()); HttpData data = new ByteBufHttpData(chunk, true); chunk.retain(); return httpClient.execute(headers, data).aggregate(eventLoop).thenComposeAsync(msg -> { ResponseHeaders responseHeaders = msg.headers(); if (!responseHeaders.status().codeClass().equals(HttpStatusClass.SUCCESS) && responseHeaders.status().code() != 308) { chunk.release(); throw new RuntimeException("Unsuccessful response uploading chunk: endOfFile: " + endOfFile + " Request headers: " + headers + "\n" + " Response headers: " + responseHeaders + "\n" + msg.content().toStringUtf8()); } String responseRange = responseHeaders.get(HttpHeaderNames.RANGE); if (responseRange == null) { chunk.release(); return completedFuture(null); } long responseLimit = rangeHeaderLimit(responseHeaders.get(HttpHeaderNames.RANGE)); filePosition = responseLimit + 1; int notUploaded = (int) (limit - 1 - responseLimit); if (notUploaded > 0) { chunk.readerIndex(chunk.writerIndex() - notUploaded); if (endOfFile) { return doUploadChunk(chunk, true); } if (unfinishedChunk == null) { copyUnfinishedBuffer(chunk); } else { ByteBuf newUnfinished = alloc.buffer(chunk.readableBytes() + unfinishedChunk.readableBytes()); newUnfinished.writeBytes(chunk).writeBytes(unfinishedChunk); unfinishedChunk.release(); unfinishedChunk = newUnfinished; } } chunk.release(); return completedFuture(null); }, eventLoop); }
From source file:org.dcache.xrootd.security.NestedBucketBuffer.java
License:Open Source License
@Override /**// www . ja va 2s .c om * Serialize all the buckets in that buffer to an outputstream. * * @param out The ByteBuf to which this buffer will be serialized */ public void serialize(ByteBuf out) { super.serialize(out); // // The nesting is a bit tricky. First, we skip 4 bytes (here we store later the // size of the nested serialized bucket buffer, which we don't know yet). Then, we // serialize the nested bucket buffer and store it in the bytebuffer. Then we jump // back to the previously marked position and store the size of the nested bucket buffer. // int start = out.writerIndex(); out.writeInt(0); // placeholder value /* the protocol is be 0-padded to 4 bytes */ byte[] protocol = _protocol.getBytes(US_ASCII); out.writeBytes(protocol); out.writeZero(4 - protocol.length); out.writeInt(_step); for (XrootdBucket bucket : _nestedBuckets.values()) { bucket.serialize(out); } out.writeInt(BucketType.kXRS_none.getCode()); out.setInt(start, out.writerIndex() - start - 4); }
From source file:org.eclipse.neoscada.protocol.iec60870.asdu.MessageManager.java
License:Open Source License
public void encodeMessage(final Object msg, ByteBuf buf) { logger.debug("Encode message: {}", msg); final ASDU asdu = msg.getClass().getAnnotation(ASDU.class); if (asdu == null) { throw new IllegalStateException( String.format("Unable to send message of type %s, no %s annotation found", msg.getClass(), ASDU.class.getName())); }/* w w w .j a va2 s .c o m*/ final MessageCodec codec = this.codecs.get(new MessageTypeId(asdu.id(), asdu.informationStructure())); if (codec == null) { throw new IllegalStateException( String.format("Unable to send message of type %s, no codec is registered", msg.getClass())); } try { buf = buf.order(ByteOrder.LITTLE_ENDIAN); codec.encode(this.options, msg, buf); logger.debug("Encoded to {} bytes", buf.writerIndex()); } catch (final Exception e) { logger.warn("Failed to encode message", e); throw new RuntimeException(e); } }
From source file:org.elasticsearch.http.nio.HttpReadWriteHandlerTests.java
License:Apache License
public void testSuccessfulDecodeHttpRequest() throws IOException { String uri = "localhost:9090/" + randomAlphaOfLength(8); io.netty.handler.codec.http.HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri);//from ww w .ja va 2 s. co m ByteBuf buf = requestEncoder.encode(httpRequest); int slicePoint = randomInt(buf.writerIndex() - 1); ByteBuf slicedBuf = buf.retainedSlice(0, slicePoint); ByteBuf slicedBuf2 = buf.retainedSlice(slicePoint, buf.writerIndex()); try { handler.consumeReads(toChannelBuffer(slicedBuf)); verify(transport, times(0)).incomingRequest(any(HttpRequest.class), any(NioHttpChannel.class)); handler.consumeReads(toChannelBuffer(slicedBuf2)); ArgumentCaptor<HttpRequest> requestCaptor = ArgumentCaptor.forClass(HttpRequest.class); verify(transport).incomingRequest(requestCaptor.capture(), any(NioHttpChannel.class)); HttpRequest nioHttpRequest = requestCaptor.getValue(); assertEquals(HttpRequest.HttpVersion.HTTP_1_1, nioHttpRequest.protocolVersion()); assertEquals(RestRequest.Method.GET, nioHttpRequest.method()); } finally { handler.close(); buf.release(); slicedBuf.release(); slicedBuf2.release(); } }
From source file:org.freeswitch.esl.client.transport.message.EslFrameDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception { State state = state();/*w ww . ja v a 2 s . c o m*/ log.trace("decode() : state [{}]", state); switch (state) { case READ_HEADER: if (currentMessage == null) { currentMessage = new EslMessage(); } /* * read '\n' terminated lines until reach a single '\n' */ boolean reachedDoubleLF = false; while (!reachedDoubleLF) { // this will read or fail String headerLine = readToLineFeedOrFail(buffer, maxHeaderSize); log.debug("read header line [{}]", headerLine); if (!headerLine.isEmpty()) { // split the header line String[] headerParts = HeaderParser.splitHeader(headerLine); Name headerName = Name.fromLiteral(headerParts[0]); if (headerName == null) { if (treatUnknownHeadersAsBody) { // cache this 'header' as a body line <-- useful for Outbound client mode currentMessage.addBodyLine(headerLine); } else { throw new IllegalStateException("Unhandled ESL header [" + headerParts[0] + ']'); } } currentMessage.addHeader(headerName, headerParts[1]); } else { reachedDoubleLF = true; } // do not read in this line again checkpoint(); } // have read all headers - check for content-length if (currentMessage.hasContentLength()) { checkpoint(State.READ_BODY); log.debug("have content-length, decoding body .."); // force the next section break; } else { // end of message checkpoint(State.READ_HEADER); // send message upstream EslMessage decodedMessage = currentMessage; currentMessage = null; out.add(decodedMessage); break; } case READ_BODY: /* * read the content-length specified */ int contentLength = currentMessage.getContentLength(); ByteBuf bodyBytes = buffer.readBytes(contentLength); log.debug("read [{}] body bytes", bodyBytes.writerIndex()); // most bodies are line based, so split on LF while (bodyBytes.isReadable()) { String bodyLine = readLine(bodyBytes, contentLength); log.debug("read body line [{}]", bodyLine); currentMessage.addBodyLine(bodyLine); } // end of message checkpoint(State.READ_HEADER); // send message upstream EslMessage decodedMessage = currentMessage; currentMessage = null; out.add(decodedMessage); break; default: throw new Error("Illegal state: [" + state + ']'); } }
From source file:org.freeswitch.esl.client.transport.message.EslFrameDecoderTest.java
License:Apache License
private ByteBuf createInputBuffer(List<String> inputLines, boolean terminateLastLine) { ByteBuf buffer = Unpooled.buffer(); Iterator<String> it = inputLines.iterator(); while (it.hasNext()) { buffer.writeBytes(it.next().getBytes()); // only terminate last line if asked if (it.hasNext() || terminateLastLine) { buffer.writeByte('\n'); }//from ww w . jav a2s . co m } log.debug("Created buffer with [{}] bytes", buffer.writerIndex()); return buffer; }