List of usage examples for io.netty.buffer ByteBuf writerIndex
public abstract int writerIndex();
From source file:org.ratpackframework.http.internal.DefaultRequest.java
License:Apache License
@Override public byte[] getBytes() { ByteBuf buffer = getBuffer(); if (buffer.hasArray()) { return buffer.array(); } else {/*from w w w . j a va2 s . c o m*/ ByteArrayOutputStream baos = new ByteArrayOutputStream(buffer.writerIndex()); try { writeBodyTo(baos); } catch (IOException e) { throw new RuntimeException(e); } return baos.toByteArray(); } }
From source file:org.ratpackframework.http.internal.DefaultRequest.java
License:Apache License
@Override public void writeBodyTo(OutputStream destination) throws IOException { ByteBuf buffer = getBuffer(); buffer.resetReaderIndex();//from w w w. j a v a 2 s . com buffer.readBytes(destination, buffer.writerIndex()); }
From source file:org.ratpackframework.server.internal.NettyHandlerAdapter.java
License:Apache License
public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest nettyRequest) throws Exception { if (!nettyRequest.getDecoderResult().isSuccess()) { sendError(ctx, HttpResponseStatus.BAD_REQUEST); return;/*from www . j ava2 s . c om*/ } final FullHttpResponse nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); Request request = new DefaultRequest(new NettyHeadersBackedHeaders(nettyRequest.headers()), nettyRequest.getMethod().name(), nettyRequest.getUri(), nettyRequest.content()); final Channel channel = ctx.channel(); final DefaultStatus responseStatus = new DefaultStatus(); final MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyResponse.headers()); final ByteBuf responseBody = nettyResponse.content(); FileHttpTransmitter fileHttpTransmitter = new DefaultFileHttpTransmitter(nettyRequest, nettyResponse, channel); Response response = new DefaultResponse(responseStatus, responseHeaders, responseBody, fileHttpTransmitter, new Runnable() { @Override public void run() { nettyResponse.setStatus(responseStatus.getResponseStatus()); responseHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, responseBody.writerIndex()); boolean shouldClose = true; if (channel.isOpen()) { if (isKeepAlive(nettyRequest)) { responseHeaders.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); shouldClose = false; } ChannelFuture future = channel.writeAndFlush(nettyResponse); if (shouldClose) { future.addListener(ChannelFutureListener.CLOSE); } } } }); if (registry == null) { throw new IllegalStateException("Registry is not set, channel is not registered"); } final Context context = new DefaultContext(request, response, registry, ctx.executor(), blockingExecutorService, return404); handler.handle(context); }
From source file:org.redisson.client.handler.CommandDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { QueueCommand data = ctx.channel().attr(CommandsQueue.CURRENT_COMMAND).get(); if (log.isTraceEnabled()) { log.trace("channel: {} message: {}", ctx.channel(), in.toString(0, in.writerIndex(), CharsetUtil.UTF_8)); }//from ww w . j a va 2s . c o m if (state() == null) { boolean makeCheckpoint = data != null; if (data != null) { if (data instanceof CommandsData) { makeCheckpoint = false; } else { CommandData<Object, Object> cmd = (CommandData<Object, Object>) data; if (cmd.getCommand().getReplayMultiDecoder() != null && (NestedMultiDecoder.class .isAssignableFrom(cmd.getCommand().getReplayMultiDecoder().getClass()) || SlotsDecoder.class .isAssignableFrom(cmd.getCommand().getReplayMultiDecoder().getClass()) || ListMultiDecoder.class .isAssignableFrom(cmd.getCommand().getReplayMultiDecoder().getClass()))) { makeCheckpoint = false; } } } state(new State(makeCheckpoint)); } state().setDecoderState(null); if (data == null) { decode(in, null, null, ctx.channel()); } else if (data instanceof CommandData) { CommandData<Object, Object> cmd = (CommandData<Object, Object>) data; try { if (state().getLevels().size() > 0) { decodeFromCheckpoint(ctx, in, data, cmd); } else { decode(in, cmd, null, ctx.channel()); } } catch (Exception e) { cmd.tryFailure(e); } } else if (data instanceof CommandsData) { CommandsData commands = (CommandsData) data; try { decodeCommandBatch(ctx, in, data, commands); } catch (Exception e) { commands.getPromise().tryFailure(e); } return; } ctx.pipeline().get(CommandsQueue.class).sendNextCommand(ctx.channel()); state(null); }
From source file:org.redisson.client.handler.CommandDecoder.java
License:Apache License
private void decodeCommandBatch(ChannelHandlerContext ctx, ByteBuf in, QueueCommand data, CommandsData commandBatch) {/*from w w w . java 2 s. c o m*/ int i = state().getBatchIndex(); RedisException error = null; while (in.writerIndex() > in.readerIndex()) { CommandData<Object, Object> cmd = null; try { checkpoint(); state().setBatchIndex(i); cmd = (CommandData<Object, Object>) commandBatch.getCommands().get(i); decode(in, cmd, null, ctx.channel()); i++; } catch (IOException e) { cmd.tryFailure(e); } if (!cmd.isSuccess()) { error = (RedisException) cmd.cause(); } } if (commandBatch.isNoResult() || i == commandBatch.getCommands().size()) { RPromise<Void> promise = commandBatch.getPromise(); if (error != null) { if (!promise.tryFailure(error) && promise.cause() instanceof RedisTimeoutException) { log.warn("response has been skipped due to timeout! channel: {}, command: {}", ctx.channel(), LogHelper.toString(data)); } } else { if (!promise.trySuccess(null) && promise.cause() instanceof RedisTimeoutException) { log.warn("response has been skipped due to timeout! channel: {}, command: {}", ctx.channel(), LogHelper.toString(data)); } } ctx.pipeline().get(CommandsQueue.class).sendNextCommand(ctx.channel()); state(null); } else { checkpoint(); state().setBatchIndex(i); } }
From source file:org.redisson.client.handler.CommandDecoder.java
License:Apache License
private void decode(ByteBuf in, CommandData<Object, Object> data, List<Object> parts, Channel channel) throws IOException { int code = in.readByte(); if (code == '+') { ByteBuf rb = in.readBytes(in.bytesBefore((byte) '\r')); try {/*from w w w .j ava 2s. c o m*/ String result = rb.toString(CharsetUtil.UTF_8); in.skipBytes(2); handleResult(data, parts, result, false, channel); } finally { rb.release(); } } else if (code == '-') { ByteBuf rb = in.readBytes(in.bytesBefore((byte) '\r')); try { String error = rb.toString(CharsetUtil.UTF_8); in.skipBytes(2); if (error.startsWith("MOVED")) { String[] errorParts = error.split(" "); int slot = Integer.valueOf(errorParts[1]); String addr = errorParts[2]; data.tryFailure(new RedisMovedException(slot, addr)); } else if (error.startsWith("ASK")) { String[] errorParts = error.split(" "); int slot = Integer.valueOf(errorParts[1]); String addr = errorParts[2]; data.tryFailure(new RedisAskException(slot, addr)); } else if (error.startsWith("TRYAGAIN")) { data.tryFailure(new RedisTryAgainException(error + ". channel: " + channel + " data: " + data)); } else if (error.startsWith("LOADING")) { data.tryFailure(new RedisLoadingException(error + ". channel: " + channel + " data: " + data)); } else if (error.startsWith("OOM")) { data.tryFailure(new RedisOutOfMemoryException( error.split("OOM ")[1] + ". channel: " + channel + " data: " + data)); } else if (error.contains("-OOM ")) { data.tryFailure(new RedisOutOfMemoryException( error.split("-OOM ")[1] + ". channel: " + channel + " data: " + data)); } else { if (data != null) { data.tryFailure(new RedisException(error + ". channel: " + channel + " command: " + data)); } else { log.error("Error: {} channel: {} data: {}", error, channel, data); } } } finally { rb.release(); } } else if (code == ':') { Long result = readLong(in); handleResult(data, parts, result, false, channel); } else if (code == '$') { ByteBuf buf = readBytes(in); Object result = null; if (buf != null) { Decoder<Object> decoder = selectDecoder(data, parts); result = decoder.decode(buf, state()); } handleResult(data, parts, result, false, channel); } else if (code == '*') { int level = state().incLevel(); long size = readLong(in); List<Object> respParts; if (state().getLevels().size() - 1 >= level) { StateLevel stateLevel = state().getLevels().get(level); respParts = stateLevel.getParts(); size = stateLevel.getSize(); } else { respParts = new ArrayList<Object>(); if (state().isMakeCheckpoint()) { state().addLevel(new StateLevel(size, respParts)); } } decodeList(in, data, parts, channel, size, respParts); } else { String dataStr = in.toString(0, in.writerIndex(), CharsetUtil.UTF_8); throw new IllegalStateException("Can't decode replay: " + dataStr); } }
From source file:org.redisson.client.handler.CommandDecoder.java
License:Apache License
private void decodeList(ByteBuf in, CommandData<Object, Object> data, List<Object> parts, Channel channel, long size, List<Object> respParts) throws IOException { for (int i = respParts.size(); i < size; i++) { decode(in, data, respParts, channel); if (state().isMakeCheckpoint()) { checkpoint();//from ww w .ja v a2s . c o m } } MultiDecoder<Object> decoder = messageDecoder(data, respParts, channel); if (decoder == null) { return; } Object result = decoder.decode(respParts, state()); if (data != null) { handleResult(data, parts, result, true, channel); return; } if (result instanceof Message) { // store current message index checkpoint(); handlePublishSubscribe(data, null, channel, result); // has next messages? if (in.writerIndex() > in.readerIndex()) { decode(in, data, null, channel); } } }
From source file:org.redisson.client.handler.CommandPubSubDecoder.java
License:Apache License
@Override protected void decodeCommand(Channel channel, ByteBuf in, QueueCommand data) throws Exception { if (data == null) { try {/*from w ww .j ava 2s . c o m*/ while (in.writerIndex() > in.readerIndex()) { decode(in, null, null, channel, false, null); } sendNext(channel); } catch (Exception e) { log.error("Unable to decode data. channel: " + channel + ", reply: " + LogHelper.toString(in), e); sendNext(channel); throw e; } } else if (data instanceof CommandData) { CommandData<Object, Object> cmd = (CommandData<Object, Object>) data; try { while (in.writerIndex() > in.readerIndex()) { decode(in, cmd, null, channel, false, null); } sendNext(channel, data); } catch (Exception e) { log.error("Unable to decode data. channel: " + channel + ", reply: " + LogHelper.toString(in), e); cmd.tryFailure(e); sendNext(channel); throw e; } } }
From source file:org.restcomm.protocols.ss7.m3ua.impl.message.M3UAMessageImpl.java
License:Open Source License
public void encode(ByteBuf byteBuf) { byteBuf.writeByte(1);//from ww w . ja v a 2 s. co m byteBuf.writeByte(0); byteBuf.writeByte(messageClass); byteBuf.writeByte(messageType); byteBuf.markWriterIndex(); byteBuf.writeInt(8); int currIndex = byteBuf.writerIndex(); encodeParams(byteBuf); int newIndex = byteBuf.writerIndex(); byteBuf.resetWriterIndex(); byteBuf.writeInt(newIndex - currIndex + 8); byteBuf.writerIndex(newIndex); }
From source file:org.rhq.metrics.netty.collectd.packet.PacketDecodingTest.java
License:Apache License
static ByteBuf createValuesPartBuffer(Values values) { Number[] data = values.getData(); DataType[] dataTypes = values.getDataTypes(); ByteBuf payloadBuffer = Unpooled.buffer(); for (int i = 0; i < data.length; i++) { payloadBuffer.writeByte(dataTypes[i].getId()); }/*from w w w.ja v a 2s.c om*/ for (int i = 0; i < data.length; i++) { DataType dataType = dataTypes[i]; switch (dataType) { case COUNTER: case ABSOLUTE: BigInteger bigInteger = (BigInteger) data[i]; payloadBuffer.writeBytes(bigInteger.toByteArray()); break; case DERIVE: payloadBuffer.writeLong((Long) data[i]); break; case GAUGE: payloadBuffer.writeLong(ByteBufUtil.swapLong(Double.doubleToLongBits((Double) data[i]))); break; default: fail("Unknown data type: " + dataType); } } ByteBuf headerBuffer = Unpooled.buffer(); headerBuffer.writeShort(VALUES.getId()); headerBuffer.writeShort(6 + payloadBuffer.writerIndex()); headerBuffer.writeShort(data.length); ByteBuf buffer = Unpooled.buffer(); buffer.writeBytes(headerBuffer.duplicate()).writeBytes(payloadBuffer.duplicate()); return buffer; }