Example usage for io.netty.channel ChannelHandlerContext channel

List of usage examples for io.netty.channel ChannelHandlerContext channel

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext channel.

Prototype

Channel channel();

Source Link

Document

Return the Channel which is bound to the ChannelHandlerContext .

Usage

From source file:com.book.netty5.server.LoginAuthRespHandler.java

License:Apache License

/**
 * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward to the next {@link ChannelHandler} in the {@link ChannelPipeline}.
 * //w  w  w.  j  a  v a 2  s.c  om
 * Sub-classes may override this method to change behavior.
 */
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;

    // ?????
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_REQ.value()) {
        String nodeIndex = ctx.channel().remoteAddress().toString();
        NettyMessage loginResp = null;
        // ???
        if (nodeCheck.containsKey(nodeIndex)) {
            loginResp = buildResponse((byte) -1);
        } else {
            InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
            String ip = address.getAddress().getHostAddress();
            boolean isOK = false;
            for (String WIP : whitekList) {
                if (WIP.equals(ip)) {
                    isOK = true;
                    break;
                }
            }
            loginResp = isOK ? buildResponse((byte) 0) : buildResponse((byte) -1);
            if (isOK)
                nodeCheck.put(nodeIndex, true);
        }
        System.out.println("The login response is : " + loginResp + " body [" + loginResp.getBody() + "]");
        ctx.writeAndFlush(loginResp);
    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:com.brainlounge.zooterrain.netty.WebSocketServerInboundHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    // Handle a bad request.
    if (!req.getDecoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;//from  ww w  . ja va  2s  . c  o  m
    }

    // Allow only GET methods.
    if (req.getMethod() != GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // Send the demo page and favicon.ico
    if ("/favicon.ico".equals(req.getUri())) {
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
        sendHttpResponse(ctx, req, res);
        return;
    } else if ("/hexdump.js".equals(req.getUri())) {
        final WebSocketServerJSPage webSocketServerJSPage = new WebSocketServerJSPage();
        ByteBuf content = webSocketServerJSPage.getContent(getWebSocketLocation(req));
        sendHttpResponse(ctx, req, content, "text/javascript; charset=UTF-8");
        return;
    } else if ("/".equals(req.getUri())) {
        WebSocketServerIndexPage webSocketServerIndexPage = new WebSocketServerIndexPage();
        ByteBuf content = webSocketServerIndexPage.getContent(getWebSocketLocation(req));
        sendHttpResponse(ctx, req, content, "text/html; charset=UTF-8");
        return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
            null, false);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
        zkStateObserver.addListener(new OutboundConnector(ctx));
    }
}

From source file:com.brainlounge.zooterrain.netty.WebSocketServerInboundHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;//from  www. j  a v  a 2  s .  c  om
    }
    if (frame instanceof PingWebSocketFrame) {
        ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
        return;
    }
    if (!(frame instanceof TextWebSocketFrame)) {
        throw new UnsupportedOperationException(
                String.format("%s frame types not supported", frame.getClass().getName()));
    }

    String request = ((TextWebSocketFrame) frame).text();
    if (logger.isLoggable(Level.FINE)) {
        logger.fine(String.format("%s received %s", ctx.channel(), request));
    }

    // expecting JSON, parse now
    TreeNode jsonRequest;
    ClientRequest.Type requestType;
    try {
        final JsonParser parser = jsonMapper.getFactory().createParser(request);
        jsonRequest = parser.readValueAsTree();
        TextNode type = (TextNode) jsonRequest.get("r");
        requestType = ClientRequest.Type.valueOf(type.textValue());
    } catch (Exception e) {
        logger.info("parsing JSON failed for '" + request + "'");
        // TODO return error to client
        return;
    }

    if (requestType == ClientRequest.Type.i) {
        // client requested initial data

        // sending connection string info
        final ControlMessage handshakeInfo = new ControlMessage(zkStateObserver.getZkConnection(),
                ControlMessage.Type.H);
        writeClientMessage(ctx, handshakeInfo);

        // sending initial znodes
        try {
            zkStateObserver.initialTree("/", 6, Sets.<ZkStateListener>newHashSet(new OutboundConnector(ctx)));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } else if (requestType == ClientRequest.Type.b) {
        final String znode;
        try {
            znode = ((TextNode) jsonRequest.get("z")).textValue();
        } catch (Exception e) {
            return; // TODO return error
        }
        final DataMessage dataMessage = zkStateObserver.retrieveNodeData(znode);
        if (dataMessage != null) {
            writeClientMessage(ctx, dataMessage);
        }
    } else {
        System.out.println("unknown, unhandled client request = " + request);
    }
}

From source file:com.brainlounge.zooterrain.netty.WebSocketServerInboundHandler.java

License:Apache License

protected void writeClientMessage(ChannelHandlerContext ctx, ClientMessage clientMessage) {
    ctx.channel().writeAndFlush(new TextWebSocketFrame(clientMessage.toJson()));
}

From source file:com.bunjlabs.fuga.network.netty.NettyHttpServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
    if (msg instanceof HttpRequest) {
        this.httprequest = (HttpRequest) msg;

        requestBuilder = new Request.Builder();

        requestBuilder.requestMethod(RequestMethod.valueOf(httprequest.method().name())).uri(httprequest.uri());

        try {/*from ww w  .java  2s .  c o m*/

            // Decode URI GET query parameters
            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httprequest.uri());
            requestBuilder.path(queryStringDecoder.path()).query(queryStringDecoder.parameters());

            // Process cookies
            List<Cookie> cookies = new ArrayList<>();

            String cookieString = httprequest.headers().get(HttpHeaderNames.COOKIE);
            if (cookieString != null) {
                ServerCookieDecoder.STRICT.decode(cookieString).stream().forEach((cookie) -> {
                    cookies.add(NettyCookieConverter.convertToFuga(cookie));
                });
            }

            requestBuilder.cookies(cookies);

            // Process headers
            Map<String, String> headers = new HashMap<>();
            httprequest.headers().entries().stream().forEach((e) -> {
                headers.put(e.getKey(), e.getValue());
            });

            requestBuilder.headers(headers);

            // Get real parameters from frontend HTTP server
            boolean isSecure = false;
            SocketAddress remoteAddress = ctx.channel().remoteAddress();

            if (forwarded == 1) { // RFC7239
                if (headers.containsKey("Forwarded")) {
                    String fwdStr = headers.get("Forwarded");

                    List<String> fwdparams = Stream.of(fwdStr.split("; ")).map((s) -> s.trim())
                            .collect(Collectors.toList());

                    for (String f : fwdparams) {
                        String p[] = f.split("=");

                        switch (p[0]) {
                        case "for":
                            remoteAddress = parseAddress(p[1]);
                            break;
                        case "proto":
                            isSecure = p[1].equals("https");
                            break;
                        }
                    }
                }
            } else if (forwarded == 0) { // X-Forwarded
                if (headers.containsKey("X-Forwarded-Proto")) {
                    if (headers.get("X-Forwarded-Proto").equalsIgnoreCase("https")) {
                        isSecure = true;
                    }
                }

                if (headers.containsKey("X-Forwarded-For")) {
                    String fwdfor = headers.get("X-Forwarded-For");
                    remoteAddress = parseAddress(
                            fwdfor.contains(",") ? fwdfor.substring(0, fwdfor.indexOf(',')) : fwdfor);
                } else if (headers.containsKey("X-Real-IP")) {
                    remoteAddress = parseAddress(headers.get("X-Real-IP"));
                }
            }

            requestBuilder.remoteAddress(remoteAddress).isSecure(isSecure);

            if (headers.containsKey("Accept-Language")) {
                String acceptLanguage = headers.get("Accept-Language");

                List<Locale> acceptLocales = Stream.of(acceptLanguage.split(","))
                        .map((s) -> s.contains(";") ? s.substring(0, s.indexOf(";")).trim() : s.trim())
                        .map((s) -> s.contains("-") ? new Locale(s.split("-")[0], s.split("-")[0])
                                : new Locale(s))
                        .collect(Collectors.toList());

                requestBuilder.acceptLocales(acceptLocales);
            }
            //

            if (httprequest.method().equals(HttpMethod.GET)) {
                processResponse(ctx);
                return;
            }
            decoder = true;
        } catch (Exception e) {
            processClientError(ctx, requestBuilder.build(), 400);
            return;
        }
    }

    if (msg instanceof HttpContent && decoder) {
        HttpContent httpContent = (HttpContent) msg;

        contentBuffer.writeBytes(httpContent.content());

        if (httpContent instanceof LastHttpContent) {
            requestBuilder.content(new BufferedContent(contentBuffer.nioBuffer()));
            processResponse(ctx);
        }
    }
}

From source file:com.butor.netty.handler.codec.ftp.cmd.CommandUtil.java

License:Apache License

public static void send(String response, ChannelHandlerContext ctx) {
    String line = response + "\r\n";
    byte[] data = line.getBytes(CharsetUtil.US_ASCII);
    ctx.channel().writeAndFlush(Unpooled.wrappedBuffer(data));
}

From source file:com.butor.netty.handler.codec.ftp.FtpServerHandler.java

License:Apache License

private static void send(String response, ChannelHandlerContext ctx) {
    if (logger.isDebugEnabled()) {
        logger.debug("<- " + response);
    }/*from w w w. ja v a2  s.co m*/
    String line = response + "\r\n";
    byte[] data = line.getBytes(ASCII);
    ctx.channel().writeAndFlush(Unpooled.wrappedBuffer(data));
}

From source file:com.caocao.nio.server.CustomerInboundHandler.java

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    // Close the connection when an exception is raised.
    logger.error("??{}", cause.getMessage());
    ctx.channel().close();
    ctx.channel().disconnect();/*from w  w w. j  a v a 2 s  .c  o m*/
}

From source file:com.caocao.nio.server.CustomerInboundHandler.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
        IdleStateEvent event = (IdleStateEvent) evt;
        if (event.state().equals(IdleState.READER_IDLE)) {
            ctx.channel().close();
            ctx.channel().disconnect();/*w  ww . j  a va 2  s .co  m*/
            logger.info("{}?", ctx.channel().remoteAddress());
        }
    }
    // TODO Auto-generated method stub
    super.userEventTriggered(ctx, evt);
}

From source file:com.caricah.iotracah.server.httpserver.netty.HttpServerHandler.java

License:Apache License

/**
 * Is called for each message of type {@link MqttMessage}.
 *
 * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
 *            belongs to//from   www.j ava  2 s . c  om
 * @param msg the message to handle
 * @throws Exception is thrown if an error occurred
 */
@Override
protected void messageReceived(ChannelHandlerContext ctx, FullHttpMessage msg) throws Exception {

    log.debug(" messageReceived : received the message {}", msg);

    String connectionId = ctx.channel().attr(ServerImpl.REQUEST_CONNECTION_ID).get();

    getInternalServer().pushToWorker(connectionId, null, msg);

}