Java Code Examples for io.netty.util.Attribute#get()

The following examples show how to use io.netty.util.Attribute#get() . 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: RegisterNodeHandler.java    From litchi with Apache License 2.0 6 votes vote down vote up
@Override
public void channelUnregistered(ChannelHandlerContext ctx) {
    Attribute<Long> attrId = ctx.channel().attr(NettySession.SESSION_ID);
    Long sessionId = attrId.get();
    if (sessionId == null) {
        return;
    }

    try {
        // rpc node disconnect event
        NettySession session = litchi.nodeSessionService().getSession(sessionId);
        String nodeType = session.channel().attr(NettySession.FROM_NODE_TYPE).get();
        String nodeId = session.channel().attr(NettySession.FROM_NODE_ID).get();
        litchi.event().post(new RpcDisconnectEvent(nodeType, nodeId));
    } finally {
        //remove
        litchi.nodeSessionService().removeSession(sessionId);
    }
}
 
Example 2
Source File: CompatibleObjectEncoder.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: ConnectionUtil.java    From sofa-bolt with Apache License 2.0 5 votes vote down vote up
public static Connection getConnectionFromChannel(Channel channel) {
    if (channel == null) {
        return null;
    }

    Attribute<Connection> connAttr = channel.attr(Connection.CONNECTION);
    if (connAttr != null) {
        Connection connection = connAttr.get();
        return connection;
    }
    return null;
}
 
Example 4
Source File: HttpsAwareFiltersAdapter.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
/**
 * Returns the original host and port of this HTTPS request, as sent by the client. Does not reflect any modifications
 * by other filters.
 * TODO: evaluate this (unused) method and its capture mechanism in HttpsOriginalHostCaptureFilter; remove if not useful.
 *
 * @return host and port of this HTTPS request
 * @throws IllegalStateException if this is not an HTTPS request
 */
private String getHttpsOriginalRequestHostAndPort() throws IllegalStateException {
    if (!isHttps()) {
        throw new IllegalStateException("Request is not HTTPS. Cannot get original host and port on non-HTTPS request using this method.");
    }

    Attribute<String> hostnameAttr = ctx.attr(AttributeKey.<String>valueOf(ORIGINAL_HOST_ATTRIBUTE_NAME));
    return hostnameAttr.get();
}
 
Example 5
Source File: ChannelInfo.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
public static ChannelInfo getOrCreateServerChannelInfo(Channel channel) {
    Attribute<ChannelInfo> attribute = channel.attr(ChannelInfo.SERVER_CHANNEL_KEY);
    ChannelInfo channelInfo = attribute.get();
    if (channelInfo == null) {
        channelInfo = new ChannelInfo();
        channelInfo.setChannel(channel);
        attribute.set(channelInfo);
    }
    return channelInfo;
}
 
Example 6
Source File: ClientChannelHandler.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    super.channelUnregistered(ctx);
    Attribute<Node> nodeAttribute = ctx.channel().attr(key);
    Node node = nodeAttribute.get();
    if (node != null && node.getDisconnectListener() != null) {
        LoggerUtil.COMMON_LOG.info("-----------------client channelInactive  node is channelUnregistered node={}-----------------", node.getId());
        node.getDisconnectListener().action();
    }
}
 
Example 7
Source File: BytesMetricsChannelHandler.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
public static BytesMetrics getOrSetMetrics(Channel channel) {
    Attribute<BytesMetrics> attribute = channel.attr(ATTR_KEY_METRICS);
    BytesMetrics metrics = attribute.get();
    if(metrics == null) {
        metrics = new BytesMetrics();
        attribute.set(metrics);
    }
    return metrics;
}
 
Example 8
Source File: WebSocketSession.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
/**
 * Get httpSession from the properties bound in the pipe
 * @param channel channel
 * @return WebSocketSession
 */
public static WebSocketSession getSession(Channel channel){
    if(isChannelActive(channel)) {
        Attribute<WebSocketSession> attribute = channel.attr(CHANNEL_ATTR_KEY_SESSION);
        if(attribute != null){
            return attribute.get();
        }
    }
    return null;
}
 
Example 9
Source File: DefaultRegistry.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
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 10
Source File: NettyChannel.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: ProxyRouterEndpointExecutionHandler.java    From riposte with Apache License 2.0 5 votes vote down vote up
protected ProxyRouterProcessingState getOrCreateProxyRouterProcessingState(ChannelHandlerContext ctx) {
    Attribute<ProxyRouterProcessingState> proxyRouterStateAttribute =
        ChannelAttributes.getProxyRouterProcessingStateForChannel(ctx);

    ProxyRouterProcessingState proxyRouterState = proxyRouterStateAttribute.get();
    if (proxyRouterState == null) {
        proxyRouterState = new ProxyRouterProcessingState();
        proxyRouterStateAttribute.set(proxyRouterState);
        //noinspection deprecation
        proxyRouterState.setDistributedTracingConfig(distributedTracingConfig);
    }

    return proxyRouterState;
}
 
Example 12
Source File: HighPerformanceChannelWriter.java    From sailfish with Apache License 2.0 5 votes vote down vote up
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 13
Source File: DefaultRegistryServer.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
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 14
Source File: ClientChannelHandler.java    From nuls with MIT License 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception{
    if (!(cause instanceof IOException) && !(cause instanceof TooLongFrameException)) {
        Attribute<Node> nodeAttribute = ctx.channel().attr(NodeAttributeKey.NODE_KEY);
        Node node = nodeAttribute.get();
        Log.error("----------------nodeId:" + node.getId());
        Log.error(cause);
    }
    ctx.close();
}
 
Example 15
Source File: ClientChannelHandler.java    From nuls with MIT License 5 votes vote down vote up
@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 16
Source File: ChannelUtil.java    From qmq with Apache License 2.0 4 votes vote down vote up
public static Object getAttribute(Channel channel) {
    synchronized (channel) {
        Attribute<Object> attr = channel.attr(DEFAULT_ATTRIBUTE);
        return attr != null ? attr.get() : null;
    }
}
 
Example 17
Source File: ChannelUtil.java    From sailfish with Apache License 2.0 4 votes vote down vote up
public static boolean clientSide(ChannelHandlerContext ctx) {
	Attribute<Boolean> clientSideAttr = ctx.channel().attr(ChannelAttrKeys.clientSide);
	return (null != clientSideAttr && null != clientSideAttr.get() && clientSideAttr.get());
}
 
Example 18
Source File: RpcCommandEncoderV2.java    From sofa-bolt with Apache License 2.0 4 votes vote down vote up
/**
 * @see CommandEncoder#encode(ChannelHandlerContext, Serializable, ByteBuf)
 */
@Override
public void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception {
    try {
        if (msg instanceof RpcCommand) {
            /*
             * proto: magic code for protocol
             * ver: version for protocol
             * type: request/response/request oneway
             * cmdcode: code for remoting command
             * ver2:version for remoting command
             * requestId: id of request
             * codec: code for codec
             * switch: function switch
             * (req)timeout: request timeout.
             * (resp)respStatus: response status
             * classLen: length of request or response class name
             * headerLen: length of header
             * cotentLen: length of content
             * className
             * header
             * content
             * crc (optional)
             */
            int index = out.writerIndex();
            RpcCommand cmd = (RpcCommand) msg;
            out.writeByte(RpcProtocolV2.PROTOCOL_CODE);
            Attribute<Byte> version = ctx.channel().attr(Connection.VERSION);
            byte ver = RpcProtocolV2.PROTOCOL_VERSION_1;
            if (version != null && version.get() != null) {
                ver = version.get();
            }
            out.writeByte(ver);
            out.writeByte(cmd.getType());
            out.writeShort(((RpcCommand) msg).getCmdCode().value());
            out.writeByte(cmd.getVersion());
            out.writeInt(cmd.getId());
            out.writeByte(cmd.getSerializer());
            out.writeByte(cmd.getProtocolSwitch().toByte());
            if (cmd instanceof RequestCommand) {
                //timeout
                out.writeInt(((RequestCommand) cmd).getTimeout());
            }
            if (cmd instanceof ResponseCommand) {
                //response status
                ResponseCommand response = (ResponseCommand) cmd;
                out.writeShort(response.getResponseStatus().getValue());
            }
            out.writeShort(cmd.getClazzLength());
            out.writeShort(cmd.getHeaderLength());
            out.writeInt(cmd.getContentLength());
            if (cmd.getClazzLength() > 0) {
                out.writeBytes(cmd.getClazz());
            }
            if (cmd.getHeaderLength() > 0) {
                out.writeBytes(cmd.getHeader());
            }
            if (cmd.getContentLength() > 0) {
                out.writeBytes(cmd.getContent());
            }
            if (ver == RpcProtocolV2.PROTOCOL_VERSION_2
                && cmd.getProtocolSwitch().isOn(ProtocolSwitch.CRC_SWITCH_INDEX)) {
                // compute the crc32 and write to out
                byte[] frame = new byte[out.readableBytes()];
                out.getBytes(index, frame);
                out.writeInt(CrcUtil.crc32(frame));
            }
        } else {
            String warnMsg = "msg type [" + msg.getClass() + "] is not subclass of RpcCommand";
            logger.warn(warnMsg);
        }
    } catch (Exception e) {
        logger.error("Exception caught!", e);
        throw e;
    }
}
 
Example 19
Source File: NettyUtil.java    From ext-opensource-netty with Mozilla Public License 2.0 4 votes vote down vote up
public static String getClientId(Channel channel) {
	Attribute<String> attr = channel.attr(NettyConstant.CLIENTID_KEY);
	return attr.get();
}
 
Example 20
Source File: ChannelInfo.java    From brpc-java with Apache License 2.0 4 votes vote down vote up
public static ChannelInfo getClientChannelInfo(Channel channel) {
    Attribute<ChannelInfo> attribute = channel.attr(ChannelInfo.CLIENT_CHANNEL_KEY);
    return attribute.get();
}