List of usage examples for io.netty.buffer ByteBuf hasArray
public abstract boolean hasArray();
From source file:appeng.tile.misc.TilePaint.java
License:Open Source License
@TileEvent(TileEventType.WORLD_NBT_WRITE) public void writeToNBT_TilePaint(final NBTTagCompound data) { final ByteBuf myDat = Unpooled.buffer(); this.writeBuffer(myDat); if (myDat.hasArray()) { data.setByteArray("dots", myDat.array()); }/*from w ww . jav a 2 s. c om*/ }
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/* w w w . j av a2s . c om*/ 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 w w. j a va2s.c om 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 {// ww w. j a va 2s . co 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 {//from w w w . j a v a 2s. c om 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:cn.wantedonline.puppy.httpserver.component.HttpRequest.java
License:Apache License
public String getContentString() { ByteBuf content = content(); if (content.hasArray()) { return new String(content.array(), charset4ContentDecoder); }// w ww . j av a 2 s. c o m return ""; }
From source file:com.athena.dolly.websocket.server.test.WebSocketServerHandler.java
License:Apache License
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); try {//from w ww . j a v a 2 s. c o m fos.flush(); fos.close(); fos = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { // Send the uppercase string back. String fileName = ((TextWebSocketFrame) frame).text(); logger.debug(String.format("Received file name is [%s]", fileName)); destFile = new File(fileName + ".received"); try { fos = new FileOutputStream(destFile); } catch (FileNotFoundException e) { e.printStackTrace(); } ctx.channel().write(new TextWebSocketFrame(fileName.toUpperCase())); } if (frame instanceof BinaryWebSocketFrame) { byte[] buffer = null; ByteBuf rawMessage = ((BinaryWebSocketFrame) frame).content(); //logger.debug(">>>> BinaryWebSocketFrame Found, " + rawMessage); // check if this ByteBuf is DIRECT (no backing byte[]) if (rawMessage.hasArray() == false) { int size = rawMessage.readableBytes(); buffer = new byte[size]; rawMessage.readBytes(buffer); try { fos.write(buffer); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { buffer = rawMessage.array(); } logger.debug(">>>> Read Byte Array: " + buffer.length); return; } }
From source file:com.beeswax.hexbid.parser.BidProtobufParser.java
License:Apache License
/** * Parse serialized protocol buffer Bytebuf to protobuf object.</br> * Preferencing implementation of {@link ProtobufDecoder} * /*w w w . jav a 2 s . c o m*/ * @param bytebuf * @return protocol buffer message * @throws InvalidProtocolBufferException */ public static <T extends Message.Builder> Message parseProtoBytebuf(ByteBuf bytebuf, T messageBuilder) throws InvalidProtocolBufferException { final byte[] array; final int offset; final int length = bytebuf.readableBytes(); if (bytebuf.hasArray()) { array = bytebuf.array(); offset = bytebuf.arrayOffset() + bytebuf.readerIndex(); } else { array = new byte[length]; bytebuf.getBytes(bytebuf.readerIndex(), array, 0, length); offset = 0; } return messageBuilder.mergeFrom(array, offset, length).buildPartial(); }
From source file:com.chat.common.netty.handler.decode.ProtobufDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { final byte[] array; final int offset; final int length = msg.readableBytes(); if (msg.hasArray()) { array = msg.array();/*from www. ja v a 2 s. c o m*/ offset = msg.arrayOffset() + msg.readerIndex(); } else { array = new byte[length]; msg.getBytes(msg.readerIndex(), array, 0, length); offset = 0; } if (extensionRegistry == null) { if (HAS_PARSER) { out.add(prototype.getParserForType().parseFrom(array, offset, length)); } else { out.add(prototype.newBuilderForType().mergeFrom(array, offset, length).build()); } } else { if (HAS_PARSER) { out.add(prototype.getParserForType().parseFrom(array, offset, length, extensionRegistry)); } else { out.add(prototype.newBuilderForType().mergeFrom(array, offset, length, extensionRegistry).build()); } } }
From source file:com.datastax.driver.core.CBUtil.java
License:Apache License
public static byte[] readRawBytes(ByteBuf cb) { if (cb.hasArray() && cb.readableBytes() == cb.array().length) { // Move the readerIndex just so we consistently consume the input cb.readerIndex(cb.writerIndex()); return cb.array(); }//w w w . j a v a 2s . c om // Otherwise, just read the bytes in a new array byte[] bytes = new byte[cb.readableBytes()]; cb.readBytes(bytes); return bytes; }