Java Code Examples for io.netty.buffer.ByteBuf#isDirect()

The following examples show how to use io.netty.buffer.ByteBuf#isDirect() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NioSctpChannel.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
protected final Object filterOutboundMessage(Object msg) throws Exception {
    if (msg instanceof SctpMessage) {
        SctpMessage m = (SctpMessage) msg;
        ByteBuf buf = m.content();
        if (buf.isDirect() && buf.nioBufferCount() == 1) {
            return m;
        }

        return new SctpMessage(m.protocolIdentifier(), m.streamIdentifier(), newDirectBuffer(m, buf));
    }

    throw new UnsupportedOperationException(
            "unsupported message type: " + StringUtil.simpleClassName(msg) +
            " (expected: " + StringUtil.simpleClassName(SctpMessage.class));
}
 
Example 2
Source File: NIOSequentialFile.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public void flushBuffer(ByteBuf byteBuf, boolean requestedSync, List<IOCallback> callbacks) {
   //maybe no need to perform any copy
   final int bytes = byteBuf.readableBytes();
   if (bytes == 0) {
      IOCallback.done(callbacks);
   } else {
      //enable zero copy case
      if (byteBuf.nioBufferCount() == 1 && byteBuf.isDirect()) {
         final ByteBuffer buffer = byteBuf.internalNioBuffer(byteBuf.readerIndex(), bytes);
         final IOCallback callback = new DelegateCallback(callbacks);
         try {
            //no need to pool the buffer and don't care if the NIO buffer got modified
            internalWrite(buffer, requestedSync, callback, false);
         } catch (Exception e) {
            callback.onError(ActiveMQExceptionType.GENERIC_EXCEPTION.getCode(), e.getMessage());
         }
      } else {
         super.flushBuffer(byteBuf, requestedSync, callbacks);
      }
   }
}
 
Example 3
Source File: AbstractNioByteChannel.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected final Object filterOutboundMessage(Object msg) {
    if (msg instanceof ByteBuf) {
        ByteBuf buf = (ByteBuf) msg;
        if (buf.isDirect()) {
            return msg;
        }

        return newDirectBuffer(buf);
    }

    if (msg instanceof FileRegion) {
        return msg;
    }

    throw new UnsupportedOperationException(
            "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES);
}
 
Example 4
Source File: NioSctpChannel.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected final Object filterOutboundMessage(Object msg) throws Exception {
    if (msg instanceof SctpMessage) {
        SctpMessage m = (SctpMessage) msg;
        ByteBuf buf = m.content();
        if (buf.isDirect() && buf.nioBufferCount() == 1) {
            return m;
        }

        return new SctpMessage(m.protocolIdentifier(), m.streamIdentifier(), m.isUnordered(),
                               newDirectBuffer(m, buf));
    }

    throw new UnsupportedOperationException(
            "unsupported message type: " + StringUtil.simpleClassName(msg) +
            " (expected: " + StringUtil.simpleClassName(SctpMessage.class));
}
 
Example 5
Source File: CryptoServiceTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Create a {@link CompositeByteBuf} from the given byte array.
 * @param data the byte array.
 * @return A {@link CompositeByteBuf}.
 */
private CompositeByteBuf fromByteArrayToCompositeByteBuf(byte[] data) {
  int size = data.length;
  ByteBuf toEncrypt = Unpooled.wrappedBuffer(data);
  CompositeByteBuf composite = new CompositeByteBuf(toEncrypt.alloc(), toEncrypt.isDirect(), size);
  int start = 0;
  int end = 0;
  for (int j = 0; j < 3; j++) {
    start = end;
    end = TestUtils.RANDOM.nextInt(size / 2 - 1) + end;
    if (j == 2) {
      end = size;
    }
    ByteBuf c = Unpooled.buffer(end - start);
    c.writeBytes(data, start, end - start);
    composite.addComponent(true, c);
  }
  return composite;
}
 
Example 6
Source File: Zlib.java    From Protocol with Apache License 2.0 5 votes vote down vote up
public void deflate(ByteBuf toCompress, ByteBuf into) throws DataFormatException {
    ByteBuf destination = null;
    ByteBuf source = null;
    try {
        if (!toCompress.isDirect()) {
            // Source is not a direct buffer. Work on a temporary direct buffer and then write the contents out.
            source = PooledByteBufAllocator.DEFAULT.directBuffer();
            source.writeBytes(toCompress);
        } else {
            source = toCompress;
        }

        if (!into.isDirect()) {
            // Destination is not a direct buffer. Work on a temporary direct buffer and then write the contents out.
            destination = PooledByteBufAllocator.DEFAULT.directBuffer();
        } else {
            destination = into;
        }

        deflaterLocal.get().process(source, destination);

        if (destination != into) {
            into.writeBytes(destination);
        }
    } finally {
        if (source != null && source != toCompress) {
            source.release();
        }
        if (destination != null && destination != into) {
            destination.release();
        }
    }
}
 
Example 7
Source File: NioSctpChannel.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean doWriteMessage(Object msg, ChannelOutboundBuffer in) throws Exception {
    SctpMessage packet = (SctpMessage) msg;
    ByteBuf data = packet.content();
    int dataLen = data.readableBytes();
    if (dataLen == 0) {
        return true;
    }

    ByteBufAllocator alloc = alloc();
    boolean needsCopy = data.nioBufferCount() != 1;
    if (!needsCopy) {
        if (!data.isDirect() && alloc.isDirectBufferPooled()) {
            needsCopy = true;
        }
    }
    ByteBuffer nioData;
    if (!needsCopy) {
        nioData = data.nioBuffer();
    } else {
        data = alloc.directBuffer(dataLen).writeBytes(data);
        nioData = data.nioBuffer();
    }
    final MessageInfo mi = MessageInfo.createOutgoing(association(), null, packet.streamIdentifier());
    mi.payloadProtocolID(packet.protocolIdentifier());
    mi.streamNumber(packet.streamIdentifier());

    final int writtenBytes = javaChannel().send(nioData, mi);
    return writtenBytes > 0;
}
 
Example 8
Source File: CompressionUtil.java    From Nemisys with GNU General Public License v3.0 5 votes vote down vote up
public static void zlibDeflate(ByteBuf toCompress, ByteBuf into) throws DataFormatException {
    ByteBuf destination = null;
    ByteBuf source = null;
    try {
        if (!toCompress.isDirect()) {
            // Source is not a direct buffer. Work on a temporary direct buffer and then write the contents out.
            source = PooledByteBufAllocator.DEFAULT.directBuffer();
            source.writeBytes(toCompress);
        } else {
            source = toCompress;
        }

        if (!into.isDirect()) {
            // Destination is not a direct buffer. Work on a temporary direct buffer and then write the contents out.
            destination = PooledByteBufAllocator.DEFAULT.directBuffer();
        } else {
            destination = into;
        }

        zlibDeflaterLocal.get().process(source, destination);

        if (destination != into) {
            into.writeBytes(destination);
        }
    } finally {
        if (source != null && source != toCompress) {
            source.release();
        }
        if (destination != null && destination != into) {
            destination.release();
        }
    }
}
 
Example 9
Source File: CompressionUtil.java    From Nemisys with GNU General Public License v3.0 5 votes vote down vote up
public static ByteBuf zlibInflate(ByteBuf buffer) throws DataFormatException {
    // Ensure that this buffer is direct.
    if (buffer.getByte(0) != 0x78) throw new DataFormatException("No zlib header");
    ByteBuf source = null;
    ByteBuf decompressed = PooledByteBufAllocator.DEFAULT.directBuffer();

    try {
        if (!buffer.isDirect()) {
            // We don't have a direct buffer. Create one.
            ByteBuf temporary = PooledByteBufAllocator.DEFAULT.directBuffer();
            temporary.writeBytes(buffer);
            source = temporary;
        } else {
            source = buffer;
        }

        zlibInflaterLocal.get().process(source, decompressed);
        return decompressed;
    } catch (DataFormatException e) {
        decompressed.release();
        throw e;
    } finally {
        if (source != null && source != buffer) {
            source.release();
        }
    }
}
 
Example 10
Source File: DebugUtils.java    From cassandana with Apache License 2.0 5 votes vote down vote up
public static String payload2Str(ByteBuf content) {
    final ByteBuf copy = content.copy();
    final byte[] bytesContent;
    if (copy.isDirect()) {
        final int size = copy.readableBytes();
        bytesContent = new byte[size];
        copy.readBytes(bytesContent);
    } else {
        bytesContent = copy.array();
    }
    return new String(bytesContent, StandardCharsets.UTF_8);
}
 
Example 11
Source File: Zlib.java    From Protocol with Apache License 2.0 5 votes vote down vote up
public ByteBuf inflate(ByteBuf buffer) throws DataFormatException {
    // Ensure that this buffer is direct.
    if (buffer.getByte(buffer.readerIndex()) != 0x78) throw new DataFormatException("No zlib header");
    ByteBuf source = null;
    ByteBuf decompressed = PooledByteBufAllocator.DEFAULT.directBuffer();

    try {
        if (!buffer.isDirect()) {
            // We don't have a direct buffer. Create one.
            ByteBuf temporary = PooledByteBufAllocator.DEFAULT.directBuffer();
            temporary.writeBytes(buffer);
            source = temporary;
        } else {
            source = buffer;
        }

        inflaterLocal.get().process(source, decompressed);
        return decompressed;
    } catch (DataFormatException e) {
        decompressed.release();
        throw e;
    } finally {
        if (source != null && source != buffer) {
            source.release();
        }
    }
}
 
Example 12
Source File: NioSctpChannel.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean doWriteMessage(Object msg, ChannelOutboundBuffer in) throws Exception {
    SctpMessage packet = (SctpMessage) msg;
    ByteBuf data = packet.content();
    int dataLen = data.readableBytes();
    if (dataLen == 0) {
        return true;
    }

    ByteBufAllocator alloc = alloc();
    boolean needsCopy = data.nioBufferCount() != 1;
    if (!needsCopy) {
        if (!data.isDirect() && alloc.isDirectBufferPooled()) {
            needsCopy = true;
        }
    }
    ByteBuffer nioData;
    if (!needsCopy) {
        nioData = data.nioBuffer();
    } else {
        data = alloc.directBuffer(dataLen).writeBytes(data);
        nioData = data.nioBuffer();
    }
    final MessageInfo mi = MessageInfo.createOutgoing(association(), null, packet.streamIdentifier());
    mi.payloadProtocolID(packet.protocolIdentifier());
    mi.streamNumber(packet.streamIdentifier());
    mi.unordered(packet.isUnordered());

    final int writtenBytes = javaChannel().send(nioData, mi);
    return writtenBytes > 0;
}
 
Example 13
Source File: ReferenceCountedOpenSslContext.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
static long toBIO(ByteBufAllocator allocator, PemEncoded pem) throws Exception {
    try {
        // We can turn direct buffers straight into BIOs. No need to
        // make a yet another copy.
        ByteBuf content = pem.content();

        if (content.isDirect()) {
            return newBIO(content.retainedSlice());
        }

        ByteBuf buffer = allocator.directBuffer(content.readableBytes());
        try {
            buffer.writeBytes(content, content.readerIndex(), content.readableBytes());
            return newBIO(buffer.retainedSlice());
        } finally {
            try {
                // If the contents of the ByteBuf is sensitive (e.g. a PrivateKey) we
                // need to zero out the bytes of the copy before we're releasing it.
                if (pem.isSensitive()) {
                    SslUtils.zeroout(buffer);
                }
            } finally {
                buffer.release();
            }
        }
    } finally {
        pem.release();
    }
}
 
Example 14
Source File: SslHandler.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
private SSLEngineResult wrap(ByteBufAllocator alloc, SSLEngine engine, ByteBuf in, ByteBuf out)
        throws SSLException {
    ByteBuf newDirectIn = null;
    try {
        int readerIndex = in.readerIndex();
        int readableBytes = in.readableBytes();

        // We will call SslEngine.wrap(ByteBuffer[], ByteBuffer) to allow efficient handling of
        // CompositeByteBuf without force an extra memory copy when CompositeByteBuffer.nioBuffer() is called.
        final ByteBuffer[] in0;
        if (in.isDirect() || !wantsDirectBuffer) {
            // As CompositeByteBuf.nioBufferCount() can be expensive (as it needs to check all composed ByteBuf
            // to calculate the count) we will just assume a CompositeByteBuf contains more then 1 ByteBuf.
            // The worst that can happen is that we allocate an extra ByteBuffer[] in CompositeByteBuf.nioBuffers()
            // which is better then walking the composed ByteBuf in most cases.
            if (!(in instanceof CompositeByteBuf) && in.nioBufferCount() == 1) {
                in0 = singleBuffer;
                // We know its only backed by 1 ByteBuffer so use internalNioBuffer to keep object allocation
                // to a minimum.
                in0[0] = in.internalNioBuffer(readerIndex, readableBytes);
            } else {
                in0 = in.nioBuffers();
            }
        } else {
            // We could even go further here and check if its a CompositeByteBuf and if so try to decompose it and
            // only replace the ByteBuffer that are not direct. At the moment we just will replace the whole
            // CompositeByteBuf to keep the complexity to a minimum
            newDirectIn = alloc.directBuffer(readableBytes);
            newDirectIn.writeBytes(in, readerIndex, readableBytes);
            in0 = singleBuffer;
            in0[0] = newDirectIn.internalNioBuffer(0, readableBytes);
        }

        for (;;) {
            ByteBuffer out0 = out.nioBuffer(out.writerIndex(), out.writableBytes());
            SSLEngineResult result = engine.wrap(in0, out0);
            in.skipBytes(result.bytesConsumed());
            out.writerIndex(out.writerIndex() + result.bytesProduced());

            switch (result.getStatus()) {
            case BUFFER_OVERFLOW:
                out.ensureWritable(maxPacketBufferSize);
                break;
            default:
                return result;
            }
        }
    } finally {
        // Null out to allow GC of ByteBuffer
        singleBuffer[0] = null;

        if (newDirectIn != null) {
            newDirectIn.release();
        }
    }
}
 
Example 15
Source File: SslHandler.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
private SSLEngineResult wrap(ByteBufAllocator alloc, SSLEngine engine, ByteBuf in, ByteBuf out)
        throws SSLException {
    ByteBuf newDirectIn = null;
    try {
        int readerIndex = in.readerIndex();
        int readableBytes = in.readableBytes();

        // We will call SslEngine.wrap(ByteBuffer[], ByteBuffer) to allow efficient handling of
        // CompositeByteBuf without force an extra memory copy when CompositeByteBuffer.nioBuffer() is called.
        final ByteBuffer[] in0;
        if (in.isDirect() || !engineType.wantsDirectBuffer) {
            // As CompositeByteBuf.nioBufferCount() can be expensive (as it needs to check all composed ByteBuf
            // to calculate the count) we will just assume a CompositeByteBuf contains more then 1 ByteBuf.
            // The worst that can happen is that we allocate an extra ByteBuffer[] in CompositeByteBuf.nioBuffers()
            // which is better then walking the composed ByteBuf in most cases.
            if (!(in instanceof CompositeByteBuf) && in.nioBufferCount() == 1) {
                in0 = singleBuffer;
                // We know its only backed by 1 ByteBuffer so use internalNioBuffer to keep object allocation
                // to a minimum.
                in0[0] = in.internalNioBuffer(readerIndex, readableBytes);
            } else {
                in0 = in.nioBuffers();
            }
        } else {
            // We could even go further here and check if its a CompositeByteBuf and if so try to decompose it and
            // only replace the ByteBuffer that are not direct. At the moment we just will replace the whole
            // CompositeByteBuf to keep the complexity to a minimum
            newDirectIn = alloc.directBuffer(readableBytes);
            newDirectIn.writeBytes(in, readerIndex, readableBytes);
            in0 = singleBuffer;
            in0[0] = newDirectIn.internalNioBuffer(newDirectIn.readerIndex(), readableBytes);
        }

        for (;;) {
            ByteBuffer out0 = out.nioBuffer(out.writerIndex(), out.writableBytes());
            SSLEngineResult result = engine.wrap(in0, out0);
            in.skipBytes(result.bytesConsumed());
            out.writerIndex(out.writerIndex() + result.bytesProduced());

            switch (result.getStatus()) {
            case BUFFER_OVERFLOW:
                out.ensureWritable(engine.getSession().getPacketBufferSize());
                break;
            default:
                return result;
            }
        }
    } finally {
        // Null out to allow GC of ByteBuffer
        singleBuffer[0] = null;

        if (newDirectIn != null) {
            newDirectIn.release();
        }
    }
}
 
Example 16
Source File: UnixChannelUtil.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
static boolean isBufferCopyNeededForWrite(ByteBuf byteBuf, int iovMax) {
    return !byteBuf.hasMemoryAddress() && (!byteBuf.isDirect() || byteBuf.nioBufferCount() > iovMax);
}
 
Example 17
Source File: UkcpClientUdpChannel.java    From kcp-netty with MIT License 2 votes vote down vote up
/**
 * Checks if the specified buffer is a direct buffer and is composed of a single NIO buffer.
 * (We check this because otherwise we need to make it a non-composite buffer.)
 */
private static boolean isSingleDirectBuffer(ByteBuf buf) {
    return buf.isDirect() && buf.nioBufferCount() == 1;
}
 
Example 18
Source File: UkcpServerChannel.java    From kcp-netty with MIT License 2 votes vote down vote up
/**
 * Checks if the specified buffer is a direct buffer and is composed of a single NIO buffer.
 * (We check this because otherwise we need to make it a non-composite buffer.)
 */
private static boolean isSingleDirectBuffer(ByteBuf buf) {
    return buf.isDirect() && buf.nioBufferCount() == 1;
}
 
Example 19
Source File: NioDatagramChannel.java    From netty-4.1.22 with Apache License 2.0 2 votes vote down vote up
/**
 * Checks if the specified buffer is a direct buffer and is composed of a single NIO buffer.
 * (We check this because otherwise we need to make it a non-composite buffer.)
 */
private static boolean isSingleDirectBuffer(ByteBuf buf) {
    return buf.isDirect() && buf.nioBufferCount() == 1;
}
 
Example 20
Source File: NioDatagramChannel.java    From netty4.0.27Learn with Apache License 2.0 2 votes vote down vote up
/**
 * Checks if the specified buffer is a direct buffer and is composed of a single NIO buffer.
 * (We check this because otherwise we need to make it a non-composite buffer.)
 */
private static boolean isSingleDirectBuffer(ByteBuf buf) {
    return buf.isDirect() && buf.nioBufferCount() == 1;
}