io.netty.util.Attribute Java Examples
The following examples show how to use
io.netty.util.Attribute.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpLifecycleChannelHandler.java From zuul with Apache License 2.0 | 6 votes |
protected static boolean fireStartEvent(ChannelHandlerContext ctx, HttpRequest request) { // Only allow this method to run once per request. Channel channel = ctx.channel(); Attribute<State> attr = channel.attr(ATTR_STATE); State state = attr.get(); if (state == State.STARTED) { // This could potentially happen if a bad client sends a 2nd request on the same connection // without waiting for the response from the first. And we don't support HTTP Pipelining. LOG.error("Received a http request on connection where we already have a request being processed. " + "Closing the connection now. channel = " + channel.id().asLongText()); channel.close(); ctx.pipeline().fireUserEventTriggered(new RejectedPipeliningEvent()); return false; } channel.attr(ATTR_STATE).set(State.STARTED); channel.attr(ATTR_HTTP_REQ).set(request); ctx.pipeline().fireUserEventTriggered(new StartEvent(request)); return true; }
Example #2
Source File: RequestFilterHandlerTest.java From riposte with Apache License 2.0 | 6 votes |
@Before public void beforeMethod() { channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); stateAttributeMock = mock(Attribute.class); state = new HttpProcessingState(); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(state).when(stateAttributeMock).get(); firstChunkMsgMock = mock(HttpRequest.class); lastChunkMsgMock = mock(LastHttpContent.class); filter1Mock = mock(RequestAndResponseFilter.class); filter2Mock = mock(RequestAndResponseFilter.class); filtersList = Arrays.asList(filter1Mock, filter2Mock); handlerSpy = spy(new RequestFilterHandler(filtersList)); requestInfoMock = mock(RequestInfo.class); state.setRequestInfo(requestInfoMock); }
Example #3
Source File: LoginDecoder.java From luna with MIT License | 6 votes |
@Override protected Object decodeMsg(ChannelHandlerContext ctx, ByteBuf in, DecodeState state) { switch (state) { case HANDSHAKE: Attribute<Client<?>> attribute = ctx.channel().attr(Client.KEY); attribute.set(new LoginClient(ctx.channel(), context, repository)); decodeHandshake(ctx, in); break; case LOGIN_TYPE: decodeLoginType(ctx, in); break; case RSA_BLOCK: return decodeRsaBlock(ctx, in); } return null; }
Example #4
Source File: Netty4MessageChannelHandler.java From crate with Apache License 2.0 | 6 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { Transports.assertTransportThread(); if (!(msg instanceof ByteBuf)) { ctx.fireChannelRead(msg); return; } final ByteBuf buffer = (ByteBuf) msg; final int remainingMessageSize = buffer.getInt(buffer.readerIndex() - TcpHeader.MESSAGE_LENGTH_SIZE); final int expectedReaderIndex = buffer.readerIndex() + remainingMessageSize; try { Channel channel = ctx.channel(); InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress(); // netty always copies a buffer, either in NioWorker in its read handler, where it copies to a fresh // buffer, or in the cumulative buffer, which is cleaned each time so it could be bigger than the actual size BytesReference reference = Netty4Utils.toBytesReference(buffer, remainingMessageSize); Attribute<NettyTcpChannel> channelAttribute = channel.attr(Netty4Transport.CHANNEL_KEY); transport.messageReceived(reference, channelAttribute.get(), profileName, remoteAddress, remainingMessageSize); } finally { // Set the expected position of the buffer, no matter what happened buffer.readerIndex(expectedReaderIndex); } }
Example #5
Source File: PojoEndpointServer.java From netty-websocket-spring-boot-starter with Apache License 2.0 | 6 votes |
public void doOnBinary(Channel channel, WebSocketFrame frame) { Attribute<String> attrPath = channel.attr(PATH_KEY); PojoMethodMapping methodMapping = null; if (pathMethodMappingMap.size() == 1) { methodMapping = pathMethodMappingMap.values().iterator().next(); } else { String path = attrPath.get(); methodMapping = pathMethodMappingMap.get(path); } if (methodMapping.getOnBinary() != null) { BinaryWebSocketFrame binaryWebSocketFrame = (BinaryWebSocketFrame) frame; Object implement = channel.attr(POJO_KEY).get(); try { methodMapping.getOnBinary().invoke(implement, methodMapping.getOnBinaryArgs(channel, binaryWebSocketFrame)); } catch (Throwable t) { logger.error(t); } } }
Example #6
Source File: ConsumerWithTracingAndMdcSupportTest.java From riposte with Apache License 2.0 | 6 votes |
@Before public void beforeMethod() { channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); stateAttributeMock = mock(Attribute.class); state = new HttpProcessingState(); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(state).when(stateAttributeMock).get(); consumerMock = mock(Consumer.class); inObj = new Object(); throwExceptionDuringCall = false; currentSpanStackWhenConsumerWasCalled = new ArrayList<>(); currentMdcInfoWhenConsumerWasCalled = new ArrayList<>(); doAnswer(invocation -> { currentSpanStackWhenConsumerWasCalled.add(Tracer.getInstance().getCurrentSpanStackCopy()); currentMdcInfoWhenConsumerWasCalled.add(MDC.getCopyOfContextMap()); if (throwExceptionDuringCall) throw new RuntimeException("kaboom"); return null; }).when(consumerMock).accept(inObj); resetTracingAndMdc(); }
Example #7
Source File: CompatibleObjectEncoder.java From netty4.0.27Learn with Apache License 2.0 | 6 votes |
@Override protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception { Attribute<ObjectOutputStream> oosAttr = ctx.attr(OOS); ObjectOutputStream oos = oosAttr.get(); if (oos == null) { oos = newObjectOutputStream(new ByteBufOutputStream(out)); ObjectOutputStream newOos = oosAttr.setIfAbsent(oos); if (newOos != null) { oos = newOos; } } synchronized (oos) { if (resetInterval != 0) { // Resetting will prevent OOM on the receiving side. writtenObjects ++; if (writtenObjects % resetInterval == 0) { oos.reset(); } } oos.writeObject(msg); oos.flush(); } }
Example #8
Source File: IdentificationHandler.java From Cleanstone with MIT License | 6 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress(); InetAddress inetaddress = socketAddress.getAddress(); String ipAddress = inetaddress.getHostAddress(); if (addressBlacklist.contains(ipAddress)) { ctx.close(); } Attribute<Connection> connectionKey = ctx.channel().attr(AttributeKey.valueOf("connection")); if (connectionKey.get() == null) { log.info("New connection from " + ipAddress); Connection connection = new NettyConnection(ctx.channel(), inetaddress, networking.getProtocol() .getDefaultClientLayer(), networking.getProtocol().getDefaultState()); connectionKey.set(connection); if (CleanstoneServer.publishEvent(new ConnectionOpenEvent(connection, networking)).isCancelled()) { ctx.close(); return; } ctx.channel().closeFuture().addListener((a) -> { log.info("Connection from " + ipAddress + " closed"); CleanstoneServer.publishEvent(new ConnectionClosedEvent(connection, networking)); }); } ctx.fireChannelRead(msg); }
Example #9
Source File: ChannelFutureListenerWithTracingAndMdcTest.java From riposte with Apache License 2.0 | 6 votes |
@Before public void beforeMethod() { channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); stateAttributeMock = mock(Attribute.class); state = new HttpProcessingState(); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(state).when(stateAttributeMock).get(); consumerMock = mock(Consumer.class); inObj = mock(ChannelFuture.class); throwExceptionDuringCall = false; currentSpanStackWhenChannelFutureWasCalled = new ArrayList<>(); currentMdcInfoWhenChannelFutureWasCalled = new ArrayList<>(); doAnswer(invocation -> { currentSpanStackWhenChannelFutureWasCalled.add(Tracer.getInstance().getCurrentSpanStackCopy()); currentMdcInfoWhenChannelFutureWasCalled.add(MDC.getCopyOfContextMap()); if (throwExceptionDuringCall) throw new RuntimeException("kaboom"); return null; }).when(consumerMock).accept(inObj); resetTracingAndMdc(); }
Example #10
Source File: HttpsHostCaptureFilter.java From browserup-proxy with Apache License 2.0 | 6 votes |
@Override public HttpResponse clientToProxyRequest(HttpObject httpObject) { if (httpObject instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) httpObject; if (ProxyUtils.isCONNECT(httpRequest)) { Attribute<String> hostname = ctx.channel().attr(AttributeKey.valueOf(HOST_ATTRIBUTE_NAME)); String hostAndPort = httpRequest.uri(); // CONNECT requests contain the port, even when using the default port. a sensible default is to remove the // default port, since in most cases it is not explicitly specified and its presence (in a HAR file, for example) // would be unexpected. String hostNoDefaultPort = BrowserUpHttpUtil.removeMatchingPort(hostAndPort, 443); hostname.set(hostNoDefaultPort); } } return null; }
Example #11
Source File: NettyChannel.java From joyrpc with Apache License 2.0 | 6 votes |
@Override public <T> T getAttribute(final String key, final Function<String, T> function) { if (key == null) { return null; } Attribute<T> attribute = channel.attr(AttributeKey.valueOf(key)); T result = attribute.get(); if (result == null && function != null) { T target = function.apply(key); if (target != null) { if (attribute.compareAndSet(null, target)) { return target; } else { return attribute.get(); } } } return result; }
Example #12
Source File: ClientChannelHandler.java From nuls with MIT License | 5 votes |
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); Attribute<Node> nodeAttribute = ctx.channel().attr(NodeAttributeKey.NODE_KEY); Node node = nodeAttribute.get(); if (node != null) { node.setChannel(ctx.channel()); } if (node != null && node.getConnectedListener() != null) { node.getConnectedListener().action(); } }
Example #13
Source File: IdleHeartbeatHandler.java From joyrpc with Apache License 2.0 | 5 votes |
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { if (heartbeatTrigger == null) { Attribute<HeartbeatTrigger> attr = ctx.channel().attr(HEARTBEAT_TRIGGER); heartbeatTrigger = attr != null ? attr.get() : null; } if (heartbeatTrigger != null) { heartbeatTrigger.run(); } } else { super.userEventTriggered(ctx, evt); } }
Example #14
Source File: ContextBoundUnmarshallerProvider.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
@Override public Unmarshaller getUnmarshaller(ChannelHandlerContext ctx) throws Exception { Attribute<Unmarshaller> attr = ctx.attr(UNMARSHALLER); Unmarshaller unmarshaller = attr.get(); if (unmarshaller == null) { unmarshaller = super.getUnmarshaller(ctx); attr.set(unmarshaller); } return unmarshaller; }
Example #15
Source File: ServerChannelHandler.java From nuls-v2 with MIT License | 5 votes |
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) { SocketChannel channel = (SocketChannel) ctx.channel(); ByteBuf buf = (ByteBuf) msg; String remoteIP = channel.remoteAddress().getHostString(); NulsByteBuffer byteBuffer = null; Node node = null; try { String nodeId = IpUtil.getNodeId(channel.remoteAddress()); Attribute<Node> nodeAttribute = channel.attr(AttributeKey.valueOf("node-" + nodeId)); node = nodeAttribute.get(); if (node != null) { byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); byteBuffer = new NulsByteBuffer(bytes); } else { LoggerUtil.COMMON_LOG.error("-----------------Server channelRead node is null -----------------" + remoteIP + ":" + channel.remoteAddress().getPort()); ctx.channel().close(); } } catch (Exception e) { LoggerUtil.COMMON_LOG.error(e); // throw e; } finally { buf.clear(); } MessageManager.getInstance().receiveMessage(byteBuffer, node); }
Example #16
Source File: ChannelUtil.java From qmq with Apache License 2.0 | 5 votes |
public static boolean setAttributeIfAbsent(Channel channel, Object o) { synchronized (channel) { Attribute<Object> attr = channel.attr(DEFAULT_ATTRIBUTE); if (attr == null || attr.get() == null) { channel.attr(DEFAULT_ATTRIBUTE).set(o); return true; } return false; } }
Example #17
Source File: ServerChannelHandler.java From nuls with MIT License | 5 votes |
@Override public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { super.channelUnregistered(ctx); SocketChannel channel = (SocketChannel) ctx.channel(); String nodeId = IpUtil.getNodeId(channel.remoteAddress()); Attribute<Node> nodeAttribute = channel.attr(AttributeKey.valueOf("node-" + nodeId)); Node node = nodeAttribute.get(); if (node != null && node.getDisconnectListener() != null) { node.getDisconnectListener().action(); } //channelUnregistered之前,channel就已经close了,可以调用channel.isOpen()查看状态 //channel.close(); }
Example #18
Source File: StreamingAsyncHttpClientTest.java From riposte with Apache License 2.0 | 5 votes |
private ChannelHandlerContext mockChannelHandlerContext() { ChannelHandlerContext mockContext = mock(ChannelHandlerContext.class); when(mockContext.channel()).thenReturn(mock(Channel.class)); @SuppressWarnings("unchecked") Attribute<HttpProcessingState> mockHttpProcessingStateAttribute = mock(Attribute.class); Attribute<ProxyRouterProcessingState> mockProxyStateAttribute = mock(Attribute.class); when(mockContext.channel().attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY)).thenReturn(mockHttpProcessingStateAttribute); when(mockContext.channel().attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY).get()).thenReturn(mock(HttpProcessingState.class)); when(mockContext.channel().attr(ChannelAttributes.PROXY_ROUTER_PROCESSING_STATE_ATTRIBUTE_KEY)).thenReturn(mockProxyStateAttribute); when(mockContext.channel().attr(ChannelAttributes.PROXY_ROUTER_PROCESSING_STATE_ATTRIBUTE_KEY).get()).thenReturn(mock(ProxyRouterProcessingState.class)); return mockContext; }
Example #19
Source File: ClientChannelHandler.java From nuls with MIT License | 5 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { try { Attribute<Node> nodeAttribute = ctx.channel().attr(NodeAttributeKey.NODE_KEY); Node node = nodeAttribute.get(); ByteBuf buf = (ByteBuf) msg; messageProcessor.processor(buf, node); } catch (Exception e) { Log.error("----------------exceptionCaught 111 ---------"); throw e; } }
Example #20
Source File: IncompleteHttpCallTimeoutHandlerTest.java From riposte with Apache License 2.0 | 5 votes |
@Before public void beforeMethod() { channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); doReturn(channelMock).when(ctxMock).channel(); doReturn(mock(Attribute.class)).when(channelMock).attr(any(AttributeKey.class)); }
Example #21
Source File: ServletHttpExchange.java From spring-boot-protocol with Apache License 2.0 | 5 votes |
public <T> T getAttribute(AttributeKey<T> key){ if(channelHandlerContext != null && channelHandlerContext.channel() != null) { Attribute<T> attribute = channelHandlerContext.channel().attr(key); if(attribute != null){ return attribute.get(); } } return null; }
Example #22
Source File: SocketControlImpl.java From sds with Apache License 2.0 | 5 votes |
@Override public void bindKey(Channel ctx, String key) { Attribute<String> attr = ctx.attr(attributeKey); if(attr!=null){ attr.set(key); //put delivery deliveryClient.putKey(getModelName(),getUniqueKey(ctx),key); } }
Example #23
Source File: FtdcTraderApiAdapter.java From ftdc with Apache License 2.0 | 5 votes |
private FtdcTraderSpi getSpi(Channel ftdcChannel) { FtdcTraderSpi ftdcTraderSpi = null; Verify.verifyNotNull(ftdcChannel, "ftdcChannel is null"); if(ftdcChannel.hasAttr(FtdcTraderSpi.TRADER_API)) { Attribute<FtdcTraderSpi> attr = ftdcChannel.attr(FtdcTraderSpi.TRADER_API); ftdcTraderSpi = attr.get(); } Verify.verifyNotNull(ftdcTraderSpi, "FtdcTraderSpi not register, pls register it first"); return ftdcTraderSpi; }
Example #24
Source File: DefaultRegistry.java From Jupiter with Apache License 2.0 | 5 votes |
private static boolean attachPublishEventOnChannel(RegisterMeta meta, Channel channel) { Attribute<ConcurrentSet<RegisterMeta>> attr = channel.attr(C_PUBLISH_KEY); ConcurrentSet<RegisterMeta> registerMetaSet = attr.get(); if (registerMetaSet == null) { ConcurrentSet<RegisterMeta> newRegisterMetaSet = new ConcurrentSet<>(); registerMetaSet = attr.setIfAbsent(newRegisterMetaSet); if (registerMetaSet == null) { registerMetaSet = newRegisterMetaSet; } } return registerMetaSet.add(meta); }
Example #25
Source File: AsyncNettyHelperTest.java From riposte with Apache License 2.0 | 5 votes |
@Before public void beforeMethod() { channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); stateAttributeMock = mock(Attribute.class); proxyRouterStateAttrMock = mock(Attribute.class); state = new HttpProcessingState(); proxyRouterStateMock = mock(ProxyRouterProcessingState.class); requestInfoMock = mock(RequestInfo.class); executor = Executors.newCachedThreadPool(); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(state).when(stateAttributeMock).get(); doReturn(proxyRouterStateAttrMock).when(channelMock).attr(ChannelAttributes.PROXY_ROUTER_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(proxyRouterStateMock).when(proxyRouterStateAttrMock).get(); state.setRequestInfo(requestInfoMock); runnableMock = mock(Runnable.class); callableMock = mock(Callable.class); supplierMock = mock(Supplier.class); functionMock = mock(Function.class); biFunctionMock = mock(BiFunction.class); consumerMock = mock(Consumer.class); biConsumerMock = mock(BiConsumer.class); currentSpanStackWhenRequestResourcesReleased = new ArrayList<>(); currentMdcInfoWhenRequestResourcesReleased = new ArrayList<>(); doAnswer(invocation -> { currentSpanStackWhenRequestResourcesReleased.add(Tracer.getInstance().getCurrentSpanStackCopy()); currentMdcInfoWhenRequestResourcesReleased.add(MDC.getCopyOfContextMap()); return null; }).when(requestInfoMock).releaseAllResources(); resetTracingAndMdc(); }
Example #26
Source File: NettyChannel.java From joyrpc with Apache License 2.0 | 5 votes |
@Override public <T> T getAttribute(final String key) { if (key == null) { return null; } Attribute<T> attribute = channel.attr(AttributeKey.valueOf(key)); return attribute.get(); }
Example #27
Source File: HighPerformanceChannelWriter.java From sailfish with Apache License 2.0 | 5 votes |
private static HighPerformanceChannelWriter getWriter(Channel channel) { Attribute<HighPerformanceChannelWriter> attr = channel.attr(ChannelAttrKeys.highPerformanceWriter); HighPerformanceChannelWriter writer = attr.get(); if (null == writer) { HighPerformanceChannelWriter old = attr.setIfAbsent(writer = new HighPerformanceChannelWriter(channel)); if (null != old) { writer = old; } } return writer; }
Example #28
Source File: FunctionWithTracingAndMdcSupportTest.java From riposte with Apache License 2.0 | 5 votes |
@Before public void beforeMethod() { channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); stateAttributeMock = mock(Attribute.class); state = new HttpProcessingState(); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(state).when(stateAttributeMock).get(); functionMock = mock(Function.class); inObj = new Object(); outObj = new Object(); throwExceptionDuringCall = false; currentSpanStackWhenFunctionWasCalled = new ArrayList<>(); currentMdcInfoWhenFunctionWasCalled = new ArrayList<>(); doAnswer(invocation -> { currentSpanStackWhenFunctionWasCalled.add(Tracer.getInstance().getCurrentSpanStackCopy()); currentMdcInfoWhenFunctionWasCalled.add(MDC.getCopyOfContextMap()); if (throwExceptionDuringCall) throw new RuntimeException("kaboom"); return outObj; }).when(functionMock).apply(inObj); resetTracingAndMdc(); }
Example #29
Source File: DefaultRegistryServer.java From Jupiter with Apache License 2.0 | 5 votes |
private static boolean attachSubscribeEventOnChannel(RegisterMeta.ServiceMeta serviceMeta, Channel channel) { Attribute<ConcurrentSet<RegisterMeta.ServiceMeta>> attr = channel.attr(S_SUBSCRIBE_KEY); ConcurrentSet<RegisterMeta.ServiceMeta> serviceMetaSet = attr.get(); if (serviceMetaSet == null) { ConcurrentSet<RegisterMeta.ServiceMeta> newServiceMetaSet = new ConcurrentSet<>(); serviceMetaSet = attr.setIfAbsent(newServiceMetaSet); if (serviceMetaSet == null) { serviceMetaSet = newServiceMetaSet; } } return serviceMetaSet.add(serviceMeta); }
Example #30
Source File: ContextBoundUnmarshallerProvider.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
@Override public Unmarshaller getUnmarshaller(ChannelHandlerContext ctx) throws Exception { Attribute<Unmarshaller> attr = ctx.channel().attr(UNMARSHALLER); Unmarshaller unmarshaller = attr.get(); if (unmarshaller == null) { unmarshaller = super.getUnmarshaller(ctx); attr.set(unmarshaller); } return unmarshaller; }