Example usage for io.netty.util AttributeKey valueOf

List of usage examples for io.netty.util AttributeKey valueOf

Introduction

In this page you can find the example usage for io.netty.util AttributeKey valueOf.

Prototype

@SuppressWarnings("unchecked")
public static <T> AttributeKey<T> valueOf(String name) 

Source Link

Document

Returns the singleton instance of the AttributeKey which has the specified name .

Usage

From source file:com.linecorp.armeria.internal.DefaultAttributeMapTest.java

License:Apache License

@Test
public void testGetAndSetWithNull() {
    AttributeKey<Integer> key = AttributeKey.valueOf("key");

    Attribute<Integer> attr = map.attr(key);
    attr.set(1);//from ww w  .j av  a 2s . co  m
    assertSame(1, attr.getAndSet(null));

    Attribute<Integer> attr2 = map.attr(key);
    attr2.set(2);
    assertSame(2, attr2.get());
    assertSame(attr, attr2);
}

From source file:com.linecorp.armeria.server.metrics.MetricCollectingServiceCodecTest.java

License:Apache License

@SuppressWarnings("unchecked")
protected static void setupServer(ServerBuilder sb, ServiceInvocationHandler handler,
        final MetricConsumer consumer) throws Exception {
    ServiceCodec codec = Mockito.mock(ServiceCodec.class);
    DecodeResult decodeResult = Mockito.mock(DecodeResult.class);
    DefaultAttributeMap defaultAttributeMap = new DefaultAttributeMap();
    ServiceInvocationContext invocationContext = Mockito.mock(ServiceInvocationContext.class);

    when(decodeResult.type()).thenReturn(DecodeResultType.SUCCESS);
    when(decodeResult.invocationContext()).thenReturn(invocationContext);
    when(invocationContext.attr(any())).then(x -> defaultAttributeMap.attr(AttributeKey.valueOf("TEST")));
    when(invocationContext.method()).thenReturn("someMethod");

    when(codec.decodeRequest(any(), any(), any(), any(), any(), any(), any(), any(), any()))
            .thenReturn(decodeResult);/*from w  w  w.j  a v  a 2  s.c o m*/

    when(codec.encodeResponse(any(), any())).thenReturn(Unpooled.EMPTY_BUFFER);
    when(codec.encodeFailureResponse(any(), any())).thenReturn(Unpooled.EMPTY_BUFFER);

    sb.serviceAt("/", Service.of(new MetricCollectingServiceCodec(codec, consumer), handler));
}

From source file:com.mapple.forward.socks.SocksServerConnectHandlerEx.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    ConcurrentSet<Channel> proxyList = ForwardLoginHandler.INSTANCE.proxyList();
    String id = null;/*from  w  w w  .j a  va  2  s .  c o  m*/
    Channel channel = null;
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        id = request.userId();
    } else if (message instanceof Socks5CommandRequest) {
        AttributeKey<String> SOCKS5 = AttributeKey.valueOf("socks5");
        id = ctx.channel().attr(SOCKS5).get();
    }
    if (id != null) {
        //            System.out.println("id:" + id + " size:" + proxyList.size());
        //            id = "Mapple";
        if (id.equals("Mapple") && proxyList.size() > 0) {
            int pos = new Random().nextInt() % proxyList.size();
            int i = 0;

            Iterator<Channel> it = proxyList.iterator();
            while (it.hasNext()) {
                Channel ch = it.next();
                if (pos == i++) {
                    channel = ch;
                    break;
                }
            }
        } else {
            Iterator<Channel> it = proxyList.iterator();
            while (it.hasNext()) {
                Channel ch = it.next();
                ForwardLogin p = ch.attr(Session).get();
                if (p.getProvince2() != null && id.toUpperCase().equals(p.getProvince2().toUpperCase())) {
                    channel = ch;
                    break;
                }
                if (id.equals(p.getRemoteAddr())) {
                    channel = ch;
                    break;
                }
            }
        }
    }

    if (channel == null || !channel.isActive()) {
        if (message instanceof Socks4CommandRequest) {
            ctx.writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
            SocksServerUtils.closeOnFlush(ctx.channel());
        } else if (message instanceof Socks5CommandRequest) {
            final Socks5CommandRequest request = (Socks5CommandRequest) message;
            ctx.writeAndFlush(
                    new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE, request.dstAddrType()));
            SocksServerUtils.closeOnFlush(ctx.channel());
        } else {
            ctx.close();
        }
        return;
    }
    if (message instanceof Socks4CommandRequest) {
        //            System.out.println("SocksServerConnectHandlerEx Socks4CommandRequest");
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        InetSocketAddress addr = (InetSocketAddress) ctx.channel().remoteAddress();
        ForwardConnect fc = new ForwardConnect(addr.getAddress().getHostAddress(), addr.getPort(),
                Socks5AddressType.DOMAIN, request.dstAddr(), request.dstPort());
        fc.setSrcChannel(ctx.channel());
        ctx.channel().attr(AttributeKey.valueOf("socks4"));
        channel.writeAndFlush(fc);

        System.out.println("socks4:" + request.userId());
    } else if (message instanceof Socks5CommandRequest) {
        System.out.println("SocksServerConnectHandlerEx Socks5CommandRequest");
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        InetSocketAddress addr = (InetSocketAddress) ctx.channel().remoteAddress();
        ForwardConnect fc = new ForwardConnect(addr.getAddress().getHostAddress(), addr.getPort(),
                request.dstAddrType(), request.dstAddr(), request.dstPort());
        fc.setSrcChannel(ctx.channel());
        channel.writeAndFlush(fc);
    } else {
        ctx.close();
    }
}

From source file:com.mapple.forward.socks.SocksServerHandlerEx.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, SocksMessage socksRequest) throws Exception {
    switch (socksRequest.version()) {
    case SOCKS4a:
        Socks4CommandRequest socksV4CmdRequest = (Socks4CommandRequest) socksRequest;
        if (socksV4CmdRequest.type() == Socks4CommandType.CONNECT) {
            ctx.pipeline().addLast(SocksServerConnectHandlerEx.INSTANCE);
            ctx.pipeline().remove(this);
            ctx.fireChannelRead(socksRequest);
        } else {/*from w  ww . j a  v  a  2 s  . com*/
            ctx.close();
        }
        break;
    case SOCKS5:
        if (socksRequest instanceof Socks5InitialRequest) {
            // auth support example
            ctx.pipeline().addFirst(new Socks5PasswordAuthRequestDecoder());
            ctx.write(new DefaultSocks5InitialResponse(Socks5AuthMethod.PASSWORD));
            //                    ctx.pipeline().addFirst(new Socks5CommandRequestDecoder());
            //                    ctx.write(new DefaultSocks5InitialResponse(Socks5AuthMethod.NO_AUTH));
        } else if (socksRequest instanceof Socks5PasswordAuthRequest) {
            ctx.pipeline().addFirst(new Socks5CommandRequestDecoder());

            Socks5PasswordAuthRequest request = (Socks5PasswordAuthRequest) socksRequest;
            //                    System.out.println("Socks5:" + request.username() + " " + request.password());

            AttributeKey<String> SOCKS5 = AttributeKey.valueOf("socks5");
            ctx.channel().attr(SOCKS5).set(request.username());

            ctx.write(new DefaultSocks5PasswordAuthResponse(Socks5PasswordAuthStatus.SUCCESS));
        } else if (socksRequest instanceof Socks5CommandRequest) {
            /*Socks5InitialRequestDecoder handle = ctx.pipeline().get(Socks5InitialRequestDecoder.class);
            if(handle != null) {
                System.out.println("LWZ Remove" + handle);
                ctx.pipeline().remove(handle);
            }*/
            Socks5CommandRequest socks5CmdRequest = (Socks5CommandRequest) socksRequest;
            if (socks5CmdRequest.type() == Socks5CommandType.CONNECT) {
                ctx.pipeline().addLast(SocksServerConnectHandlerEx.INSTANCE);
                ctx.pipeline().remove(this);
                ctx.fireChannelRead(socksRequest);
            } else {
                ctx.close();
            }
        } else {
            ctx.close();
        }
        break;
    case UNKNOWN:
        ctx.close();
        break;
    }
}

From source file:com.mapple.http.HttpHelloWorldServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        if (HttpUtil.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }//from   w  ww. ja  v a 2s . c o  m

        QueryStringDecoder decoder = new QueryStringDecoder(req.uri());
        List<String> close = decoder.parameters().get("close");
        int pos = -1;
        if (close != null && close.size() > 0) {
            pos = Integer.valueOf(close.get(0));
        }

        StringBuilder body = new StringBuilder();
        ConcurrentSet<Channel> proxyList = ForwardLoginHandler.INSTANCE.proxyList();
        int i = 0;
        AttributeKey<ForwardLogin> Session = AttributeKey.valueOf("Session");
        Iterator<Channel> it = proxyList.iterator();
        while (it.hasNext()) {
            Channel ch = it.next();
            ForwardLogin p = ch.attr(Session).get();
            body.append(i + 1);
            body.append("  ");
            body.append(p.getUserName());
            body.append("  ");
            body.append(
                    p.getProvince() + (p.getCity() == null ? "" : p.getCity()) + "[" + p.getProvince2() + "]");
            body.append("  ");
            body.append(p.getRemoteAddr() + ":" + p.getRemotePort());
            body.append("  ");
            body.append(p.getCarrier());
            body.append("  ");
            if (ch instanceof SocketChannel) {
                body.append("TCP");
            } else {
                body.append("UDT");
            }
            if (i++ == pos) {
                body.append("  [CLOSED]");
                ch.writeAndFlush(new ForwardForceClose());
            }
            body.append("\n");
        }
        String data = body.toString();
        if (data.isEmpty()) {
            data = "?";
        }

        //            boolean keepAlive = HttpUtil.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
                Unpooled.wrappedBuffer(data.getBytes(CharsetUtil.UTF_8)));
        response.headers().set(CONTENT_TYPE, "text/plain; charset=utf-8");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

        //            if (!keepAlive) {
        ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        //            } else {
        //                response.headers().set(CONNECTION, KEEP_ALIVE);
        //                ctx.write(response);
        //            }
    }
}

From source file:com.mpcc.springmvc.configuration.ServerUtils.java

public static void sendMessages(Object objEvent) {

    System.out.println(ServerHandler.ctxs);

    if (Collections.synchronizedList(ServerHandler.ctxs) != null
            && !Collections.synchronizedList(ServerHandler.ctxs).isEmpty()) {
        for (ChannelHandlerContext ctx : ServerHandler.ctxs) {
            AttributeKey<String> aKey = AttributeKey.valueOf(objEvent.toString());
            if (null == ctx.channel().attr(aKey).get()) {
                ctx.channel().writeAndFlush(new TextWebSocketFrame(String.valueOf(objEvent)));
                ctx.channel().attr(aKey).setIfAbsent(objEvent.toString());
            }/* w  w  w  .  j  a  v a  2s .c o  m*/
        }
    }
}

From source file:com.qq.servlet.demo.netty.telnet.client.ClientHandler.java

License:Apache License

@Override
protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
    Channel ch = ctx.channel();/*from ww w .ja v  a2 s .  co  m*/
    AttributeKey<String> key = AttributeKey.valueOf("ASYNC_CONTEXT");
    Attribute<String> attr = ch.attr(key);
    System.out.println("----------->" + attr.get() + "\t" + msg);
    ChannelFuture future = ch.close();
    future.await(100);
}

From source file:com.qq.servlet.demo.netty.telnet.client.TelnetClient.java

License:Apache License

private void test(Bootstrap b, int i) throws InterruptedException {
    // Start the connection attempt.
    Channel ch = b.connect(host, port).sync().channel();

    String body = "[" + i + "]aaaaaaa" + Thread.currentThread().getName() + "aaaaa";

    AttributeKey<String> key = AttributeKey.valueOf("ASYNC_CONTEXT");
    Attribute<String> attr = ch.attr(key);
    String andSet = attr.getAndSet(Thread.currentThread().getName());
    System.out.println(andSet);//from w  w  w . j ava  2 s  .  co m

    ChannelFuture lastWriteFuture = ch.writeAndFlush(body + "\r\n");
    // Wait until all messages are flushed before closing the channel.
    if (lastWriteFuture != null) {
        lastWriteFuture.sync();
    }
}

From source file:com.qq.servlet.demo.netty.telnet.TelnetClientHandler.java

License:Apache License

@Override
protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
    Channel ch = ctx.channel();/*from   ww w  .j  a va 2s  .  com*/
    AttributeKey<AsyncContext> key = AttributeKey.valueOf("ASYNC_CONTEXT");
    Attribute<AsyncContext> attr = ch.attr(key);
    AsyncContext context = attr.get();

    if (context != null) {
        HttpServletRequest request = (HttpServletRequest) context.getRequest();
        HttpServletResponse response = (HttpServletResponse) context.getResponse();
        Object object = request.getAttribute("beginTime");
        long bt = Long.parseLong(object.toString());
        PrintWriter writer = response.getWriter();
        writer.println("invoke api result: \t");
        long time = System.currentTimeMillis() - bt;
        //         writer.println("???"+time);
        writer.flush();
        //servlet?http?
        System.err.println(context + "\t" + request.getAttribute("REQUEST_ID"));
        context.complete();
    } else {
        System.out.println(context + "----------->" + msg);
    }
    ChannelFuture future = ch.close();
    future.await(100);
}

From source file:com.qq.servlet.demo.thrift.netty.client.NettyThriftClient.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup(2);
    try {/*w  ww  .  ja v a 2  s . c  o m*/
        final Bootstrap b = new Bootstrap();
        b.group(group);
        b.channel(NioSocketChannel.class);
        b.handler(new NettyThriftClientInitializer());

        // Start the connection attempt.
        ChannelFuture future = b.connect(host, port);
        ChannelFuture sync = future.sync();
        Channel ch = sync.channel();

        AttributeKey<String> key = AttributeKey.valueOf("ASYNC_CONTEXT");
        Attribute<String> attr = ch.attr(key);
        String andSet = attr.getAndSet(Thread.currentThread().getName());

        TMemoryBuffer transportr = new TMemoryBuffer(1024);
        TProtocol protocol = new TBinaryProtocol(transportr);
        TMultiplexedProtocol multiProtocol3 = new TMultiplexedProtocol(protocol,
                IdGenService.class.getSimpleName());
        IdGenService.Client aoClient = new IdGenService.Client(multiProtocol3);
        IdGenReq req = new IdGenReq();
        req.setTableName("t_lottery_append_task-----------");
        req.setSource(andSet);
        aoClient.send_idGen(req);
        int length = transportr.length();
        byte[] buf = new byte[length];
        transportr.read(buf, 0, length);
        System.out.println(Arrays.toString(buf));

        ChannelFuture lastWriteFuture = ch.writeAndFlush(buf);
        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }

        System.in.read();
    } finally {
        group.shutdownGracefully();
    }
}