Example usage for java.lang Integer BYTES

List of usage examples for java.lang Integer BYTES

Introduction

In this page you can find the example usage for java.lang Integer BYTES.

Prototype

int BYTES

To view the source code for java.lang Integer BYTES.

Click Source Link

Document

The number of bytes used to represent an int value in two's complement binary form.

Usage

From source file:de.micromata.genome.logging.spi.ifiles.IndexHeader.java

public void writeFileHeader(OutputStream os, File indexFile, IndexDirectory indexDirectory) throws IOException {
    indexDirectoryIdx = indexDirectory.createNewLogIdxFile(indexFile);
    ByteBuffer lbb = ByteBuffer.wrap(new byte[Long.BYTES]);
    ByteBuffer ibb = ByteBuffer.wrap(new byte[Integer.BYTES]);
    os.write(INDEX_FILE_TYPE);//  ww w  . ja v a2s .  c  o m
    os.write(INDEX_FILE_VERSION);
    lbb.putLong(0, System.currentTimeMillis());
    os.write(lbb.array());
    ibb.putInt(0, indexDirectoryIdx);
    os.write(ibb.array());
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    for (Pair<String, Integer> headerp : headerOrder) {
        String hn = StringUtils.rightPad(headerp.getFirst(), HEADER_NAME_LENGTH);
        bout.write(hn.getBytes());
        ibb.putInt(0, headerp.getSecond());
        bout.write(ibb.array());
    }
    byte[] headerar = bout.toByteArray();
    int idxOffset = FILE_TYPE_LENGTH + FILE_VERSION_LENGTH + Long.BYTES /* timestamp */
            + Integer.BYTES /** indexDirectory */
            + Integer.BYTES /* indexOfset */
            + headerar.length;
    ibb.putInt(0, idxOffset);
    os.write(ibb.array());
    os.write(headerar);
    os.flush();
}

From source file:org.onlab.util.ImmutableByteSequence.java

/**
 * Creates a new byte sequence of 4 bytes containing the given int value.
 *
 * @param original an int value//w  w  w.  jav a 2  s.c o m
 * @return a new immutable byte sequence
 */
public static ImmutableByteSequence copyFrom(int original) {
    return new ImmutableByteSequence(ByteBuffer.allocate(Integer.BYTES).putInt(original));
}

From source file:edu.umass.cs.reconfiguration.reconfigurationutils.ReconfigurationPacketDemultiplexer.java

@Override
public Integer getPacketType(JSONObject json) {
    if (json instanceof JSONMessenger.JSONObjectWrapper) {
        byte[] bytes = (byte[]) ((JSONMessenger.JSONObjectWrapper) json).getObj();
        if (!JSONPacket.couldBeJSON(bytes, NIOHeader.BYTES)) {
            // first 4 bytes (after 12 bytes of address) must be the type
            return ByteBuffer.wrap(bytes, NIOHeader.BYTES, Integer.BYTES).getInt();
        } else {// w  w  w .j  a  v  a2 s.c  o  m
            // return any valid type (assuming no more chained demultiplexers)
            return PacketType.ECHO_REQUEST.getInt();
        }
    } else
        try {
            //            assert(ReconfigurationPacket.isReconfigurationPacket(json)) : json;
            return JSONPacket.getPacketType(json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    return null;
}

From source file:io.pravega.controller.store.stream.tables.HistoryRecord.java

public static Optional<HistoryRecord> fetchPrevious(final HistoryRecord record, final byte[] historyTable) {
    if (record.getOffset() == 0) { // if first record
        return Optional.empty();
    } else {/* w ww  . j  ava 2  s .  c o  m*/
        final int rowStartOffset = record.offset
                - BitConverter.readInt(historyTable, record.getOffset() - (Integer.BYTES));
        assert rowStartOffset >= 0;
        return HistoryRecord.readRecord(historyTable, rowStartOffset, true);
    }
}

From source file:io.pravega.controller.store.stream.tables.HistoryRecord.java

private static HistoryRecord parsePartial(final byte[] table, final int offset) {
    final int length = BitConverter.readInt(table, offset + lengthOffset());
    assert length > FIXED_FIELDS_LENGTH && (length - FIXED_FIELDS_LENGTH) % Integer.BYTES == 0;
    final int epoch = BitConverter.readInt(table, offset + epochOffset());
    int count = getCount(length);
    final List<Integer> segments = new ArrayList<>();
    for (int i = 0; i < count; i++) {
        segments.add(BitConverter.readInt(table, offset + segmentOffset() + i * Integer.BYTES));
    }/*from  www  . ja v a 2  s.co m*/

    final int backToTop = BitConverter.readInt(table, offset + offsetOffset(count));
    assert backToTop == (count + 3) * Integer.BYTES;

    return new HistoryRecord(epoch, segments, offset);
}

From source file:io.druid.indexing.common.task.AppenderatorDriverRealtimeIndexTask.java

private static String makeTaskId(RealtimeAppenderatorIngestionSpec spec) {
    final StringBuilder suffix = new StringBuilder(8);
    for (int i = 0; i < Integer.BYTES * 2; ++i) {
        suffix.append((char) ('a' + ((random.nextInt() >>> (i * 4)) & 0x0F)));
    }//from   w w w.ja va  2 s. c om
    return StringUtils.format("index_realtime_%s_%d_%s_%s", spec.getDataSchema().getDataSource(),
            spec.getTuningConfig().getShardSpec().getPartitionNum(), DateTimes.nowUtc(), suffix);
}

From source file:de.micromata.genome.logging.spi.ifiles.IndexHeader.java

private void parse(MappedByteBuffer mem, long fileSize) {
    fileType = new byte[INDEX_FILE_TYPE.length];
    fileVersion = new byte[INDEX_FILE_VERSION.length];
    //    mem.position(0);
    int pos = 0;//from   w  ww.  j  a  v  a2  s  .  co  m
    NIOUtils.getBytes(mem, pos, fileType);
    pos += fileType.length;
    NIOUtils.getBytes(mem, pos, fileVersion);
    pos += fileVersion.length;
    created = mem.getLong(pos);
    pos += Long.BYTES;
    indexDirectoryIdx = mem.getInt(pos);
    pos += Integer.BYTES;
    startIndex = mem.getInt(pos);
    pos += Integer.BYTES;

    int max = startIndex - (Integer.BYTES + HEADER_NAME_LENGTH);
    int offset = 0;
    while (pos < max) {
        String headerName = NIOUtils.readAsciiString(mem, pos, HEADER_NAME_LENGTH);
        pos += HEADER_NAME_LENGTH;
        int fieldLength = mem.getInt(pos);
        pos += Integer.BYTES;
        headerName = StringUtils.trim(headerName);
        headerOrder.add(Pair.make(headerName, fieldLength));
        searchFieldsLength.put(headerName, fieldLength);
        searchFieldsOffsets.put(headerName, offset);
        offset += fieldLength + 1;
    }
}

From source file:ie.peternagy.jcrypto.algo.EllipticCurveWrapper.java

/**
 * Extract header parameters from data//from w  ww .j a va 2 s.  co  m
 * @param data - content with header signature
 * @return 
 */
public byte[] extractRawHeader(byte[] data) {
    int version = data[0];
    int currentPosition = 1;
    int keyIdSize = ByteBuffer.wrap(ArrayUtils.subarray(data, currentPosition, currentPosition + Integer.BYTES))
            .getInt();
    currentPosition += Integer.BYTES;
    long crcSum = ByteBuffer.wrap(ArrayUtils.subarray(data, currentPosition, currentPosition + Long.BYTES))
            .getLong();
    currentPosition += Long.BYTES;
    byte[] keyId = ArrayUtils.subarray(data, currentPosition, currentPosition + keyIdSize);
    currentPosition += keyIdSize;
    byte[] content = ArrayUtils.subarray(data, currentPosition, data.length);

    if (version != 100 || !Arrays.equals(keyId, getKeyId())
            || CryptoSignatureUtil.calculateCrc32(content) != crcSum) {
        String reason = version != 100 ? "Invalid version "
                : !Arrays.equals(keyId, getKeyId()) ? " Invalid key id" : " Invalid data checksum";
        throw new RuntimeException("EC headers do not match - decrypt " + reason);
    }

    return content;
}

From source file:org.springframework.kafka.listener.DeadLetterPublishingRecoverer.java

private void enhanceHeaders(RecordHeaders kafkaHeaders, ConsumerRecord<?, ?> record, Exception exception) {
    kafkaHeaders.add(/*w  ww.ja  va  2 s  . co m*/
            new RecordHeader(KafkaHeaders.DLT_ORIGINAL_TOPIC, record.topic().getBytes(StandardCharsets.UTF_8)));
    kafkaHeaders.add(new RecordHeader(KafkaHeaders.DLT_ORIGINAL_PARTITION,
            ByteBuffer.allocate(Integer.BYTES).putInt(record.partition()).array()));
    kafkaHeaders.add(new RecordHeader(KafkaHeaders.DLT_ORIGINAL_OFFSET,
            ByteBuffer.allocate(Long.BYTES).putLong(record.offset()).array()));
    kafkaHeaders.add(new RecordHeader(KafkaHeaders.DLT_ORIGINAL_TIMESTAMP,
            ByteBuffer.allocate(Long.BYTES).putLong(record.timestamp()).array()));
    kafkaHeaders.add(new RecordHeader(KafkaHeaders.DLT_ORIGINAL_TIMESTAMP_TYPE,
            record.timestampType().toString().getBytes(StandardCharsets.UTF_8)));
    kafkaHeaders.add(new RecordHeader(KafkaHeaders.DLT_EXCEPTION_FQCN,
            exception.getClass().getName().getBytes(StandardCharsets.UTF_8)));
    kafkaHeaders.add(new RecordHeader(KafkaHeaders.DLT_EXCEPTION_MESSAGE,
            exception.getMessage().getBytes(StandardCharsets.UTF_8)));
    kafkaHeaders.add(new RecordHeader(KafkaHeaders.DLT_EXCEPTION_STACKTRACE,
            getStackTraceAsString(exception).getBytes(StandardCharsets.UTF_8)));
}

From source file:org.cryptomator.crypto.engine.impl.CryptorImpl.java

@Override
public byte[] writeKeysToMasterkeyFile(CharSequence passphrase) {
    final byte[] scryptSalt = new byte[SCRYPT_SALT_LENGTH];
    randomSource.nextBytes(scryptSalt);//  w w  w .j  av  a 2  s . c o  m

    final byte[] kekBytes = Scrypt.scrypt(passphrase, scryptSalt, SCRYPT_COST_PARAM, SCRYPT_BLOCK_SIZE,
            KEYLENGTH_IN_BYTES);
    final byte[] wrappedEncryptionKey;
    final byte[] wrappedMacKey;
    try {
        final SecretKey kek = new SecretKeySpec(kekBytes, ENCRYPTION_ALG);
        wrappedEncryptionKey = AesKeyWrap.wrap(kek, encryptionKey);
        wrappedMacKey = AesKeyWrap.wrap(kek, macKey);
    } finally {
        Arrays.fill(kekBytes, (byte) 0x00);
    }

    final Mac mac = new ThreadLocalMac(macKey, MAC_ALG).get();
    final byte[] versionMac = mac
            .doFinal(ByteBuffer.allocate(Integer.BYTES).putInt(CURRENT_VAULT_VERSION).array());

    final KeyFile keyfile = new KeyFile();
    keyfile.setVersion(CURRENT_VAULT_VERSION);
    keyfile.setScryptSalt(scryptSalt);
    keyfile.setScryptCostParam(SCRYPT_COST_PARAM);
    keyfile.setScryptBlockSize(SCRYPT_BLOCK_SIZE);
    keyfile.setEncryptionMasterKey(wrappedEncryptionKey);
    keyfile.setMacMasterKey(wrappedMacKey);
    keyfile.setVersionMac(versionMac);

    try {
        final ObjectMapper om = new ObjectMapper();
        return om.writeValueAsBytes(keyfile);
    } catch (JsonProcessingException e) {
        throw new IllegalArgumentException("Unable to create JSON from " + keyfile, e);
    }
}