List of usage examples for io.netty.buffer ByteBuf isReadable
public abstract boolean isReadable();
From source file:io.jsync.http.impl.DefaultHttpServerResponse.java
License:Open Source License
private void end0(ByteBuf data) { checkWritten();/* w w w . jav a2 s . c om*/ if (!headWritten) { // if the head was not written yet we can write out everything in on go // which is more cheap. prepareHeaders(); FullHttpResponse resp; if (trailing != null) { resp = new AssembledFullHttpResponse(response, data, trailing.trailingHeaders(), trailing.decoderResult()); } else { resp = new AssembledFullHttpResponse(response, data); } channelFuture = conn.write(resp); headWritten = true; } else { if (!data.isReadable()) { if (trailing == null) { channelFuture = conn.write(LastHttpContent.EMPTY_LAST_CONTENT); } else { channelFuture = conn.write(trailing); } } else { LastHttpContent content; if (trailing != null) { content = new AssembledLastHttpContent(data, trailing.trailingHeaders(), trailing.decoderResult()); } else { content = new DefaultLastHttpContent(data, false); } channelFuture = conn.write(content); } } if (!keepAlive) { closeConnAfterWrite(); } written = true; conn.responseComplete(); }
From source file:io.lettuce.core.protocol.CommandHandler.java
License:Apache License
/** * @see io.netty.channel.ChannelInboundHandlerAdapter#channelRead(io.netty.channel.ChannelHandlerContext, java.lang.Object) *//* w ww .ja va 2s . c o m*/ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf input = (ByteBuf) msg; if (!input.isReadable() || input.refCnt() == 0) { logger.warn("{} Input not readable {}, {}", logPrefix(), input.isReadable(), input.refCnt()); return; } if (debugEnabled) { logger.debug("{} Received: {} bytes, {} commands in the stack", logPrefix(), input.readableBytes(), stack.size()); } try { if (buffer.refCnt() < 1) { logger.warn("{} Ignoring received data for closed or abandoned connection", logPrefix()); return; } if (debugEnabled && ctx.channel() != channel) { logger.debug("{} Ignoring data for a non-registered channel {}", logPrefix(), ctx.channel()); return; } if (traceEnabled) { logger.trace("{} Buffer: {}", logPrefix(), input.toString(Charset.defaultCharset()).trim()); } buffer.writeBytes(input); decode(ctx, buffer); } finally { input.release(); } }
From source file:io.lettuce.core.protocol.CommandHandler.java
License:Apache License
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer) throws InterruptedException { if (pristine && stack.isEmpty() && buffer.isReadable()) { if (debugEnabled) { logger.debug("{} Received response without a command context (empty stack)", logPrefix()); }// w ww . jav a 2 s . c o m if (consumeResponse(buffer)) { pristine = false; } return; } while (canDecode(buffer)) { RedisCommand<?, ?, ?> command = stack.peek(); if (debugEnabled) { logger.debug("{} Stack contains: {} commands", logPrefix(), stack.size()); } pristine = false; try { if (!decode(ctx, buffer, command)) { return; } } catch (Exception e) { ctx.close(); throw e; } if (isProtectedMode(command)) { onProtectedMode(command.getOutput().getError()); } else { if (canComplete(command)) { stack.poll(); try { complete(command); } catch (Exception e) { logger.warn("{} Unexpected exception during request: {}", logPrefix, e.toString(), e); } } } afterDecode(ctx, command); } if (buffer.refCnt() != 0) { buffer.discardReadBytes(); } }
From source file:io.lettuce.core.protocol.CommandHandler.java
License:Apache License
/** * Decoding hook: Can the buffer be decoded to a command. * * @param buffer/*w ww . j a v a 2 s .co m*/ * @return */ protected boolean canDecode(ByteBuf buffer) { return !stack.isEmpty() && buffer.isReadable(); }
From source file:io.lettuce.core.protocol.RedisStateMachine.java
License:Apache License
/** * Attempt to decode a redis response and return a flag indicating whether a complete response was read. * * @param buffer Buffer containing data from the server. * @param command the command itself/*w ww .j a va 2 s.c o m*/ * @param output Current command output. * @return true if a complete response was read. */ public boolean decode(ByteBuf buffer, RedisCommand<?, ?, ?> command, CommandOutput<?, ?, ?> output) { int length, end; ByteBuffer bytes; if (debugEnabled) { logger.debug("Decode {}", command); } if (isEmpty(stack)) { add(stack, new State()); } if (output == null) { return isEmpty(stack); } loop: while (!isEmpty(stack)) { State state = peek(stack); if (state.type == null) { if (!buffer.isReadable()) { break; } state.type = readReplyType(buffer); buffer.markReaderIndex(); } switch (state.type) { case SINGLE: if ((bytes = readLine(buffer)) == null) { break loop; } if (!QUEUED.equals(bytes)) { safeSetSingle(output, bytes, command); } break; case ERROR: if ((bytes = readLine(buffer)) == null) { break loop; } safeSetError(output, bytes, command); break; case INTEGER: if ((end = findLineEnd(buffer)) == -1) { break loop; } long integer = readLong(buffer, buffer.readerIndex(), end); safeSet(output, integer, command); break; case BULK: if ((end = findLineEnd(buffer)) == -1) { break loop; } length = (int) readLong(buffer, buffer.readerIndex(), end); if (length == -1) { safeSet(output, null, command); } else { state.type = BYTES; state.count = length + 2; buffer.markReaderIndex(); continue loop; } break; case MULTI: if (state.count == -1) { if ((end = findLineEnd(buffer)) == -1) { break loop; } length = (int) readLong(buffer, buffer.readerIndex(), end); state.count = length; buffer.markReaderIndex(); safeMulti(output, state.count, command); } if (state.count <= 0) { break; } state.count--; addFirst(stack, new State()); continue loop; case BYTES: if ((bytes = readBytes(buffer, state.count)) == null) { break loop; } safeSet(output, bytes, command); break; default: throw new IllegalStateException("State " + state.type + " not supported"); } buffer.markReaderIndex(); remove(stack); output.complete(size(stack)); } if (debugEnabled) { logger.debug("Decoded {}, empty stack: {}", command, isEmpty(stack)); } return isEmpty(stack); }
From source file:io.lettuce.core.pubsub.PubSubCommandHandler.java
License:Apache License
@SuppressWarnings("unchecked") @Override/*w w w . j a v a 2 s .com*/ protected void decode(ChannelHandlerContext ctx, ByteBuf buffer) throws InterruptedException { if (!getStack().isEmpty()) { super.decode(ctx, buffer); } ReplayOutput<K, V> replay; while ((replay = queue.poll()) != null) { replay.replay(output); endpoint.notifyMessage(output); output = new PubSubOutput<>(codec); } while (super.getStack().isEmpty() && buffer.isReadable()) { if (!super.decode(buffer, output)) { return; } endpoint.notifyMessage(output); output = new PubSubOutput<>(codec); } buffer.discardReadBytes(); }
From source file:io.liveoak.stomp.common.StompFrameDecoder.java
License:Open Source License
protected FrameHeader decodeHeader(ByteBuf buffer) { FrameHeader header = null;//from ww w . ja v a 2s . c om while (header == null || buffer.isReadable()) { int nonNewLineBytes = buffer.bytesBefore((byte) '\n'); if (nonNewLineBytes == 0) { buffer.readByte(); break; } if (nonNewLineBytes >= 0) { ByteBuf line = buffer.readBytes(nonNewLineBytes); buffer.readByte(); header = processHeaderLine(header, line.toString(UTF_8)); } } return header; }
From source file:io.netlibs.bgp.handlers.BGPv4Codec.java
License:Apache License
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf buffer, final List<Object> out) throws Exception { if (failed) { return;/* w ww . j av a2 s .co m*/ } try { if (!buffer.isReadable()) { return; } final BGPv4Packet packet = this.packetDecoder.decodePacket(buffer); log.trace("Received: {}", packet); if (packet != null) { out.add(packet); } } catch (final ProtocolPacketException ex) { log.error("received malformed protocol packet, closing connection", ex); NotificationHelper.sendNotification(ctx, ex.toNotificationPacket(), new BgpEventFireChannelFutureListener(ctx)); this.failed = true; } catch (final Exception ex) { log.error("generic decoding exception, closing connection", ex); ctx.channel().close(); } }
From source file:io.netlibs.bgp.netty.codec.OpenPacketDecoder.java
License:Apache License
/** * decode the OPEN network packet. The passed channel buffer MUST point to the first packet octet AFTER the packet type and the buffer * must be at least 9 octets large at this point. * * @param buffer//from www . ja v a 2 s. c om * the buffer containing the data. * @return */ public OpenPacket decodeOpenPacket(final ByteBuf buffer) { OpenPacketBuilder b = OpenPacket.builder(); ProtocolPacketUtils.verifyPacketSize(buffer, BGPv4Constants.BGP_PACKET_MIN_SIZE_OPEN, -1); short version = buffer.readUnsignedByte(); if (version != BGPv4Constants.BGP_VERSION) { throw new UnsupportedVersionNumberException(BGPv4Constants.BGP_VERSION); } b.protocolVersion(version); b.autonomousSystem(buffer.readUnsignedShort()); b.holdTime(buffer.readUnsignedShort()); long identifier = buffer.readUnsignedInt(); if ((identifier & IPV4_MULTICAST_MASK) == IPV4_MULTICAST_MASK) { throw new BadBgpIdentifierException(); } b.bgpIdentifier(identifier); final int parameterLength = buffer.readUnsignedByte(); if (parameterLength > 0) { while (buffer.isReadable()) { final int parameterType = buffer.readUnsignedByte(); final int paramLength = buffer.readUnsignedByte(); final ByteBuf valueBuffer = Unpooled.buffer(paramLength); buffer.readBytes(valueBuffer); switch (parameterType) { case BGPv4Constants.BGP_OPEN_PARAMETER_TYPE_AUTH: log.warn("Ignoring auth parameter"); // RFC 4271 says auth is deprecated. break; case BGPv4Constants.BGP_OPEN_PARAMETER_TYPE_CAPABILITY: b.capabilities(CapabilityCodec.decodeCapabilities(valueBuffer)); break; default: throw new UnsupportedOptionalParameterException(); } } } return b.build(); }
From source file:io.netlibs.bgp.netty.codec.RouteRefreshPacketDecoder.java
License:Apache License
/** * decode the REFRESH network packet. The passed channel buffer MUST point to the first packet octet AFTER the type octet. * /*from w ww. ja va 2 s . c om*/ * @param buffer * the buffer containing the data. * * @return the decoded packet or null on decoding problems. Neither RFC2918 nor RFC5291 nor RFC4271 describe an error handling procedure, * so best advise is to ignore invalid packets for now. */ public BGPv4Packet decodeRouteRefreshPacket(ByteBuf buffer) { RouteRefreshPacket packet = null; try { AddressFamily af = AddressFamily.fromCode(buffer.readUnsignedShort()); buffer.readByte(); // swallow reserved octet SubsequentAddressFamily saf = SubsequentAddressFamily.fromCode(buffer.readUnsignedByte()); packet = new RouteRefreshPacket(af, saf); if (buffer.isReadable()) { // we have outbound router filter rules here OutboundRouteFilter orf = new OutboundRouteFilter(af, saf); orf.setRefreshType(ORFRefreshType.fromCode(buffer.readUnsignedByte())); while (buffer.isReadable()) { ORFType orfType = ORFType.fromCode(buffer.readUnsignedByte()); ByteBuf entriesBuffer = Unpooled.buffer(buffer.readUnsignedShort()); buffer.readBytes(entriesBuffer); orf.addAllORFEntries(decodeORFEntries(entriesBuffer, orfType)); } packet.setOutboundRouteFilter(orf); } } catch (Exception e) { log.error("cannot decode ROUTE_REFRESH packet, suppressing it from further processing", e); packet = null; } return packet; }