List of usage examples for io.netty.buffer Unpooled wrappedBuffer
public static ByteBuf wrappedBuffer(ByteBuffer... buffers)
From source file:cloudeventbus.codec.Encoder.java
License:Open Source License
@Override public void encode(ChannelHandlerContext ctx, Frame frame, ByteBuf out) throws Exception { LOGGER.debug("Encoding frame {}", frame); switch (frame.getFrameType()) { case AUTHENTICATE: final AuthenticationRequestFrame authenticationRequestFrame = (AuthenticationRequestFrame) frame; out.writeByte(FrameType.AUTHENTICATE.getOpcode()); out.writeByte(' '); final String challenge = Base64.encodeBase64String(authenticationRequestFrame.getChallenge()); writeString(out, challenge);//from ww w .jav a 2 s. co m break; case AUTH_RESPONSE: final AuthenticationResponseFrame authenticationResponseFrame = (AuthenticationResponseFrame) frame; out.writeByte(FrameType.AUTH_RESPONSE.getOpcode()); out.writeByte(' '); // Write certificate chain final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final OutputStream base64Out = new Base64OutputStream(outputStream, true, Integer.MAX_VALUE, new byte[0]); CertificateStoreLoader.store(base64Out, authenticationResponseFrame.getCertificates()); out.writeBytes(outputStream.toByteArray()); out.writeByte(' '); // Write salt final byte[] encodedSalt = Base64.encodeBase64(authenticationResponseFrame.getSalt()); out.writeBytes(encodedSalt); out.writeByte(' '); // Write signature final byte[] encodedDigitalSignature = Base64 .encodeBase64(authenticationResponseFrame.getDigitalSignature()); out.writeBytes(encodedDigitalSignature); break; case ERROR: final ErrorFrame errorFrame = (ErrorFrame) frame; out.writeByte(FrameType.ERROR.getOpcode()); out.writeByte(' '); writeString(out, Integer.toString(errorFrame.getCode().getErrorNumber())); if (errorFrame.getMessage() != null) { out.writeByte(' '); writeString(out, errorFrame.getMessage()); } break; case GREETING: final GreetingFrame greetingFrame = (GreetingFrame) frame; out.writeByte(FrameType.GREETING.getOpcode()); out.writeByte(' '); writeString(out, Integer.toString(greetingFrame.getVersion())); out.writeByte(' '); writeString(out, greetingFrame.getAgent()); out.writeByte(' '); writeString(out, Long.toString(greetingFrame.getId())); break; case PING: out.writeByte(FrameType.PING.getOpcode()); break; case PONG: out.writeByte(FrameType.PONG.getOpcode()); break; case PUBLISH: final PublishFrame publishFrame = (PublishFrame) frame; out.writeByte(FrameType.PUBLISH.getOpcode()); out.writeByte(' '); writeString(out, publishFrame.getSubject().toString()); if (publishFrame.getReplySubject() != null) { out.writeByte(' '); writeString(out, publishFrame.getReplySubject().toString()); } out.writeByte(' '); final ByteBuf body = Unpooled.wrappedBuffer(publishFrame.getBody().getBytes(CharsetUtil.UTF_8)); writeString(out, Integer.toString(body.readableBytes())); out.writeBytes(Codec.DELIMITER); out.writeBytes(body); break; case SERVER_READY: out.writeByte(FrameType.SERVER_READY.getOpcode()); break; case SUBSCRIBE: final SubscribeFrame subscribeFrame = (SubscribeFrame) frame; out.writeByte(FrameType.SUBSCRIBE.getOpcode()); out.writeByte(' '); writeString(out, subscribeFrame.getSubject().toString()); break; case UNSUBSCRIBE: final UnsubscribeFrame unsubscribeFrame = (UnsubscribeFrame) frame; out.writeByte(FrameType.UNSUBSCRIBE.getOpcode()); out.writeByte(' '); writeString(out, unsubscribeFrame.getSubject().toString()); break; default: throw new EncodingException("Don't know how to encode message of type " + frame.getClass().getName()); } out.writeBytes(Codec.DELIMITER); }
From source file:cn.dennishucd.nettyhttpserver.HttpServerHandler.java
License:Apache License
@SuppressWarnings("deprecation") @Override//from w ww .j av a2 s . c o m public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { request = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(request)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } if (!request.uri().equalsIgnoreCase(URL)) { sendError(ctx, NOT_FOUND); return; } } if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; ByteBuf buf = content.content(); UserToken ut = CTools.JSONStr2Object(buf.toString(io.netty.util.CharsetUtil.UTF_8), UserToken.class); logger.info("request body: " + buf.toString(io.netty.util.CharsetUtil.UTF_8)); buf.release(); boolean keepAlive = HttpUtil.isKeepAlive(request); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT.getBytes())); response.headers().set(CONTENT_TYPE, "application/json"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); logger.info("response body: " + CONTENT); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, KEEP_ALIVE); ctx.write(response); } } else { ctx.fireChannelRead(msg); } }
From source file:cn.liutils.api.player.ControlData.java
License:Open Source License
@Override public void loadNBTData(NBTTagCompound tag) { byte[] bytes = tag.getByteArray(IDENTIFIER); if (bytes.length > 0) fromBytes(Unpooled.wrappedBuffer(bytes)); else/*from w w w . ja v a 2 s. c om*/ clear(); }
From source file:cn.npt.net.websocket.WebSocketClient.java
License:Apache License
public static void main(String[] args) throws Exception { URI uri = new URI(URL); String scheme = uri.getScheme() == null ? "ws" : uri.getScheme(); final String host = uri.getHost() == null ? "192.168.20.71" : uri.getHost(); final int port; if (uri.getPort() == -1) { if ("ws".equalsIgnoreCase(scheme)) { port = 80;/*w w w .ja v a 2 s . c om*/ } else if ("wss".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) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } 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 BaseWebSocketClientHandler handler = new EchoWebSocketClientHandler( 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), 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:co.rsk.rpc.netty.JsonRpcWeb3ServerHandler.java
License:Open Source License
private ByteBuf buildErrorContent(int errorCode, String errorMessage) throws JsonProcessingException { Map<String, JsonNode> errorProperties = new HashMap<>(); errorProperties.put("code", jsonNodeFactory.numberNode(errorCode)); errorProperties.put("message", jsonNodeFactory.textNode(errorMessage)); JsonNode error = jsonNodeFactory.objectNode().set("error", jsonNodeFactory.objectNode().setAll(errorProperties)); return Unpooled.wrappedBuffer(mapper.writeValueAsBytes(mapper.treeToValue(error, Object.class))); }
From source file:com.addthis.basis.chars.ByteArrayReadOnlyUtfBuf.java
License:Apache License
@Override public ByteBuf toByteBuf() { return Unpooled.wrappedBuffer(data); }
From source file:com.addthis.basis.chars.ReadOnlyUtfBufTest.java
License:Apache License
@Override public CharSequence getCharSequenceForString(CharSequence control) { return new ReadOnlyUtfBuf(Unpooled.wrappedBuffer(control.toString().getBytes(StandardCharsets.UTF_8))); }
From source file:com.addthis.hydra.data.tree.prop.DataCounting.java
License:Apache License
@Override public void bytesDecode(byte[] b, long version) { ByteBuf buffer = Unpooled.wrappedBuffer(b); try {/*from ww w.j a v a 2 s . c o m*/ ver = Varint.readUnsignedVarInt(buffer); M = new byte[Varint.readUnsignedVarInt(buffer)]; buffer.readBytes(M); } finally { buffer.release(); } postDecode(); }
From source file:com.addthis.hydra.data.tree.prop.DataKeyTop.java
License:Apache License
@Override public void bytesDecode(byte[] b, long version) { top = new ConcurrentKeyTopper(); ByteBuf buf = Unpooled.wrappedBuffer(b); try {//from www .j av a 2 s . co m int topBytesLength = Varint.readUnsignedVarInt(buf); if (topBytesLength > 0) { byte[] topBytes = new byte[topBytesLength]; buf.readBytes(topBytes); top.bytesDecode(topBytes, version); } else { top.init(); } size = Varint.readUnsignedVarInt(buf); } finally { buf.release(); } }
From source file:com.addthis.hydra.data.tree.prop.DataMap.java
License:Apache License
@Override public void bytesDecode(byte[] b, long version) { ByteBuf buf = Unpooled.wrappedBuffer(b); try {//from w w w. ja v a 2 s. c om int length = Varint.readUnsignedVarInt(buf); keys = new String[length]; vals = new String[length]; try { for (int i = 0; i < length; i++) { keys[i] = readString(buf); } for (int i = 0; i < length; i++) { vals[i] = readString(buf); } if (buf.readableBytes() > 0) { size = Varint.readUnsignedVarInt(buf); } else { if (!IGNORE_DESERIALIZATION_ERROR) { throw new RuntimeException("Tried to deserialize a corrupted DataMap attachment. " + "set the system property hydra.tree.data.map=true to ignore (Map Attachment will be empty on old nodes)"); } } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } finally { buf.release(); } postDecode(); }