Example usage for io.netty.util CharsetUtil US_ASCII

List of usage examples for io.netty.util CharsetUtil US_ASCII

Introduction

In this page you can find the example usage for io.netty.util CharsetUtil US_ASCII.

Prototype

Charset US_ASCII

To view the source code for io.netty.util CharsetUtil US_ASCII.

Click Source Link

Document

7-bit ASCII, as known as ISO646-US or the Basic Latin block of the Unicode character set

Usage

From source file:org.mitre.svmp.webrtc.http.PeerConnectionServerHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    //System.out.println(msg.getClass().getName());

    DefaultFullHttpResponse response = null;

    if (msg instanceof HttpRequest) {

        // All HTTP messages used by the peerconnection_client:
        ///*from   w w  w . j a  va 2s  .c  om*/
        // "GET /sign_in?%s HTTP/1.0\r\n\r\n", client_name_.c_str());
        // "POST /message?peer_id=%i&to=%i HTTP/1.0\r\n"
        // "GET /sign_out?peer_id=%i HTTP/1.0\r\n\r\n", my_id_);
        // "GET /wait?peer_id=%i HTTP/1.0\r\n\r\n", my_id_);

        HttpRequest request = (HttpRequest) msg;

        System.out.println(request.toString());

        HttpMethod method = request.getMethod();
        String uri = request.getUri();
        //        QueryStringDecoder queryDecoder = new QueryStringDecoder(uri);
        //        Map<String, List<String>> params = queryDecoder.parameters();

        System.out.println("Incoming HTTP request:\n" + method + " " + uri);

        if (method.equals(HttpMethod.GET)) {

            // Case: GET /sign_in?%s
            if (uri.startsWith("/sign_in")) {
                // should have a username parameter and it should be "fbstreamer"
                String username = uri.split("[?]")[1];

                // return a comma delimited list of name,peer_id,is_connected
                // where the first line is the info of the peer we're talking to
                // and all subsequent lines are the set of other connected peers

                // since fbstreamer on the HTTP side will always be the first peer to connect
                // lie about the other peer being there

                ByteBuf content = copiedBuffer(
                        username + "," + FBSTREAM_PEER_ID + ",1\n" + "svmpclient," + CLIENT_PEER_ID + ",1",
                        CharsetUtil.US_ASCII);
                response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK, content);

                response.headers().set(CONTENT_TYPE, "text/plain");
                response.headers().set(CONNECTION, "close");
                response.headers().set(PRAGMA, FBSTREAM_PEER_ID);

                // do we have to set the content-length header ourselves?
                // if so, how do we calculate it?
            }

            // Case: GET /sign_out?peer_id=%i
            else if (uri.startsWith("/sign_out")) {
                // TODO might be worth checking that the peer_id is actually FBSTREAM_PEER_ID
                // doesn't really matter though

                response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
                response.headers().set(CONNECTION, "close");
                response.headers().set(CONTENT_LENGTH, 0);

                // create a BYE message, no other peers to notify
                // add it to the sendQueue
                // TODO
            }

            // Case: GET /wait?peer_id=%i
            else if (uri.startsWith("/wait")) {
                // pull something off receiveQueue
                SVMPProtocol.Request pbMsg = receiveQueue.take();

                // convert it to JSON
                String json = Translator.ProtobufToJSON(pbMsg.getWebrtcMsg());
                ByteBuf content = copiedBuffer(json, CharsetUtil.US_ASCII);

                System.out.println("JSON from client:\n" + json);

                // make HTTP response
                response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK, content);
                response.headers().set(CONTENT_TYPE, "text/plain");

                // if it's a peer presence info message, set pragma to the client's ID
                // function handleServerNotification(data) {(String)
                //   trace("Server notification: " + data);
                //   var parsed = data.split(',');
                //   if (parseInt(parsed[2]) != 0)
                //   other_peers[parseInt(parsed[1])] = parsed[0];
                // }

                // shouldn't be any presence messages since we're hard coding
                // it above in the sign_in case

                // if it's a message from another peer, set pragma to that peer's ID
                response.headers().set(PRAGMA, CLIENT_PEER_ID);
                // peerconnection_server appears to set "Connection: close" for these
                response.headers().set(CONNECTION, "close");

                // send in HTTP response
                response = null;
            } else {
                // some other bad URL
                response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.NOT_FOUND);
            }

            // send response
            System.out.println("HTTP response:\n" + response.toString());
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);

        } else if (method.equals(HttpMethod.POST) && uri.startsWith("/message")) {
            // Case: POST /message?peer_id=%i&to=%i

            isProcessingPost = true;

        } else {
            // some other HTTP request we don't support
            // send an error or something
            response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST);

            // send response
            System.out.println("HTTP response:\n" + response.toString());
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        }
    } else if (msg instanceof HttpContent && isProcessingPost) {
        // handle body of the POST /message

        // decode the JSON payload
        String content = ((HttpContent) msg).content().toString(CharsetUtil.UTF_8);
        System.out.println("JSON in from fbstream:\n" + content);

        // convert it to protobuf
        SVMPProtocol.Response.Builder pbResp = SVMPProtocol.Response.newBuilder();
        pbResp.setType(ResponseType.WEBRTC);
        pbResp.setWebrtcMsg(Translator.JSONToProtobuf(content));

        // add it to sendQueue
        sendQueue.add(pbResp.build());

        // generate appropriate HTTP response
        response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK);
        response.headers().set(CONNECTION, "close");

        // send response
        System.out.println("HTTP response:\n" + response.toString());
        ctx.write(response).addListener(ChannelFutureListener.CLOSE);

        isProcessingPost = false;
    }
}

From source file:org.onosproject.artemis.impl.moas.MoasClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException {
    ByteBuf in = (ByteBuf) msg;// ww w.  ja v  a 2s.co  m
    String strMsg = in.toString(io.netty.util.CharsetUtil.US_ASCII);

    ObjectMapper mapper = new ObjectMapper();
    ArtemisMessage actObj = mapper.readValue(strMsg, ArtemisMessage.class);

    packetProcessor.processMoasPacket(actObj, ctx);
}

From source file:org.shelloid.vpt.rms.server.VPTServerHandler.java

License:Open Source License

public static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, String content,
        HttpContentTypes contentType, HttpResponseStatus httpResponse) {
    ByteBuf buffer = Unpooled.copiedBuffer(content, CharsetUtil.US_ASCII);
    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, httpResponse, buffer);
    res.headers().set(CONTENT_TYPE, contentType);
    setContentLength(res, buffer.readableBytes());
    sendHttpResponse(ctx, req, res);//  w w w  . j  av a 2  s.  co  m
}

From source file:org.spout.vanilla.protocol.rcon.codec.RconCodec.java

License:Open Source License

@Override
public ByteBuf encode(T message) {
    byte[] bytes = message.getPayload().getBytes(CharsetUtil.US_ASCII);
    ByteBuf buffer = Unpooled.buffer(bytes.length + 2);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.writeBytes(bytes);/*from   ww  w.java2  s  . c om*/
    buffer.writeByte(0);
    buffer.writeByte(0);
    return buffer;
}

From source file:org.spout.vanilla.protocol.rcon.codec.RconCodec.java

License:Open Source License

@Override
public T decode(ByteBuf buffer) {
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    ByteBuf expandingBytes = Unpooled.buffer(buffer.writerIndex());
    byte b;/* w w  w  .  j a v a  2s  . co  m*/
    while ((b = buffer.readByte()) != 0) {
        expandingBytes.writeByte(b);
    }
    assert buffer.readByte() == 0; // Second null byte

    String value = new String(expandingBytes.array(), CharsetUtil.US_ASCII);
    return createMessage(value);
}

From source file:org.wyb.sows.client.SocksServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    File configFile = new File("./config/sows.config");
    if (!configFile.exists()) {
        System.err.println("Cannot find config file: ./config/sows.config");
        System.exit(-1);/*from  w  ww.  j av a2s . co m*/
    }
    PropertyConfigurator.configure("./config/serverlog.config");
    Properties props = new Properties();
    props.load(new FileInputStream(configFile));
    String uri = props.getProperty("sows.uri");
    int port = Integer.parseInt(props.getProperty("socks.port"));
    String userName = props.getProperty("sows.user");
    String password = props.getProperty("sows.pass");
    byte[] sha1 = SowsAuthHelper.sha1((password).getBytes(CharsetUtil.US_ASCII));
    String passcode = SowsAuthHelper.base64(sha1);
    isDebug = Boolean.parseBoolean(props.getProperty("debug", "false"));
    URI bridgeServiceUri = new URI(uri);
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                // .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new SocksServerInitializer(bridgeServiceUri, userName, passcode));
        System.out.printf("Socks server is listening on port %d. Remote URI is %s \r\n", port, uri);
        b.bind(port).sync().channel().closeFuture().sync();

    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:org.wyb.sows.client.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    if (request.host().equals("127.0.0.1") || request.host().equals("localhost")) {
        System.err.println("Not able to establish bridge. Inform proxy client.");
        ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
        SocksServerUtils.closeOnFlush(ctx.channel());
    }// w  w w  .j  a va  2 s. co  m

    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                if (SocksServer.isDebug) {
                    System.out.println("Bridge is established. Inform proxy client.");
                }
                SocksCmdResponse resp = new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType());
                resp.setProtocolVersion(request.protocolVersion());
                ctx.channel().writeAndFlush(resp).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) {
                        ChannelPipeline pipeline = ctx.pipeline();
                        pipeline.remove(SocksServerConnectHandler.this);
                        // ctx.pipeline().addLast(new StringByteCodec());
                        pipeline.addLast(new WebSocketRelayHandler(outboundChannel));
                    }
                });
            } else {
                System.err.println("Not able to establish bridge. Inform proxy client.");
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
    final Channel inboundChannel = ctx.channel();

    // Add authentication headers
    HttpHeaders authHeader = new DefaultHttpHeaders();
    authHeader.add(SowsAuthHelper.HEADER_SOWS_USER, this.userName);
    byte[] nonce = SowsAuthHelper.randomBytes(16);
    String seed = SowsAuthHelper.base64(nonce);
    authHeader.add(SowsAuthHelper.HEADER_SOWS_SEED, seed);
    byte[] sha1 = SowsAuthHelper.sha1((this.passcode + seed).getBytes(CharsetUtil.US_ASCII));
    String token = SowsAuthHelper.base64(sha1);
    authHeader.add(SowsAuthHelper.HEADER_SOWS_TOKEN, token);

    // initiating websocket client handler
    final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
            .newHandshaker(bridgeServiceUri, WebSocketVersion.V13, null, false, authHeader), promise,
            request.host(), request.port(), inboundChannel);
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
                }
            });
    if (SocksServer.isDebug) {
        System.out.println("Try to connect to bridge service.");
    }
    b.connect(bridgeServiceUri.getHost(), bridgeServiceUri.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection established use handler provided results
                if (SocksServer.isDebug) {
                    System.out.printf("Brige service connection is established. host=%s,port=%d \r\n",
                            bridgeServiceUri.getHost(), bridgeServiceUri.getPort());
                }
            } else {
                // Close the connection if the connection attempt has
                // failed.
                System.err.printf("Not able to connect bridge service! host=%s,port=%d \r\n",
                        bridgeServiceUri.getHost(), bridgeServiceUri.getPort());
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });

}

From source file:srebrinb.messagebroker.websocket.WebSocketIndexPageHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    // Handle a bad request.
    if (!req.decoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;//from w  w  w.ja v a2s .co  m
    }
    /*
    // Allow only GET methods.
    if (req.method() != GET) {
    sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
    return;
    }
    */
    if (req.method() == PUT) {
        String strChannalID = req.uri().replaceAll("/", "");
        String buf = req.content().toString(Charset.forName("UTF-8"));
        List<String> chennals = srebrinb.messagebroker.WebSockerMessager.getChennals("groupName", strChannalID);
        System.out.println("chennals = " + chennals);
        allChannels.forEach(Channel -> {
            //System.out.println(Channel.id()+"\t"+(Channel.isActive()?"Y":"N")+"\t"+(Channel.isOpen()?"Y":"N")+"\t"+(Channel.isWritable()?"Y":"N"));

            if (chennals.contains(Channel.id().asLongText())) {
                Channel.writeAndFlush(new TextWebSocketFrame(buf));
                System.out.println("send;");
            }
        });

        ByteBuf content = Unpooled.copiedBuffer("ok", CharsetUtil.US_ASCII);
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
        res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpUtil.setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
        return;
    }
    if ("/test.html".equals(req.uri())) {
        String strContent = IOUtils.toString(new FileInputStream("test.html"), "UTF-8");
        ByteBuf content = Unpooled.copiedBuffer(strContent, CharsetUtil.UTF_8);
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

        res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpUtil.setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
        return;
    }
    // Send the index page
    if ("/".equals(req.uri()) || "/index.html".equals(req.uri())) {
        String webSocketLocation = getWebSocketLocation(ctx.pipeline(), req, websocketPath);
        ByteBuf content = WebSocketServerIndexPage.getContent(webSocketLocation);
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

        res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpUtil.setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
    } else {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
    }
}

From source file:srebrinb.messagebroker.websocket.WebSocketServerIndexPage.java

License:Apache License

public static ByteBuf getContent(String webSocketLocation) {
    return Unpooled.copiedBuffer("<html><head><title>Web Socket Test</title></head>" + NEWLINE + "<body>"
            + NEWLINE + "<script type=\"text/javascript\">" + NEWLINE + "var socket;" + NEWLINE
            + "if (!window.WebSocket) {" + NEWLINE + "  window.WebSocket = window.MozWebSocket;" + NEWLINE + '}'
            + NEWLINE + "if (window.WebSocket) {" + NEWLINE + "  socket = new WebSocket(\"" + webSocketLocation
            + "\");" + NEWLINE + "  socket.onmessage = function(event) {" + NEWLINE
            + "    var ta = document.getElementById('responseText');" + NEWLINE
            + "    ta.value = ta.value + '\\n' + event.data" + NEWLINE
            + " ta.value = ta.value + typeof event.data;" + NEWLINE + "  eval(event.data);" + NEWLINE + "  };"
            + NEWLINE + "  socket.onopen = function(event) {" + NEWLINE
            + "    var ta = document.getElementById('responseText');" + NEWLINE
            + "    ta.value = \"Web Socket opened!\";" + NEWLINE + "  };" + NEWLINE
            + "  socket.onclose = function(event) {" + NEWLINE
            + "    var ta = document.getElementById('responseText');" + NEWLINE
            + "    ta.value = ta.value + \"Web Socket closed\"; " + NEWLINE + "  };" + NEWLINE + "} else {"
            + NEWLINE + "  alert(\"Your browser does not support Web Socket.\");" + NEWLINE + '}' + NEWLINE
            + NEWLINE + "function send(message) {" + NEWLINE + "  if (!window.WebSocket) { return; }" + NEWLINE
            + "  if (socket.readyState == WebSocket.OPEN) {" + NEWLINE + "    socket.send(message);" + NEWLINE
            + "  } else {" + NEWLINE + "    alert(\"The socket is not open.\");" + NEWLINE + "  }" + NEWLINE
            + '}' + NEWLINE + "</script>" + NEWLINE + "<form onsubmit=\"return false;\">" + NEWLINE
            + "<input type=\"text\" name=\"message\" value=\"Hello, World!\"/>"
            + "<input type=\"button\" value=\"Send Web Socket Data\"" + NEWLINE
            + "       onclick=\"send(this.form.message.value)\" />" + NEWLINE + "<h3>Output</h3>" + NEWLINE
            + "<textarea id=\"responseText\" style=\"width:500px;height:300px;\"></textarea>" + NEWLINE
            + "</form>" + NEWLINE + "<button onclick=\"reg(1)\">test</button>\n" + "<script>\n"
            + "var users=[{\"userName\":\"testUserName\",\"custId\":12,\"groupName\":\"testGroupName\"},{\"userName\":\"testUserName2\",\"custId\":12,\"groupName\":\"testGroupName\"}];\n"
            + "function reg(i){\n" + "   send(\"reg(\"+JSON.stringify(users[i])+\")\");\n" + "}\n" + "</script>"
            + "</body>" + NEWLINE + "</html>" + NEWLINE, CharsetUtil.US_ASCII);
}