List of usage examples for io.netty.buffer ByteBuf isReadable
public abstract boolean isReadable();
From source file:divconq.net.ssl.SslHandler.java
License:Apache License
private void finishWrap(ChannelHandlerContext ctx, ByteBuf out, ChannelPromise promise, boolean inUnwrap) { if (out == null) { out = Unpooled.EMPTY_BUFFER;//from w w w . j ava 2 s .c om } else if (!out.isReadable()) { out.release(); out = Unpooled.EMPTY_BUFFER; } if (promise != null) { ctx.write(out, promise); } else { ctx.write(out); } if (inUnwrap) { needsFlush = true; } }
From source file:divconq.net.ssl.SslHandler.java
License:Apache License
private void unwrap(ChannelHandlerContext ctx, ByteBuffer packet, int initialOutAppBufCapacity) throws SSLException { // If SSLEngine expects a heap buffer for unwrapping, do the conversion. final ByteBuffer oldPacket; final ByteBuf newPacket; final int oldPos = packet.position(); if (wantsInboundHeapBuffer && packet.isDirect()) { newPacket = ctx.alloc().heapBuffer(packet.limit() - oldPos); newPacket.writeBytes(packet);/*from ww w . j a v a2 s . c o m*/ oldPacket = packet; packet = newPacket.nioBuffer(); } else { oldPacket = null; newPacket = null; } boolean wrapLater = false; ByteBuf decodeOut = allocate(ctx, initialOutAppBufCapacity); try { for (;;) { final SSLEngineResult result = unwrap(engine, packet, decodeOut); final Status status = result.getStatus(); final HandshakeStatus handshakeStatus = result.getHandshakeStatus(); final int produced = result.bytesProduced(); final int consumed = result.bytesConsumed(); if (status == Status.CLOSED) { // notify about the CLOSED state of the SSLEngine. See #137 sslCloseFuture.trySuccess(ctx.channel()); break; } switch (handshakeStatus) { case NEED_UNWRAP: break; case NEED_WRAP: wrapNonAppData(ctx, true); break; case NEED_TASK: runDelegatedTasks(); break; case FINISHED: setHandshakeSuccess(); wrapLater = true; continue; case NOT_HANDSHAKING: if (setHandshakeSuccessIfStillHandshaking()) { wrapLater = true; continue; } if (flushedBeforeHandshakeDone) { // We need to call wrap(...) in case there was a flush done before the handshake completed. // // See https://github.com/netty/netty/pull/2437 flushedBeforeHandshakeDone = false; wrapLater = true; } break; default: throw new IllegalStateException("Unknown handshake status: " + handshakeStatus); } if (status == Status.BUFFER_UNDERFLOW || consumed == 0 && produced == 0) { break; } } if (wrapLater) { wrap(ctx, true); } } catch (SSLException e) { setHandshakeFailure(e); throw e; } finally { // If we converted packet into a heap buffer at the beginning of this method, // we should synchronize the position of the original buffer. if (newPacket != null) { oldPacket.position(oldPos + packet.position()); newPacket.release(); } if (decodeOut.isReadable()) { ctx.fireChannelRead(decodeOut); } else { decodeOut.release(); } } }
From source file:eu.jangos.realm.network.packet.client.auth.CMSG_AUTH_SESSION.java
License:Apache License
@Override public void decode(ByteBuf buf) throws Exception { if (buf.readableBytes() < this.size) { throw new Exception(); }/*ww w .j a v a2 s . c o m*/ buf.readShort(); this.build = buf.readInt(); this.unknown = buf.readInt(); StringBuilder b = new StringBuilder(); byte c; while ((c = buf.readByte()) != 0) { b.append((char) c); } this.account = b.toString(); this.seed = buf.readBytes(4).array(); this.digest = buf.readBytes(20).array(); int sizeAddons = buf.readInt(); byte[] compressedAddons = buf.readBytes(buf.readableBytes()).array(); Inflater decompressor = new Inflater(); decompressor.setInput(compressedAddons); ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedAddons.length); final byte[] buffer = new byte[1024]; while (!decompressor.finished()) { try { final int count = decompressor.inflate(buffer); bos.write(buffer, 0, count); } catch (final DataFormatException e) { } } try { bos.close(); } catch (final IOException e) { } final byte[] decompressedAddons = bos.toByteArray(); if (sizeAddons != decompressedAddons.length) { System.out.println("Something went wrong"); return; } ByteBuf addonBuffer = Unpooled.wrappedBuffer(decompressedAddons).order(ByteOrder.LITTLE_ENDIAN); this.listAddon = new ArrayList<>(); while (addonBuffer.isReadable()) { String name; byte unk6; int crc, unk7; b = new StringBuilder(); while ((c = addonBuffer.readByte()) != 0) { b.append((char) c); } name = b.toString(); crc = addonBuffer.readInt(); unk7 = addonBuffer.readInt(); unk6 = addonBuffer.readByte(); AddonInfo info = new AddonInfo(name, unk6, crc, unk7); this.listAddon.add(info); } }
From source file:eu.stratosphere.runtime.io.network.netty.InboundEnvelopeDecoder.java
License:Apache License
/** * Decodes all Envelopes contained in a Netty ByteBuf and forwards them in the pipeline. * Returns true and releases the buffer, if it was fully consumed. Otherwise, returns false and retains the buffer. * </p>/*from w ww .ja v a 2s. co m*/ * In case of no buffer availability (returns false), a buffer availability listener is registered and the input * buffer is staged for later consumption. * * @return <code>true</code>, if buffer fully consumed, <code>false</code> otherwise * @throws IOException */ private boolean decodeBuffer(ByteBuf in, ChannelHandlerContext ctx) throws IOException { DecoderState decoderState; while ((decoderState = decodeEnvelope(in)) != DecoderState.PENDING) { if (decoderState == DecoderState.COMPLETE) { ctx.fireChannelRead(this.currentEnvelope); this.currentEnvelope = null; } else if (decoderState == DecoderState.NO_BUFFER_AVAILABLE) { switch (this.currentBufferProvider.registerBufferAvailabilityListener(this)) { case SUCCEEDED_REGISTERED: if (ctx.channel().config().isAutoRead()) { ctx.channel().config().setAutoRead(false); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Set channel %s auto read to false.", ctx.channel())); } } this.stagedBuffer = in; this.stagedBuffer.retain(); return false; case FAILED_BUFFER_AVAILABLE: continue; case FAILED_BUFFER_POOL_DESTROYED: this.bytesToSkip = skipBytes(in, this.currentBufferRequestSize); this.currentBufferRequestSize = 0; this.currentEventsBuffer = null; this.currentEnvelope = null; } } } if (in.isReadable()) { throw new IllegalStateException("Every buffer should have been fully" + "consumed after *successfully* decoding it (if it was not successful, " + "the buffer will be staged for later consumption)."); } in.release(); return true; }
From source file:eu.stratosphere.runtime.io.network.netty.InboundEnvelopeDecoder.java
License:Apache License
/** * Copies min(from.readableBytes(), to.remaining() bytes from Nettys ByteBuf to the Java NIO ByteBuffer. */// w w w .j ava 2 s.c om private void copy(ByteBuf src, ByteBuffer dst) { // This branch is necessary, because an Exception is thrown if the // destination buffer has more remaining (writable) bytes than // currently readable from the Netty ByteBuf source. if (src.isReadable()) { if (src.readableBytes() < dst.remaining()) { int oldLimit = dst.limit(); dst.limit(dst.position() + src.readableBytes()); src.readBytes(dst); dst.limit(oldLimit); } else { src.readBytes(dst); } } }
From source file:firebats.http.server.exts.form.Form.java
License:Apache License
public static Form decode(Context context, ByteBuf content) { return content != null && content.isReadable() ? Form.decodeWithContent(context, content) : Form.decodeWithoutContent(context); }
From source file:gwlpr.protocol.NettyGWCodec.java
License:Open Source License
@Override public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> result) { ByteBuf buf = in.order(ByteOrder.LITTLE_ENDIAN); while (buf.isReadable()) { buf.markReaderIndex();/* w ww . j a va 2s. com*/ // get the header failsafe int header = buf.readableBytes() >= 2 ? buf.readShort() : -1; // failcheck if (header == -1) { return; } // try get the message class Class<? extends GWMessage> messageClazz = getByHeader(header); // failcheck if (messageClazz == null) { buf.resetReaderIndex(); return; } // try retrieve the serialization filter NettySerializationFilter filter = GWMessageSerializationRegistry.getFilter(messageClazz); // failcheck if (filter == null) { buf.resetReaderIndex(); return; } // try create the message Message message; try { message = messageClazz.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { LOGGER.error("Could not create an instance of an message.", ex); buf.resetReaderIndex(); return; } // dont forget to initialize the message message.init(ctx.channel()); // try serialize the message if (!filter.deserialize(buf, message)) { buf.resetReaderIndex(); return; } // finally add the message result.add(message); LOGGER.debug("Got: {}", message.toString()); } }
From source file:http.HTTPResponseHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { Integer streamId = msg.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text()); if (streamId == null) { log.error("HTTP2ResponseHandler unexpected message received: " + msg); return;/*from w w w . j a v a 2 s .c o m*/ } Entry<ChannelFuture, ChannelPromise> entry = streamIdPromiseMap.get(streamId); if (entry == null) { if (streamId == 1) { log.error("HTTP2 Upgrade request has received from stream : " + streamId); } } else { ByteBuf content = msg.content(); if (content.isReadable()) { int contentLength = content.readableBytes(); byte[] arr = new byte[contentLength]; content.readBytes(arr); streamIdResponseMap.put(streamId, new String(arr, 0, contentLength, CharsetUtil.UTF_8)); } entry.getValue().setSuccess(); } }
From source file:http2.client.HttpResponseHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { Integer streamId = msg.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text()); if (streamId == null) { System.err.println("HttpResponseHandler unexpected message received: " + msg); return;/*from www . j a v a 2 s . co m*/ } Entry<ChannelFuture, ChannelPromise> entry = streamidPromiseMap.get(streamId); if (entry == null) { System.err.println("Message received for unknown stream id " + streamId); } else { // Do stuff with the message (for now just print it) ByteBuf content = msg.content(); if (content.isReadable()) { int contentLength = content.readableBytes(); byte[] arr = new byte[contentLength]; content.readBytes(arr); System.out.println("finally channel read 0 is " + new String(arr, 0, contentLength, CharsetUtil.UTF_8) + " streamId : " + streamId); } entry.getValue().setSuccess(); } }
From source file:info.zhoumin.dat.AbstractDoubleArrayTrie.java
License:Apache License
private boolean branchInTail(int sepNode, int c, ByteBuf suffix, V data) { /* adjust separate point in old path */ int oldTail = getTailIndex(sepNode); ByteBuf oldSuffix = tail.getSuffix(oldTail); if (oldSuffix == null) return false; byte oldByte, newByte; int s = sepNode; suffix.resetReaderIndex();/*from w ww . ja va2 s . c o m*/ oldSuffix.resetReaderIndex(); do { newByte = suffix.readByte(); oldByte = oldSuffix.readByte(); if (newByte != oldByte) break; int t = insertBranch(s, newByte + 1); if (TRIE_INDEX_ERROR == t) { // /* failed, undo previous insertions and return error */ // da_prune_upto (trie->da, sep_node, s); // trie_da_set_tail_index (trie->da, sep_node, old_tail); // throw new RuntimeException("error happened!"); return false; } s = t; } while (suffix.isReadable() && oldSuffix.isReadable()); int oldDA = insertBranch(s, oldByte + 1); if (TRIE_INDEX_ERROR == oldDA) { // /* failed, undo previous insertions and return error */ // da_prune_upto (trie->da, sep_node, s); // trie_da_set_tail_index (trie->da, sep_node, old_tail); // throw new RuntimeException("error happened!"); return false; } tail.setSuffix(oldTail, oldSuffix.discardReadBytes().copy()); setTailIndex(oldDA, oldTail); /* insert the new branch at the new separate point */ return branchInBranch(s, newByte + 1, suffix.discardReadBytes().copy(), data); }