Example usage for java.nio ByteBuffer array

List of usage examples for java.nio ByteBuffer array

Introduction

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

Prototype

public final byte[] array() 

Source Link

Document

Returns the byte array which this buffer is based on, if there is one.

Usage

From source file:cn.ac.ncic.mastiff.io.coding.DictionaryBitPackingRLEIntReader.java

@Override
public byte[] ensureDecompressed() throws IOException {
    FlexibleEncoding.ORC.DynamicByteArray dynamicBuffer = new FlexibleEncoding.ORC.DynamicByteArray();
    dynamicBuffer.add(inBuf.getData(), 12, inBuf.getLength() - 12);
    ByteBuffer byteBuf = ByteBuffer.allocate(dynamicBuffer.size());
    dynamicBuffer.setByteBuffer(byteBuf, 0, dynamicBuffer.size());
    byteBuf.flip();//from  w w  w . j a v a2  s  . co  m
    DataInputBuffer dib = new DataInputBuffer();
    dib.reset(byteBuf.array(), 0, byteBuf.array().length);
    int dictionarySize = dib.readInt();
    int OnlydictionarySize = dib.readInt();
    dib.reset(byteBuf.array(), 8, dictionarySize - 4);
    byte[] dictionaryBuffer = dib.getData();
    dib.reset(byteBuf.array(), 4 + dictionarySize, (byteBuf.array().length - dictionarySize - 4));
    byte[] dictionaryId = dib.getData();
    dib.close();
    DictionaryValuesReader cr = initDicReader(OnlydictionarySize, dictionaryBuffer,
            PrimitiveType.PrimitiveTypeName.INT32);
    cr.initFromPage(numPairs, dictionaryId, 0);
    DataOutputBuffer decoding = new DataOutputBuffer();
    decoding.writeInt(decompressedSize);
    decoding.writeInt(numPairs);
    decoding.writeInt(startPos);
    for (int i = 0; i < numPairs; i++) {
        int tmp = cr.readInteger();
        decoding.writeInt(tmp);
    }
    byteBuf.clear();
    inBuf.close();
    return decoding.getData();
}

From source file:cn.ac.ncic.mastiff.io.coding.DictionaryBitPackingRLEByteReader.java

@Override
public byte[] ensureDecompressed() throws IOException {
    FlexibleEncoding.ORC.DynamicByteArray dynamicBuffer = new FlexibleEncoding.ORC.DynamicByteArray();
    dynamicBuffer.add(inBuf.getData(), 12, inBuf.getLength() - 12);
    ByteBuffer byteBuf = ByteBuffer.allocate(dynamicBuffer.size());
    dynamicBuffer.setByteBuffer(byteBuf, 0, dynamicBuffer.size());
    byteBuf.flip();//from  w  ww  .  j ava2s  . c  o  m
    DataInputBuffer dib = new DataInputBuffer();
    dib.reset(byteBuf.array(), 0, byteBuf.array().length);
    int dictionarySize = dib.readInt();
    int OnlydictionarySize = dib.readInt();
    dib.reset(byteBuf.array(), 8, dictionarySize - 4);
    byte[] dictionaryBuffer = dib.getData();
    dib.reset(byteBuf.array(), 4 + dictionarySize, (byteBuf.array().length - dictionarySize - 4));
    byte[] dictionaryId = dib.getData();
    dib.close();
    DictionaryValuesReader cr = initDicReader(OnlydictionarySize, dictionaryBuffer,
            PrimitiveType.PrimitiveTypeName.BINARY);
    cr.initFromPage(numPairs, dictionaryId, 0);
    DataOutputBuffer decoding = new DataOutputBuffer();
    decoding.writeInt(decompressedSize);
    decoding.writeInt(numPairs);
    decoding.writeInt(startPos);
    for (int i = 0; i < numPairs; i++) {
        byte tmp = Byte.parseByte(cr.readBytes().toStringUsingUTF8());
        decoding.writeInt(tmp);
    }
    byteBuf.clear();
    inBuf.close();
    return decoding.getData();

}

From source file:cn.ac.ncic.mastiff.io.coding.DictionaryBitPackingRLEIntReader.java

public byte[] CompressensureDecompressed() throws IOException {
    FlexibleEncoding.ORC.DynamicByteArray dynamicBuffer = new FlexibleEncoding.ORC.DynamicByteArray();
    dynamicBuffer.add(inBuf.getData(), 0, inBuf.getLength());
    ByteBuffer byteBuf = ByteBuffer.allocate(dynamicBuffer.size());
    dynamicBuffer.setByteBuffer(byteBuf, 0, dynamicBuffer.size());
    byteBuf.flip();/*from ww  w  .j a  va2  s.  co  m*/
    DataInputBuffer dib = new DataInputBuffer();
    dib.reset(byteBuf.array(), 0, byteBuf.array().length);
    int dictionarySize = dib.readInt();
    int OnlydictionarySize = dib.readInt();
    dib.reset(byteBuf.array(), 8, dictionarySize - 4);
    byte[] dictionaryBuffer = dib.getData();
    dib.reset(byteBuf.array(), 4 + dictionarySize, (byteBuf.array().length - dictionarySize - 4));
    byte[] dictionaryId = dib.getData();
    dib.close();
    DictionaryValuesReader cr = initDicReader(OnlydictionarySize, dictionaryBuffer,
            PrimitiveType.PrimitiveTypeName.INT32);
    cr.initFromPage(numPairs, dictionaryId, 0);
    DataOutputBuffer decoding = new DataOutputBuffer();
    decoding.writeInt(decompressedSize);
    decoding.writeInt(numPairs);
    decoding.writeInt(startPos);
    for (int i = 0; i < numPairs; i++) {
        int tmp = cr.readInteger();
        decoding.writeInt(tmp);
    }
    byteBuf.clear();

    inBuf.close();
    return decoding.getData();

}

From source file:au.org.ala.delta.io.BinFile.java

protected byte[] readBytes(int count) {
    ByteBuffer b = readByteBuffer(count);
    _stats.ReadBytes++;//  w w w .j av a2s  . c  o  m
    return b.array();
}

From source file:mobisocial.musubi.nearby.scanner.GpsScannerTask.java

@Override
protected List<NearbyItem> doInBackground(Void... params) {
    if (DBG)/*from w  w  w .ja v  a  2  s .  c o  m*/
        Log.d(TAG, "Scanning for nearby gps...");
    while (!mmLocationScanComplete) {
        synchronized (mmLocationResult) {
            if (!mmLocationScanComplete) {
                try {
                    if (DBG)
                        Log.d(TAG, "Waiting for location results...");
                    mmLocationResult.wait();
                } catch (InterruptedException e) {
                }
            }
        }
    }
    if (DBG)
        Log.d(TAG, "Got location " + mmLocation);
    if (isCancelled()) {
        return null;
    }

    try {
        if (DBG)
            Log.d(TAG, "Querying gps server...");
        Uri uri = Uri.parse("http://bumblebee.musubi.us:6253/nearbyapi/0/findgroup");

        StringBuffer sb = new StringBuffer();
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(uri.toString());
        httpPost.addHeader("Content-Type", "application/json");
        JSONArray buckets = new JSONArray();

        double lat = mmLocation.getLatitude();
        double lng = mmLocation.getLongitude();

        long[] coords = GridHandler.getGridCoords(lat, lng, 5280 / 2);
        Log.i(TAG, "coords: " + Arrays.toString(coords));

        //TODO: encrypt coords with mmPassword

        for (long c : coords) {
            MessageDigest md;
            try {
                byte[] obfuscate = ("sadsalt193s" + mmPassword).getBytes();
                md = MessageDigest.getInstance("SHA-256");
                ByteBuffer b = ByteBuffer.allocate(8 + obfuscate.length);
                b.putLong(c);
                b.put(obfuscate);
                String secret_bucket = Base64.encodeToString(md.digest(b.array()), Base64.DEFAULT);
                buckets.put(buckets.length(), secret_bucket);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("your platform does not support sha256", e);
            }
        }
        Log.i(TAG, "buckets: " + buckets);
        httpPost.setEntity(new StringEntity(buckets.toString()));
        try {
            HttpResponse execute = client.execute(httpPost);
            InputStream content = execute.getEntity().getContent();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
            String s = "";
            while ((s = buffer.readLine()) != null) {
                if (isCancelled()) {
                    return null;
                }
                sb.append(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashSet<Pair<TByteArrayList, TByteArrayList>> dupes = new HashSet<Pair<TByteArrayList, TByteArrayList>>();

        String response = sb.toString();
        JSONArray groupsJSON = new JSONArray(response);
        Log.d(TAG, "Got " + groupsJSON.length() + " groups");
        for (int i = 0; i < groupsJSON.length(); i++) {
            try {
                String s_enc_data = groupsJSON.get(i).toString();
                byte[] enc_data = Base64.decode(s_enc_data, Base64.DEFAULT);
                byte[] key = Util.sha256(("happysalt621" + mmPassword).getBytes());
                byte[] data;

                Cipher cipher;
                AlgorithmParameterSpec iv_spec;
                SecretKeySpec sks;
                try {
                    cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
                } catch (Exception e) {
                    throw new RuntimeException("AES not supported on this platform", e);
                }
                try {
                    iv_spec = new IvParameterSpec(enc_data, 0, 16);
                    sks = new SecretKeySpec(key, "AES");
                    cipher.init(Cipher.DECRYPT_MODE, sks, iv_spec);
                } catch (Exception e) {
                    throw new RuntimeException("bad iv or key", e);
                }
                try {
                    data = cipher.doFinal(enc_data, 16, enc_data.length - 16);
                } catch (Exception e) {
                    throw new RuntimeException("body decryption failed", e);
                }

                JSONObject group = new JSONObject(new String(data));

                String group_name = group.getString("group_name");
                byte[] group_capability = Base64.decode(group.getString("group_capability"), Base64.DEFAULT);
                String sharer_name = group.getString("sharer_name");
                byte[] sharer_hash = Base64.decode(group.getString("sharer_hash"), Base64.DEFAULT);
                byte[] thumbnail = null;
                if (group.has("thumbnail"))
                    thumbnail = Base64.decode(group.getString("thumbnail"), Base64.DEFAULT);
                int member_count = group.getInt("member_count");
                int sharer_type = group.getInt("sharer_type");
                Pair<TByteArrayList, TByteArrayList> p = Pair.with(new TByteArrayList(sharer_hash),
                        new TByteArrayList(group_capability));
                if (dupes.contains(p))
                    continue;
                dupes.add(p);
                addNearbyItem(new NearbyFeed(mContext, group_name, group_capability, sharer_name,
                        Authority.values()[sharer_type], sharer_hash, thumbnail, member_count));
            } catch (Throwable e) {
                Log.e(TAG, "Failed to parse group " + i, e);
            }
        }
    } catch (Exception e) {
        if (DBG)
            Log.d(TAG, "Error searching nearby feeds", e);
    }
    return null;
}

From source file:com.buaa.cfs.nfs3.WriteCtx.java

public void writeData(DataOutputStream fos) throws IOException {
    Preconditions.checkState(fos != null);

    ByteBuffer dataBuffer;
    try {//ww  w . j a  v  a 2s  .  com
        dataBuffer = getData();
    } catch (Exception e1) {
        LOG.error("Failed to get request data offset:" + offset + " count:" + count + " error:" + e1);
        throw new IOException("Can't get WriteCtx.data");
    }

    byte[] data = dataBuffer.array();
    int position = dataBuffer.position();
    int limit = dataBuffer.limit();
    Preconditions.checkState(limit - position == count);
    // Modified write has a valid original count
    if (position != 0) {
        if (limit != getOriginalCount()) {
            throw new IOException("Modified write has differnt original size." + "buff position:" + position
                    + " buff limit:" + limit + ". " + toString());
        }
    }

    // Now write data
    //        fos.write(data, position, count);
}

From source file:com.l2jfree.gameserver.network.L2Client.java

@Override
public boolean decrypt(ByteBuffer buf, int size) {
    getCrypt().decrypt(buf.array(), buf.position(), size);
    return true;/* w  ww .java 2  s. co m*/
}

From source file:com.rackspacecloud.blueflood.io.serializers.SerializationTest.java

@Test
public void testRollupSerializationAndDeserialization() throws IOException {
    // works the same way as testFullResSerializationAndDeserialization

    if (System.getProperty("GENERATE_ROLLUP_SERIALIZATION") != null) {
        OutputStream os = new FileOutputStream(
                "src/test/resources/serializations/rollup_version_" + Constants.VERSION_1_ROLLUP + ".bin",
                false);//from   w  w  w.  ja  va 2 s  .c o m
        for (BasicRollup basicRollup : TO_SERIALIZE_BASIC_ROLLUP) {
            ByteBuffer bb = NumericSerializer.serializerFor(BasicRollup.class).toByteBuffer(basicRollup);
            os.write(Base64.encodeBase64(bb.array()));
            os.write("\n".getBytes());
        }
        os.close();
    }

    Assert.assertTrue(new File("src/test/resources/serializations").exists());

    // ensure we can read historical serializations.
    int version = 0;
    int maxVersion = Constants.VERSION_1_ROLLUP;
    while (version <= maxVersion) {
        BufferedReader reader = new BufferedReader(
                new FileReader("src/test/resources/serializations/rollup_version_" + version + ".bin"));
        for (int i = 0; i < TO_SERIALIZE_BASIC_ROLLUP.length; i++) {
            for (Granularity g : Granularity.rollupGranularities()) {
                ByteBuffer bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
                BasicRollup basicRollup = (BasicRollup) NumericSerializer.serializerFor(BasicRollup.class)
                        .fromByteBuffer(bb);
                Assert.assertTrue(String.format("Deserialization for rollup broken at %d", version),
                        TO_SERIALIZE_BASIC_ROLLUP[i].equals(basicRollup));
            }
            version += 1;
        }
    }

    // current round tripping.
    for (BasicRollup basicRollup : TO_SERIALIZE_BASIC_ROLLUP) {
        for (Granularity g : Granularity.rollupGranularities()) {
            ByteBuffer bb = NumericSerializer.serializerFor(BasicRollup.class).toByteBuffer(basicRollup);
            Assert.assertTrue(
                    basicRollup.equals(NumericSerializer.serializerFor(BasicRollup.class).fromByteBuffer(bb)));
        }
    }
}

From source file:idgs.client.SocketChannelHandler.java

/**
 * handle connect/*from   w  ww  .  j a v a2s  .c  om*/
 * @throws IOException
 */
public void onConnected(SocketChannel channel) throws IOException {
    ClientLogin login = new ClientLogin();
    ByteBuffer buffer = login.toBuffer();
    buffer.flip();
    int writeClientLoginSize = channel.write(buffer);
    if (writeClientLoginSize > 0) {
        log.debug("writer client login content: " + new String(login.toString()));
        log.debug("byte size: " + writeClientLoginSize + ", order by " + RpcBuffer.DEFAULT_BYTE_ORDER.toString()
                + " bytes: " + Arrays.toString(buffer.array()));
    }
}

From source file:at.treedb.jslib.JsLib.java

/**
 * Returns the binary data of an archive entry.
 * /*w w w .j a  va 2  s.  com*/
 * @param path
 *            archive path
 * @return binary data
 * @throws IOException
 */
public byte[] getArchiveEntry(String path) throws IOException {
    if (!archiveMap.containsKey(path)) {
        return null;
    }
    byte[] data = fileCache.get(path);
    if (data == null) {
        ArchiveEntry e = archiveMap.get(path);
        ByteBuffer buf = ByteBuffer.allocate(e.getLength());
        inChannel.read(buf, e.getOffset());
        data = buf.array();
        fileCache.put(path, data);
    }
    return data;
}