Example usage for com.google.common.primitives Longs toByteArray

List of usage examples for com.google.common.primitives Longs toByteArray

Introduction

In this page you can find the example usage for com.google.common.primitives Longs toByteArray.

Prototype

public static byte[] toByteArray(long value) 

Source Link

Document

Returns a big-endian representation of value in an 8-element byte array; equivalent to ByteBuffer.allocate(8).putLong(value).array() .

Usage

From source file:io.druid.segment.data.TableLongEncodingWriter.java

@Override
public void putMeta(OutputStream metaOut, CompressedObjectStrategy.CompressionStrategy strategy)
        throws IOException {
    metaOut.write(CompressionFactory.setEncodingFlag(strategy.getId()));
    metaOut.write(CompressionFactory.LongEncodingFormat.TABLE.getId());
    metaOut.write(CompressionFactory.TABLE_ENCODING_VERSION);
    metaOut.write(Ints.toByteArray(table.size()));
    BiMap<Integer, Long> inverse = table.inverse();
    for (int i = 0; i < table.size(); i++) {
        metaOut.write(Longs.toByteArray(inverse.get(i)));
    }// www .  j a  v  a  2  s  .c o m
}

From source file:org.onosproject.ipfix.PortStatsListener.java

@Override
public void event(DeviceEvent event) {

    Device device = event.subject();/*from   ww w.j a  v a 2 s  .  c  o  m*/

    switch (event.type()) {
    case PORT_STATS_UPDATED:
        if (ipfixManager.deviceService.getRole(device.id()) == MastershipRole.MASTER) {
            ipfixManager.log.trace("PortStats Updated: I am MASTER for deviceId={}", device.id().toString());

            List<DataRecord> recordsInList = new ArrayList<DataRecord>();
            List<DataRecord> recordsOutList = new ArrayList<DataRecord>();

            IpAddress exporterIpv4 = IpAddress
                    .valueOf(device.annotations().toString().split("=")[2].split(":")[0]);
            long dpid = Dpid.dpid(device.id().uri()).value();
            byte[] byteExporterIpv6 = new byte[16];
            System.arraycopy(Longs.toByteArray(0), 0, byteExporterIpv6, 0, 8);
            System.arraycopy(Longs.toByteArray(dpid), 0, byteExporterIpv6, 8, 8);
            Ip6Address exporterIpv6 = Ip6Address.valueOf(byteExporterIpv6);

            for (PortStatistics stat : ipfixManager.deviceService.getPortDeltaStatistics(device.id())) {

                final String format = "PortStatsListener Delta Stats: port={}, pktRx={}, pktTx={},"
                        + "bytesRx={}, bytesTx={}, pktRxDrp={}, pktTxDrp={}, Dur={}.{}";
                ipfixManager.log.trace(format, stat.port(), stat.packetsReceived(), stat.packetsSent(),
                        stat.bytesReceived(), stat.bytesSent(), stat.packetsRxDropped(),
                        stat.packetsTxDropped(), stat.durationSec(), (stat.durationNano() / 1000000));

                long inBytes = stat.bytesReceived();
                long inPackets = stat.packetsReceived();
                long outBytes = stat.bytesSent();
                long outPackets = stat.packetsSent();
                long endTime = System.currentTimeMillis();
                long startTime = endTime - (stat.durationSec() * TimeUnit.SECONDS.toMillis(1)
                        + stat.durationNano() / TimeUnit.MILLISECONDS.toNanos(1));

                DataRecordPortStatsIn recordIn = new DataRecordPortStatsIn(exporterIpv4, exporterIpv6,
                        stat.port(), inBytes, inPackets, startTime, endTime);
                DataRecordPortStatsOut recordOut = new DataRecordPortStatsOut(exporterIpv4, exporterIpv6,
                        stat.port(), outBytes, outPackets, startTime, endTime);

                recordsInList.add(recordIn);
                recordsOutList.add(recordOut);
            }

            if (recordsInList.isEmpty() && recordsOutList.isEmpty()) {
                ipfixManager.log.trace(
                        "PortStats: Previous PortStats for device={} where zero," + "not sending IPFIX flow",
                        device.id());
            } else {
                TemplateRecord trIn = DataRecordPortStatsIn.portStatsInTemplateRecord();
                TemplateRecord trOut = DataRecordPortStatsOut.portStatsOutTemplateRecord();
                ipfixManager.ipfixSender.sendRecords(trIn, recordsInList, dpid, IpfixManager.collectorIp,
                        IpfixManager.collectorPort);
                ipfixManager.ipfixSender.sendRecords(trOut, recordsOutList, dpid, IpfixManager.collectorIp,
                        IpfixManager.collectorPort);
            }
        }
        break;

    default:
        break;
    }
}

From source file:se.sics.datamodel.client.ycsb.DataModel.java

private Triplet<ByteId, ByteId, ByteId> getObjId(String key) {
    Long lkey = Long.parseLong(key);
    byte[] byteKey = Longs.toByteArray(lkey);
    if (byteKey.length > 8) {
        throw new RuntimeException("" + byteKey.length);
    }/*from w  w  w .ja v  a 2  s. c  o m*/
    byte[] bkey = new byte[9];
    bkey[0] = (byte) 8;
    System.arraycopy(byteKey, 0, bkey, 9 - byteKey.length, byteKey.length);
    return typeId.add(new ByteId(bkey));
}

From source file:com.heliosapm.streams.serialization.TimeWindowLongValueSerde.java

/**
 * {@inheritDoc}/* w  w w  . j ava  2 s.c  o m*/
 * @see org.apache.kafka.common.serialization.Serializer#serialize(java.lang.String, java.lang.Object)
 */
@Override
public byte[] serialize(final String topic, final long[] data) {
    if (data == null)
        throw new IllegalArgumentException("SER: The passed data was null");
    if (data.length != 3)
        throw new IllegalArgumentException(
                "SER: The passed data length was expected to be 3 but was [" + data.length + "]");

    return Bytes.concat(Longs.toByteArray(data[0]), Longs.toByteArray(data[1]), Longs.toByteArray(data[2]));
}

From source file:org.onosproject.ipfix.DataRecordPortStatsIn.java

@Override
public byte[] getBytes() throws HeaderException {
    try {/*ww  w  .j  a v a2 s . co m*/
        byte[] data = new byte[LENGTH];

        System.arraycopy(exporterIPv4Address.toOctets(), 0, data, 0, 4);
        System.arraycopy(exporterIPv6Address.toOctets(), 0, data, 4, 16);
        System.arraycopy(Ints.toByteArray(ingressInterface), 0, data, 20, 4);
        System.arraycopy(Longs.toByteArray(octetDeltaCount), 0, data, 24, 8);
        System.arraycopy(Longs.toByteArray(packetDeltaCount), 0, data, 32, 8);
        System.arraycopy(Longs.toByteArray(flowStartMilliseconds), 0, data, 40, 8);
        System.arraycopy(Longs.toByteArray(flowEndMilliseconds), 0, data, 48, 8);

        return data;
    } catch (Exception e) {
        throw new HeaderException("Error while generating the bytes: " + e.getMessage());
    }
}

From source file:org.onosproject.ipfix.DataRecordPortStatsOut.java

@Override
public byte[] getBytes() throws HeaderException {
    try {/*from  w w w  .  j a v a 2  s. co  m*/
        byte[] data = new byte[LENGTH];

        System.arraycopy(exporterIPv4Address.toOctets(), 0, data, 0, 4);
        System.arraycopy(exporterIPv6Address.toOctets(), 0, data, 4, 16);
        System.arraycopy(Ints.toByteArray(egressInterface), 0, data, 20, 4);
        System.arraycopy(Longs.toByteArray(octetDeltaCount), 0, data, 24, 8);
        System.arraycopy(Longs.toByteArray(packetDeltaCount), 0, data, 32, 8);
        System.arraycopy(Longs.toByteArray(flowStartMilliseconds), 0, data, 40, 8);
        System.arraycopy(Longs.toByteArray(flowEndMilliseconds), 0, data, 48, 8);

        return data;
    } catch (Exception e) {
        throw new HeaderException("Error while generating the bytes: " + e.getMessage());
    }
}

From source file:com.subitarius.domain.License.java

@Transient
@Override/*from w  w  w.j a v a 2  s  .  c  o m*/
public byte[] getBytes() {
    byte[] idBytes = getIdBytes();
    byte[] teamBytes = team.getIdBytes();
    // XOR all MACs together to prevent the order from affecting the hash
    long macBytes = 0;
    for (long mac : macAddresses) {
        macBytes ^= mac;
    }
    return DistributedEntity.merge(idBytes, teamBytes, Longs.toByteArray(macBytes));
}

From source file:sx.kenji.sharpserializerjvm.write.BinaryWriter.java

private void writeValueCore(Object value) throws IOException {
    if (value == null) {
        logger.error("Cannot write null value!%n");
        return;//from   w w  w.  j  ava  2  s  . co m
    }

    if (value instanceof byte[] || value instanceof Byte[]) {
        writeNumber(Array.getLength(value));
        out.write(unboxBytes(value));
        return;
    }

    if (value instanceof String) {
        writeString((String) value);
        return;
    }

    if (value instanceof Boolean) {
        out.writeBoolean((boolean) value);
        return;
    }

    if (value instanceof Byte) {
        out.writeByte((byte) value);
        return;
    }

    if (value instanceof Character) {
        out.writeChar((char) value);
        return;
    }

    if (value instanceof UUID) {
        UUID uuid = (UUID) value;
        byte[] guid = new byte[16];
        long mostSig = uuid.getMostSignificantBits();
        long leastSig = uuid.getLeastSignificantBits();
        byte[] ms = Longs.toByteArray(mostSig);
        byte[] ls = Longs.toByteArray(leastSig);
        int a = Integer.reverseBytes(ByteBuffer.wrap(ms).getInt(0));
        System.arraycopy(Ints.toByteArray(a), 0, guid, 0, 4);
        guid[4] = ms[5];
        guid[5] = ms[4];
        guid[6] = ms[7];
        guid[7] = ms[6];
        System.arraycopy(ls, 0, guid, 8, 8);

        out.write(guid);
        return;
    }

    if (value instanceof Double) {
        out.writeDouble((double) value);
        return;
    }

    if (value instanceof Short) {
        out.writeShort((short) value);
        return;
    }

    if (value instanceof Integer) {
        out.writeInt((int) value);
        return;
    }

    if (value instanceof UnsignedInteger) {
        out.writeInt(((UnsignedInteger) value).intValue());
        return;
    }

    if (value instanceof Long) {
        out.writeLong((long) value);
        return;
    }

    if (value instanceof Float) {
        out.writeFloat((float) value);
        return;
    }

    if (value.getClass().isEnum()) {
        int ordinal;
        Class cls = value.getClass();

        try {
            Field nField = cls.getField("n");
            ordinal = nField.getInt(value);
            out.writeInt(ordinal);
            return;
        } catch (NoSuchFieldException | IllegalAccessException ignored) {
        }

        Object[] constants = cls.getEnumConstants();
        for (int i = 0; i < constants.length; i++) {
            if (value == constants[i]) {
                out.writeInt(i);
                return;
            }
        }

        logger.error("Supposed enum value couldn't be " + "matched with any enum constants.");

        return;
    }

    if (value instanceof CSharpType) {
        writeString(((CSharpType) value).type);
        return;
    }

    if (value instanceof Class) {
        logger.error("Trying to write Class type unimplemented.");
        return;
    }

    logger.error("Don't know how to write object of type `{}`.", value.getClass().getSimpleName());
}

From source file:org.apache.gobblin.converter.objectstore.ObjectStoreDeleteConverter.java

@Override
public Iterable<ObjectStoreDeleteOperation> convertRecord(Class<?> outputSchema, GenericRecord inputRecord,
        WorkUnitState workUnit) throws DataConversionException {
    Optional<Object> fieldValue = AvroUtils.getFieldValue(inputRecord, this.objectIdField);
    byte[] objectId;
    if (fieldValue.isPresent()) {
        if (fieldValue.get() instanceof Utf8) {
            objectId = ((Utf8) fieldValue.get()).getBytes();
        } else if (fieldValue.get() instanceof String) {
            objectId = ((String) fieldValue.get()).getBytes(Charsets.UTF_8);
        } else if (fieldValue.get() instanceof Long) {
            objectId = Longs.toByteArray((Long) fieldValue.get());
        } else if (fieldValue.get() instanceof Integer) {
            objectId = Ints.toByteArray((Integer) fieldValue.get());
        } else {//  www  .j a v a2s.c  om
            objectId = (byte[]) fieldValue.get();
        }
        return new SingleRecordIterable<ObjectStoreDeleteOperation>(
                ObjectStoreOperationBuilder.deleteBuilder().withObjectId(objectId).build());
    } else {
        throw new DataConversionException(
                String.format("Object Id field %s not found in record %s", this.objectIdField, inputRecord));
    }
}

From source file:org.voltdb.VoltSystemProcedure.java

/**
 * Since sysprocs still use long fragids in places (rather than sha1 hashes),
 * provide a utility method to convert between longs and hashes. This method
 * is the inverse of {@link VoltSystemProcedure#hashToFragId(byte[])}.
 *
 * @param fragId 8 bytes of frag id/* w  w w .  j  a  va2s  . com*/
 * @return 20 bytes of hash padded with 12 empty bytes
 */
public static byte[] fragIdToHash(long fragId) {
    // use 12 bytes to pad the fake 20-byte sha1 hash after the 8-byte long
    return ArrayUtils.addAll(Longs.toByteArray(fragId), new byte[12]);
}