Example usage for java.nio ByteBuffer putLong

List of usage examples for java.nio ByteBuffer putLong

Introduction

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

Prototype

public abstract ByteBuffer putLong(long value);

Source Link

Document

Writes the given long to the current position and increases the position by 8.

Usage

From source file:org.apache.bookkeeper.bookie.EntryLogTest.java

private ByteBuffer generateEntry(long ledger, long entry) {
    byte[] data = ("ledger-" + ledger + "-" + entry).getBytes();
    ByteBuffer bb = ByteBuffer.wrap(new byte[8 + 8 + data.length]);
    bb.putLong(ledger);
    bb.putLong(entry);//from   ww  w. ja  v a 2  s.co  m
    bb.put(data);
    bb.flip();
    return bb;
}

From source file:com.alibaba.napoli.metamorphosis.client.consumer.RecoverStorageManager.java

@Override
public void append(final String group, final Message message) throws IOException {
    final Store store = this.getOrCreateStore(message.getTopic(), group);
    long key = message.getId();
    IOException error = null;/*  w w  w.j a  v a 2s . c o m*/
    for (int i = 0; i < 5; i++) {
        try {
            final ByteBuffer buf = ByteBuffer.allocate(16);
            buf.putLong(key);
            store.add(buf.array(), this.serializer.encodeObject(message));
            return;
        } catch (final IOException e) {
            final String msg = e.getMessage();
            // key??
            if (msg.contains("??")) {
                error = e;
                log.warn("recover store,key=" + key + "," + e.getMessage() + ",retry...");
                key += this.count.incrementAndGet();
            } else {
                throw e;
            }
        }
    }

    if (error != null) {
        throw error;
    }

}

From source file:org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6FlowMod.java

/**
 * This method forms the Vendor extension IPv6 Flow Mod message.It uses the
 * fields in V6FlowMod class, and writes the data according to vendor 
 * extension format. The fields include flow properties (cookie, timeout,
 * priority, etc), flow match, and action list. It also takes care of 
 * required padding./*from w  w  w . j  a  v  a 2 s.  c om*/
 */

@Override
public void writeTo(ByteBuffer data) {
    super.writeTo(data);
    data.putInt(getIPv6ExtensionFlowModAddSubType());
    data.putLong(this.cookie);
    data.putShort(command); /* should be OFPFC_ADD, OFPFC_DELETE_STRICT, etc*/
    data.putShort(this.idleTimeout);
    data.putShort(this.hardTimeout);
    data.putShort(this.priority);
    data.putInt(OFPacketOut.BUFFER_ID_NONE);
    data.putShort(outPort); /* output_port */
    data.putShort(flags); /* flags */
    match_len = this.match.getIPv6MatchLen();
    data.putShort(match_len);
    byte[] pad = new byte[6];
    data.put(pad);
    this.match.writeTo(data);

    pad_size = (short) (((match_len + 7) / 8) * 8 - match_len);

    /*
     * action list should be preceded by a padding of 0 to 7 bytes based upon
     * above formula.
     */

    byte[] pad2 = new byte[pad_size];
    data.put(pad2);
    if (actions != null) {
        for (OFAction action : actions) {
            actions_len += action.getLength();
            action.writeTo(data);
        }
    }
    logger.trace("{}", this);
}

From source file:io.warp10.quasar.encoder.QuasarTokenEncoder.java

private ByteBuffer toByteBuffer(String strUUID) {
    ByteBuffer buffer = ByteBuffer.allocate(16);
    buffer.order(ByteOrder.BIG_ENDIAN);

    UUID uuid = UUID.fromString(strUUID);

    buffer.putLong(uuid.getMostSignificantBits());
    buffer.putLong(uuid.getLeastSignificantBits());

    buffer.position(0);//from ww  w  . ja v  a  2 s .c  om
    return buffer;
}

From source file:com.alibaba.napoli.metamorphosis.client.extension.producer.LocalMessageStorageManager.java

@Override
public void append(final Message message, final Partition partition) throws IOException {
    final Store store = this.getOrCreateStore(message.getTopic(), partition);
    final ByteBuffer buf = ByteBuffer.allocate(16);
    buf.putLong(this.idWorker.nextId());
    store.add(buf.array(), this.serializer.encodeObject(message));
}

From source file:com.alibaba.jstorm.utils.JStormUtils.java

public static byte[] longToBytes(long x) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE);
    buffer.putLong(x);
    return buffer.array();
}

From source file:org.bimserver.webservices.authorization.Authorization.java

public String asHexToken(Key key) {
    try {/*from  w  w w  . ja va  2 s  .c o m*/
        Cipher encodingCipher = Cipher.getInstance("AES");
        encodingCipher.init(Cipher.ENCRYPT_MODE, key);

        ByteBuffer buffer = ByteBuffer.allocate(16 + 1 + 8 + 8 + getBufferSize());
        buffer.position(16);
        buffer.put(getId());
        buffer.putLong(getExpires().getTimeInMillis());
        buffer.putLong(getUoid());
        getBytes(buffer);
        if (buffer.position() != buffer.capacity()) {
            throw new RuntimeException(
                    "Buffer's position should be at the end " + buffer.position() + "/" + buffer.capacity());
        }
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        buffer.position(16);
        messageDigest.update(buffer);
        buffer.position(0);
        buffer.put(messageDigest.digest());

        byte[] encodedBytes = encodingCipher.doFinal(buffer.array());
        String encodedHexString = new String(Hex.encodeHex(encodedBytes));
        return encodedHexString;
    } catch (Exception e) {
        LOGGER.error("", e);
    }
    return null;
}

From source file:com.sm.connector.server.ServerStore.java

public void writeExistBlock(CacheBlock<byte[]> block) throws IOException {
    ByteBuffer dataBuf = ByteBuffer.wrap(block.getData());
    // don't use flip() before it write when use wrap
    //dataBuf.flip();
    dataChannel.write(dataBuf, block.getDataOffset());
    long pos = OFFSET + (long) block.getRecordNo() * RECORD_SIZE;
    int off = 9;//from  ww w.j  a  v  a2 s.  com
    ByteBuffer buf = ByteBuffer.allocate(RECORD_SIZE - off);
    buf.putLong(block.getDataOffset2Len());
    buf.putLong(block.getBlock2Version());
    buf.putShort(block.getNode());
    // must flip() before it write
    buf.flip();
    indexChannel.write(buf, pos + off);
}

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

@Override
protected List<NearbyItem> doInBackground(Void... params) {
    if (DBG)//from   w ww . java 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:org.wso2.carbon.analytics.datasource.core.util.GenericUtils.java

public static byte[] encodeElement(String name, Object value) throws AnalyticsException {
    ByteBuffer buffer = ByteBuffer.allocate(calculateBufferSizePerElement(name, value));
    String strVal;/*w ww.  j  a v a  2 s  . c  om*/
    boolean boolVal;
    byte[] binData;

    buffer.putInt(name.getBytes(StandardCharsets.UTF_8).length);
    buffer.put(name.getBytes(StandardCharsets.UTF_8));
    if (value instanceof String) {
        buffer.put(DATA_TYPE_STRING);
        strVal = (String) value;
        buffer.putInt(strVal.getBytes(StandardCharsets.UTF_8).length);
        buffer.put(strVal.getBytes(StandardCharsets.UTF_8));
    } else if (value instanceof Long) {
        buffer.put(DATA_TYPE_LONG);
        buffer.putLong((Long) value);
    } else if (value instanceof Double) {
        buffer.put(DATA_TYPE_DOUBLE);
        buffer.putDouble((Double) value);
    } else if (value instanceof Boolean) {
        buffer.put(DATA_TYPE_BOOLEAN);
        boolVal = (Boolean) value;
        if (boolVal) {
            buffer.put(BOOLEAN_TRUE);
        } else {
            buffer.put(BOOLEAN_FALSE);
        }
    } else if (value instanceof Integer) {
        buffer.put(DATA_TYPE_INTEGER);
        buffer.putInt((Integer) value);
    } else if (value instanceof Float) {
        buffer.put(DATA_TYPE_FLOAT);
        buffer.putFloat((Float) value);
    } else if (value instanceof byte[]) {
        buffer.put(DATA_TYPE_BINARY);
        binData = (byte[]) value;
        buffer.putInt(binData.length);
        buffer.put(binData);
    } else if (value == null) {
        buffer.put(DATA_TYPE_NULL);
    } else {
        buffer.put(DATA_TYPE_OBJECT);
        binData = GenericUtils.serializeObject(value);
        buffer.putInt(binData.length);
        buffer.put(binData);
    }

    return buffer.array();
}