List of usage examples for io.netty.buffer Unpooled wrappedBuffer
public static ByteBuf wrappedBuffer(ByteBuffer... buffers)
From source file:cc.agentx.client.net.nio.XConnectHandler.java
License:Apache License
@Override public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception { boolean proxyMode = isAgentXNeeded(request.host()); log.info("\tClient -> Proxy \tTarget {}:{} [{}]", request.host(), request.port(), proxyMode ? "AGENTX" : "DIRECT"); Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override//www. j a v a2s. co m public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType())) .addListener(channelFuture -> { ByteBuf byteBuf = Unpooled.buffer(); request.encodeAsByteBuf(byteBuf); if (byteBuf.hasArray()) { byte[] xRequestBytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, xRequestBytes); if (proxyMode) { // handshaking to remote proxy xRequestBytes = requestWrapper.wrap(xRequestBytes); outboundChannel.writeAndFlush(Unpooled.wrappedBuffer( exposeRequest ? xRequestBytes : wrapper.wrap(xRequestBytes))); } // task handover ReferenceCountUtil.retain(request); // auto-release? a trap? ctx.pipeline().remove(XConnectHandler.this); outboundChannel.pipeline().addLast(new XRelayHandler(ctx.channel(), proxyMode ? wrapper : rawWrapper, false)); ctx.pipeline().addLast(new XRelayHandler(outboundChannel, proxyMode ? wrapper : rawWrapper, true)); } }); } else { ctx.channel() .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }); String host = request.host(); int port = request.port(); if (host.equals(config.getConsoleDomain())) { host = "localhost"; port = config.getConsolePort(); } else if (proxyMode) { host = config.getServerHost(); port = config.getServerPort(); } // ping target bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true) .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.channel().writeAndFlush( new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType())); if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }); }
From source file:cc.agentx.client.net.nio.XRelayHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (dstChannel.isActive()) { ByteBuf byteBuf = (ByteBuf) msg; try {/*from w ww.j a v a2s . c o m*/ if (!byteBuf.hasArray()) { byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, bytes); if (uplink) { dstChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(bytes))); log.info("\tClient ==========> Target \tSend [{} bytes]", bytes.length); } else { bytes = wrapper.unwrap(bytes); if (bytes != null) { dstChannel.writeAndFlush(Unpooled.wrappedBuffer(bytes)); log.info("\tClient <========== Target \tGet [{} bytes]", bytes.length); } } } } finally { ReferenceCountUtil.release(msg); } } }
From source file:cc.agentx.server.net.nio.XConnectHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { try {/*from ww w . ja v a 2 s .c o m*/ ByteBuf byteBuf = (ByteBuf) msg; if (!byteBuf.hasArray()) { byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, bytes); if (!requestParsed) { if (!exposedRequest) { bytes = wrapper.unwrap(bytes); if (bytes == null) { log.info("\tClient -> Proxy \tHalf Request"); return; } } XRequest xRequest = requestWrapper.parse(bytes); String host = xRequest.getHost(); int port = xRequest.getPort(); int dataLength = xRequest.getSubsequentDataLength(); if (dataLength > 0) { byte[] tailData = Arrays.copyOfRange(bytes, bytes.length - dataLength, bytes.length); if (exposedRequest) { tailData = wrapper.unwrap(tailData); if (tailData != null) { tailDataBuffer.write(tailData, 0, tailData.length); } } else { tailDataBuffer.write(tailData, 0, tailData.length); } } log.info("\tClient -> Proxy \tTarget {}:{}{}", host, port, DnsCache.isCached(host) ? " [Cached]" : ""); if (xRequest.getAtyp() == XRequest.Type.DOMAIN) { try { host = DnsCache.get(host); if (host == null) { host = xRequest.getHost(); } } catch (UnknownHostException e) { log.warn("\tClient <- Proxy \tBad DNS! ({})", e.getMessage()); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); return; } } Promise<Channel> promise = ctx.executor().newPromise(); promise.addListener(new FutureListener<Channel>() { @Override public void operationComplete(final Future<Channel> future) throws Exception { final Channel outboundChannel = future.getNow(); if (future.isSuccess()) { // handle tail byte[] tailData = tailDataBuffer.toByteArray(); tailDataBuffer.close(); if (tailData.length > 0) { log.info("\tClient ==========> Target \tSend Tail [{} bytes]", tailData.length); } outboundChannel .writeAndFlush((tailData.length > 0) ? Unpooled.wrappedBuffer(tailData) : Unpooled.EMPTY_BUFFER) .addListener(channelFuture -> { // task handover outboundChannel.pipeline() .addLast(new XRelayHandler(ctx.channel(), wrapper, false)); ctx.pipeline() .addLast(new XRelayHandler(outboundChannel, wrapper, true)); ctx.pipeline().remove(XConnectHandler.this); }); } else { if (ctx.channel().isActive()) { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); final String finalHost = host; bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.SO_KEEPALIVE, true) .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { if (ctx.channel().isActive()) { log.warn("\tClient <- Proxy \tBad Ping! ({}:{})", finalHost, port); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } } } }); requestParsed = true; } else { bytes = wrapper.unwrap(bytes); if (bytes != null) tailDataBuffer.write(bytes, 0, bytes.length); } } } finally { ReferenceCountUtil.release(msg); } }
From source file:cc.agentx.server.net.nio.XRelayHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (dstChannel.isActive()) { ByteBuf byteBuf = (ByteBuf) msg; try {/* ww w . jav a2 s .c o m*/ if (!byteBuf.hasArray()) { byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, bytes); if (uplink) { bytes = wrapper.unwrap(bytes); if (bytes != null) { dstChannel.writeAndFlush(Unpooled.wrappedBuffer(bytes)); log.info("\tClient ==========> Target \tSend [{} bytes]", bytes.length); } } else { dstChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(bytes))); log.info("\tClient <========== Target \tGet [{} bytes]", bytes.length); } } } finally { ReferenceCountUtil.release(msg); } } }
From source file:cc.changic.platform.etl.schedule.http.HttpServerHandler.java
License:Apache License
public void channelRead0(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 w w. j ava 2 s.c o m*/ 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:cd4017be.automation.jetpack.TickHandler.java
private void checkJetpack() { ItemStack item = mc.thePlayer.getCurrentArmor(ItemJetpack.slotPos); if (item == null || !(item.getItem() instanceof ItemJetpack)) return;// w w w .jav a 2 s. c o m this.updateKeyStates(item); NBTTagCompound nbt = item.stackTagCompound; if (nbt == null || !nbt.getBoolean("On")) return; if (GameSettings.isKeyDown(mc.gameSettings.keyBindJump)) power++; if (GameSettings.isKeyDown(mc.gameSettings.keyBindSneak)) power--; if (power < 0) power = 0; if (power > ItemJetpack.maxPower) power = ItemJetpack.maxPower; Vec3 dir; Mode mode = JetPackConfig.getMode(); if (mode.vertAngleFaktor == 0) { dir = Vec3.Def(0, mode.verticalComp, 0); } else { float a = mode.vertAngleOffset - mode.vertAngleFaktor * mc.thePlayer.rotationPitch; float f1 = MathHelper.cos(-mc.thePlayer.rotationYaw * 0.017453292F);// - (float)Math.PI float f2 = MathHelper.sin(-mc.thePlayer.rotationYaw * 0.017453292F);// - (float)Math.PI float f3 = MathHelper.cos(a * 0.017453292F); float f4 = MathHelper.sin(a * 0.017453292F); dir = Vec3.Def((double) (f2 * f3), (double) f4, (double) (f1 * f3)).scale(mode.verticalComp); } if (mode.moveStrength > 0) { Vec2 ctr = Vec2.Def(0, 0); if (GameSettings.isKeyDown(mc.gameSettings.keyBindForward)) ctr.z--; if (GameSettings.isKeyDown(mc.gameSettings.keyBindBack)) ctr.z++; if (GameSettings.isKeyDown(mc.gameSettings.keyBindRight)) ctr.x++; if (GameSettings.isKeyDown(mc.gameSettings.keyBindLeft)) ctr.x--; dirVec = dirVec.scale(1 - mode.moveStrength).add(ctr.scale(mode.moveStrength)); float cos = MathHelper.cos(-mc.thePlayer.rotationYaw * 0.017453292F - (float) Math.PI); float sin = MathHelper.sin(-mc.thePlayer.rotationYaw * 0.017453292F - (float) Math.PI); dir = dir.add(new Vec3(dirVec.rotate(cos, sin), 0)); } dir = dir.norm(); if (nbt.getInteger("power") < 0) return; ItemJetpack.updateMovement(mc.thePlayer, dir, power); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); //command-ID dos.writeByte(0); dos.writeInt(power); dos.writeFloat((float) dir.x); dos.writeFloat((float) dir.y); dos.writeFloat((float) dir.z); /* dos.writeFloat((float)mc.thePlayer.posX); dos.writeFloat((float)mc.thePlayer.posY); dos.writeFloat((float)mc.thePlayer.posZ); dos.writeFloat((float)mc.thePlayer.motionX); dos.writeFloat((float)mc.thePlayer.motionY); dos.writeFloat((float)mc.thePlayer.motionZ); */ PacketHandler.eventChannel.sendToServer( new FMLProxyPacket(Unpooled.wrappedBuffer(bos.toByteArray()), PacketHandler.channel)); } catch (IOException e) { } }
From source file:cd4017be.automation.jetpack.TickHandler.java
private void updateKeyStates(ItemStack item) { boolean pressOn = !lastKeyOnState && keyOn.isPressed(); boolean pressMode = !lastKeyModeState && keyMode.isPressed(); lastKeyOnState = keyOn.isPressed();//from w ww.ja va 2 s .com lastKeyModeState = keyMode.isPressed(); if (mc.currentScreen == null) { if (pressOn) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); dos.writeByte(2); PacketHandler.eventChannel.sendToServer( new FMLProxyPacket(Unpooled.wrappedBuffer(bos.toByteArray()), PacketHandler.channel)); } catch (IOException e) { e.printStackTrace(); } } if (pressMode && item.stackTagCompound != null && item.stackTagCompound.getBoolean("On")) { JetPackConfig.mode++; return; } else if (pressMode) { FMLClientHandler.instance().showGuiScreen(new GuiJetpackConfig()); } } }
From source file:cf.service.NettyBrokerServer.java
License:Open Source License
private HttpResponse encodeResponse(JsonObject jsonBody) throws RequestException { final String json = toString(jsonBody); LOGGER.debug("JSON response to server {}", json); final byte[] bytes = json.getBytes(); final ByteBuf buffer = Unpooled.wrappedBuffer(bytes); final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer);// www . j a v a 2 s . co m response.headers().add(HttpHeaders.Names.CONTENT_TYPE, "application/json"); response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, bytes.length); return response; }
From source file:ch.ethz.globis.distindex.middleware.net.MiddlewareChannelHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg;//from w w w. jav a 2s .co m String clientHost = ctx.channel().remoteAddress().toString(); ByteBuffer response = ioHandler.handle(clientHost, buf.nioBuffer()); ByteBuf nettyBuf = Unpooled.wrappedBuffer(response); ByteBuf sizeBuf = Unpooled.copyInt(nettyBuf.readableBytes()); ctx.write(sizeBuf); ctx.write(nettyBuf); ctx.flush(); buf.release(); }
From source file:chat.viska.xmpp.NettyTcpSession.java
License:Apache License
@SchedulerSupport(SchedulerSupport.CUSTOM) @Override/*from w w w. j a v a2 s . c o m*/ protected Completable openConnection(final Compression connectionCompression, final Compression tlsCompression) { final Bootstrap bootstrap = new Bootstrap(); bootstrap.group(nettyEventLoopGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) throws SSLException { if (getConnection().getTlsMethod() == Connection.TlsMethod.DIRECT) { tlsHandler = TLS_CONTEXT_BUILDER.build().newHandler(channel.alloc()); channel.pipeline().addLast(PIPE_TLS, tlsHandler); } else { channel.pipeline().addLast(PIPE_TLS, new ChannelDuplexHandler()); } channel.pipeline().addLast(PIPE_COMPRESSOR, new ChannelDuplexHandler()); channel.pipeline().addLast(new DelimiterBasedFrameDecoder(MAX_STANZA_SIZE_BYTE, false, false, Unpooled.wrappedBuffer(">".getBytes(StandardCharsets.UTF_8)))); channel.pipeline().addLast(new StreamClosingDetector()); channel.pipeline().addLast(PIPE_DECODER_XML, new XmlDecoder()); channel.pipeline().addLast(new SimpleChannelInboundHandler<XmlDocumentStart>() { @Override protected void channelRead0(final ChannelHandlerContext ctx, final XmlDocumentStart msg) throws Exception { if (!"UTF-8".equalsIgnoreCase(msg.encoding())) { sendError(new StreamErrorException(StreamErrorException.Condition.UNSUPPORTED_ENCODING, "Only UTF-8 is supported in XMPP stream.")); } } }); channel.pipeline().addLast(new StreamOpeningDetector()); channel.pipeline().addLast(new XmlFrameDecoder(MAX_STANZA_SIZE_BYTE)); channel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8)); channel.pipeline().addLast(new SimpleChannelInboundHandler<String>() { @Override protected void channelRead0(final ChannelHandlerContext ctx, final String msg) throws Exception { try { feedXmlPipeline(preprocessInboundXml(msg)); } catch (SAXException ex) { sendError(new StreamErrorException(StreamErrorException.Condition.BAD_FORMAT)); } } }); channel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8)); channel.pipeline().addLast(new SimpleChannelInboundHandler<Object>() { @Override protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) { } @Override public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) { if (cause instanceof Exception) { triggerEvent(new ExceptionCaughtEvent(NettyTcpSession.this, (Exception) cause)); } else { throw new RuntimeException(cause); } } }); } }); final ChannelFuture channelFuture = bootstrap.connect(getConnection().getDomain(), getConnection().getPort()); return Completable.fromFuture(channelFuture).andThen(Completable.fromAction(() -> { this.nettyChannel = (SocketChannel) channelFuture.channel(); nettyChannel.closeFuture().addListener(it -> changeStateToDisconnected()); })); }