List of usage examples for io.netty.buffer Unpooled wrappedBuffer
public static ByteBuf wrappedBuffer(ByteBuffer... buffers)
From source file:fr.kissy.zergling_push.infrastructure.FlatBufferMessageHandler.java
License:Apache License
private BinaryWebSocketFrame createPlayerConnectedMessage(Channel channel) { FlatBufferBuilder fbb = new FlatBufferBuilder(); int idOffset = fbb.createString(channel.id().asShortText()); int nameOffset = fbb.createString(channel.id().asShortText()); int offset = PlayerConnected.createPlayerConnected(fbb, idOffset, nameOffset, STARTING_X, STARTING_Y, STARTING_ROTATION, (float) Player.VELOCITY_FACTOR, (float) Player.ANGULAR_VELOCITY_FACTOR, (float) Player.DECELERATION_FACTOR, Laser.VELOCITY_FACTOR); PlayerConnected.finishPlayerConnectedBuffer(fbb, offset); ByteBuf byteBuf = Unpooled.wrappedBuffer(fbb.dataBuffer()); return new BinaryWebSocketFrame(byteBuf); }
From source file:godfinger.util.NettyHttpUtil.java
License:Apache License
public static FullHttpResponse fullHttpResponse(HttpResponseStatus status, String contentType, String stringContent) {// ww w. j a va 2 s . c o m ByteBuf content = Unpooled.wrappedBuffer(stringContent.getBytes()); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, content); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); return response; }
From source file:holon.internal.http.netty.NettyOutput.java
License:Open Source License
@Override public void write(FileChannel channel) throws IOException { int size = (int) channel.size(); ByteBuffer bb = ByteBuffer.allocateDirect(size); while (bb.position() < bb.capacity()) { channel.read(bb);/*from w ww. jav a2 s . c o m*/ } bb.position(0); buffer = Unpooled.wrappedBuffer(bb); }
From source file:httprestfulserver.HttpRESTfulServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { byte[] CONTENT = "Hello World".getBytes(); HttpRequest req = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }/*from w ww. ja va 2 s . c om*/ boolean keepAlive = HttpHeaders.isKeepAlive(req); HttpMethod method = req.getMethod(); CONTENT = method.name().getBytes(); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } }
From source file:impl.underdark.transport.bluetooth.discovery.ble.ManufacturerData.java
License:Open Source License
public static ManufacturerData parse(byte[] data) { if (data == null || data.length < (1 + 6 + 4)) return null; ByteBuf buf = Unpooled.wrappedBuffer(data); byte version = buf.readByte(); if (version != 1) return null; int appId = buf.readInt(); byte[] address = new byte[deviceAddressLen]; buf.readBytes(address);/*from w w w.j av a 2s. c om*/ int channelsMask = buf.readInt(); List<Integer> channels = new ArrayList<>(); for (int channel = 0; channelsMask != 0; ++channel) { if (channelsMask % 2 != 0) channels.add(channel); channelsMask >>= 1; } return new ManufacturerData(appId, address, channels); }
From source file:impl.underdark.transport.bluetooth.discovery.ble.ManufacturerData.java
License:Open Source License
public byte[] build() { ByteBuf data = Unpooled.wrappedBuffer(new byte[27]); data.clear();/* ww w. j a va 2 s .com*/ data.writeByte(1); // Version data.writeInt(appId); data.writeBytes(address); int channelsMask = 0; for (int channel : channels) { if (channel < 0 || channel > BtUtils.channelNumberMax) continue; // http://www.vipan.com/htdocs/bitwisehelp.html int channelBit = ipow(2, channel); channelsMask |= channelBit; } data.writeInt(channelsMask); return data.array(); }
From source file:io.aos.netty5.http.helloworld.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (HttpHeaderUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }// w ww . j a v a2 s. com boolean keepAlive = HttpHeaderUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } }
From source file:io.aos.netty5.http.websocketx.client.WebSocketClient.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(); final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); final int port; if (uri.getPort() == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80;//from w w w. ja v a 2 s .co m } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } else { port = -1; } } else { port = uri.getPort(); } if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) { System.err.println("Only WS(S) is supported."); return; } final boolean ssl = "wss".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } else { sslCtx = null; } EventLoopGroup group = new NioEventLoopGroup(); try { // 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())); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), host, port)); } p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), new WebSocketClientCompressionHandler(), handler); } }); 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.wrappedBuffer(new byte[] { 8, 1, 8, 1 })); ch.writeAndFlush(frame); } else { WebSocketFrame frame = new TextWebSocketFrame(msg); ch.writeAndFlush(frame); } } } finally { group.shutdownGracefully(); } }
From source file:io.aos.netty5.memcache.binary.MemcacheClientHandler.java
License:Apache License
/** * Transforms basic string requests to binary memcache requests *///from w w w . j a va 2 s . c o m @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { String command = (String) msg; if (command.startsWith("get ")) { String key = command.substring("get ".length()); BinaryMemcacheRequest req = new DefaultBinaryMemcacheRequest(key); req.setOpcode(BinaryMemcacheOpcodes.GET); req.setKeyLength((short) key.length()); req.setTotalBodyLength(key.length()); ctx.write(req, promise); } else if (command.startsWith("set ")) { String[] parts = command.split(" ", 3); if (parts.length < 3) { throw new IllegalArgumentException("Malformed Command: " + command); } String key = parts[1]; String value = parts[2]; ByteBuf content = Unpooled.wrappedBuffer(value.getBytes(CharsetUtil.UTF_8)); ByteBuf extras = ctx.alloc().buffer(8); BinaryMemcacheRequest req = new DefaultFullBinaryMemcacheRequest(key, extras, content); req.setOpcode(BinaryMemcacheOpcodes.SET); req.setKeyLength((short) key.length()); req.setExtrasLength((byte) 8); req.setTotalBodyLength(key.length() + 8 + value.length()); ctx.write(req, promise); } else { throw new IllegalStateException("Unknown Message: " + msg); } }
From source file:io.apigee.trireme.container.netty.UpgradedSocketHandler.java
License:Open Source License
public int write(ByteBuffer buf, final IOCompletionHandler<Integer> handler) { final int len = buf.remaining(); ByteBuf nettyBuf = Unpooled.wrappedBuffer(buf); ChannelFuture future = channel.writeAndFlush(nettyBuf); if (log.isDebugEnabled()) { log.debug("Writing {} bytes to the upgraded socket", len); }// w w w . j a v a2s. co m future.addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(Future<Void> voidFuture) { if (log.isDebugEnabled()) { log.debug("Upgraded socket write complete"); } handler.ioComplete(0, len); } }); return len; }