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:cc.blynk.core.http.handlers.OTAHandler.java

License:Apache License

private Response singleUserOTA(ChannelHandlerContext ctx, UserKey userKey, String projectName,
        String pathToFirmware) {//w  ww  .  j a v a  2 s.  co m
    User initiator = ctx.channel().attr(AuthHeadersBaseHttpHandler.USER).get();
    User user = userDao.users.get(userKey);

    if (user == null) {
        log.info("Requested user {} not found.", userKey);
        return badRequest("Requested user not found.");
    }

    otaManager.initiate(initiator, userKey, projectName, pathToFirmware);

    return ok(pathToFirmware);
}

From source file:cc.blynk.core.http.handlers.OTAHandler.java

License:Apache License

private Response singleDeviceOTA(ChannelHandlerContext ctx, String token, String pathToFirmware) {
    TokenValue tokenValue = tokenManager.getTokenValueByToken(token);

    if (tokenValue == null) {
        log.debug("Requested token {} not found.", token);
        return badRequest("Invalid token.");
    }//from   w w  w .  j a v a 2s. c  om

    User user = tokenValue.user;
    int dashId = tokenValue.dash.id;
    int deviceId = tokenValue.device.id;

    Session session = sessionDao.userSession.get(new UserKey(user));
    if (session == null) {
        log.debug("No session for user {}.", user.email);
        return badRequest("Device wasn't connected yet.");
    }

    String body = OTAInfo.makeHardwareBody(otaManager.serverHostUrl, pathToFirmware);
    if (session.sendMessageToHardware(dashId, BLYNK_INTERNAL, 7777, body, deviceId)) {
        log.debug("No device in session.");
        return badRequest("No device in session.");
    }

    User initiator = ctx.channel().attr(AuthHeadersBaseHttpHandler.USER).get();
    if (initiator != null) {
        tokenValue.device.updateOTAInfo(initiator.email);
    }

    return ok(pathToFirmware);
}

From source file:cc.blynk.integration.model.websocket.AppWebSocketClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        log.trace("WebSocket Client connected!");
        if (handshakeFuture != null) {
            handshakeFuture.setSuccess();
        }/*from   w  ww .j  a  va2 s.  c  om*/
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status()
                + ", content=" + response.content().toString(StandardCharsets.UTF_8) + ')');
    }

    if (msg instanceof BinaryWebSocketFrame) {
        BinaryWebSocketFrame frame = (BinaryWebSocketFrame) msg;
        log.trace("WebSocket Client received message: " + frame.content());
        ctx.fireChannelRead(((WebSocketFrame) msg).retain());
    } else if (msg instanceof CloseWebSocketFrame) {
        log.trace("WebSocket Client received closing");
        ch.close();
    }
}

From source file:cc.blynk.integration.model.websocket.WebSocketClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        log.trace("WebSocket Client connected!");
        if (handshakeFuture != null) {
            handshakeFuture.setSuccess();
        }/*from   w ww. j av a 2 s .  c o m*/
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status()
                + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof BinaryWebSocketFrame) {
        BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
        log.trace("WebSocket Client received message: " + binaryFrame.content());
        ctx.fireChannelRead(binaryFrame.retain().content());
    } else if (frame instanceof CloseWebSocketFrame) {
        log.trace("WebSocket Client received closing");
        ch.close();
    }
}

From source file:cc.io.lessons.server.HttpUploadServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

    if (msg instanceof HttpRequest) {
        System.out.println(msg.toString());
    } else {/*  ww w  .  java  2  s .co m*/
        System.out.println(ByteBufUtil.hexDump(((HttpContent) msg).content()));
        //System.out.println(((HttpContent) msg).content().toString(Charset.defaultCharset()));
    }

    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        URI uri = new URI(request.getUri());
        if (!uri.getPath().startsWith("/form")) {
            // Write Menu
            writeMenu(ctx);
            return;
        }
        responseContent.setLength(0);
        responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        responseContent.append("===================================\r\n");

        responseContent.append("VERSION: " + request.getProtocolVersion().text() + "\r\n");

        responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n");
        responseContent.append("\r\n\r\n");

        // new getMethod
        List<Entry<String, String>> headers = request.headers().entries();
        for (Entry<String, String> entry : headers) {
            responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        // new getMethod
        Set<Cookie> cookies;
        String value = request.headers().get(COOKIE);
        if (value == null) {
            cookies = Collections.emptySet();
        } else {
            cookies = CookieDecoder.decode(value);
        }
        for (Cookie cookie : cookies) {
            responseContent.append("COOKIE: " + cookie.toString() + "\r\n");
        }
        responseContent.append("\r\n\r\n");

        QueryStringDecoder decoderQuery = new QueryStringDecoder(request.getUri());
        Map<String, List<String>> uriAttributes = decoderQuery.parameters();
        for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
            for (String attrVal : attr.getValue()) {
                responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n");
            }
        }
        responseContent.append("\r\n\r\n");

        // if GET Method: should not try to create a HttpPostRequestDecoder
        try {
            decoder = new HttpPostRequestDecoder(factory, request);
        } catch (ErrorDataDecoderException e1) {
            e1.printStackTrace();
            responseContent.append(e1.getMessage());
            writeResponse(ctx.channel());
            ctx.channel().close();
            return;
        } catch (IncompatibleDataDecoderException e1) {
            // GET Method: should not try to create a HttpPostRequestDecoder
            // So OK but stop here
            responseContent.append(e1.getMessage());
            responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n");
            writeResponse(ctx.channel());
            return;
        }

        readingChunks = HttpHeaders.isTransferEncodingChunked(request);
        responseContent.append("Is Chunked: " + readingChunks + "\r\n");
        responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n");
        if (readingChunks) {
            // Chunk version
            responseContent.append("Chunks: ");
            readingChunks = true;
        }
    }

    // check if the decoder was constructed before
    // if not it handles the form get
    if (decoder != null) {
        if (msg instanceof HttpContent) {
            // New chunk is received
            HttpContent chunk = (HttpContent) msg;
            try {
                decoder.offer(chunk);
            } catch (ErrorDataDecoderException e1) {
                e1.printStackTrace();
                responseContent.append(e1.getMessage());
                writeResponse(ctx.channel());
                ctx.channel().close();
                return;
            }
            responseContent.append('o');
            // example of reading chunk by chunk (minimize memory usage due to
            // Factory)
            readHttpDataChunkByChunk();
            // example of reading only if at the end
            if (chunk instanceof LastHttpContent) {
                writeResponse(ctx.channel());
                readingChunks = false;

                reset();
            }
        }
    }
}

From source file:cc.io.lessons.server.HttpUploadServerHandler.java

License:Apache License

private void writeMenu(ChannelHandlerContext ctx) {
    // print several HTML forms
    // Convert the response content to a ChannelBuffer.
    responseContent.setLength(0);//from   ww w.  ja va  2 s.  com

    // create Pseudo Menu
    responseContent.append("<html>");
    responseContent.append("<head>");
    responseContent.append("<title>Netty Test Form</title>\r\n");
    responseContent.append("</head>\r\n");
    responseContent.append("<body bgcolor=white><style>td{font-size: 12pt;}</style>");

    responseContent.append("<table border=\"0\">");
    responseContent.append("<tr>");
    responseContent.append("<td>");
    responseContent.append("<h1>Netty Test Form</h1>");
    responseContent.append("Choose one FORM");
    responseContent.append("</td>");
    responseContent.append("</tr>");
    responseContent.append("</table>\r\n");

    // GET
    responseContent.append("<CENTER>GET FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
    responseContent.append("<FORM ACTION=\"/formget\" METHOD=\"GET\">");
    responseContent.append("<input type=hidden name=getform value=\"GET\">");
    responseContent.append("<table border=\"0\">");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>");
    responseContent
            .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>");
    responseContent.append("</td></tr>");
    responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>");
    responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>");
    responseContent.append("</table></FORM>\r\n");
    responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");

    // POST
    responseContent.append("<CENTER>POST FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
    responseContent.append("<FORM ACTION=\"/formpost\" METHOD=\"POST\">");
    responseContent.append("<input type=hidden name=getform value=\"POST\">");
    responseContent.append("<table border=\"0\">");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>");
    responseContent
            .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>");
    responseContent.append("<tr><td>Fill with file (only file name will be transmitted): <br> "
            + "<input type=file name=\"myfile\">");
    responseContent.append("</td></tr>");
    responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>");
    responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>");
    responseContent.append("</table></FORM>\r\n");
    responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");

    // POST with enctype="multipart/form-data"
    responseContent.append("<CENTER>POST MULTIPART FORM<HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");
    responseContent
            .append("<FORM ACTION=\"/formpostmultipart\" ENCTYPE=\"multipart/form-data\" METHOD=\"POST\">");
    responseContent.append("<input type=hidden name=getform value=\"POST\">");
    responseContent.append("<table border=\"0\">");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"info\" size=10></td></tr>");
    responseContent.append("<tr><td>Fill with value: <br> <input type=text name=\"secondinfo\" size=20>");
    responseContent
            .append("<tr><td>Fill with value: <br> <textarea name=\"thirdinfo\" cols=40 rows=10></textarea>");
    responseContent.append("<tr><td>Fill with file: <br> <input type=file name=\"myfile\">");
    responseContent.append("</td></tr>");
    responseContent.append("<tr><td><INPUT TYPE=\"submit\" NAME=\"Send\" VALUE=\"Send\"></INPUT></td>");
    responseContent.append("<td><INPUT TYPE=\"reset\" NAME=\"Clear\" VALUE=\"Clear\" ></INPUT></td></tr>");
    responseContent.append("</table></FORM>\r\n");
    responseContent.append("<CENTER><HR WIDTH=\"75%\" NOSHADE color=\"blue\"></CENTER>");

    responseContent.append("</body>");
    responseContent.append("</html>");

    ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);

    response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    response.headers().set(CONTENT_LENGTH, buf.readableBytes());

    // Write the response.
    ctx.channel().writeAndFlush(response);
}

From source file:ch.ethz.globis.distindex.middleware.net.MiddlewareChannelHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buf = (ByteBuf) msg;/*  ww  w  .  j a  v  a 2s.co m*/
    String clientHost = ctx.channel().remoteAddress().toString();
    ByteBuffer response = ioHandler.handle(clientHost, buf.nioBuffer());
    ByteBuf nettyBuf = Unpooled.wrappedBuffer(response);
    ByteBuf sizeBuf = Unpooled.copyInt(nettyBuf.readableBytes());

    ctx.write(sizeBuf);
    ctx.write(nettyBuf);
    ctx.flush();
    buf.release();
}

From source file:ch.ethz.globis.distindex.middleware.net.MiddlewareChannelHandler.java

License:Open Source License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    String clientHost = ctx.channel().remoteAddress().toString();
    LOG.debug("Client " + clientHost + " disconnected.");
    ioHandler.cleanup(clientHost);// www.ja  va2  s .co m
    super.channelInactive(ctx);
}

From source file:ch.ethz.globis.distindex.middleware.net.MiddlewareChannelHandler.java

License:Open Source License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    String clientHost = ctx.channel().remoteAddress().toString();
    LOG.debug("Client " + clientHost + " disconnected.");
    ioHandler.cleanup(clientHost);/*from  ww w.  ja  v  a 2s  .  c o m*/
    super.exceptionCaught(ctx, cause);
}

From source file:chapter10.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {

    // HTTP?HTTP//www .  ja va2  s  . c  om
    if (!req.decoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;
    }

    // ??
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
            "ws://localhost:8080/websocket", null, false);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}