List of usage examples for io.netty.buffer Unpooled copiedBuffer
public static ByteBuf copiedBuffer(ByteBuffer... buffers)
From source file:com.github.spapageo.jannel.transcode.TranscoderHelperTest.java
License:Open Source License
@Test public void testEncodeSmsEncodesCorrectly() throws Exception { byte[] data = { 0x25 }; ByteBuf udh = Unpooled.copiedBuffer(data); Sms sms = new Sms(); sms.setSender("from"); sms.setReceiver("to"); sms.setUdhData(udh);/*from w ww . j av a2 s .c om*/ sms.setMsgData("content"); sms.setTime(0); sms.setSmscId("smsc"); sms.setSmscNumber("smscNumber"); sms.setForeignId("foreignId"); sms.setService("service"); sms.setAccount("account"); sms.setId(UUID.randomUUID()); sms.setSmsType(SmsType.MOBILE_TERMINATED_REPLY); sms.setMessageClass(MessageClass.MC_CLASS2); sms.setMwi(MessageWaitingIndicator.fromValue(3)); sms.setCoding(DataCoding.fromValue(2)); sms.setCompress(Compress.fromValue(1)); sms.setValidity(6); sms.setDeferred(7); sms.setDlrMask(8); sms.setDlrUrl("dlrUrl"); sms.setPid(9); sms.setAltDcs(10); sms.setRpi(ReturnPathIndicator.fromValue(1)); sms.setCharset(Charsets.UTF_8); sms.setBoxId("box"); sms.setBillingInfo("binfo"); sms.setMsgLeft(12); sms.setPriority(13); sms.setResendTry(14); sms.setResendTime(15); sms.setMetaData("metadata"); ByteBuf byteBuf = Unpooled.buffer(); transcoderHelper.encodeSms(sms, byteBuf); assertEquals("The from is incorrect", "from", ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8)); assertEquals("The to is incorrect", "to", ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8)); assertEquals("The udhdata is incorrect", udh.readerIndex(0), ChannelBufferUtils.readOctetStringToBytes(byteBuf)); assertEquals("The message data is incorrect", "content", ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8)); assertEquals("The time is incorrect", 0, byteBuf.readInt()); assertEquals("The smsc is incorrect", "smsc", ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8)); assertEquals("The smscNumber is incorrect", "smscNumber", ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8)); assertEquals("The foreignId is incorrect", "foreignId", ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8)); assertEquals("The service is incorrect", "service", ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8)); assertEquals("The account is incorrect", "account", ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8)); assertEquals("The id is incorrect", sms.getId(), ChannelBufferUtils.readUUID(byteBuf, Charsets.UTF_8)); assertEquals("The sms type is incorrect", sms.getSmsType(), SmsType.fromValue(byteBuf.readInt())); assertEquals("The m class is incorrect", 2, byteBuf.readInt()); assertEquals("The mwi is incorrect", 3, byteBuf.readInt()); assertEquals("The coding is incorrect", 2, byteBuf.readInt()); assertEquals("The compress is incorrect", 1, byteBuf.readInt()); assertEquals("The validity is incorrect", 6, byteBuf.readInt()); assertEquals("The deferred is incorrect", 7, byteBuf.readInt()); assertEquals("The dlr mask is incorrect", 8, byteBuf.readInt()); assertEquals("The dlr url is incorrect", "dlrUrl", ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8)); assertEquals("The pid is incorrect", 9, byteBuf.readInt()); assertEquals("The alt dcs is incorrect", 10, byteBuf.readInt()); assertEquals("The rpi is incorrect", 1, byteBuf.readInt()); assertEquals("The charset is incorrect", "UTF-8", ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8)); assertEquals("The box id is incorrect", "box", ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8)); assertEquals("The binfo is incorrect", "binfo", ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8)); assertEquals("The msgLeft is incorrect", 12, byteBuf.readInt()); assertEquals("The priority is incorrect", 13, byteBuf.readInt()); assertEquals("The resend try is incorrect", 14, byteBuf.readInt()); assertEquals("The resend time is incorrect", 15, byteBuf.readInt()); assertEquals("The meta data is incorrect", "metadata", ChannelBufferUtils.readOctetStringToString(byteBuf, Charsets.UTF_8)); udh.release(); }
From source file:com.guowl.websocket.client.WebSocketClientRunner.java
License:Apache License
public void run() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {/*from w ww . j ava2s. com*/ // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())); final String protocol = uri.getScheme(); int defaultPort; ChannelInitializer<SocketChannel> initializer; // Normal WebSocket if ("ws".equals(protocol)) { initializer = new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("http-codec", new HttpClientCodec()) .addLast("aggregator", new HttpObjectAggregator(8192)) .addLast("ws-handler", handler); } }; defaultPort = 80; // Secure WebSocket } else if ("wss".equals(protocol)) { initializer = new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { SSLEngine engine = WebSocketSslClientContextFactory.getContext().createSSLEngine(); engine.setUseClientMode(true); ch.pipeline().addFirst("ssl", new SslHandler(engine)) .addLast("http-codec", new HttpClientCodec()) .addLast("aggregator", new HttpObjectAggregator(8192)) .addLast("ws-handler", handler); } }; defaultPort = 443; } else { throw new IllegalArgumentException("Unsupported protocol: " + protocol); } Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(initializer); int port = uri.getPort(); // If no port was specified, we'll try the default port: https://tools.ietf.org/html/rfc6455#section-1.7 if (uri.getPort() == -1) { port = defaultPort; } Channel ch = b.connect(uri.getHost(), port).sync().channel(); handler.handshakeFuture().sync(); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); while (true) { String msg = console.readLine(); if (msg == null) { break; } else if ("bye".equals(msg.toLowerCase())) { ch.writeAndFlush(new CloseWebSocketFrame()); ch.closeFuture().sync(); break; } else if ("ping".equals(msg.toLowerCase())) { WebSocketFrame frame = new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[] { 8, 1, 8, 1 })); ch.writeAndFlush(frame); } else { WebSocketFrame frame = new TextWebSocketFrame(msg); ch.writeAndFlush(frame); } } } finally { group.shutdownGracefully(); } }
From source file:com.gw.services.client.HttpsClient.java
License:Apache License
public static void main(String[] args) throws Exception { URI uri = new URI(URL); String scheme = uri.getScheme() == null ? "http" : uri.getScheme(); String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); int port = uri.getPort(); if (port == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80;//from w w w . java 2 s. com } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } } if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { System.err.println("Only HTTP(S) is supported."); return; } // Configure SSL context if necessary. final boolean ssl = "https".equalsIgnoreCase(scheme); final SSLContext sslCtx; if (ssl) { sslCtx = CLIENT_CONTEXT; } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new HttpsClientInitializer(sslCtx)); // Make the connection attempt. Channel ch = b.connect(host, port).sync().channel(); String requestBody = "{\"productId\": 11,\"userName\": \"caiwei\",\"amount\": 1000}"; ByteBuf content = Unpooled.copiedBuffer(requestBody.getBytes(CharsetUtil.UTF_8)); // Prepare the HTTP request. HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath(), content); request.headers().set(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json"); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes()); // Set some example cookies. request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // Send the HTTP request. ch.writeAndFlush(request); // Wait for the server to close the connection. ch.closeFuture().sync(); } finally { // Shut down executor threads to exit. group.shutdownGracefully(); } }
From source file:com.heliosapm.tsdblite.handlers.http.HttpRequestManager.java
License:Apache License
/** * Creates a new HttpRequestManager/*from w w w.j a va2s .c om*/ */ private HttpRequestManager() { favicon = Unpooled.unmodifiableBuffer(Unpooled.copiedBuffer( URLHelper.getBytesFromURL(getClass().getClassLoader().getResource("www/favicon.ico")))); favSize = favicon.readableBytes(); log.info("Loaded favicon: [{}] Bytes", favSize); requestHandlers.put("/api/put", new SubmitTracesHandler()); requestHandlers.put("/api/s", HttpStaticFileServerHandler.getInstance()); }
From source file:com.heliosapm.tsdblite.handlers.http.HttpSwitch.java
License:Apache License
/** * Creates a new HttpSwitch/*ww w . j a va 2s .co m*/ */ public HttpSwitch(final EventExecutorGroup eventExecutorGroup) { this.eventExecutorGroup = eventExecutorGroup; favicon = Unpooled.unmodifiableBuffer(Unpooled.copiedBuffer( URLHelper.getBytesFromURL(getClass().getClassLoader().getResource("www/favicon.ico")))); favSize = favicon.readableBytes(); }
From source file:com.heliosapm.tsdblite.handlers.http.TSDBHttpRequest.java
License:Apache License
private static ByteBuf join(final String... msgs) { final String s; if (msgs.length == 0 || msgs[0] == null) { return EMPTY_BUFF; }/*from www. j a v a2 s. c o m*/ if (msgs.length == 1) { s = msgs[0]; } else { final StringBuilder b = new StringBuilder(); for (String msg : msgs) { b.append(msg); } s = b.toString(); } return Unpooled.copiedBuffer(s.getBytes(UTF8)); }
From source file:com.hipishare.chat.SecureChatClientHandler.java
License:Apache License
public SecureChatClientHandler() { /*firstMessage = Unpooled.buffer(EchoClient.SIZE); for (int i = 0; i < firstMessage.capacity(); i++) { firstMessage.writeByte((byte) i); }*//* www. ja va 2 s. c o m*/ firstMessage = Unpooled.copiedBuffer("hello".getBytes()); }
From source file:com.hipishare.chat.SecureChatClientHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { LOG.info("?" + msg); if ("ping".equals(msg)) { ByteBuf buf = Unpooled.copiedBuffer(("[id=" + ctx.channel().id() + "]" + "ok").getBytes()); ctx.writeAndFlush(buf);/* w ww . j ava2 s . c o m*/ } System.err.println(msg); }
From source file:com.hipishare.chat.securetest.SecureChatClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .build();/*from w ww. ja v a 2 s .c om*/ EventLoopGroup group = new NioEventLoopGroup(); try { bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new SecureChatClientInitializer(sslCtx)); // Start the connection attempt. ChannelFuture channelFuture = bootstrap.connect(HOST, PORT).sync(); channel = channelFuture.channel(); // add reconnect listener reConnectListener = new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { channel.close(); channel = future.channel(); LOG.info("???"); } else { LOG.info("??"); // 3?? future.channel().eventLoop().schedule(new Runnable() { @Override public void run() { reConnect(); } }, 3, TimeUnit.SECONDS); } } }; // Read commands from the stdin. ChannelFuture lastWriteFuture = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (;;) { String line = in.readLine(); if (line == null) { break; } // Sends the received line to the server. if (!channel.isOpen()) { reConnect(); } MsgObject msgObj = new MsgObject(); Gson gson = new Gson(); if ("1".equals(line)) { User user = new User(); user.setAccount("peter"); user.setPwd("666666"); msgObj.setC(CmdEnum.LOGIN.getCmd()); msgObj.setM(gson.toJson(user)); } else if ("2".equals(line)) { ChatObject co = new ChatObject(); co.setContent("hello,jack. I am peter."); co.setMsgType("text"); co.setMsgTo("jack"); co.setMsgFrom("peter"); co.setCreateTime(System.currentTimeMillis()); msgObj.setC(CmdEnum.CHAT.getCmd()); msgObj.setM(gson.toJson(co)); } else if ("3".equals(line)) { RegisterCode rc = new RegisterCode(); rc.setMobile("13410969042"); rc.setSign("fdsafsadf"); msgObj.setC(CmdEnum.REGISTER_CODE.getCmd()); msgObj.setM(gson.toJson(rc)); } else if ("4".equals(line)) { RegisterCode rc = new RegisterCode(); rc.setMobile("13410969042"); rc.setCode("3243"); rc.setSign("fdsafsadf"); msgObj.setC(CmdEnum.REGISTER.getCmd()); msgObj.setM(gson.toJson(rc)); } String msg = gson.toJson(msgObj); ByteBuf buf = Unpooled.copiedBuffer(msg.getBytes()); lastWriteFuture = channel.writeAndFlush(buf); // If user typed the 'bye' command, wait until the server closes // the connection. if ("bye".equals(line.toLowerCase())) { channel.closeFuture().sync(); break; } } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.sync(); } channel.closeFuture().sync(); } finally { // The connection is closed automatically on shutdown. group.shutdownGracefully(); } }
From source file:com.hipishare.chat.securetest.SecureChatClientHandler.java
License:Apache License
public SecureChatClientHandler() { /*firstMessage = Unpooled.buffer(EchoClient.SIZE); for (int i = 0; i < firstMessage.capacity(); i++) { firstMessage.writeByte((byte) i); }*///from ww w. j a v a 2 s. co m MsgObject msgObj = new MsgObject(); Gson gson = new Gson(); msgObj.setC(CmdEnum.HEART_BEAT.getCmd()); msgObj.setM("o"); String msg = gson.toJson(msgObj); firstMessage = Unpooled.copiedBuffer(msg.getBytes()); }