Java Code Examples for io.netty.util.AttributeKey#valueOf()

The following examples show how to use io.netty.util.AttributeKey#valueOf() . 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: ChannelHandlerContextHelper.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public static EnumChannelProtocolVersion getProtocolVersion(ChannelHandlerContext ctx) {

        SocketChannel socketChannel = (SocketChannel) ctx.channel();
        String hostAddress = socketChannel.remoteAddress().getAddress().getHostAddress();
        int port = socketChannel.remoteAddress().getPort();

        String host = hostAddress + ":" + port;
        AttributeKey<ChannelProtocol> attributeKey =
                AttributeKey.valueOf(EnumSocketChannelAttributeKey.CHANNEL_PROTOCOL_KEY.getKey());

        if (ctx.channel().hasAttr(attributeKey)) {
            ChannelProtocol channelProtocol = ctx.channel().attr(attributeKey).get();

            if (null != channelProtocol) {
                // logger.trace(" host: {}, channel protocol: {}", host, channelProtocol);

                return channelProtocol.getEnumProtocol();
            } else {
                logger.debug(" channel has attr but get null, host: {}", host);
            }
        }

        return null;
    }
 
Example 2
Source File: RequestContextExporterBuilder.java    From armeria with Apache License 2.0 6 votes vote down vote up
private ExportEntry<AttributeKey<?>> parseAttrPattern(String keyPattern, @Nullable String exportKey) {
    final String[] components = keyPattern.split(":");
    if (components.length < 2 || components.length > 3) {
        if (exportKey == null) {
            throw new IllegalArgumentException(
                    "invalid attribute export: " + keyPattern +
                    " (expected: attrs.<alias>:<AttributeKey.name>[:<FQCN of Function<?, String>>])");
        } else {
            throw new IllegalArgumentException(
                    "invalid attribute export: " + keyPattern +
                    " (expected: <alias>=attr:<AttributeKey.name>[:<FQCN of Function<?, String>>])");
        }
    }

    if (exportKey == null) {
        exportKey = components[0];
    }
    final AttributeKey<Object> attributeKey = AttributeKey.valueOf(components[1]);
    if (components.length == 3) {
        return new ExportEntry<>(attributeKey, exportKey, newStringifier(keyPattern, components[2]));
    } else {
        return new ExportEntry<>(attributeKey, exportKey);
    }
}
 
Example 3
Source File: RequestContextExportingAppenderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testMutabilityAndImmutability() {
    final AttributeKey<Object> someAttr =
            AttributeKey.valueOf(RequestContextExportingAppenderTest.class, "SOME_ATTR");
    final RequestContextExportingAppender a = new RequestContextExportingAppender();

    // Ensure mutability before start.
    a.addBuiltIn(BuiltInProperty.ELAPSED_NANOS);
    a.addAttribute("some-attr", someAttr);
    a.addRequestHeader(HttpHeaderNames.USER_AGENT);
    a.addResponseHeader(HttpHeaderNames.SET_COOKIE);

    final ListAppender<ILoggingEvent> la = new ListAppender<>();
    a.addAppender(la);
    a.start();
    la.start();

    // Ensure immutability after start.
    assertThatThrownBy(() -> a.addBuiltIn(BuiltInProperty.REQ_PATH))
            .isExactlyInstanceOf(IllegalStateException.class);

    assertThatThrownBy(() -> a.addAttribute("my-attr", MY_ATTR))
            .isExactlyInstanceOf(IllegalStateException.class);

    assertThatThrownBy(() -> a.addRequestHeader(HttpHeaderNames.ACCEPT))
            .isExactlyInstanceOf(IllegalStateException.class);

    assertThatThrownBy(() -> a.addResponseHeader(HttpHeaderNames.DATE))
            .isExactlyInstanceOf(IllegalStateException.class);
}
 
Example 4
Source File: DefaultAttributeMapTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testGetSetWithNull() {
    final DefaultAttributeMap map = new DefaultAttributeMap(null);
    final AttributeKey<Integer> key = AttributeKey.valueOf("key");

    map.setAttr(key, 1);
    assertThat(map.attr(key)).isEqualTo(1);

    map.setAttr(key, null);
    assertThat(map.attr(key)).isNull();
}
 
Example 5
Source File: DefaultAttributeMapTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testGetSetInt() {
    final DefaultAttributeMap map = new DefaultAttributeMap(null);
    final AttributeKey<Integer> key = AttributeKey.valueOf("int");
    assertThat(map.attr(key)).isNull();

    map.setAttr(key, 3653);
    assertThat(map.attr(key)).isEqualTo(3653);
    map.setAttr(key, 1);
    assertThat(map.attr(key)).isEqualTo(1);
}
 
Example 6
Source File: DefaultAttributeMapTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testGetSetString() {
    final DefaultAttributeMap map = new DefaultAttributeMap(null);
    final AttributeKey<String> key = AttributeKey.valueOf("str");
    assertThat(map.attr(key)).isNull();
    map.setAttr(key, "Whoohoo");
    assertThat(map.attr(key)).isEqualTo("Whoohoo");

    map.setAttr(key, "What");
    assertThat(map.attr(key)).isEqualTo("What");
}
 
Example 7
Source File: DefaultClientRequestContextTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void deriveContext() {
    final DefaultClientRequestContext originalCtx = newContext();

    mutateAdditionalHeaders(originalCtx);

    final AttributeKey<String> foo = AttributeKey.valueOf(DefaultClientRequestContextTest.class, "foo");
    originalCtx.setAttr(foo, "foo");

    final RequestId newId = RequestId.random();
    final HttpRequest newRequest = HttpRequest.of(RequestHeaders.of(
            HttpMethod.POST, "/foo",
            HttpHeaderNames.SCHEME, "http",
            HttpHeaderNames.AUTHORITY, "example.com:8080",
            "foo", "bar"));
    final ClientRequestContext derivedCtx = originalCtx.newDerivedContext(newId, newRequest, null);
    assertThat(derivedCtx.endpoint()).isSameAs(originalCtx.endpoint());
    assertThat(derivedCtx.sessionProtocol()).isSameAs(originalCtx.sessionProtocol());
    assertThat(derivedCtx.method()).isSameAs(originalCtx.method());
    assertThat(derivedCtx.options()).isSameAs(originalCtx.options());
    assertThat(derivedCtx.id()).isSameAs(newId);
    assertThat(derivedCtx.request()).isSameAs(newRequest);

    assertThat(derivedCtx.path()).isEqualTo(originalCtx.path());
    assertThat(derivedCtx.maxResponseLength()).isEqualTo(originalCtx.maxResponseLength());
    assertThat(derivedCtx.responseTimeoutMillis()).isEqualTo(originalCtx.responseTimeoutMillis());
    assertThat(derivedCtx.writeTimeoutMillis()).isEqualTo(originalCtx.writeTimeoutMillis());
    assertThat(derivedCtx.additionalRequestHeaders()).isSameAs(originalCtx.additionalRequestHeaders());
    // the attribute is derived as well
    assertThat(derivedCtx.attr(foo)).isEqualTo("foo");

    // log is different
    assertThat(derivedCtx.log()).isNotSameAs(originalCtx.log());

    final AttributeKey<String> bar = AttributeKey.valueOf(DefaultClientRequestContextTest.class, "bar");
    originalCtx.setAttr(bar, "bar");

    // the Attribute added to the original context after creation is not propagated to the derived context
    assertThat(derivedCtx.attr(bar)).isEqualTo(null);
}
 
Example 8
Source File: DefaultClientRequestContextTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void attrsDoNotIterateRootWhenKeyIsSame() {
    final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
    final ServiceRequestContext serviceContext = ServiceRequestContext.of(req);
    try (SafeCloseable ignored = serviceContext.push()) {
        final ClientRequestContext clientContext = ClientRequestContext.of(req);
        final AttributeKey<String> fooKey = AttributeKey.valueOf(DefaultClientRequestContextTest.class,
                                                                 "foo");
        clientContext.setAttr(fooKey, "foo");
        serviceContext.setAttr(fooKey, "bar");
        final Iterator<Entry<AttributeKey<?>, Object>> attrs = clientContext.attrs();
        assertThat(attrs.next().getValue()).isEqualTo("foo");
        assertThat(attrs.hasNext()).isFalse();
    }
}
 
Example 9
Source File: DefaultAttributeMapTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void hasNoAttributeInRoot() {
    final ServiceRequestContext root = ServiceRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    final DefaultAttributeMap child = new DefaultAttributeMap(root);

    final AttributeKey<String> foo = AttributeKey.valueOf("foo");
    // root: [foo], child: []
    child.setAttr(foo, "foo");

    assertThat(root.attr(foo)).isNull();
    assertThat(child.attr(foo)).isEqualTo("foo");

    final AttributeKey<String> bar = AttributeKey.valueOf("bar");
    // root: [foo], child: [bar]
    assertThat(child.setAttrIfAbsent(bar, "bar")).isNull();
    assertThat(root.attr(bar)).isNull();
    assertThat(child.attr(bar)).isEqualTo("bar");

    // Do not change.
    // root: [foo], child: [bar]
    assertThat(child.setAttrIfAbsent(bar, "bar2")).isEqualTo("bar");
    assertThat(child.attr(bar)).isEqualTo("bar");

    final AttributeKey<String> baz = AttributeKey.valueOf("baz");
    // root: [foo], child: [bar, baz]
    assertThat(child.computeAttrIfAbsent(baz, key -> "baz")).isEqualTo("baz");
    assertThat(root.attr(baz)).isNull();
    assertThat(child.attr(baz)).isEqualTo("baz");

    // Do not change.
    // root: [foo], child: [bar, baz]
    assertThat(child.computeAttrIfAbsent(baz, key -> "baz2")).isEqualTo("baz");
    assertThat(child.attr(baz)).isEqualTo("baz");
}
 
Example 10
Source File: NettyUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * @return an {@code AttributeKey} for {@code attr}. This returns an existing instance if it was previously created.
 */
public static <T> AttributeKey<T> getOrCreateAttributeKey(String attr) {
    if (AttributeKey.exists(attr)) {
        return AttributeKey.valueOf(attr);
    }
    //CHECKSTYLE:OFF - This is the only place allowed to call AttributeKey.newInstance()
    return AttributeKey.newInstance(attr);
    //CHECKSTYLE:ON
}
 
Example 11
Source File: NodeManager.java    From nuls with MIT License 5 votes vote down vote up
private void cacheNode(Node node, SocketChannel channel) {

        String name = "node-" + node.getId();
        boolean exists = AttributeKey.exists(name);
        AttributeKey attributeKey;
        if (exists) {
            attributeKey = AttributeKey.valueOf(name);
        } else {
            attributeKey = AttributeKey.newInstance(name);
        }
        Attribute<Node> attribute = channel.attr(attributeKey);
        attribute.set(node);
    }
 
Example 12
Source File: ConnectionManager.java    From nuls-v2 with MIT License 5 votes vote down vote up
private void cacheNode(Node node, SocketChannel channel) {

        String name = "node-" + node.getId();
        boolean exists = AttributeKey.exists(name);
        AttributeKey attributeKey;
        if (exists) {
            attributeKey = AttributeKey.valueOf(name);
        } else {
            attributeKey = AttributeKey.newInstance(name);
        }
        Attribute<Node> attribute = channel.attr(attributeKey);

        attribute.set(node);
    }
 
Example 13
Source File: NettyClientTransport.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Get the existing {@link ChannelLogger} key in case a separate, isolated class loader has
 * already created {@link LOGGER_KEY}.
 */
private static final AttributeKey<ChannelLogger> getOrCreateChannelLogger() {
  AttributeKey<ChannelLogger> key = AttributeKey.valueOf("channelLogger");
  if (key == null) {
    key = AttributeKey.newInstance("channelLogger");
  }
  return key;
}
 
Example 14
Source File: BaseSocketSession.java    From ext-opensource-netty with Mozilla Public License 2.0 4 votes vote down vote up
public <T> void setAttribute(String name, T value) {
	AttributeKey<T> sessionIdKey = AttributeKey.valueOf(name);
	channel.attr(sessionIdKey).set(value);
}
 
Example 15
Source File: AccessLogComponent.java    From armeria with Apache License 2.0 4 votes vote down vote up
AttributeComponent(String attributeName, Function<Object, String> stringifer, boolean addQuote,
                   @Nullable Function<ResponseHeaders, Boolean> condition) {
    super(condition, addQuote);
    key = AttributeKey.valueOf(requireNonNull(attributeName, "attributeName"));
    this.stringifer = requireNonNull(stringifer, "stringifer");
}
 
Example 16
Source File: ChannelHandlerContextHelper.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public static void setCtxAttibuteValue(ChannelHandlerContext ctx, String key, String value) {

        AttributeKey<String> attributeKey = AttributeKey.valueOf(key);
        ctx.channel().attr(attributeKey).set(value);
    }
 
Example 17
Source File: DefaultAttributeMapTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void hasAttributeInRoot() {
    final ServiceRequestContext root = ServiceRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
    final DefaultAttributeMap child = new DefaultAttributeMap(root);

    // root: [foo], child: []
    final AttributeKey<String> foo = AttributeKey.valueOf("foo");
    root.setAttr(foo, "foo");

    assertThat(root.attr(foo)).isEqualTo("foo");
    assertThat(child.attr(foo)).isEqualTo("foo");
    assertThat(child.ownAttr(foo)).isNull();

    // root: [foo], child: [foo2]
    child.setAttr(foo, "foo2");
    assertThat(child.ownAttr(foo)).isEqualTo("foo2");
    assertThat(child.attr(foo)).isEqualTo("foo2");
    assertThat(root.attr(foo)).isEqualTo("foo");

    final AttributeKey<String> bar = AttributeKey.valueOf("bar");
    // root: [foo, bar], child: [foo2]
    root.setAttr(bar, "bar");
    // root: [foo, bar], child: [foo2, bar2]
    assertThat(child.setAttrIfAbsent(bar, "bar2")).isNull();

    assertThat(child.attr(bar)).isEqualTo("bar2");
    assertThat(root.attr(bar)).isEqualTo("bar");

    // Do not change.
    // root: [foo, bar], child: [foo2, bar2]
    assertThat(child.setAttrIfAbsent(bar, "bar3")).isEqualTo("bar2");
    assertThat(child.attr(bar)).isEqualTo("bar2");

    final AttributeKey<String> baz = AttributeKey.valueOf("baz");
    // root: [foo, bar, baz], child: [foo2, bar2]
    root.setAttr(baz, "baz");
    // root: [foo, bar, baz], child: [foo2, bar2, baz2]
    assertThat(child.computeAttrIfAbsent(baz, key -> "baz2")).isEqualTo("baz2");

    assertThat(child.attr(baz)).isEqualTo("baz2");
    assertThat(root.attr(baz)).isEqualTo("baz");

    // Do not change.
    // root: [foo, bar, baz], child: [foo2, bar2, baz2]
    assertThat(child.computeAttrIfAbsent(baz, key -> "baz3")).isEqualTo("baz2");
    assertThat(child.attr(baz)).isEqualTo("baz2");
}
 
Example 18
Source File: DefaultServiceRequestContextTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void deriveContext() {
    final HttpRequest request = HttpRequest.of(HttpMethod.GET, "/hello");
    final ServiceRequestContext originalCtx = ServiceRequestContext.builder(request).build();

    mutateAdditionalHeaders(originalCtx);
    mutateAdditionalTrailers(originalCtx);

    final AttributeKey<String> foo = AttributeKey.valueOf(DefaultServiceRequestContextTest.class, "foo");
    originalCtx.setAttr(foo, "foo");

    final RequestId newId = RequestId.random();
    final HttpRequest newRequest = HttpRequest.of(HttpMethod.GET, "/derived/hello");
    final ServiceRequestContext derivedCtx = originalCtx.newDerivedContext(newId, newRequest, null);

    // A ServiceRequestContext must always have itself as its root.
    assertThat(derivedCtx.root()).isSameAs(derivedCtx);

    assertThat(derivedCtx.config().server()).isSameAs(originalCtx.config().server());
    assertThat(derivedCtx.sessionProtocol()).isSameAs(originalCtx.sessionProtocol());
    assertThat(derivedCtx.config().service()).isSameAs(originalCtx.config().service());
    assertThat(derivedCtx.config().route()).isSameAs(originalCtx.config().route());
    assertThat(derivedCtx.id()).isSameAs(newId);
    assertThat(derivedCtx.request()).isSameAs(newRequest);

    assertThat(derivedCtx.path()).isEqualTo(originalCtx.path());
    assertThat(derivedCtx.maxRequestLength()).isEqualTo(originalCtx.maxRequestLength());
    assertThat(derivedCtx.requestTimeoutMillis()).isEqualTo(originalCtx.requestTimeoutMillis());
    assertThat(derivedCtx.additionalResponseHeaders()).isSameAs(originalCtx.additionalResponseHeaders());
    assertThat(derivedCtx.additionalResponseTrailers()).isSameAs(originalCtx.additionalResponseTrailers());
    // the attribute is derived as well
    assertThat(derivedCtx.attr(foo)).isEqualTo("foo");

    // log is different
    assertThat(derivedCtx.log()).isNotSameAs(originalCtx.log());

    final AttributeKey<String> bar = AttributeKey.valueOf(DefaultServiceRequestContextTest.class, "bar");
    originalCtx.setAttr(bar, "bar");

    // the Attribute added to the original context after creation is not propagated to the derived context
    assertThat(derivedCtx.attr(bar)).isEqualTo(null);
}
 
Example 19
Source File: Session.java    From netty-websocket-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
public <T> void setAttribute(String name, T value) {
    AttributeKey<T> sessionIdKey = AttributeKey.valueOf(name);
    channel.attr(sessionIdKey).set(value);
}
 
Example 20
Source File: BaseSocketSession.java    From ext-opensource-netty with Mozilla Public License 2.0 4 votes vote down vote up
public <T> T getAttribute(String name) {
	AttributeKey<T> sessionIdKey = AttributeKey.valueOf(name);
	return channel.attr(sessionIdKey).get();
}