List of usage examples for io.netty.channel ChannelInboundHandlerAdapter ChannelInboundHandlerAdapter
ChannelInboundHandlerAdapter
From source file:com.comphenix.protocol.compat.netty.independent.NettyProtocolInjector.java
License:Open Source License
/** * Inject into the spigot connection class. *//*w ww . j a v a2 s .c o m*/ @Override @SuppressWarnings("unchecked") public synchronized void inject() { if (injected) throw new IllegalStateException("Cannot inject twice."); try { FuzzyReflection fuzzyServer = FuzzyReflection.fromClass(MinecraftReflection.getMinecraftServerClass()); List<Method> serverConnectionMethods = fuzzyServer .getMethodListByParameters(MinecraftReflection.getServerConnectionClass(), new Class[] {}); // Get the server connection Object server = fuzzyServer.getSingleton(); Object serverConnection = null; for (Method method : serverConnectionMethods) { try { serverConnection = method.invoke(server); // Continue until we get a server connection if (serverConnection != null) { break; } } catch (Exception e) { // Try the next though e.printStackTrace(); } } // Handle connected channels final ChannelInboundHandler endInitProtocol = new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) throws Exception { try { // This can take a while, so we need to stop the main thread from interfering synchronized (networkManagers) { injectionFactory.fromChannel(channel, NettyProtocolInjector.this, playerFactory) .inject(); } } catch (Exception e) { reporter.reportDetailed(NettyProtocolInjector.this, Report .newBuilder(REPORT_CANNOT_INJECT_INCOMING_CHANNEL).messageParam(channel).error(e)); } } }; // This is executed before Minecraft's channel handler final ChannelInboundHandler beginInitProtocol = new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) throws Exception { // Our only job is to add init protocol channel.pipeline().addLast(endInitProtocol); } }; // Add our handler to newly created channels final ChannelHandler connectionHandler = new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { Channel channel = (Channel) msg; // Prepare to initialize ths channel channel.pipeline().addFirst(beginInitProtocol); ctx.fireChannelRead(msg); } }; // Get the current NetworkMananger list networkManagers = (List<Object>) FuzzyReflection.fromObject(serverConnection, true).invokeMethod(null, "getNetworkManagers", List.class, serverConnection); // Insert ProtocolLib's connection interceptor bootstrapFields = getBootstrapFields(serverConnection); for (VolatileField field : bootstrapFields) { final List<Object> list = (List<Object>) field.getValue(); // We don't have to override this list if (list == networkManagers) { continue; } // Synchronize with each list before we attempt to replace them. field.setValue(new NettyBootstrapList(list, connectionHandler)); } injected = true; } catch (Exception e) { throw new RuntimeException("Unable to inject channel futures.", e); } }
From source file:com.comphenix.protocol.injector.netty.ChannelInjector.java
License:Open Source License
@Override @SuppressWarnings("unchecked") public boolean inject() { synchronized (networkManager) { if (closed) return false; if (originalChannel instanceof Factory) return false; if (!originalChannel.isActive()) return false; // Main thread? We should synchronize with the channel thread, otherwise we might see a // pipeline with only some of the handlers removed if (Bukkit.isPrimaryThread()) { // Just like in the close() method, we'll avoid blocking the main thread executeInChannelThread(new Runnable() { @Override//w w w .j a v a2 s . co m public void run() { inject(); } }); return false; // We don't know } // Don't inject the same channel twice if (findChannelHandler(originalChannel, ChannelInjector.class) != null) { return false; } // Get the vanilla decoder, so we don't have to replicate the work vanillaDecoder = (ByteToMessageDecoder) originalChannel.pipeline().get("decoder"); vanillaEncoder = (MessageToByteEncoder<Object>) originalChannel.pipeline().get("encoder"); if (vanillaDecoder == null) throw new IllegalArgumentException( "Unable to find vanilla decoder in " + originalChannel.pipeline()); if (vanillaEncoder == null) throw new IllegalArgumentException( "Unable to find vanilla encoder in " + originalChannel.pipeline()); patchEncoder(vanillaEncoder); if (DECODE_BUFFER == null) DECODE_BUFFER = Accessors.getMethodAccessor(vanillaDecoder.getClass(), "decode", ChannelHandlerContext.class, ByteBuf.class, List.class); if (ENCODE_BUFFER == null) ENCODE_BUFFER = Accessors.getMethodAccessor(vanillaEncoder.getClass(), "encode", ChannelHandlerContext.class, Object.class, ByteBuf.class); // Intercept sent packets MessageToByteEncoder<Object> protocolEncoder = new MessageToByteEncoder<Object>() { @Override protected void encode(ChannelHandlerContext ctx, Object packet, ByteBuf output) throws Exception { if (packet instanceof WirePacket) { // Special case for wire format ChannelInjector.this.encodeWirePacket((WirePacket) packet, output); } else { ChannelInjector.this.encode(ctx, packet, output); } } @Override public void write(ChannelHandlerContext ctx, Object packet, ChannelPromise promise) throws Exception { super.write(ctx, packet, promise); ChannelInjector.this.finalWrite(ctx, packet, promise); } }; // Intercept recieved packets ChannelInboundHandlerAdapter finishHandler = new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // Execute context first ctx.fireChannelRead(msg); ChannelInjector.this.finishRead(ctx, msg); } }; // Insert our handlers - note that we effectively replace the vanilla encoder/decoder originalChannel.pipeline().addBefore("decoder", "protocol_lib_decoder", this); originalChannel.pipeline().addBefore("protocol_lib_decoder", "protocol_lib_finish", finishHandler); originalChannel.pipeline().addAfter("encoder", "protocol_lib_encoder", protocolEncoder); // Intercept all write methods channelField.setValue(new ChannelProxy(originalChannel, MinecraftReflection.getPacketClass()) { // Compatibility with Spigot 1.8 private final PipelineProxy pipelineProxy = new PipelineProxy(originalChannel.pipeline(), this) { @Override public ChannelPipeline addBefore(String baseName, String name, ChannelHandler handler) { // Correct the position of the decoder if ("decoder".equals(baseName)) { if (super.get("protocol_lib_decoder") != null && guessCompression(handler)) { super.addBefore("protocol_lib_decoder", name, handler); return this; } } return super.addBefore(baseName, name, handler); } }; @Override public ChannelPipeline pipeline() { return pipelineProxy; } @Override protected <T> Callable<T> onMessageScheduled(final Callable<T> callable, FieldAccessor packetAccessor) { final PacketEvent event = handleScheduled(callable, packetAccessor); // Handle cancelled events if (event != null && event.isCancelled()) return null; return new Callable<T>() { @Override public T call() throws Exception { T result = null; // This field must only be updated in the pipeline thread currentEvent = event; result = callable.call(); currentEvent = null; return result; } }; } @Override protected Runnable onMessageScheduled(final Runnable runnable, FieldAccessor packetAccessor) { final PacketEvent event = handleScheduled(runnable, packetAccessor); // Handle cancelled events if (event != null && event.isCancelled()) return null; return new Runnable() { @Override public void run() { currentEvent = event; runnable.run(); currentEvent = null; } }; } protected PacketEvent handleScheduled(Object instance, FieldAccessor accessor) { // Let the filters handle this packet Object original = accessor.get(instance); // See if we've been instructed not to process packets if (!scheduleProcessPackets.get()) { NetworkMarker marker = getMarker(original); if (marker != null) { PacketEvent result = new PacketEvent(ChannelInjector.class); result.setNetworkMarker(marker); return result; } else { return BYPASSED_PACKET; } } PacketEvent event = processSending(original); if (event != null && !event.isCancelled()) { Object changed = event.getPacket().getHandle(); // Change packet to be scheduled if (original != changed) accessor.set(instance, changed); } ; return event != null ? event : BYPASSED_PACKET; } }); injected = true; return true; } }
From source file:com.comphenix.protocol.injector.netty.ProtocolInjector.java
License:Open Source License
/** * Inject into the spigot connection class. *//*from w w w .j av a 2 s . c o m*/ @SuppressWarnings("unchecked") public synchronized void inject() { if (injected) throw new IllegalStateException("Cannot inject twice."); try { FuzzyReflection fuzzyServer = FuzzyReflection.fromClass(MinecraftReflection.getMinecraftServerClass()); List<Method> serverConnectionMethods = fuzzyServer .getMethodListByParameters(MinecraftReflection.getServerConnectionClass(), new Class[] {}); // Get the server connection Object server = fuzzyServer.getSingleton(); Object serverConnection = null; for (Method method : serverConnectionMethods) { try { serverConnection = method.invoke(server); // Continue until we get a server connection if (serverConnection != null) { break; } } catch (Exception e) { // Try the next though e.printStackTrace(); } } // Handle connected channels final ChannelInboundHandler endInitProtocol = new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel channel) throws Exception { try { synchronized (networkManagers) { // For some reason it needs to be delayed on 1.12, but the delay breaks 1.11 and below // TODO I see this more as a temporary hotfix than a permanent solution if (MinecraftVersion.getCurrentVersion().getMinor() >= 12) { channel.eventLoop().submit(() -> injectionFactory .fromChannel(channel, ProtocolInjector.this, playerFactory).inject()); } else { injectionFactory.fromChannel(channel, ProtocolInjector.this, playerFactory) .inject(); } } } catch (Exception e) { reporter.reportDetailed(ProtocolInjector.this, Report .newBuilder(REPORT_CANNOT_INJECT_INCOMING_CHANNEL).messageParam(channel).error(e)); } } }; // This is executed before Minecraft's channel handler final ChannelInboundHandler beginInitProtocol = new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) throws Exception { // Our only job is to add init protocol channel.pipeline().addLast(endInitProtocol); } }; // Add our handler to newly created channels final ChannelHandler connectionHandler = new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { Channel channel = (Channel) msg; // Prepare to initialize ths channel channel.pipeline().addFirst(beginInitProtocol); ctx.fireChannelRead(msg); } }; FuzzyReflection fuzzy = FuzzyReflection.fromObject(serverConnection, true); try { List<Field> fields = fuzzy.getFieldListByType(List.class); for (Field field : fields) { ParameterizedType param = (ParameterizedType) field.getGenericType(); if (param.getActualTypeArguments()[0].equals(MinecraftReflection.getNetworkManagerClass())) { field.setAccessible(true); networkManagers = (List<Object>) field.get(serverConnection); } } } catch (Exception ex) { networkManagers = (List<Object>) fuzzy .getMethodByParameters("getNetworkManagers", List.class, serverConnection.getClass()) .invoke(null, serverConnection); } if (networkManagers == null) { throw new RuntimeException("Failed to obtain list of network managers."); } // Insert ProtocolLib's connection interceptor bootstrapFields = getBootstrapFields(serverConnection); for (VolatileField field : bootstrapFields) { final List<Object> list = (List<Object>) field.getValue(); // We don't have to override this list if (list == networkManagers) { continue; } // Synchronize with each list before we attempt to replace them. field.setValue(new BootstrapList(list, connectionHandler)); } injected = true; } catch (Exception e) { throw new RuntimeException("Unable to inject channel futures.", e); } }
From source file:com.digitalpetri.modbus.master.ChannelManager.java
License:Apache License
private CompletableFuture<Channel> connect(CompletableFuture<Channel> future) { CompletableFuture<Channel> bootstrap = ModbusTcpMaster.bootstrap(master, master.getConfig()); bootstrap.whenComplete((ch, ex) -> { if (ch != null) { logger.debug("Channel bootstrap succeeded: localAddress={}, remoteAddress={}", ch.localAddress(), ch.remoteAddress()); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override/*from w w w . ja va 2 s .c om*/ public void channelInactive(ChannelHandlerContext ctx) throws Exception { State currentState = state.get(); if (currentState instanceof Connected) { if (state.compareAndSet(currentState, new Idle())) { logger.debug("channelInactive(), transitioned to Idle"); } } super.channelInactive(ctx); } }); future.complete(ch); } else { logger.debug("Channel bootstrap failed: {}", ex.getMessage(), ex); future.completeExceptionally(ex); } }); return future; }
From source file:com.digitalpetri.modbus.master.ChannelManager.java
License:Apache License
CompletableFuture<Void> disconnect() { final CompletableFuture<Void> future = new CompletableFuture<>(); final State currentState = state.get(); BiConsumer<Channel, Throwable> disconnect = (ch, ex) -> { state.compareAndSet(currentState, new Idle()); if (ch != null) { ch.pipeline().addFirst(new ChannelInboundHandlerAdapter() { @Override//from w w w. ja v a 2 s . c om public void channelInactive(ChannelHandlerContext ctx) throws Exception { logger.debug("channelInactive(), disconnect complete"); future.complete(null); } }); ch.close(); } else { future.complete(null); } }; if (currentState instanceof Idle) { future.complete(null); } else if (currentState instanceof Connecting) { ((Connecting) currentState).future.whenComplete(disconnect); } else if (currentState instanceof Connected) { ((Connected) currentState).future.whenComplete(disconnect); } return future; }
From source file:com.digitalpetri.opcua.sdk.client.fsm.states.Active.java
License:Open Source License
@Override public void activate(SessionStateEvent event, SessionStateContext context) { OpcUaClient client = context.getClient(); UaTcpStackClient stackClient = client.getStackClient(); client.addFaultHandler(faultHandler = serviceFault -> { long statusCode = serviceFault.getResponseHeader().getServiceResult().getValue(); if (statusCode == StatusCodes.Bad_SessionIdInvalid) { logger.warn("ServiceFault: {}", serviceFault.getResponseHeader().getServiceResult()); context.handleEvent(SessionStateEvent.ERR_SESSION_INVALID); }/*www . j a v a 2 s .c o m*/ }); stackClient.getChannelFuture().thenAccept(ch -> { ch.pipeline().addLast(channelHandler = new ChannelInboundHandlerAdapter() { @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { context.handleEvent(SessionStateEvent.ERR_CONNECTION_LOST); } }); }); client.getSubscriptionManager().restartPublishing(); future.complete(session); }
From source file:com.digitalpetri.opcua.stack.client.fsm.states.Connected.java
License:Apache License
@Override public CompletableFuture<Void> activate(ConnectionEvent event, ConnectionStateFsm fsm) { inactivityListener = new ChannelInboundHandlerAdapter() { @Override/*from w ww. j a va2s. c o m*/ public void channelInactive(ChannelHandlerContext ctx) throws Exception { logger.warn("Channel went inactive: {}", ctx.channel()); fsm.handleEvent(ConnectionEvent.ConnectionLost); super.channelInactive(ctx); } }; secureChannel.getChannel().pipeline().addLast(inactivityListener); channelFuture.complete(secureChannel); return CF_VOID_COMPLETED; }
From source file:com.digitalpetri.opcua.stack.client.fsm.states.Disconnecting.java
License:Apache License
private CompletableFuture<Void> closeSecureChannel(ConnectionStateFsm fsm, ClientSecureChannel sc) { CompletableFuture<Void> future = new CompletableFuture<>(); RequestHeader requestHeader = new RequestHeader(NodeId.NULL_VALUE, DateTime.now(), uint(0), uint(0), null, uint(0), null);//from w w w . jav a 2 s. co m sc.getChannel().pipeline().addFirst(new ChannelInboundHandlerAdapter() { @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { fsm.handleEvent(ConnectionEvent.DisconnectSucceeded); future.complete(null); super.channelInactive(ctx); } }); CloseSecureChannelRequest request = new CloseSecureChannelRequest(requestHeader); sc.getChannel().pipeline().fireUserEventTriggered(request); return future; }
From source file:com.eucalyptus.ws.IoHandlers.java
License:Open Source License
public static Map<String, ChannelHandler> channelMonitors(final TimeUnit unit, final long timeout) { final Map<String, ChannelHandler> monitors = Maps.newHashMap(); monitors.put("idlehandler", new IdleStateHandler(0L, 0L, timeout, unit)); monitors.put("idlecloser", new ChannelInboundHandlerAdapter() { @Override//from w w w . jav a2 s .c o m public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent e = (IdleStateEvent) evt; if (e.state() == IdleState.ALL_IDLE) { ctx.channel().close(); } } } }); monitors.putAll(extraMonitors); return monitors; }
From source file:com.github.liyp.netty.App.java
License:Apache License
public static void main(String[] args) throws Exception { EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup worker = new NioEventLoopGroup(); try {// w w w . ja v a2s . c o m ServerBootstrap b = new ServerBootstrap(); b.group(boss, worker).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ReplayingDecoder() { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { short magicHeader = in.readShort(); logger.debug("Receive magic header: {}.", magicHeader); if (magicHeader != HEADER) { logger.error("Receive illegal magic header: {}, close channel: {}.", magicHeader, ctx.channel().remoteAddress()); ctx.close(); } short dataLen = in.readShort(); logger.debug("Receive message data length: {}.", dataLen); if (dataLen < 0) { logger.error("Data length is negative, close channel: {}.", ctx.channel().remoteAddress()); ctx.close(); } ByteBuf payload = in.readBytes(dataLen); String cloudMsg = payload.toString(CharsetUtil.UTF_8); logger.debug("Receive data: {}.", cloudMsg); out.add(cloudMsg); } }).addLast(new MessageToByteEncoder<String>() { @Override protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception { out.writeBytes(msg.getBytes()); } }).addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { logger.info("start receive msg..."); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { logger.info("receive msg: {}", msg); logger.info("echo msg"); ctx.writeAndFlush(msg); } }); } }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(PORT).sync(); logger.info("9999"); f.channel().closeFuture().sync(); } finally { worker.shutdownGracefully(); boss.shutdownGracefully(); } }