List of usage examples for io.netty.buffer Unpooled EMPTY_BUFFER
ByteBuf EMPTY_BUFFER
To view the source code for io.netty.buffer Unpooled EMPTY_BUFFER.
Click Source Link
From source file:rereverse.ReReverseHandler.java
License:Open Source License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { final Channel inboundChannel = ctx.channel(); Bootstrap b = new Bootstrap(); b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass()) .handler(new ChannelInboundHandlerAdapter() { @Override//from w ww . j a v a 2s. c om public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.read(); ctx.write(Unpooled.EMPTY_BUFFER); } @Override public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { ctx.channel().read(); } else { future.channel().close(); } } }); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { closeChannel(inboundChannel); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); closeChannel(ctx.channel()); } }).option(ChannelOption.AUTO_READ, false); //TODO map using url without port (?) ChannelFuture f = b.connect(application.remoteHost, application.remotePort); outbound = f.channel(); f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { inboundChannel.read(); } else { // failed inboundChannel.close(); } } }); }
From source file:rereverse.ReReverseHandler.java
License:Open Source License
static void closeChannel(Channel ch) { if (ch != null && ch.isActive()) { ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } }
From source file:sas.systems.imflux.network.DataPacketEncoder.java
License:Apache License
/** * Encodes a DataPacket if and only if {@code message} is of type {@link DataPacket}. Otherwise an empty ChannelBuffer * is added to the list./*from w w w . ja va2s. com*/ * * @param ctx The context of the ChannelHandler * @param message the message which should be encoded * @param out a list where all messages are written to */ @Override protected void encode(ChannelHandlerContext ctx, DataPacket message, List<Object> out) throws Exception { if (message.getDataSize() == 0) { out.add(Unpooled.EMPTY_BUFFER); } else { out.add(message.encode()); } }
From source file:sas.systems.imflux.network.udp.UdpControlPacketEncoder.java
License:Apache License
/** * Encodes a {@link CompoundControlPacket} wrapped into an {@link AddressedEnvelope} to a {@link ByteBuf} also wrapped * into an {@link AddressedEnvelope}. // w ww. j av a 2 s.c om * * @param ctx The context of the ChannelHandler * @param message the message which should be encoded * @param out a list where all messages are written to */ @Override protected void encode(ChannelHandlerContext ctx, AddressedEnvelope<CompoundControlPacket, SocketAddress> msg, List<Object> out) throws Exception { // encode CompountControlPacket here and forward destination (recipient) of the packet final CompoundControlPacket compoundControlPacket = msg.content(); final List<ControlPacket> packets = compoundControlPacket.getControlPackets(); ByteBuf compoundBuffer = Unpooled.EMPTY_BUFFER; if (packets.isEmpty()) { final ByteBuf[] buffers = new ByteBuf[packets.size()]; for (int i = 0; i < buffers.length; i++) { buffers[i] = packets.get(i).encode(); } compoundBuffer = Unpooled.wrappedBuffer(buffers); } AddressedEnvelope<ByteBuf, SocketAddress> newMsg = new DefaultAddressedEnvelope<ByteBuf, SocketAddress>( compoundBuffer, msg.recipient(), ctx.channel().localAddress()); out.add(newMsg); }
From source file:sas.systems.imflux.network.udp.UdpDataPacketEncoder.java
License:Apache License
/** * Encodes a {@link DataPacket} wrapped into an {@link AddressedEnvelope} in a {@link ByteBuf} also wrapped into an * {@link AddressedEnvelope}. If the {@link DataPacket}'s content is not empty it is added, otherwise an empty ByteBuf * is added to the AddressedEnvelope.//from w w w .j a va 2 s. co m * * @param ctx The context of the ChannelHandler * @param message the message which should be encoded * @param out a list where all messages are written to */ @Override protected void encode(ChannelHandlerContext ctx, AddressedEnvelope<DataPacket, SocketAddress> msg, List<Object> out) throws Exception { // encode CompountControlPacket here and forward destination (recipient) of the packet final DataPacket dataPacket = msg.content(); final SocketAddress recipient = msg.recipient(); final SocketAddress sender = ctx.channel().localAddress(); final ByteBuf buffer; if (dataPacket.getDataSize() == 0) { buffer = Unpooled.EMPTY_BUFFER; } else { buffer = dataPacket.encode(); } final AddressedEnvelope<ByteBuf, SocketAddress> newMsg = new DefaultAddressedEnvelope<ByteBuf, SocketAddress>( buffer, recipient, sender); out.add(newMsg); }
From source file:server.util.ChannelUtil.java
License:Apache License
/** * Closes the specified channel after all queued write requests are flushed. *//*from ww w . j av a2 s . co m*/ public static void closeOnFlush(Channel ch) { if (ch != null && ch.isActive()) { ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } }
From source file:uapi.web.http.netty.internal.HttpRequestDispatcher.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { if (this._request == null) { this._request = new NettyHttpRequest(this._logger, (HttpRequest) msg); }/*from w ww. ja va 2 s . com*/ if (this._response == null) { this._response = new NettyHttpResponse(ctx, this._request); } } // Find out mapped handler if (this._handler == null) { List<IHttpHandler> handlers = Looper.from(this._handlers) .filter(handler -> this._request.uri().startsWith(handler.getUriMapping())).toList(); if (handlers.size() == 0) { throw new NotFoundException("No handler is mapped to uri - {}", this._request.uri()); } this._handler = handlers.get(0); if (handlers.size() > 1) { for (int i = 1; i < handlers.size(); i++) { if (handlers.get(i).getUriMapping().length() > this._handler.getUriMapping().length()) { this._handler = handlers.get(i); break; } } } } if (this._handler == null) { throw new NotFoundException("No handler is mapped to uri - {}", this._request.uri()); } if (this._handler instanceof ILargeHttpHandler) { switch (this._request.method()) { case GET: this._handler.get(this._request, this._response); break; case PUT: this._handler.put(this._request, this._response); break; case PATCH: this._handler.patch(this._request, this._response); break; case POST: this._handler.post(this._request, this._response); break; case DELETE: this._handler.delete(this._request, this._response); break; default: throw new BadRequestException("Unsupported http method - {}", this._request.method()); } } if (msg instanceof HttpContent) { this._request.appendBodyPart((HttpContent) msg); // Check body size if (this._request.getBodySize() > this._maxBufferSize) { throw new InternalServerException("The max buffer size has been reached - {}", this._maxBufferSize); } if (msg instanceof LastHttpContent) { this._request.addTrailer((LastHttpContent) msg); switch (this._request.method()) { case GET: this._handler.get(this._request, this._response); break; case PUT: this._handler.put(this._request, this._response); break; case POST: this._handler.post(this._request, this._response); break; case DELETE: this._handler.delete(this._request, this._response); break; default: throw new BadRequestException("Unsupported http method {}", this._request.method()); } this._response.flush(); if (!this._request.isKeepAlive()) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } ReferenceCountUtil.release(msg); }
From source file:ws.wamp.jawampa.transport.netty.NettyWampClientConnectorProvider.java
License:Apache License
@Override public IWampConnector createConnector(final URI uri, IWampClientConnectionConfig configuration, List<WampSerialization> serializations, final SocketAddress proxyAddress) throws Exception { String scheme = uri.getScheme(); scheme = scheme != null ? scheme : ""; // Check if the configuration is a netty configuration. // However null is an allowed value final NettyWampConnectionConfig nettyConfig; if (configuration instanceof NettyWampConnectionConfig) { nettyConfig = (NettyWampConnectionConfig) configuration; } else if (configuration != null) { throw new ApplicationError(ApplicationError.INVALID_CONNECTION_CONFIGURATION); } else {//www . jav a2 s .c o m nettyConfig = null; } if (scheme.equalsIgnoreCase("ws") || scheme.equalsIgnoreCase("wss")) { // Check the host and port field for validity if (uri.getHost() == null || uri.getPort() == 0) { throw new ApplicationError(ApplicationError.INVALID_URI); } // Initialize SSL when required final boolean needSsl = uri.getScheme().equalsIgnoreCase("wss"); final SslContext sslCtx0; if (needSsl && (nettyConfig == null || nettyConfig.sslContext() == null)) { // Create a default SslContext when we got none provided through the constructor try { sslCtx0 = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } catch (SSLException e) { throw e; } } else if (needSsl) { sslCtx0 = nettyConfig.sslContext(); } else { sslCtx0 = null; } final String subProtocols = WampSerialization.makeWebsocketSubprotocolList(serializations); final int maxFramePayloadLength = (nettyConfig == null) ? NettyWampConnectionConfig.DEFAULT_MAX_FRAME_PAYLOAD_LENGTH : nettyConfig.getMaxFramePayloadLength(); // Return a factory that creates a channel for websocket connections return new IWampConnector() { @Override public IPendingWampConnection connect(final ScheduledExecutorService scheduler, final IPendingWampConnectionListener connectListener, final IWampConnectionListener connectionListener) { // Use well-known ports if not explicitly specified final int port; if (uri.getPort() == -1) { if (needSsl) port = 443; else port = 80; } else port = uri.getPort(); final WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, subProtocols, false, new DefaultHttpHeaders(), maxFramePayloadLength); /** * Netty handler for that receives and processes WampMessages and state * events from the pipeline. * A new instance of this is created for each connection attempt. */ final ChannelHandler connectionHandler = new SimpleChannelInboundHandler<WampMessage>() { boolean connectionWasEstablished = false; /** Guard to prevent forwarding events aftert the channel was closed */ boolean wasClosed = false; @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { if (wasClosed) return; wasClosed = true; if (connectionWasEstablished) { connectionListener.transportClosed(); } else { // The transport closed before the websocket handshake was completed connectListener .connectFailed(new ApplicationError(ApplicationError.TRANSPORT_CLOSED)); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (wasClosed) return; wasClosed = true; if (connectionWasEstablished) { connectionListener.transportError(cause); } else { // The transport closed before the websocket handshake was completed connectListener.connectFailed(cause); } super.exceptionCaught(ctx, cause); } @Override public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception { if (wasClosed) return; if (evt instanceof ConnectionEstablishedEvent) { ConnectionEstablishedEvent ev = (ConnectionEstablishedEvent) evt; final WampSerialization serialization = ev.serialization(); IWampConnection connection = new IWampConnection() { @Override public WampSerialization serialization() { return serialization; } @Override public boolean isSingleWriteOnly() { return false; } @Override public void sendMessage(WampMessage message, final IWampConnectionPromise<Void> promise) { ChannelFuture f = ctx.writeAndFlush(message); f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess() || future.isCancelled()) promise.fulfill(null); else promise.reject(future.cause()); } }); } @Override public void close(boolean sendRemaining, final IWampConnectionPromise<Void> promise) { // sendRemaining is ignored. Remaining data is always sent ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { future.channel().close() .addListener(new ChannelFutureListener() { @Override public void operationComplete( ChannelFuture future) throws Exception { if (future.isSuccess() || future.isCancelled()) promise.fulfill(null); else promise.reject(future.cause()); } }); } }); } }; connectionWasEstablished = true; // Connection to the remote host was established // However the WAMP session is not established until the handshake was finished connectListener.connectSucceeded(connection); } } @Override protected void channelRead0(ChannelHandlerContext ctx, WampMessage msg) throws Exception { if (wasClosed) return; assert (connectionWasEstablished); connectionListener.messageReceived(msg); } }; // If the assigned scheduler is a netty eventloop use this final EventLoopGroup nettyEventLoop; if (scheduler instanceof EventLoopGroup) { nettyEventLoop = (EventLoopGroup) scheduler; } else { connectListener.connectFailed(new ApplicationError(ApplicationError.INCOMATIBLE_SCHEDULER)); return IPendingWampConnection.Dummy; } Bootstrap b = new Bootstrap(); // things should be resolved on via the socks5 proxy if (proxyAddress != null) b.resolver(NoopAddressResolverGroup.INSTANCE); b.group(nettyEventLoop).channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (proxyAddress != null) { p.addFirst("proxy", new Socks5ProxyHandler(proxyAddress)); } if (sslCtx0 != null) { p.addLast(sslCtx0.newHandler(ch.alloc(), uri.getHost(), port)); } p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), new WebSocketClientProtocolHandler(handshaker, false), new WebSocketFrameAggregator( WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE), new WampClientWebsocketHandler(handshaker), connectionHandler); } }); final ChannelFuture connectFuture = b.connect(uri.getHost(), port); connectFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Do nothing. The connection is only successful when the websocket handshake succeeds } else { // Remark: Might be called directly in addListener // Therefore addListener should be the last call // Remark2: This branch will be taken upon cancellation. // This is required by the contract. connectListener.connectFailed(future.cause()); } } }); // Return the connection in progress with the ability for cancellation return new IPendingWampConnection() { @Override public void cancelConnect() { connectFuture.cancel(false); } }; } }; } throw new ApplicationError(ApplicationError.INVALID_URI); }
From source file:ws.wamp.jawampa.transport.netty.WampDeserializationHandler.java
License:Apache License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // We caught an exception. // Most probably because we received an invalid message readState = ReadState.Error;/* w w w. j av a2s . co m*/ ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }
From source file:ws.wamp.jawampa.WampClient.java
License:Apache License
/** * Starts an connection attempt to the router *//* w w w . j av a 2 s . co m*/ private void beginConnect() { handler = new SessionHandler(); try { connectFuture = channelFactory.createChannel(handler, eventLoop, objectMapper); connectFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) throws Exception { if (f.isSuccess()) { if (f == connectFuture) { // Our new channel is connected channel = f.channel(); connectFuture = null; } else { // We we're connected but aren't interested in the channel anymore // Therefore we close the new channel f.channel().writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } else if (!f.isCancelled()) { // Remark: Might be called directly in addListener // Therefore addListener should be the last call in beginConnect closeCurrentTransport(); // Try reconnect if possible, otherwise announce close if (mayReconnect()) { scheduleReconnect(); } else { statusObservable.onNext(status); } } } }); } catch (Exception e) { // Catch exceptions that can happen during creating the channel // These are normally signs that something is wrong with our configuration // Therefore we don't trigger retries closeCurrentTransport(); statusObservable.onNext(status); completeStatus(e); } }