List of usage examples for io.netty.buffer ByteBuf readableBytes
public abstract int readableBytes();
From source file:cc.agentx.client.net.nio.XRelayHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (dstChannel.isActive()) { ByteBuf byteBuf = (ByteBuf) msg; try {// w ww .j a v a2 s. co m if (!byteBuf.hasArray()) { byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, bytes); if (uplink) { dstChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(bytes))); log.info("\tClient ==========> Target \tSend [{} bytes]", bytes.length); } else { bytes = wrapper.unwrap(bytes); if (bytes != null) { dstChannel.writeAndFlush(Unpooled.wrappedBuffer(bytes)); log.info("\tClient <========== Target \tGet [{} bytes]", bytes.length); } } } } finally { ReferenceCountUtil.release(msg); } } }
From source file:cc.agentx.server.net.nio.XConnectHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { try {/*from w w w . j a va2s. co m*/ ByteBuf byteBuf = (ByteBuf) msg; if (!byteBuf.hasArray()) { byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, bytes); if (!requestParsed) { if (!exposedRequest) { bytes = wrapper.unwrap(bytes); if (bytes == null) { log.info("\tClient -> Proxy \tHalf Request"); return; } } XRequest xRequest = requestWrapper.parse(bytes); String host = xRequest.getHost(); int port = xRequest.getPort(); int dataLength = xRequest.getSubsequentDataLength(); if (dataLength > 0) { byte[] tailData = Arrays.copyOfRange(bytes, bytes.length - dataLength, bytes.length); if (exposedRequest) { tailData = wrapper.unwrap(tailData); if (tailData != null) { tailDataBuffer.write(tailData, 0, tailData.length); } } else { tailDataBuffer.write(tailData, 0, tailData.length); } } log.info("\tClient -> Proxy \tTarget {}:{}{}", host, port, DnsCache.isCached(host) ? " [Cached]" : ""); if (xRequest.getAtyp() == XRequest.Type.DOMAIN) { try { host = DnsCache.get(host); if (host == null) { host = xRequest.getHost(); } } catch (UnknownHostException e) { log.warn("\tClient <- Proxy \tBad DNS! ({})", e.getMessage()); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); return; } } Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { // handle tail byte[] tailData = tailDataBuffer.toByteArray(); tailDataBuffer.close(); if (tailData.length > 0) { log.info("\tClient ==========> Target \tSend Tail [{} bytes]", tailData.length); } outboundChannel .writeAndFlush((tailData.length > 0) ? Unpooled.wrappedBuffer(tailData) : Unpooled.EMPTY_BUFFER) .addListener(channelFuture -> { // task handover outboundChannel.pipeline() .addLast(new XRelayHandler(ctx.channel(), wrapper, false)); ctx.pipeline() .addLast(new XRelayHandler(outboundChannel, wrapper, true)); ctx.pipeline().remove(XConnectHandler.this); }); } else { if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); final String finalHost = host; bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.SO_KEEPALIVE, true) .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { if (ctx.channel().isActive()) { log.warn("\tClient <- Proxy \tBad Ping! ({}:{})", finalHost, port); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); requestParsed = true; } else { bytes = wrapper.unwrap(bytes); if (bytes != null) tailDataBuffer.write(bytes, 0, bytes.length); } } } finally { ReferenceCountUtil.release(msg); } }
From source file:cc.agentx.server.net.nio.XRelayHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (dstChannel.isActive()) { ByteBuf byteBuf = (ByteBuf) msg; try {/*from w w w.j a v a2 s . c o m*/ if (!byteBuf.hasArray()) { byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, bytes); if (uplink) { bytes = wrapper.unwrap(bytes); if (bytes != null) { dstChannel.writeAndFlush(Unpooled.wrappedBuffer(bytes)); log.info("\tClient ==========> Target \tSend [{} bytes]", bytes.length); } } else { dstChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(bytes))); log.info("\tClient <========== Target \tGet [{} bytes]", bytes.length); } } } finally { ReferenceCountUtil.release(msg); } } }
From source file:cc.io.lessons.server.HttpUploadServerHandler.java
License:Apache License
private void writeResponse(Channel channel) { // Convert the response content to a ChannelBuffer. ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8); responseContent.setLength(0);/*from w w w. ja v a2 s .co m*/ // Decide whether to close the connection or not. boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(CONNECTION)) || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.headers().get(CONNECTION)); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); if (!close) { // There's no need to add 'Content-Length' header // if this is the last response. response.headers().set(CONTENT_LENGTH, buf.readableBytes()); } Set<Cookie> cookies; String value = request.headers().get(COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = CookieDecoder.decode(value); } if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie)); } } // Write the response. ChannelFuture future = channel.writeAndFlush(response); // Close the connection after the write operation is done if necessary. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }
From source file:cc.io.lessons.server.HttpUploadServerHandler.java
License:Apache License
private void writeMenu(ChannelHandlerContext ctx) { // print several HTML forms // Convert the response content to a ChannelBuffer. responseContent.setLength(0);//from w ww . jav a 2 s . c o m // create Pseudo Menu responseContent.append("<html>"); responseContent.append("<head>"); responseContent.append("<title>Netty Test Form</title>\r\n"); responseContent.append("</head>\r\n"); responseContent.append("<body bgcolor=white><style>td{font-size: 12pt;}</style>"); responseContent.append("<table border=\"0\">"); responseContent.append("<tr>"); responseContent.append("<td>"); responseContent.append("<h1>Netty Test Form</h1>"); responseContent.append("Choose one FORM"); responseContent.append("</td>"); responseContent.append("</tr>"); responseContent.append("</table>\r\n"); // GET responseContent.append("<CENTER>GET FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); responseContent.append("<FORM ACTION=\"/formget\" METHOD=\"GET\">"); responseContent.append("<input type=hidden name=getform value=\"GET\">"); responseContent.append("<table border=\"0\">"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>"); responseContent .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>"); responseContent.append("</td></tr>"); responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>"); responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>"); responseContent.append("</table></FORM>\r\n"); responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); // POST responseContent.append("<CENTER>POST FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); responseContent.append("<FORM ACTION=\"/formpost\" METHOD=\"POST\">"); responseContent.append("<input type=hidden name=getform value=\"POST\">"); responseContent.append("<table border=\"0\">"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>"); responseContent .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>"); responseContent.append("<tr><td>Fill with file (only file name will be transmitted): <br> " + "<input type=file name=\"myfile\">"); responseContent.append("</td></tr>"); responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>"); responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>"); responseContent.append("</table></FORM>\r\n"); responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); // POST with enctype="multipart/form-data" responseContent.append("<CENTER>POST MULTIPART FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); responseContent .append("<FORM ACTION=\"/formpostmultipart\" ENCTYPE=\"multipart/form-data\" METHOD=\"POST\">"); responseContent.append("<input type=hidden name=getform value=\"POST\">"); responseContent.append("<table border=\"0\">"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>"); responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>"); responseContent .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>"); responseContent.append("<tr><td>Fill with file: <br> <input type=file name=\"myfile\">"); responseContent.append("</td></tr>"); responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>"); responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>"); responseContent.append("</table></FORM>\r\n"); responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>"); responseContent.append("</body>"); responseContent.append("</html>"); ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); response.headers().set(CONTENT_LENGTH, buf.readableBytes()); // Write the response. ctx.channel().writeAndFlush(response); }
From source file:ccwihr.client.t2.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 w ww. ja va 2s. c o 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(new String(arr, 0, contentLength, CharsetUtil.UTF_8)); } entry.getValue().setSuccess(); } }
From source file:cf.component.http.JsonTextResponseRequestHandler.java
License:Open Source License
@Override public HttpResponse handleRequest(HttpRequest request, Matcher uriMatcher, ByteBuf body) throws RequestException { final String responseBody = handle(request, uriMatcher, body); final ByteBuf buffer = Unpooled.copiedBuffer(responseBody, CharsetUtil.UTF_8); final HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer);/*from w ww . jav a 2 s.co m*/ final HttpHeaders headers = response.headers(); headers.add(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=UTF-8"); headers.add(HttpHeaders.Names.CONTENT_LENGTH, buffer.readableBytes()); return response; }
From source file:ch.ethz.globis.distindex.middleware.net.MiddlewareChannelHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg;//from w w w .j a v a 2 s. c o m String clientHost = ctx.channel().remoteAddress().toString(); ByteBuffer response = ioHandler.handle(clientHost, buf.nioBuffer()); ByteBuf nettyBuf = Unpooled.wrappedBuffer(response); ByteBuf sizeBuf = Unpooled.copyInt(nettyBuf.readableBytes()); ctx.write(sizeBuf); ctx.write(nettyBuf); ctx.flush(); buf.release(); }
From source file:ch.ethz.globis.distindex.middleware.net.MiddlewareMessageDecoder.java
License:Open Source License
/** * Checks whether the bytes accumulated in the in Buffer constitute a full message sent * from the client. If that is the case, the message is copied to the out list and the * next handler is notified.//w w w .java 2 s. c om * * @param ctx The Netty context associated with the channel. * @param in A Netty managed buffer that holds the accumulated received chunks. * @param out The list of objects to be passed to the next handler. * @throws Exception */ @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() < 4) { //need to know exactly how many bytes to read return; } if (bytesToRead == -1) { bytesToRead = in.readInt(); } if (in.readableBytes() == bytesToRead) { out.add(in.readBytes(in.readableBytes())); bytesToRead = -1; } }
From source file:cloudeventbus.codec.Decoder.java
License:Open Source License
@Override public Frame decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { in.markReaderIndex();//from w w w . j ava2s. c o m final int frameLength = indexOf(in, Codec.DELIMITER); // Frame hasn't been fully read yet. if (frameLength < 0) { if (in.readableBytes() > maxMessageSize) { throw new TooLongFrameException("Frame exceeds maximum size"); } in.resetReaderIndex(); return null; } // Empty frame, discard and continue decoding if (frameLength == 0) { in.skipBytes(Codec.DELIMITER.length); return decode(ctx, in); } if (frameLength > maxMessageSize) { throw new TooLongFrameException("Frame exceeds maximum size"); } final String command = in.readBytes(frameLength).toString(CharsetUtil.UTF_8); in.skipBytes(Codec.DELIMITER.length); final String[] parts = command.split("\\s+"); final char frameTypeChar = parts[0].charAt(0); final FrameType frameType = FrameType.getFrameType(frameTypeChar); if (frameType == null) { throw new DecodingException("Invalid frame type " + frameTypeChar); } LOGGER.debug("Decoding frame of type {}", frameType); final int argumentsLength = parts.length - 1; switch (frameType) { case AUTH_RESPONSE: assertArgumentsLength(3, argumentsLength, "authentication response"); final CertificateChain certificates = new CertificateChain(); final byte[] rawCertificates = Base64.decodeBase64(parts[1].getBytes()); CertificateStoreLoader.load(new ByteArrayInputStream(rawCertificates), certificates); final byte[] salt = Base64.decodeBase64(parts[2]); final byte[] digitalSignature = Base64.decodeBase64(parts[3]); return new AuthenticationResponseFrame(certificates, salt, digitalSignature); case AUTHENTICATE: assertArgumentsLength(1, argumentsLength, "authentication request"); final byte[] challenge = Base64.decodeBase64(parts[1]); return new AuthenticationRequestFrame(challenge); case ERROR: if (parts.length == 0) { throw new DecodingException("Error is missing error code"); } final Integer errorNumber = Integer.valueOf(parts[1]); final ErrorFrame.Code errorCode = ErrorFrame.Code.lookupCode(errorNumber); int messageIndex = 1; messageIndex = skipWhiteSpace(messageIndex, command); while (messageIndex < command.length() && Character.isDigit(command.charAt(messageIndex))) { messageIndex++; } messageIndex = skipWhiteSpace(messageIndex, command); final String errorMessage = command.substring(messageIndex).trim(); if (errorMessage.length() > 0) { return new ErrorFrame(errorCode, errorMessage); } else { return new ErrorFrame(errorCode); } case GREETING: assertArgumentsLength(3, argumentsLength, "greeting"); final int version = Integer.valueOf(parts[1]); final String agent = parts[2]; final long id = Long.valueOf(parts[3]); return new GreetingFrame(version, agent, id); case PING: return PingFrame.PING; case PONG: return PongFrame.PONG; case PUBLISH: if (argumentsLength < 2 || argumentsLength > 3) { throw new DecodingException( "Expected message frame to have 2 or 3 arguments. It has " + argumentsLength + "."); } final String messageSubject = parts[1]; final String replySubject; final Integer messageLength; if (parts.length == 3) { replySubject = null; messageLength = Integer.valueOf(parts[2]); } else { replySubject = parts[2]; messageLength = Integer.valueOf(parts[3]); } if (in.readableBytes() < messageLength + Codec.DELIMITER.length) { // If we haven't received the entire message body (plus the CRLF), wait until it arrives. in.resetReaderIndex(); return null; } final ByteBuf messageBytes = in.readBytes(messageLength); final String messageBody = new String(messageBytes.array(), CharsetUtil.UTF_8); in.skipBytes(Codec.DELIMITER.length); // Ignore the CRLF after the message body. return new PublishFrame(new Subject(messageSubject), replySubject == null ? null : new Subject(replySubject), messageBody); case SERVER_READY: return ServerReadyFrame.SERVER_READY; case SUBSCRIBE: assertArgumentsLength(1, argumentsLength, "subscribe"); return new SubscribeFrame(new Subject(parts[1])); case UNSUBSCRIBE: assertArgumentsLength(1, argumentsLength, "unsubscribe"); return new UnsubscribeFrame(new Subject(parts[1])); default: throw new DecodingException("Unknown frame type " + frameType); } }