List of usage examples for io.netty.buffer Unpooled wrappedBuffer
public static ByteBuf wrappedBuffer(ByteBuffer... buffers)
From source file:com.digitalpetri.modbus.requests.WriteMultipleRegistersRequest.java
License:Apache License
/** * @param address 0x0000 to 0xFFFF (0 to 65535) * @param quantity 0x0001 to 0x007B (1 to 123) * @param values buffer of at least N bytes, where N = quantity * 2 *///w ww . j ava 2s . c o m public WriteMultipleRegistersRequest(int address, int quantity, byte[] values) { this(address, quantity, Unpooled.wrappedBuffer(values)); }
From source file:com.digitalpetri.modbus.requests.WriteMultipleRegistersRequest.java
License:Apache License
/** * @param address 0x0000 to 0xFFFF (0 to 65535) * @param quantity 0x0001 to 0x007B (1 to 123) * @param values buffer of at least N bytes, where N = quantity * 2 *//* w w w. j av a 2 s .co m*/ public WriteMultipleRegistersRequest(int address, int quantity, ByteBuffer values) { this(address, quantity, Unpooled.wrappedBuffer(values)); }
From source file:com.digitalpetri.opcua.sdk.client.api.identity.UsernameProvider.java
License:Open Source License
@Override public Tuple2<UserIdentityToken, SignatureData> getIdentityToken(EndpointDescription endpoint, ByteString serverNonce) throws Exception { UserTokenPolicy tokenPolicy = Arrays.stream(endpoint.getUserIdentityTokens()) .filter(t -> t.getTokenType() == UserTokenType.UserName).findFirst() .orElseThrow(() -> new Exception("no username token policy found")); String policyId = tokenPolicy.getPolicyId(); SecurityPolicy securityPolicy = SecurityPolicy.None; String securityPolicyUri = tokenPolicy.getSecurityPolicyUri(); try {//from w w w. ja v a 2 s. c om if (securityPolicyUri != null && !securityPolicyUri.isEmpty()) { securityPolicy = SecurityPolicy.fromUri(securityPolicyUri); } else { securityPolicyUri = endpoint.getSecurityPolicyUri(); securityPolicy = SecurityPolicy.fromUri(securityPolicyUri); } } catch (Throwable t) { logger.warn("Error parsing SecurityPolicy for uri={}, falling back to no security.", securityPolicyUri); } byte[] passwordBytes = password.getBytes("UTF-8"); byte[] nonceBytes = Optional.ofNullable(serverNonce.bytes()).orElse(new byte[0]); ByteBuf buffer = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN); if (securityPolicy == SecurityPolicy.None) { buffer.writeBytes(passwordBytes); } else { buffer.writeInt(passwordBytes.length + nonceBytes.length); buffer.writeBytes(passwordBytes); buffer.writeBytes(nonceBytes); ByteString bs = endpoint.getServerCertificate(); X509Certificate certificate = CertificateUtil.decodeCertificate(bs.bytes()); int plainTextBlockSize = getPlainTextBlockSize(certificate, securityPolicy); int blockCount = (buffer.readableBytes() + plainTextBlockSize - 1) / plainTextBlockSize; Cipher cipher = getAndInitializeCipher(certificate, securityPolicy); ByteBuffer plainTextNioBuffer = buffer.nioBuffer(); ByteBuffer cipherTextNioBuffer = Unpooled.buffer().order(ByteOrder.LITTLE_ENDIAN).nioBuffer(); for (int blockNumber = 0; blockNumber < blockCount; blockNumber++) { int position = blockNumber * plainTextBlockSize; int limit = (blockNumber + 1) * plainTextBlockSize; plainTextNioBuffer.position(position).limit(limit); cipher.doFinal(plainTextNioBuffer, cipherTextNioBuffer); } cipherTextNioBuffer.flip(); buffer = Unpooled.wrappedBuffer(cipherTextNioBuffer); } byte[] bs = new byte[buffer.readableBytes()]; buffer.readBytes(bs); UserNameIdentityToken token = new UserNameIdentityToken(policyId, username, ByteString.of(bs), securityPolicy.getAsymmetricEncryptionAlgorithm().getUri()); return new Tuple2<>(token, new SignatureData()); }
From source file:com.digitalpetri.opcua.stack.core.application.DefaultCertificateValidator.java
License:Apache License
private void certificateRejected(X509Certificate certificate) { try {//from w ww. ja v a 2 s . c om String[] ss = certificate.getSubjectX500Principal().getName().split(","); String name = ss.length > 0 ? ss[0] : certificate.getSubjectX500Principal().getName(); String thumbprint = ByteBufUtil .hexDump(Unpooled.wrappedBuffer(DigestUtil.sha1(certificate.getEncoded()))); String filename = String.format("%s [%s].der", URLEncoder.encode(name, "UTF-8"), thumbprint); File f = new File(rejectedDir.getAbsolutePath() + File.separator + filename); FileOutputStream fos = new FileOutputStream(f); fos.write(certificate.getEncoded()); fos.flush(); fos.close(); logger.debug("Added rejected certificate entry: {}", filename); } catch (CertificateEncodingException | IOException e) { logger.error("Error adding rejected certificate entry.", e); } }
From source file:com.digitalpetri.opcua.stack.core.serialization.OpcUaDataTypeEncoding.java
License:Apache License
@Override public Object decodeFromByteString(ByteString encoded, NodeId encodingTypeId) { DecoderDelegate<Object> delegate = DelegateRegistry.getDecoder(encodingTypeId); byte[] bs = encoded.bytes(); if (bs == null) bs = new byte[0]; ByteBuf buffer = Unpooled.wrappedBuffer(bs).order(ByteOrder.LITTLE_ENDIAN); BinaryDecoder decoder = new BinaryDecoder(); decoder.setBuffer(buffer);//from w w w . ja va 2s. co m return delegate.decode(decoder); }
From source file:com.ebay.jetstream.messaging.transport.netty.autoflush.handler.NettyAutoFlushBatcher.java
License:MIT License
/** * @param ctx// ww w. j a va 2s . c om * @param queue */ public void flush(ChannelHandlerContext ctx, AutoFlushWriterChannelQueue queue) { if (queue == null) return; MessageEvent[] events = queue.get(); if (events == null) return; ByteBuf[] msgs = new ByteBuf[events.length]; for (int j = 0; j < events.length; j++) { msgs[j] = (ByteBuf) events[j].getMsg(); } try { ByteBuf composite = Unpooled.wrappedBuffer(msgs); ChannelPromise promise = new ExtendedChannelPromise(ctx.channel()); promise.addListener(new AutoFlushWriterChannelListener(events)); queue.setLastFlushTime(System.currentTimeMillis()); super.write(ctx, composite, promise); super.flush(ctx); } catch (Throwable t) { LOGGER.error("Error while Flushing : " + Arrays.toString(t.getStackTrace())); } }
From source file:com.example.http.hello.HttpHelloServerHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) { log.info("request coming[{}, hash: {}]: {}", current, hasher.hashCode(), msg); current = counter.incrementAndGet(); if (msg instanceof HttpRequest) { final HttpRequest request = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(request)) { ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); }/*from ww w.java 2s . c o m*/ final DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain"); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); final boolean keepAlive = HttpUtil.isKeepAlive(request); if (keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(response); } } }
From source file:com.fanavard.challenge.client.websocket.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 ww w . j a v a2s .c o 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) { sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } 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:com.flysoloing.learning.network.netty.binary.MemcacheClientHandler.java
License:Apache License
/** * Transforms basic string requests to binary memcache requests *//*w w w .ja va 2 s .c om*/ @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { String command = (String) msg; if (command.startsWith("get ")) { String keyString = command.substring("get ".length()); ByteBuf key = Unpooled.wrappedBuffer(keyString.getBytes(CharsetUtil.UTF_8)); BinaryMemcacheRequest req = new DefaultBinaryMemcacheRequest(key); req.setOpcode(BinaryMemcacheOpcodes.GET); 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 keyString = parts[1]; String value = parts[2]; ByteBuf key = Unpooled.wrappedBuffer(keyString.getBytes(CharsetUtil.UTF_8)); ByteBuf content = Unpooled.wrappedBuffer(value.getBytes(CharsetUtil.UTF_8)); ByteBuf extras = ctx.alloc().buffer(8); extras.writeZero(8); BinaryMemcacheRequest req = new DefaultFullBinaryMemcacheRequest(key, extras, content); req.setOpcode(BinaryMemcacheOpcodes.SET); ctx.write(req, promise); } else { throw new IllegalStateException("Unknown Message: " + msg); } }
From source file:com.flysoloing.learning.network.netty.http.helloworld.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }//from w w w .j a v a2 s .c o m boolean keepAlive = HttpUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); //response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_TYPE, "application/json"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, KEEP_ALIVE); ctx.write(response); } } }