List of usage examples for io.netty.buffer ByteBuf isReadable
public abstract boolean isReadable();
From source file:org.fusesource.hawtdispatch.netty.HawtSocketChannel.java
License:Apache License
@Override protected void doFlushByteBuffer(ByteBuf buf) throws Exception { if (!buf.isReadable()) { // Reset reader/writerIndex to 0 if the buffer is empty. buf.clear();//w w w. j a va2s. c o m return; } for (int i = config().getWriteSpinCount() - 1; i >= 0; i--) { int localFlushedAmount = doWriteBytes(buf, i == 0); if (localFlushedAmount > 0) { break; } if (!buf.isReadable()) { // Reset reader/writerIndex to 0 if the buffer is empty. buf.clear(); break; } } }
From source file:org.glassfish.jersey.netty.connector.JerseyClientHandler.java
License:Open Source License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { if (msg instanceof HttpResponse) { final HttpResponse response = (HttpResponse) msg; final ClientResponse jerseyResponse = new ClientResponse(new Response.StatusType() { @Override// www. j a v a 2s . c om public int getStatusCode() { return response.status().code(); } @Override public Response.Status.Family getFamily() { return Response.Status.Family.familyOf(response.status().code()); } @Override public String getReasonPhrase() { return response.status().reasonPhrase(); } }, jerseyRequest); for (Map.Entry<String, String> entry : response.headers().entries()) { jerseyResponse.getHeaders().add(entry.getKey(), entry.getValue()); } // request entity handling. if ((response.headers().contains(HttpHeaderNames.CONTENT_LENGTH) && HttpUtil.getContentLength(response) > 0) || HttpUtil.isTransferEncodingChunked(response)) { ctx.channel().closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { isList.add(NettyInputStream.END_OF_INPUT_ERROR); } }); jerseyResponse.setEntityStream(new NettyInputStream(isList)); } else { jerseyResponse.setEntityStream(new InputStream() { @Override public int read() throws IOException { return -1; } }); } if (asyncConnectorCallback != null) { connector.executorService.execute(new Runnable() { @Override public void run() { asyncConnectorCallback.response(jerseyResponse); future.complete(jerseyResponse); } }); } } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { // copy bytes - when netty reads last chunk, it automatically closes the channel, which invalidates all // relates ByteBuffs. byte[] bytes = new byte[content.readableBytes()]; content.getBytes(content.readerIndex(), bytes); isList.add(new ByteArrayInputStream(bytes)); } if (msg instanceof LastHttpContent) { isList.add(NettyInputStream.END_OF_INPUT); } } }
From source file:org.glassfish.jersey.netty.httpserver.JerseyServerHandler.java
License:Open Source License
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { final HttpRequest req = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); }//from www . j a v a2s .co m isList.clear(); // clearing the content - possible leftover from previous request processing. final ContainerRequest requestContext = createContainerRequest(ctx, req); requestContext.setWriter(new NettyResponseWriter(ctx, req, container)); // must be like this, since there is a blocking read from Jersey container.getExecutorService().execute(new Runnable() { @Override public void run() { container.getApplicationHandler().handle(requestContext); } }); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { isList.add(new ByteBufInputStream(content)); } if (msg instanceof LastHttpContent) { isList.add(NettyInputStream.END_OF_INPUT); } } }
From source file:org.graylog.collector.file.splitters.NewlineChunkSplitter.java
License:Open Source License
@Override public Iterable<String> split(final ByteBuf buffer, final Charset charset, final boolean includeRemainingData) { return new Iterable<String>() { @Override// w w w .java2 s. com public Iterator<String> iterator() { return new AbstractIterator<String>() { @Override protected String computeNext() { try { if (!buffer.isReadable()) { return endOfData(); } final int i = buffer.forEachByte(ByteBufProcessor.FIND_CRLF); if (i == -1) { if (includeRemainingData) { final ByteBuf remaining = buffer.readBytes(buffer.readableBytes()); return remaining.toString(charset); } else { return endOfData(); } } final ByteBuf fullLine = buffer.readBytes(i); // Strip the \r/\n bytes from the buffer. final byte readByte = buffer.readByte(); // the \r or \n byte if (readByte == '\r') { buffer.readByte(); // the \n byte if previous was \r } return fullLine.toString(charset); } finally { buffer.discardReadBytes(); } } }; } }; }
From source file:org.graylog.collector.file.splitters.PatternChunkSplitter.java
License:Open Source License
@Override public Iterable<String> split(final ByteBuf buffer, final Charset charset, final boolean includeRemainingData) { return new Iterable<String>() { @Override/*from w w w. ja v a 2 s. c o m*/ public Iterator<String> iterator() { return new AbstractIterator<String>() { // TODO Might throw an exception if multibyte charset is used and buffer is not complete. // Use CharsetDecoder to create a CharBuffer and match on that! private final String inputAsString = buffer.toString(charset); final Matcher matcher = pattern.matcher(inputAsString); private int positionInString = 0; @Override protected String computeNext() { try { if (!buffer.isReadable()) { return endOfData(); } if (matcher.find()) { int firstByte = matcher.start(); if (firstByte == 0) { // advance further, the buffer begins with our pattern. if (matcher.find()) { firstByte = matcher.start(); } else { if (!includeRemainingData) { // couldn't find the end of the entry (i.e. there wasn't a next line yet) return endOfData(); } else { // couldn't find another line, but we are asked to finish up, include everything that remains return getRemainingContent(); } } } if (firstByte == 0) { // still haven't found a non-zero length string, keep waiting for more data. return endOfData(); } final String substring = inputAsString.substring(positionInString, firstByte); positionInString = firstByte; buffer.skipBytes(substring.getBytes(charset).length); // TODO performance return substring; } else { if (includeRemainingData) { return getRemainingContent(); } return endOfData(); } } catch (IllegalStateException e) { // the cause contains the CharacterCodingException from the ChannelBuffer.toString() methods // this usually means the buffer ended with an incomplete encoding of a unicode character. // WHY U SO SUCK CHARACTER ENCODINGS? // we need to wait until more data is available return endOfData(); } finally { buffer.discardReadBytes(); } } private String getRemainingContent() { final ByteBuf channelBuffer = buffer.readBytes(buffer.readableBytes()); return channelBuffer.toString(charset); } }; } }; }
From source file:org.graylog2.inputs.syslog.tcp.SyslogTCPFramingRouterHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { if (msg.isReadable()) { // "Dynamically manipulating a pipeline is relatively an expensive operation." // https://stackoverflow.com/a/28846565 if (handler == null) { if (usesOctetCountFraming(msg)) { handler = new SyslogOctetCountFrameDecoder(); } else { handler = new DelimiterBasedFrameDecoder(maxFrameLength, delimiter); }/*from w ww . ja va2 s.co m*/ } handler.channelRead(ctx, ReferenceCountUtil.retain(msg)); } else { ctx.fireChannelRead(msg); } }
From source file:org.graylog2.inputs.transports.netty.LenientDelimiterBasedFrameDecoder.java
License:Open Source License
private static void validateDelimiter(ByteBuf delimiter) { if (delimiter == null) { throw new NullPointerException("delimiter"); }/*from w w w. j a v a 2s.com*/ if (!delimiter.isReadable()) { throw new IllegalArgumentException("empty delimiter"); } }
From source file:org.hornetq.tests.integration.transports.netty.HornetQFrameDecoder2Test.java
License:Apache License
@Test public void testOrdinaryFragmentation() throws Exception { final EmbeddedChannel decoder = new EmbeddedChannel(new HornetQFrameDecoder2()); final byte[] data = new byte[HornetQFrameDecoder2Test.MSG_LEN]; HornetQFrameDecoder2Test.rand.nextBytes(data); ByteBuf src = Unpooled.buffer(HornetQFrameDecoder2Test.MSG_CNT * (HornetQFrameDecoder2Test.MSG_LEN + 4)); while (src.writerIndex() < src.capacity()) { src.writeInt(HornetQFrameDecoder2Test.MSG_LEN); src.writeBytes(data);/* w w w . j av a 2 s. co m*/ } List<ByteBuf> packets = new ArrayList<ByteBuf>(); while (src.isReadable()) { int length = Math.min(HornetQFrameDecoder2Test.rand.nextInt(HornetQFrameDecoder2Test.FRAGMENT_MAX_LEN), src.readableBytes()); packets.add(src.readBytes(length)); } int cnt = 0; for (ByteBuf p : packets) { decoder.writeInbound(p); for (;;) { ByteBuf frame = (ByteBuf) decoder.readInbound(); if (frame == null) { break; } Assert.assertEquals(4, frame.readerIndex()); Assert.assertEquals(HornetQFrameDecoder2Test.MSG_LEN, frame.readableBytes()); Assert.assertEquals(Unpooled.wrappedBuffer(data), frame); cnt++; frame.release(); } } Assert.assertEquals(HornetQFrameDecoder2Test.MSG_CNT, cnt); }
From source file:org.iotivity.cloud.util.CoapLogHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof CoapMessage) { CoapMessage coapMessage = (CoapMessage) msg; StringBuilder strBuilder = new StringBuilder(); strBuilder.append(getStringCtx(ctx)); strBuilder//from w w w. j a v a2 s. c om .append("\n/******************************************************************************/\n"); strBuilder.append(getStringCoapMessage(coapMessage)); strBuilder .append("\n/******************************************************************************/\n"); Logger.d(strBuilder.toString()); } else if (msg instanceof ByteBuf) { ByteBuf inByteBuf = (ByteBuf) msg; String message = null; StringBuffer strBuffer = new StringBuffer(); while (inByteBuf.isReadable()) { strBuffer.append((char) inByteBuf.readByte()); } message = strBuffer.toString(); StringBuilder strBuilder = new StringBuilder(); strBuilder.append(getStringCtx(ctx)); strBuilder .append("\n/******************************************************************************/\n"); strBuilder.append(message); strBuilder .append("\n/******************************************************************************/\n"); Logger.d(strBuilder.toString()); } ctx.fireChannelRead(msg); }
From source file:org.ireland.jnetty.JNettyServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (is100ContinueExpected(request)) { send100Continue(ctx);/* w w w. j a v a2 s. c om*/ } buf.setLength(0); buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); buf.append("===================================\r\n"); buf.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n"); buf.append("HOSTNAME: ").append(getHost(request, "unknown")).append("\r\n"); buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n"); List<Map.Entry<String, String>> headers = request.headers().entries(); if (!headers.isEmpty()) { for (Map.Entry<String, String> h : request.headers().entries()) { String key = h.getKey(); String value = h.getValue(); buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } buf.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n"); } } buf.append("\r\n"); } appendDecoderResult(buf, request); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.data(); if (content.isReadable()) { buf.append("CONTENT: "); buf.append(content.toString(CharsetUtil.UTF_8)); buf.append("\r\n"); appendDecoderResult(buf, request); } if (msg instanceof LastHttpContent) { buf.append("END OF CONTENT\r\n"); LastHttpContent trailer = (LastHttpContent) msg; if (!trailer.trailingHeaders().isEmpty()) { buf.append("\r\n"); for (String name : trailer.trailingHeaders().names()) { for (String value : trailer.trailingHeaders().getAll(name)) { buf.append("TRAILING HEADER: "); buf.append(name).append(" = ").append(value).append("\r\n"); } } buf.append("\r\n"); } writeResponse(ctx, trailer); } } }