Example usage for java.nio ByteBuffer toString

List of usage examples for java.nio ByteBuffer toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representing the state of this byte buffer.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {

    byte[] bytes = new byte[10];
    ByteBuffer buf = ByteBuffer.wrap(bytes);

    System.out.println(Arrays.toString(buf.array()));
    System.out.println(buf.toString());
}

From source file:Main.java

public static void main(String[] argv) throws Exception {

    byte[] bytes = new byte[10];
    ByteBuffer buf = ByteBuffer.wrap(bytes, 0, 4);

    System.out.println(Arrays.toString(buf.array()));
    System.out.println(buf.toString());
}

From source file:Main.java

public static void main(String[] argv) throws Exception {

    byte[] bytes = new byte[10];
    ByteBuffer buf = ByteBuffer.allocate(10);
    buf = ByteBuffer.wrap(bytes);

    System.out.println(Arrays.toString(buf.array()));
    System.out.println(buf.toString());
}

From source file:Main.java

public static void main(String[] argv) throws Exception {

    byte[] bytes = new byte[10];
    ByteBuffer buf = ByteBuffer.allocateDirect(10);
    buf = ByteBuffer.wrap(bytes);

    System.out.println(Arrays.toString(buf.array()));
    System.out.println(buf.toString());
}

From source file:com.stratagis.geoevent.adapter.nmeaplus.NmeaPlusInboundAdapter.java

private static String deviceNameFind(ByteBuffer in) {
    try {/*from   www. j  a v a 2 s  .c o  m*/
        String input = in.toString();
        int i1 = input.indexOf("#");
        int i2 = input.indexOf("#", i1 + 1);

        if (i1 >= 0 && i2 >= 0 && i1 != i2)
            return input.substring(i1, i2);
        else
            return "NotFound";
    } catch (Exception e) {
        LOG.error("Exception while finding device name : " + e.getMessage());
        return "NotFound";
    }
}

From source file:com.albert.util.StringUtilCommon.java

public static boolean isISO88593(String v) {
    if (v == null || v.length() == 0) {
        return true;
    }//from w ww  .j  a va2s. c  om
    CharsetEncoder d = Charset.forName("ISO-8859-3").newEncoder();
    d.onMalformedInput(CodingErrorAction.REPORT);
    d.onUnmappableCharacter(CodingErrorAction.REPORT);
    try {
        ByteBuffer bb = d.encode(CharBuffer.wrap(v.toCharArray()));
        bb.toString();
    } catch (CharacterCodingException e) {
        return false;
    }
    return true;
}

From source file:com.httparchive.dataflow.HarJsonCoder.java

public JsonNode decode(ByteBuffer in) throws IOException {
    try {/* w  ww  .  j  a v a 2  s .c  o  m*/
        return MAPPER.readTree(in.toString());
    } catch (IOException e) {
        System.out.println("Failed to decode HAR: " + e);
        System.out.println(in);
        throw e;
    }
}

From source file:tachyon.master.RawTables.java

/**
 * Update the metadata of the specified raw table. It will check if the table exists.
 *
 * @param tableId The id of the raw table
 * @param metadata The new metadata of the raw table
 * @throws TachyonException/*from w w  w  .  ja  v  a  2  s  . com*/
 */
// TODO add version number.
public synchronized void updateMetadata(int tableId, ByteBuffer metadata) throws TachyonException {
    Pair<Integer, ByteBuffer> data = mData.get(tableId);

    if (null == data) {
        throw new TachyonException("The raw table " + tableId + " does not exist.");
    }

    if (metadata == null) {
        data.setSecond(ByteBuffer.allocate(0));
    } else {
        long maxVal = mTachyonConf.getBytes(Constants.MAX_TABLE_METADATA_BYTE, 0L);
        if (metadata.limit() - metadata.position() >= maxVal) {
            throw new TachyonException("Too big table metadata: " + metadata.toString());
        }
        ByteBuffer tMetadata = ByteBuffer.allocate(metadata.limit() - metadata.position());
        tMetadata.put(metadata.array(), metadata.position(), metadata.limit() - metadata.position());
        tMetadata.flip();
        data.setSecond(tMetadata);
    }
}

From source file:org.apache.hadoop.hive.serde2.compression.SnappyCompDe.java

/**
 * Compress a set of columns.//from   w  w  w .j  a va  2 s.  c o m
 *
 * The header contains a compressed array of data types.
 * The body contains compressed columns and their metadata.
 * The footer contains a compressed array of chunk sizes. The final four bytes of the footer encode the byte size of that compressed array.
 *
 * @param colSet
 *
 * @return ByteBuffer representing the compressed set.
 */
@Override
public ByteBuffer compress(ColumnBuffer[] colSet) {

    // Many compression libraries allow you to avoid allocation of intermediate arrays.
    // To use these API, we need to preallocate the output container.

    // Reserve space for the header.
    int[] dataType = new int[colSet.length];
    int maxCompressedSize = Snappy.maxCompressedLength(4 * dataType.length);

    // Reserve space for the compressed nulls BitSet for each column.
    maxCompressedSize += colSet.length * Snappy.maxCompressedLength((colSet.length / 8) + 1);

    // Track the length of `List<Integer> compressedSize` which will be declared later.
    int uncompressedFooterLength = 1 + 2 * colSet.length;

    for (int colNum = 0; colNum < colSet.length; ++colNum) {
        // Reserve space for the compressed columns.
        dataType[colNum] = colSet[colNum].getType().toTType().getValue();
        switch (TTypeId.findByValue(dataType[colNum])) {
        case BOOLEAN_TYPE:
            maxCompressedSize += Integer.SIZE / Byte.SIZE; // This is for the encoded length.
            maxCompressedSize += Snappy.maxCompressedLength((colSet.length / 8) + 1);
            break;
        case TINYINT_TYPE:
            maxCompressedSize += Snappy.maxCompressedLength(colSet.length);
            break;
        case SMALLINT_TYPE:
            maxCompressedSize += Snappy.maxCompressedLength(colSet.length * Short.SIZE / Byte.SIZE);
            break;
        case INT_TYPE:
            maxCompressedSize += Snappy.maxCompressedLength(colSet.length * Integer.SIZE / Byte.SIZE);
            break;
        case BIGINT_TYPE:
            maxCompressedSize += Snappy.maxCompressedLength(colSet.length * Long.SIZE / Byte.SIZE);
            break;
        case DOUBLE_TYPE:
            maxCompressedSize += Snappy.maxCompressedLength(colSet.length * Double.SIZE / Byte.SIZE);
            break;
        case BINARY_TYPE:
            // Reserve space for the size of the compressed array of row sizes.
            maxCompressedSize += Snappy.maxCompressedLength(colSet.length * Integer.SIZE / Byte.SIZE);

            // Reserve space for the size of the compressed flattened bytes.
            for (ByteBuffer nextBuffer : colSet[colNum].toTColumn().getBinaryVal().getValues()) {
                maxCompressedSize += Snappy.maxCompressedLength(nextBuffer.limit());
            }

            // Add an additional value to the list of compressed chunk sizes (length of `rowSize` array).
            uncompressedFooterLength++;

            break;
        case STRING_TYPE:
            // Reserve space for the size of the compressed array of row sizes.
            maxCompressedSize += Snappy.maxCompressedLength(colSet.length * Integer.SIZE / Byte.SIZE);

            // Reserve space for the size of the compressed flattened bytes.
            for (String nextString : colSet[colNum].toTColumn().getStringVal().getValues()) {
                maxCompressedSize += Snappy
                        .maxCompressedLength(nextString.getBytes(StandardCharsets.UTF_8).length);
            }

            // Add an additional value to the list of compressed chunk sizes (length of `rowSize` array).
            uncompressedFooterLength++;

            break;
        default:
            throw new IllegalStateException("Unrecognized column type");
        }
    }
    // Reserve space for the footer.
    maxCompressedSize += Snappy.maxCompressedLength(uncompressedFooterLength * Integer.SIZE / Byte.SIZE);

    // Allocate the output container.
    ByteBuffer output = ByteBuffer.allocate(maxCompressedSize);

    // Allocate the footer. This goes in the footer because we don't know the chunk sizes until after
    // the columns have been compressed and written.
    ArrayList<Integer> compressedSize = new ArrayList<Integer>(uncompressedFooterLength);

    // Write to the output buffer.
    try {
        // Write the header.
        compressedSize.add(writePrimitives(dataType, output));

        // Write the compressed columns and metadata.
        for (int colNum = 0; colNum < colSet.length; colNum++) {
            switch (TTypeId.findByValue(dataType[colNum])) {
            case BOOLEAN_TYPE: {
                TBoolColumn column = colSet[colNum].toTColumn().getBoolVal();

                List<Boolean> bools = column.getValues();
                BitSet bsBools = new BitSet(bools.size());
                for (int rowNum = 0; rowNum < bools.size(); rowNum++) {
                    bsBools.set(rowNum, bools.get(rowNum));
                }

                compressedSize.add(writePrimitives(column.getNulls(), output));

                // BitSet won't write trailing zeroes so we encode the length
                output.putInt(column.getValuesSize());

                compressedSize.add(writePrimitives(bsBools.toByteArray(), output));

                break;
            }
            case TINYINT_TYPE: {
                TByteColumn column = colSet[colNum].toTColumn().getByteVal();
                compressedSize.add(writePrimitives(column.getNulls(), output));
                compressedSize.add(writeBoxedBytes(column.getValues(), output));
                break;
            }
            case SMALLINT_TYPE: {
                TI16Column column = colSet[colNum].toTColumn().getI16Val();
                compressedSize.add(writePrimitives(column.getNulls(), output));
                compressedSize.add(writeBoxedShorts(column.getValues(), output));
                break;
            }
            case INT_TYPE: {
                TI32Column column = colSet[colNum].toTColumn().getI32Val();
                compressedSize.add(writePrimitives(column.getNulls(), output));
                compressedSize.add(writeBoxedIntegers(column.getValues(), output));
                break;
            }
            case BIGINT_TYPE: {
                TI64Column column = colSet[colNum].toTColumn().getI64Val();
                compressedSize.add(writePrimitives(column.getNulls(), output));
                compressedSize.add(writeBoxedLongs(column.getValues(), output));
                break;
            }
            case DOUBLE_TYPE: {
                TDoubleColumn column = colSet[colNum].toTColumn().getDoubleVal();
                compressedSize.add(writePrimitives(column.getNulls(), output));
                compressedSize.add(writeBoxedDoubles(column.getValues(), output));
                break;
            }
            case BINARY_TYPE: {
                TBinaryColumn column = colSet[colNum].toTColumn().getBinaryVal();

                // Initialize the array of row sizes.
                int[] rowSizes = new int[column.getValuesSize()];
                int totalSize = 0;
                for (int rowNum = 0; rowNum < column.getValuesSize(); rowNum++) {
                    rowSizes[rowNum] = column.getValues().get(rowNum).limit();
                    totalSize += column.getValues().get(rowNum).limit();
                }

                // Flatten the data for Snappy for a better compression ratio.
                ByteBuffer flattenedData = ByteBuffer.allocate(totalSize);
                for (int rowNum = 0; rowNum < column.getValuesSize(); rowNum++) {
                    flattenedData.put(column.getValues().get(rowNum));
                }

                // Write nulls bitmap.
                compressedSize.add(writePrimitives(column.getNulls(), output));

                // Write the list of row sizes.
                compressedSize.add(writePrimitives(rowSizes, output));

                // Write the compressed, flattened data.
                compressedSize.add(writePrimitives(flattenedData.array(), output));

                break;
            }
            case STRING_TYPE: {
                TStringColumn column = colSet[colNum].toTColumn().getStringVal();

                // Initialize the array of row sizes.
                int[] rowSizes = new int[column.getValuesSize()];
                int totalSize = 0;
                for (int rowNum = 0; rowNum < column.getValuesSize(); rowNum++) {
                    rowSizes[rowNum] = column.getValues().get(rowNum).length();
                    totalSize += column.getValues().get(rowNum).length();
                }

                // Flatten the data for Snappy for a better compression ratio.
                StringBuilder flattenedData = new StringBuilder(totalSize);
                for (int rowNum = 0; rowNum < column.getValuesSize(); rowNum++) {
                    flattenedData.append(column.getValues().get(rowNum));
                }

                // Write nulls bitmap.
                compressedSize.add(writePrimitives(column.getNulls(), output));

                // Write the list of row sizes.
                compressedSize.add(writePrimitives(rowSizes, output));

                // Write the flattened data.
                compressedSize.add(
                        writePrimitives(flattenedData.toString().getBytes(StandardCharsets.UTF_8), output));

                break;
            }
            default:
                throw new IllegalStateException("Unrecognized column type");
            }
        }

        // Write the footer.
        output.putInt(writeBoxedIntegers(compressedSize, output));

    } catch (IOException e) {
        e.printStackTrace();
    }
    output.flip();
    return output;
}

From source file:org.hyperic.hq.agent.server.AgentDListProvider.java

protected String getKeyvalsPass()
        throws KeyStoreException, IOException, NoSuchAlgorithmException, UnrecoverableEntryException {
    KeystoreConfig keystoreConfig = new AgentKeystoreConfig();
    KeyStore keystore = KeystoreManager.getKeystoreManager().getKeyStore(keystoreConfig);
    KeyStore.Entry e = keystore.getEntry(keystoreConfig.getAlias(),
            new KeyStore.PasswordProtection(keystoreConfig.getFilePassword().toCharArray()));
    if (e == null) {
        throw new UnrecoverableEntryException("Encryptor password generation failure: No such alias");
    }/* www  .  java 2 s  .  co m*/
    // XXX scottmf - I'm a bit concerned about this.  I tested the upgrade path on the agent on the new code with the
    // ByteBuffer and it doesn't work, the agent throws a org.jasypt.exceptions.EncryptionOperationNotPossibleException.
    // When I put back the old code with the replaceAll() everything works.
    //final String p = ((PrivateKeyEntry)e).getPrivateKey().toString();
    //return p.replaceAll("[^a-zA-Z0-9]", "_");
    byte[] pk = ((PrivateKeyEntry) e).getPrivateKey().getEncoded();
    ByteBuffer encryptionKey = Charset.forName("US-ASCII").encode(ByteBuffer.wrap(pk).toString());
    return encryptionKey.toString();
}