Example usage for java.nio ByteBuffer get

List of usage examples for java.nio ByteBuffer get

Introduction

In this page you can find the example usage for java.nio ByteBuffer get.

Prototype

public abstract byte get(int index);

Source Link

Document

Returns the byte at the specified index and does not change the position.

Usage

From source file:Main.java

/**
 * <p>Decompresses a the content of a file from {@code startPosition} of {@code compressedSize}
 * and return the bytes of it. If a {@code compressedSize} can be provided if it is known
 * how large the decompressed content will be.</p>
 *
 * @param file             the file/*from w ww  .  java 2 s.co  m*/
 * @param startPosition    the start position
 * @param compressedSize   the compresse
 * @param decompressedSize the decompressed size
 * @return the decompressed bytes
 * @throws IOException         if there was any io issues
 * @throws DataFormatException if there was an issue decompressing content
 */
public static byte[] decompress(File file, int startPosition, int compressedSize, int decompressedSize)
        throws IOException, DataFormatException {

    if (decompressedSize == 0) {
        return decompress(file, startPosition, compressedSize);
    }

    try (FileChannel fileChannel = FileChannel.open(file.toPath())) {
        ByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, startPosition, compressedSize);
        Inflater inflater = new Inflater();
        byte[] compressedBytes = new byte[compressedSize];
        byte[] bytes = new byte[decompressedSize];

        buffer.get(compressedBytes);
        inflater.setInput(compressedBytes, 0, compressedSize);
        inflater.inflate(bytes);
        inflater.end();

        return bytes;
    }
}

From source file:com.l2jfree.util.HexUtil.java

public static String printData(ByteBuffer buf, int offset, int len) {
    byte[] tmp = new byte[len];
    int pos = buf.position();
    buf.position(offset);//from www  . ja  v  a 2  s.  c  o  m
    buf.get(tmp);
    buf.position(pos);
    return printData(tmp, len);
}

From source file:com.ebay.pulsar.analytics.cache.MemcachedCache.java

private static byte[] deserializeValue(NamedKey key, byte[] bytes) {
    ByteBuffer buf = ByteBuffer.wrap(bytes);

    final int keyLength = buf.getInt();
    byte[] keyBytes = new byte[keyLength];
    buf.get(keyBytes);
    byte[] value = new byte[buf.remaining()];
    buf.get(value);//  w  w w . j a  v  a2  s  .  c o  m

    Preconditions.checkState(Arrays.equals(keyBytes, key.toByteArray()),
            "Keys do not match, possible hash collision?");
    return value;
}

From source file:com.sm.replica.ParaList.java

public static ParaList toParaList(byte[] bytes) {
    ByteBuffer buf = ByteBuffer.wrap(bytes);
    int size = buf.getInt();
    ArrayList<StoreParas> list = new ArrayList<StoreParas>(size);
    for (int i = 0; i < size; i++) {
        // length of StoreParas
        int s = buf.getInt();
        byte[] ds = new byte[s];
        buf.get(ds);
        list.add(toStoreParas(ds));// w  w  w.  jav  a 2s.c  om

    }
    return new ParaList(list);

}

From source file:com.linkedin.databus.core.util.StringUtils.java

/**
 * Dumps as a hex string the contents of a buffer around a position
 * @param buf     the ByteBuffer to dump
 * @param bufOfs  starting offset in the buffer
 * @param length  the number of bytes to print
 * @return the hexstring//from  ww w.ja  v a2s .  co  m
 */
public static String hexdumpByteBufferContents(ByteBuffer buf, int bufOfs, int length) {
    if (length < 0) {
        return "";
    }

    final int endOfs = Math.min(buf.limit(), bufOfs + length + 1);
    final byte[] bytes = new byte[endOfs - bufOfs];

    buf = buf.duplicate();
    buf.position(bufOfs);
    buf.get(bytes);
    return new String(Hex.encodeHex(bytes));
}

From source file:cn.ctyun.amazonaws.util.StringUtils.java

/**
 * Base64 encodes the data in the specified byte buffer and returns it as a
 * base64 encoded string.//from www.  jav  a  2s. co m
 *
 * @param byteBuffer
 *            The data to base64 encode and return as a string.
 *
 * @return The base64 encoded contents of the specified byte buffer.
 */
public static String fromByteBuffer(ByteBuffer byteBuffer) {
    byte[] encodedBytes = null;
    if (byteBuffer.hasArray()) {
        encodedBytes = Base64.encodeBase64(byteBuffer.array());
    } else {
        byte[] binaryData = new byte[byteBuffer.limit()];
        byteBuffer.get(binaryData);
        encodedBytes = Base64.encodeBase64(binaryData);
    }
    return new String(encodedBytes);
}

From source file:com.glaf.core.util.BinaryUtils.java

/**
 * Returns a copy of the bytes from the given <code>ByteBuffer</code>,
 * ranging from the the buffer's current position to the buffer's limit; or
 * null if the input is null.// ww w  .  ja  v  a2  s.c om
 * <p>
 * The internal states of the given byte buffer will be restored when this
 * method completes execution.
 * <p>
 * When handling <code>ByteBuffer</code> from user's input, it's typical to
 * call the {@link #copyBytesFrom(ByteBuffer)} instead of
 * {@link #copyAllBytesFrom(ByteBuffer)} so as to account for the position
 * of the input <code>ByteBuffer</code>. The opposite is typically true,
 * however, when handling <code>ByteBuffer</code> from withint the
 * unmarshallers of the low-level clients.
 */
public static byte[] copyBytesFrom(ByteBuffer bb) {
    if (bb == null)
        return null;
    if (bb.hasArray())
        return Arrays.copyOfRange(bb.array(), bb.position(), bb.limit());
    bb.mark();
    try {
        byte[] dst = new byte[bb.remaining()];
        bb.get(dst);
        return dst;
    } finally {
        bb.reset();
    }
}

From source file:io.blobkeeper.file.util.FileUtils.java

@NotNull
public static SortedMap<Long, Block> readBlob(@NotNull IndexService indexService, @NotNull File blob,
        @NotNull Partition partition) {//from  w w  w . j  a  v  a2 s.com
    List<IndexElt> elts = new ArrayList<>(indexService.getListByPartition(partition));

    // sort it by offset, to read file consequentially
    sort(elts, new IndexEltOffsetComparator());

    List<BlockElt> blockElts = new ArrayList<>();

    for (IndexElt elt : elts) {
        try {
            ByteBuffer dataBuffer = readFile(blob, elt.getOffset(), elt.getLength());
            byte[] dataBufferBytes = new byte[dataBuffer.remaining()];
            dataBuffer.get(dataBufferBytes);

            long fileCrc = FileUtils.getCrc(dataBufferBytes);
            if (fileCrc == elt.getCrc()) {
                blockElts.add(
                        new BlockElt(elt.getId(), elt.getType(), elt.getOffset(), elt.getLength(), fileCrc));
            }
        } catch (Exception e) {
            log.error("Can't read file {} from blob", elt, e);
        }
    }

    return blockElts.stream().collect(groupingBy(BlockElt::getId)).values().stream()
            .map(groupedElts -> new Block(groupedElts.get(0).getId(),
                    groupedElts.stream().sorted(new BlockEltComparator()).collect(toImmutableList())))
            .collect(
                    // TODO: replace with ImmutableSortedMap
                    toMap(Block::getId, Function.identity(), Utils.throwingMerger(), TreeMap::new));
}

From source file:Main.java

/**
 * <p>Decompresses a the content of a file from {@code startPosition} of {@code compressedSize}
 * and return the bytes of it.</p>
 *
 * @param file           the file/* w w  w. j a va 2s  . com*/
 * @param startPosition  the start position
 * @param compressedSize the compresse
 * @return the decompressed bytes
 * @throws IOException         if there was any io issues
 * @throws DataFormatException if there was an issue decompressing content
 */
public static byte[] decompress(File file, int startPosition, int compressedSize)
        throws IOException, DataFormatException {

    try (FileChannel fileChannel = FileChannel.open(file.toPath())) {
        ByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, startPosition, compressedSize);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Inflater inflater = new Inflater();
        byte[] compressedBytes = new byte[compressedSize];
        byte[] inflated = new byte[BUFSIZ];
        int read;

        buffer.get(compressedBytes);
        inflater.setInput(compressedBytes);

        // unzip contents
        while ((read = inflater.inflate(inflated)) != 0) {
            baos.write(inflated, 0, read);
        }

        inflater.end();

        return baos.toByteArray();
    }
}

From source file:com.offbynull.portmapper.pcp.PcpDiscovery.java

private static Map<InetAddress, InetAddress> discoverLocalAddressesToGateways(Set<InetAddress> gateways)
        throws IOException, InterruptedException {
    Set<InetAddress> localAddresses = NetworkUtils.getAllLocalIpv4Addresses();
    List<DatagramChannel> channels = new ArrayList<>();
    final Map<DatagramChannel, InetAddress> bindMap = Collections
            .synchronizedMap(new HashMap<DatagramChannel, InetAddress>());
    final Map<InetAddress, InetAddress> localAddrToGatewayAddrMap = Collections
            .synchronizedMap(new HashMap<InetAddress, InetAddress>());

    try {//from w ww.  j  a  v a  2  s  . c om
        for (InetAddress localAddress : localAddresses) {
            DatagramChannel unicastChannel = null;
            try {
                unicastChannel = DatagramChannel.open();
                unicastChannel.configureBlocking(false);
                unicastChannel.socket().bind(new InetSocketAddress(localAddress, 0));
            } catch (IOException ioe) {
                IOUtils.closeQuietly(unicastChannel);
                throw ioe;
            }

            channels.add(unicastChannel);
            bindMap.put(unicastChannel, localAddress);
        }
    } catch (IOException ioe) {
        for (DatagramChannel channel : channels) {
            IOUtils.closeQuietly(channel);
        }
        throw ioe;
    }

    UdpCommunicator communicator = null;
    try {
        communicator = new UdpCommunicator(channels);
        communicator.startAsync().awaitRunning();
        communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                // make sure version is 2 and error isn't ADDRESS_MISMATCH and we're good to go
                if (packet.remaining() < 4
                        || packet.get(0) == 2 && packet.get(4) == PcpResultCode.ADDRESS_MISMATCH.ordinal()) {
                    return;
                }

                InetAddress localAddress = bindMap.get(channel);
                if (localAddress == null) {
                    return;
                }
                localAddrToGatewayAddrMap.put(localAddress, sourceAddress.getAddress());
            }
        });

        for (DatagramChannel channel : bindMap.keySet()) {
            for (InetAddress gateway : gateways) {
                ByteBuffer outBuf = ByteBuffer.allocate(1100);
                MapPcpRequest mpr = new MapPcpRequest(ByteBuffer.allocate(12), 0, 0, 0,
                        InetAddress.getByName("::"), 0L);
                mpr.dump(outBuf, bindMap.get(channel));
                outBuf.flip();

                communicator.send(channel, new InetSocketAddress(gateway, 5351), outBuf.asReadOnlyBuffer());
            }
        }

        Thread.sleep(5000L);
    } finally {
        if (communicator != null) {
            communicator.stopAsync().awaitTerminated();
        }
    }

    return new HashMap<>(localAddrToGatewayAddrMap);
}