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:com.linkedin.databus.core.DbusEventPart.java

/**
 * Decodes a bytebuffer and returns DbusEventPart. Preserves the ByteBuffer position.
 * @param buf//  w w  w .j  av  a  2 s .c om
 * @return
 */
public static DbusEventPart decode(ByteBuffer buf) {
    int pos = buf.position();
    int dataLen = buf.getInt(pos);
    if (dataLen < 0) {
        throw new UnsupportedOperationException("Data length " + dataLen + " not supported");
    }
    short attributes = buf.getShort(pos + AttributesOffset);
    short schemaVersion = (short) (attributes >> VERSION_SHIFT);
    SchemaDigestType schemaDigestType = digestType(attributes);
    int digestLen = digestLen(schemaDigestType);
    byte[] digest = new byte[digestLen];
    for (int i = 0; i < digestLen; i++) {
        digest[i] = buf.get(pos + AttributesOffset + AttributesLen + i);
    }

    // NOTE - this will create a new ByteBuffer object pointing to the
    // same memory. So the position of this new BB is beginning of the data
    // and limit is set to the end of the data.
    ByteBuffer dataBuf = buf.asReadOnlyBuffer();
    dataBuf.position(pos + AttributesOffset + AttributesLen + digestLen);
    dataBuf.limit(dataBuf.position() + dataLen);

    return new DbusEventPart(schemaDigestType, digest, schemaVersion, dataBuf);
}

From source file:com.l2jfree.security.NewCipher.java

/**
 * Calculates and embeds a packet's checksum.<BR>
 * Buffer's position will not be changed.
 * //from  w w w  .j a v a 2 s  .c om
 * @param buf byte buffer
 * @param offset offset to a packet's body
 * @param size packet's body size
 * @param experimental undocumented experimental features
 */
public static void appendChecksum(ByteBuffer buf, final int offset, final int size, boolean experimental) {
    int checksum = 0;
    int end = offset + size - 4; // ignore reserved bytes

    int pos;
    for (pos = offset; pos < end; pos += 4) {
        int i = buf.getInt(pos);
        checksum ^= i;
    }

    buf.putInt(pos, checksum);

    if (experimental) {
        Integer real = _checks.get(buf.get(offset));
        if (real != null) // someone knows a better scheme?
            buf.putInt(pos, real); // let them have it
    }
}

From source file:com.ottogroup.bi.spqr.pipeline.statistics.MicroPipelineStatistics.java

/**
 * Converts the provided byte array into a {@link MicroPipelineStatistics} representation
 * @param statsContent/*from  www  .  j  a  va2s .c  o m*/
 * @return
 */
public static MicroPipelineStatistics fromByteArray(final byte[] statsContent) {

    MicroPipelineStatistics stats = new MicroPipelineStatistics();
    ByteBuffer buf = ByteBuffer.wrap(statsContent);

    // ensure that the order is the same as when populating the array 
    stats.setNumOfMessages(buf.getInt());
    stats.setStartTime(buf.getLong());
    stats.setEndTime(buf.getLong());
    stats.setMinDuration(buf.getInt());
    stats.setMaxDuration(buf.getInt());
    stats.setAvgDuration(buf.getInt());
    stats.setMinSize(buf.getInt());
    stats.setMaxSize(buf.getInt());
    stats.setAvgSize(buf.getInt());
    stats.setErrors(buf.getInt());

    byte[] procNodeId = new byte[buf.getInt()];
    buf.get(procNodeId);

    byte[] pipelineId = new byte[buf.getInt()];
    buf.get(pipelineId);

    byte[] componentId = new byte[buf.getInt()];
    buf.get(componentId);

    stats.setProcessingNodeId(new String(procNodeId));
    stats.setPipelineId(new String(pipelineId));
    stats.setComponentId(new String(componentId));

    return stats;
}

From source file:LamportBasicVersion.java

private static String byteToString(ByteBuffer byteBufferFromNeighbor, MessageInfo messageInfoFromNeighbor) {
    byteBufferFromNeighbor.position(0);//w w w .j  ava  2  s .  c  om
    byteBufferFromNeighbor.limit(messageInfoFromNeighbor.bytes());
    byte[] bufArr = new byte[byteBufferFromNeighbor.remaining()];
    byteBufferFromNeighbor.get(bufArr);
    return new String(bufArr);
}

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

/**
 * ByteBuffer adaptation of org.apache.commons.lang3.ArrayUtils.lastIndexOf
 * method/*  ww  w .j a v  a  2s  .com*/
 * 
 * @param buffer
 *            the array to traverse for looking for the object, may be
 *            <code>null</code>
 * @param valueToFind
 *            the value to find
 * @param startIndex
 *            the start index (i.e. BB position) to travers backwards from
 * @return the last index (i.e. BB position) of the value within the array
 *         [between buffer.position() and buffer.limit()]; <code>-1</code>
 *         if not found.
 */
public static int lastIndexOf(ByteBuffer buffer, byte valueToFind, int startIndex) {
    assert buffer != null;

    if (startIndex < buffer.position()) {
        return -1;
    } else if (startIndex >= buffer.limit()) {
        startIndex = buffer.limit() - 1;
    }

    for (int i = startIndex; i >= buffer.position(); i--) {
        if (valueToFind == buffer.get(i))
            return i;
    }

    return -1;
}

From source file:com.blm.orc.ReaderImpl.java

private static FileMetaInfo extractMetaInfoFromFooter(FileSystem fs, Path path, long maxFileLength)
        throws IOException {
    FSDataInputStream file = fs.open(path);

    // figure out the size of the file using the option or filesystem
    long size;//  w  w  w .j a  v  a2 s.  c o  m
    if (maxFileLength == Long.MAX_VALUE) {
        size = fs.getFileStatus(path).getLen();
    } else {
        size = maxFileLength;
    }

    //read last bytes into buffer to get PostScript
    int readSize = (int) Math.min(size, DIRECTORY_SIZE_GUESS);
    file.seek(size - readSize);
    ByteBuffer buffer = ByteBuffer.allocate(readSize);
    file.readFully(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());

    //read the PostScript
    //get length of PostScript
    int psLen = buffer.get(readSize - 1) & 0xff;
    ensureOrcFooter(file, path, psLen, buffer);
    int psOffset = readSize - 1 - psLen;
    CodedInputStream in = CodedInputStream.newInstance(buffer.array(), buffer.arrayOffset() + psOffset, psLen);
    OrcProto.PostScript ps = OrcProto.PostScript.parseFrom(in);

    checkOrcVersion(LOG, path, ps.getVersionList());

    int footerSize = (int) ps.getFooterLength();
    int metadataSize = (int) ps.getMetadataLength();
    OrcFile.WriterVersion writerVersion;
    if (ps.hasWriterVersion()) {
        writerVersion = getWriterVersion(ps.getWriterVersion());
    } else {
        writerVersion = OrcFile.WriterVersion.ORIGINAL;
    }

    //check compression codec
    switch (ps.getCompression()) {
    case NONE:
        break;
    case ZLIB:
        break;
    case SNAPPY:
        break;
    case LZO:
        break;
    default:
        throw new IllegalArgumentException("Unknown compression");
    }

    //check if extra bytes need to be read
    int extra = Math.max(0, psLen + 1 + footerSize + metadataSize - readSize);
    if (extra > 0) {
        //more bytes need to be read, seek back to the right place and read extra bytes
        file.seek(size - readSize - extra);
        ByteBuffer extraBuf = ByteBuffer.allocate(extra + readSize);
        file.readFully(extraBuf.array(), extraBuf.arrayOffset() + extraBuf.position(), extra);
        extraBuf.position(extra);
        //append with already read bytes
        extraBuf.put(buffer);
        buffer = extraBuf;
        buffer.position(0);
        buffer.limit(footerSize + metadataSize);
    } else {
        //footer is already in the bytes in buffer, just adjust position, length
        buffer.position(psOffset - footerSize - metadataSize);
        buffer.limit(psOffset);
    }

    // remember position for later
    buffer.mark();

    file.close();

    return new FileMetaInfo(ps.getCompression().toString(), (int) ps.getCompressionBlockSize(),
            (int) ps.getMetadataLength(), buffer, ps.getVersionList(), writerVersion);
}

From source file:net.pms.util.AudioUtils.java

/**
 * Parses the old RealAudio 1.0 and 2.0 formats that's not supported by
 * neither {@link org.jaudiotagger} nor MediaInfo. Returns {@code false} if
 * {@code channel} isn't one of these formats or the parsing fails.
 * <p>//w ww  . jav a2 s. co  m
 * Primary references:
 * <ul>
 * <li><a href="https://wiki.multimedia.cx/index.php/RealMedia">RealAudio on
 * MultimediaWiki</a></li>
 * <li><a
 * href="https://github.com/FFmpeg/FFmpeg/blob/master/libavformat/rmdec.c"
 * >FFmpeg rmdec.c</a></li>
 * </ul>
 *
 * @param channel the {@link Channel} containing the input. Size will only
 *            be parsed if {@code channel} is a {@link FileChannel}
 *            instance.
 * @param media the {@link DLNAMediaInfo} instance to write the parsing
 *            results to.
 * @return {@code true} if the {@code channel} input is in RealAudio 1.0 or
 *         2.0 format and the parsing succeeds; false otherwise
 */
public static boolean parseRealAudio(ReadableByteChannel channel, DLNAMediaInfo media) {
    final byte[] magicBytes = { 0x2E, 0x72, 0x61, (byte) 0xFD };
    ByteBuffer buffer = ByteBuffer.allocate(8);
    buffer.order(ByteOrder.BIG_ENDIAN);
    DLNAMediaAudio audio = new DLNAMediaAudio();
    try {
        int count = channel.read(buffer);
        if (count < 4) {
            LOGGER.trace("Input is too short to be RealAudio");
            return false;
        }
        buffer.flip();
        byte[] signature = new byte[4];
        buffer.get(signature);
        if (!Arrays.equals(magicBytes, signature)) {
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Input signature ({}) mismatches RealAudio version 1.0 or 2.0",
                        new String(signature, StandardCharsets.US_ASCII));
            }
            return false;
        }
        media.setContainer(FormatConfiguration.RA);
        short version = buffer.getShort();
        int reportedHeaderSize = 0;
        int reportedDataSize = 0;
        if (version == 3) {
            audio.setCodecA(FormatConfiguration.REALAUDIO_14_4);
            audio.getAudioProperties().setNumberOfChannels(1);
            audio.getAudioProperties().setSampleFrequency(8000);
            short headerSize = buffer.getShort();

            buffer = ByteBuffer.allocate(headerSize);
            channel.read(buffer);
            buffer.flip();
            buffer.position(8);
            int bytesPerMinute = buffer.getShort() & 0xFFFF;
            reportedDataSize = buffer.getInt();
            byte b = buffer.get();
            if (b != 0) {
                byte[] title = new byte[b & 0xFF];
                buffer.get(title);
                String titleString = new String(title, StandardCharsets.US_ASCII);
                audio.setSongname(titleString);
                audio.setAudioTrackTitleFromMetadata(titleString);
            }
            b = buffer.get();
            if (b != 0) {
                byte[] artist = new byte[b & 0xFF];
                buffer.get(artist);
                audio.setArtist(new String(artist, StandardCharsets.US_ASCII));
            }
            audio.setBitRate(bytesPerMinute * 8 / 60);
            media.setBitrate(bytesPerMinute * 8 / 60);
        } else if (version == 4 || version == 5) {
            buffer = ByteBuffer.allocate(14);
            channel.read(buffer);
            buffer.flip();
            buffer.get(signature);
            if (!".ra4".equals(new String(signature, StandardCharsets.US_ASCII))) {
                LOGGER.debug("Invalid RealAudio 2.0 signature \"{}\"",
                        new String(signature, StandardCharsets.US_ASCII));
                return false;
            }
            reportedDataSize = buffer.getInt();
            buffer.getShort(); //skip version repeated
            reportedHeaderSize = buffer.getInt();

            buffer = ByteBuffer.allocate(reportedHeaderSize);
            channel.read(buffer);
            buffer.flip();
            buffer.getShort(); // skip codec flavor
            buffer.getInt(); // skip coded frame size
            buffer.getInt(); // skip unknown
            long bytesPerMinute = buffer.getInt() & 0xFFFFFFFFL;
            buffer.getInt(); // skip unknown
            buffer.getShort(); // skip sub packet
            buffer.getShort(); // skip frame size
            buffer.getShort(); // skip sub packet size
            buffer.getShort(); // skip unknown
            if (version == 5) {
                buffer.position(buffer.position() + 6); // skip unknown
            }
            short sampleRate = buffer.getShort();
            buffer.getShort(); // skip unknown
            short sampleSize = buffer.getShort();
            short nrChannels = buffer.getShort();
            byte[] fourCC;
            if (version == 4) {
                buffer.position(buffer.get() + buffer.position()); // skip interleaver id
                fourCC = new byte[buffer.get()];
                buffer.get(fourCC);
            } else {
                buffer.getFloat(); // skip deinterlace id
                fourCC = new byte[4];
                buffer.get(fourCC);
            }
            String fourCCString = new String(fourCC, StandardCharsets.US_ASCII).toLowerCase(Locale.ROOT);
            switch (fourCCString) {
            case "lpcJ":
                audio.setCodecA(FormatConfiguration.REALAUDIO_14_4);
                break;
            case "28_8":
                audio.setCodecA(FormatConfiguration.REALAUDIO_28_8);
                break;
            case "dnet":
                audio.setCodecA(FormatConfiguration.AC3);
                break;
            case "sipr":
                audio.setCodecA(FormatConfiguration.SIPRO);
                break;
            case "cook":
                audio.setCodecA(FormatConfiguration.COOK);
            case "atrc":
                audio.setCodecA(FormatConfiguration.ATRAC);
            case "ralf":
                audio.setCodecA(FormatConfiguration.RALF);
            case "raac":
                audio.setCodecA(FormatConfiguration.AAC_LC);
            case "racp":
                audio.setCodecA(FormatConfiguration.HE_AAC);
            default:
                LOGGER.debug("Unknown RealMedia codec FourCC \"{}\" - parsing failed", fourCCString);
                return false;
            }

            if (buffer.hasRemaining()) {
                parseRealAudioMetaData(buffer, audio, version);
            }

            audio.setBitRate((int) (bytesPerMinute * 8 / 60));
            media.setBitrate((int) (bytesPerMinute * 8 / 60));
            audio.setBitsperSample(sampleSize);
            audio.getAudioProperties().setNumberOfChannels(nrChannels);
            audio.getAudioProperties().setSampleFrequency(sampleRate);
        } else {
            LOGGER.error("Could not parse RealAudio format - unknown format version {}", version);
            return false;
        }

        media.getAudioTracksList().add(audio);
        long fileSize = 0;
        if (channel instanceof FileChannel) {
            fileSize = ((FileChannel) channel).size();
            media.setSize(fileSize);
        }
        // Duration is estimated based on bitrate and might not be accurate
        if (audio.getBitRate() > 0) {
            int dataSize;
            if (fileSize > 0 && reportedHeaderSize > 0) {
                int fullHeaderSize = reportedHeaderSize + (version == 3 ? 8 : 16);
                if (reportedDataSize > 0) {
                    dataSize = (int) Math.min(reportedDataSize, fileSize - fullHeaderSize);
                } else {
                    dataSize = (int) (fileSize - fullHeaderSize);
                }
            } else {
                dataSize = reportedDataSize;
            }
            media.setDuration((double) dataSize / audio.getBitRate() * 8);
        }

    } catch (IOException e) {
        LOGGER.debug("Error while trying to parse RealAudio version 1 or 2: {}", e.getMessage());
        LOGGER.trace("", e);
        return false;
    }
    if (PMS.getConfiguration() != null
            && !PMS.getConfiguration().getAudioThumbnailMethod().equals(CoverSupplier.NONE)
            && (StringUtils.isNotBlank(media.getFirstAudioTrack().getSongname())
                    || StringUtils.isNotBlank(media.getFirstAudioTrack().getArtist()))) {
        ID3v1Tag tag = new ID3v1Tag();
        if (StringUtils.isNotBlank(media.getFirstAudioTrack().getSongname())) {
            tag.setTitle(media.getFirstAudioTrack().getSongname());
        }
        if (StringUtils.isNotBlank(media.getFirstAudioTrack().getArtist())) {
            tag.setArtist(media.getFirstAudioTrack().getArtist());
        }
        try {
            media.setThumb(DLNAThumbnail.toThumbnail(CoverUtil.get().getThumbnail(tag), 640, 480, ScaleType.MAX,
                    ImageFormat.SOURCE, false));
        } catch (IOException e) {
            LOGGER.error("An error occurred while generating thumbnail for RealAudio source: [\"{}\", \"{}\"]",
                    tag.getFirstTitle(), tag.getFirstArtist());
        }
    }
    media.setThumbready(true);
    media.setMediaparsed(true);

    return true;
}

From source file:com.github.seqware.queryengine.plugins.runners.hbasemr.MRHBasePluginRunner.java

public static List<FeatureSet> convertBase64StrToFeatureSets(final String sourceSets) {
    byte[] data = (byte[]) Base64.decodeBase64(sourceSets);
    ByteBuffer buf = ByteBuffer.wrap(data);
    int numSets = buf.getInt();
    List<FeatureSet> sSets = new ArrayList<FeatureSet>();
    for (int i = 0; i < numSets; i++) {
        // get size of blob
        int bSize = buf.getInt();
        byte[] dst = new byte[bSize];
        buf.get(dst);
        FeatureSet deserialize = SWQEFactory.getSerialization().deserialize(dst, FeatureSet.class);
        sSets.add(deserialize);/*from  w w w .  j a v a 2s.c o  m*/
    }
    return sSets;
}

From source file:com.wandrell.example.swss.test.util.factory.SecureSoapMessages.java

/**
 * Generates the digest value for the SOAP secure header.
 * <p>/*from w w w  . j av  a2s  .c  o m*/
 * This is a codified password, with the help of the date and nonce values.
 * Both of these values should be found on the SOAP secure header.
 *
 * @param password
 *            password to digest
 * @param date
 *            date used on the SOAP header
 * @param nonce
 *            nonce used on the SOAP header
 * @return the digested password
 * @throws UnsupportedEncodingException
 *             if the UTF-8 encoding is not supported
 */
private static final String generateDigest(final String password, final String date, final String nonce)
        throws UnsupportedEncodingException {
    final ByteBuffer buf; // Buffers storing the data to digest
    byte[] toHash; // Bytes to generate the hash

    // Fills buffer with data to digest
    buf = ByteBuffer.allocate(1000);
    buf.put(Base64.decodeBase64(nonce));
    buf.put(date.getBytes("UTF-8"));
    buf.put(password.getBytes("UTF-8"));

    // Initializes hash bytes to the correct size
    toHash = new byte[buf.position()];
    buf.rewind();

    // Copies bytes from the buffer to the hash bytes
    buf.get(toHash);

    return Base64.encodeBase64String(DigestUtils.sha1(toHash));
}

From source file:mil.nga.giat.geowave.datastore.accumulo.AccumuloDataStore.java

protected static GeowaveRowId getRowIdObject(final byte[] row) {
    final byte[] metadata = Arrays.copyOfRange(row, row.length - 12, row.length);
    final ByteBuffer metadataBuf = ByteBuffer.wrap(metadata);
    final int adapterIdLength = metadataBuf.getInt();
    final int dataIdLength = metadataBuf.getInt();
    final int numberOfDuplicates = metadataBuf.getInt();

    final ByteBuffer buf = ByteBuffer.wrap(row, 0, row.length - 12);
    final byte[] indexId = new byte[row.length - 12 - adapterIdLength - dataIdLength];
    final byte[] adapterId = new byte[adapterIdLength];
    final byte[] dataId = new byte[dataIdLength];
    buf.get(indexId);
    buf.get(adapterId);/*from   www .  j  av a 2s  .  c o m*/
    buf.get(dataId);
    return new GeowaveRowId(indexId, dataId, adapterId, numberOfDuplicates);
}