List of usage examples for io.netty.buffer ByteBuf hasArray
public abstract boolean hasArray();
From source file:org.restexpress.Request.java
License:Apache License
/** * Returns the byte array underlying the Netty ByteBuf for this request. * However, if the ByteBuf returns false to hasArray(), this * method returns null./*www . j a va 2 s.c o m*/ * @author actolap All ByteBufs may not have backing array (i.e. direct memory) * * @return an array of byte, or null, if the ByteBuf is not backed by a byte array. */ public byte[] getBodyAsBytes() { ByteBuf buf = getBody(); int length = buf.readableBytes(); byte[] bytes; if (buf.hasArray()) { bytes = buf.array(); } else { bytes = new byte[length]; buf.getBytes(buf.readerIndex(), bytes); } return bytes; }
From source file:org.springframework.cloud.stream.app.netty.tcp.source.NettyTcpReceivingChannelAdapter.java
License:Apache License
@Override protected void onInit() { super.onInit(); serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override/*from w w w. ja v a 2 s .c o m*/ protected void initChannel(final SocketChannel socketChannel) throws Exception { final ChannelPipeline channelPipeline = socketChannel.pipeline(); boolean first = true; ChannelInboundHandler[] channelInboundHandlers = channelInboundHandlerFactory .createChannelInboundHandlers(); for (ChannelInboundHandler channelInboundHandler : channelInboundHandlers) { if (first) { channelPipeline.addFirst(channelInboundHandler); first = false; } else { channelPipeline.addLast(channelInboundHandler); } } channelPipeline.addLast("sourceOutputHandler", new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { byte[] data; if (msg.hasArray()) { data = msg.array(); } else { data = new byte[msg.readableBytes()]; msg.readBytes(data); } AbstractIntegrationMessageBuilder<byte[]> builder = getMessageBuilderFactory() .withPayload(data); sendMessage(builder.build()); } }); socketChannel.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { socketChannel.close(); } }); } }); serverBootstrap.validate(); }
From source file:org.waarp.common.digest.FilesystemBasedDigest.java
License:Open Source License
/** * Update the digest with new buffer//from w w w . j av a 2 s . c o m */ public void Update(ByteBuf buffer) { byte[] bytes = null; int start = 0; int length = buffer.readableBytes(); if (buffer.hasArray()) { start = buffer.arrayOffset(); bytes = buffer.array(); } else { if (reusableBytes == null || reusableBytes.length != length) { reusableBytes = new byte[length]; } bytes = reusableBytes; buffer.getBytes(buffer.readerIndex(), bytes); } Update(bytes, start, length); }
From source file:org.waarp.common.digest.FilesystemBasedDigest.java
License:Open Source License
/** * Get hash with given {@link ByteBuf} (from Netty) * //from w ww . j a v a 2 s .co m * @param buffer * this buffer will not be changed * @param algo * @return the hash * @throws IOException */ public static byte[] getHash(ByteBuf buffer, DigestAlgo algo) throws IOException { Checksum checksum = null; byte[] bytes = null; int start = 0; int length = buffer.readableBytes(); if (buffer.hasArray()) { start = buffer.arrayOffset(); bytes = buffer.array(); } else { bytes = new byte[length]; buffer.getBytes(buffer.readerIndex(), bytes); } switch (algo) { case ADLER32: checksum = new Adler32(); case CRC32: if (checksum == null) { // not ADLER32 checksum = new CRC32(); } checksum.update(bytes, start, length); bytes = null; bytes = Long.toOctalString(checksum.getValue()).getBytes(UTF8); checksum = null; return bytes; case MD5: if (useFastMd5) { MD5 md5 = new MD5(); md5.Update(bytes, start, length); bytes = md5.Final(); md5 = null; return bytes; } case MD2: case SHA1: case SHA256: case SHA384: case SHA512: String algoname = algo.name; MessageDigest digest = null; try { digest = MessageDigest.getInstance(algoname); } catch (NoSuchAlgorithmException e) { throw new IOException(algoname + " Algorithm not supported by this JVM", e); } digest.update(bytes, start, length); bytes = digest.digest(); digest = null; return bytes; default: throw new IOException(algo.name + " Algorithm not supported by this JVM"); } }
From source file:org.waarp.common.digest.MD5.java
License:Open Source License
/** * Updates hash with given {@link ByteBuf} (from Netty) * //ww w .j a v a2s . c o m * @param buffer * ByteBuf to use for updating the hash and this buffer will not be changed */ public void Update(ByteBuf buffer) { byte[] bytes; int start = 0; int len = buffer.readableBytes(); if (buffer.hasArray()) { start = buffer.arrayOffset(); bytes = buffer.array(); } else { if (reusableBytes == null || reusableBytes.length != len) { reusableBytes = new byte[len]; } bytes = reusableBytes; buffer.getBytes(start, bytes); } Update(state, bytes, start, len); }
From source file:org.waarp.common.file.filesystembased.FilesystemBasedFileImpl.java
License:Open Source License
/** * Write the current FileInterface with the given ByteBuf. The file is not limited to 2^32 * bytes since this write operation is in add mode. * //from w ww.ja v a 2 s.com * In case of error, the current already written blocks are maintained and the position is not * changed. * * @param buffer * added to the file * @throws FileTransferException */ private void writeBlock(ByteBuf buffer) throws FileTransferException { if (!isReady) { throw new FileTransferException("No file is ready"); } // An empty buffer is allowed if (buffer == null) { return;// could do FileEndOfTransfer ? } if (fileOutputStream == null) { // rafOut = getRandomFile(); fileOutputStream = getFileOutputStream(position > 0); } if (fileOutputStream == null) { throw new FileTransferException("Internal error, file is not ready"); } int bufferSize = buffer.readableBytes(); int start = 0; byte[] newbuf; if (buffer.hasArray()) { start = buffer.arrayOffset(); newbuf = buffer.array(); buffer.readerIndex(buffer.readerIndex() + bufferSize); } else { if (reusableBytes == null || reusableBytes.length != bufferSize) { reusableBytes = new byte[bufferSize]; } newbuf = reusableBytes; buffer.readBytes(newbuf); } try { fileOutputStream.write(newbuf, start, bufferSize); } catch (IOException e2) { logger.error("Error during write:", e2); try { closeFile(); } catch (CommandAbstractException e1) { } // NO this.realFile.delete(); NO DELETE SINCE BY BLOCK IT CAN BE // REDO throw new FileTransferException("Internal error, file is not ready"); } position += bufferSize; }
From source file:org.waarp.ftp.core.data.handler.FtpSeekAheadData.java
License:Open Source License
/** * @param buffer// w ww . ja v a 2 s. c om */ FtpSeekAheadData(ByteBuf buffer) throws SeekAheadNoBackArrayException { if (!buffer.hasArray()) { throw new SeekAheadNoBackArrayException(); } this.buffer = buffer; this.bytes = buffer.array(); this.pos = this.readerIndex = buffer.arrayOffset() + buffer.readerIndex(); this.limit = buffer.arrayOffset() + buffer.writerIndex(); }
From source file:ratpack.util.internal.BufferUtil.java
License:Apache License
public static byte[] getBytes(ByteBuf byteBuf) { if (byteBuf.hasArray()) { return byteBuf.array(); } else {// w w w.ja v a 2 s. co m ByteArrayOutputStream baos = new ByteArrayOutputStream(byteBuf.writerIndex()); try { writeTo(byteBuf, baos); } catch (IOException e) { throw uncheck(e); } return baos.toByteArray(); } }
From source file:se.sics.kompics.network.netty.serialization.ProtobufSerializer.java
License:Open Source License
@Override public Object fromBinary(ByteBuf msg, Optional<Class> hint) { final byte[] array; final int offset; final int length = msg.readableBytes(); if (msg.hasArray()) { array = msg.array();// w w w.j ava 2s .co m offset = msg.arrayOffset() + msg.readerIndex(); } else { array = new byte[length]; msg.getBytes(msg.readerIndex(), array, 0, length); offset = 0; } Object o = null; try { if (extensionRegistry == null) { if (HAS_PARSER) { o = prototype.getParserForType().parseFrom(array, offset, length); } else { o = prototype.newBuilderForType().mergeFrom(array, offset, length).build(); } } else { if (HAS_PARSER) { o = prototype.getParserForType().parseFrom(array, offset, length, extensionRegistry); } else { o = prototype.newBuilderForType().mergeFrom(array, offset, length, extensionRegistry).build(); } } } catch (InvalidProtocolBufferException ex) { Serializers.LOG.error("ProtobufSerializer: Couldn't deserialize object.", ex); } return o; }
From source file:tp.MyJZLibDecoder.java
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (!in.isReadable()) { return;/*from w w w.j av a 2s. com*/ } try { // Configure input. int inputLength = in.readableBytes(); //totalBytes += inputLength; z.avail_in = inputLength; if (in.hasArray()) { z.next_in = in.array(); z.next_in_index = in.arrayOffset() + in.readerIndex(); } else { byte[] array = new byte[inputLength]; in.getBytes(in.readerIndex(), array); z.next_in = array; z.next_in_index = 0; } int oldNextInIndex = z.next_in_index; // Configure output. int maxOutputLength = inputLength << 1; ByteBuf decompressed = ctx.alloc().heapBuffer(maxOutputLength); try { loop: for (;;) { z.avail_out = maxOutputLength; decompressed.ensureWritable(maxOutputLength); z.next_out = decompressed.array(); z.next_out_index = decompressed.arrayOffset() + decompressed.writerIndex(); int oldNextOutIndex = z.next_out_index; // Decompress 'in' into 'out' int resultCode = z.inflate(JZlib.Z_SYNC_FLUSH); int outputLength = z.next_out_index - oldNextOutIndex; if (outputLength > 0) { decompressed.writerIndex(decompressed.writerIndex() + outputLength); } switch (resultCode) { case JZlib.Z_NEED_DICT: if (dictionary == null) { ZlibUtil.fail(z, "decompression failure", resultCode); } else { resultCode = z.inflateSetDictionary(dictionary, dictionary.length); if (resultCode != JZlib.Z_OK) { ZlibUtil.fail(z, "failed to set the dictionary", resultCode); } } break; case JZlib.Z_STREAM_END: finished = true; // Do not decode anymore. z.inflateEnd(); break loop; case JZlib.Z_OK: break; case JZlib.Z_BUF_ERROR: if (z.avail_in <= 0) { //ZlibUtil.fail(z, "decompression failure [Z_BUF_ERROR] ", resultCode); break loop; } break; default: ZlibUtil.fail(z, "decompression failure", resultCode); } } } finally { in.skipBytes(z.next_in_index - oldNextInIndex); //System.err.println("[recived][numBytes] = "+inputLength); if (decompressed.isReadable()) { out.add(decompressed); } else { decompressed.release(); } } } finally { // Deference the external references explicitly to tell the VM that // the allocated byte arrays are temporary so that the call stack // can be utilized. // I'm not sure if the modern VMs do this optimization though. z.next_in = null; z.next_out = null; } }