Java Code Examples for com.google.common.primitives.Bytes

The following examples show how to use com.google.common.primitives.Bytes. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: grpc-java   Source File: MessageDeframerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void deliverIsReentrantSafe() {
  doAnswer(
      new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
          deframer.request(1);
          return null;
        }
      })
      .when(listener)
      .messagesAvailable(ArgumentMatchers.<StreamListener.MessageProducer>any());
  deframer.deframe(buffer(new byte[]{0, 0, 0, 0, 1, 3}));
  deframer.closeWhenComplete();
  verifyNoMoreInteractions(listener);

  deframer.request(1);
  verify(listener).messagesAvailable(producer.capture());
  assertEquals(Bytes.asList(new byte[]{3}), bytes(producer.getValue().next()));
  verify(listener).deframerClosed(false);
  verify(listener, atLeastOnce()).bytesRead(anyInt());
  verifyNoMoreInteractions(listener);
}
 
Example 2
/**
 * Demonstrates false positives on conflicts due to concatenation of
 * keys for change sets (see TEPHRA-287).
 * @param pre014ChangeSetKey
 */
private void testActionChangeOverlap(boolean pre014ChangeSetKey) {
  long wp = System.currentTimeMillis();
  long rp = wp - 100;
  ConcreteTransactionAwareTable table1 = 
      new ConcreteTransactionAwareTable(ConflictDetection.ROW, false, TABLE_NAME, pre014ChangeSetKey);
  ConcreteTransactionAwareTable table2 = 
      new ConcreteTransactionAwareTable(ConflictDetection.ROW, false, 
          Bytes.concat(TABLE_NAME, ROW_PREFIX.getBytes()), pre014ChangeSetKey);
  Transaction tx = new Transaction(rp, wp, new long[] {}, new long[] {}, wp);
  table1.startTx(tx);
  table2.startTx(tx);
  table1.addToChangeSet(ROW1.getBytes(), FAM1.getBytes(), null);
  table2.addToChangeSet(ROW3.getBytes(), FAM1.getBytes(), null);
  assertNotEquals(table1.getChangeSet(), table2.getChangeSet());
  ConcreteTransactionAwareTable table3 = 
      new ConcreteTransactionAwareTable(ConflictDetection.COLUMN, false, TABLE_NAME, pre014ChangeSetKey);
  table3.startTx(tx);
  table3.addToChangeSet("e".getBytes(), "bc".getBytes(), "d".getBytes());
  table3.addToChangeSet("e".getBytes(), "b".getBytes(), "cd".getBytes());
  assertEquals(pre014ChangeSetKey ? 3 : 2, table3.getTxChanges().size());
}
 
Example 3
Source Project: jobson   Source File: JobExecutorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteEvaluatesOutputDirAsExpected() throws InterruptedException {
    final JobExecutor jobExecutor = getInstance();
    final PersistedJob req =
            standardRequestWithCommand("echo", "${outputDir}");
    final AtomicReference<byte[]> bytesEchoedToStdout = new AtomicReference<>(new byte[]{});
    final Subject<byte[]> stdoutSubject = PublishSubject.create();
    stdoutSubject.subscribe(bytes ->
            bytesEchoedToStdout.getAndUpdate(existingBytes ->
                    Bytes.concat(existingBytes, bytes)));

    final Semaphore s = new Semaphore(1);
    s.acquire();
    stdoutSubject.doOnComplete(s::release).subscribe();

    final JobEventListeners listeners =
            createStdoutListener(stdoutSubject);

    jobExecutor.execute(req, listeners);

    s.tryAcquire(TestConstants.DEFAULT_TIMEOUT, MILLISECONDS);

    final String stringFromStdout = new String(bytesEchoedToStdout.get()).trim();

    assertThat(Files.exists(Paths.get(stringFromStdout)));
}
 
Example 4
Source Project: eosio-java   Source File: EOSFormatter.java    License: MIT License 6 votes vote down vote up
/**
 * Decompresses a public key based on the algorithm used to generate it.
 *
 * @param compressedPublicKey Compressed public key as byte[]
 * @param algorithmEmployed Algorithm used during key creation
 * @return Decompressed public key as byte[]
 * @throws EOSFormatterError when public key decompression fails.
 */
@NotNull
private static byte[] decompressPublickey(byte[] compressedPublicKey,
        AlgorithmEmployed algorithmEmployed)
        throws EOSFormatterError {
    try {
        ECParameterSpec parameterSpec = ECNamedCurveTable
                .getParameterSpec(algorithmEmployed.getString());
        ECPoint ecPoint = parameterSpec.getCurve().decodePoint(compressedPublicKey);
        byte[] x = ecPoint.getXCoord().getEncoded();
        byte[] y = ecPoint.getYCoord().getEncoded();
        if (y.length > STANDARD_KEY_LENGTH) {
            y = Arrays.copyOfRange(y, 1, y.length);
        }
        return Bytes.concat(new byte[]{UNCOMPRESSED_PUBLIC_KEY_BYTE_INDICATOR}, x, y);
    } catch (Exception e) {
        throw new EOSFormatterError(ErrorConstants.PUBLIC_KEY_DECOMPRESSION_ERROR, e);
    }
}
 
Example 5
Source Project: onos   Source File: LsUpdate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets lsu header.
 *
 * @return lsu header as byte array
 */
public byte[] getLsuHeaderAsByteArray() {
    List<Byte> headerLst = new ArrayList<>();
    try {
        headerLst.add((byte) this.ospfVersion());
        headerLst.add((byte) this.ospfType());
        headerLst.addAll(Bytes.asList(OspfUtil.convertToTwoBytes(this.ospfPacLength())));
        headerLst.addAll(Bytes.asList(this.routerId().toOctets()));
        headerLst.addAll(Bytes.asList(this.areaId().toOctets()));
        headerLst.addAll(Bytes.asList(OspfUtil.convertToTwoBytes(this.checksum())));
        headerLst.addAll(Bytes.asList(OspfUtil.convertToTwoBytes(this.authType())));
        //Authentication is 0 always. Total 8 bytes consist of zero
        byte[] auth = new byte[OspfUtil.EIGHT_BYTES];
        headerLst.addAll(Bytes.asList(auth));
    } catch (Exception e) {
        log.debug("Error::LSUpdate::getLsuHeaderAsByteArray:: {}", e.getMessage());
        return Bytes.toArray(headerLst);
    }

    return Bytes.toArray(headerLst);
}
 
Example 6
Source Project: jobson   Source File: JobExecutorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteEvaluatesJoinAsExpected() throws InterruptedException {
    final JobExecutor jobExecutor = getInstance();
    final PersistedJob req =
            standardRequestWithCommand("echo", "${join(',', inputs.someList)}");
    final AtomicReference<byte[]> bytesEchoedToStdout = new AtomicReference<>(new byte[]{});
    final Subject<byte[]> stdoutSubject = PublishSubject.create();
    stdoutSubject.subscribe(bytes ->
            bytesEchoedToStdout.getAndUpdate(existingBytes ->
                    Bytes.concat(existingBytes, bytes)));

    final Semaphore s = new Semaphore(1);
    s.acquire();
    stdoutSubject.doOnComplete(s::release).subscribe();

    final JobEventListeners listeners =
            createStdoutListener(stdoutSubject);

    jobExecutor.execute(req, listeners);

    s.tryAcquire(TestConstants.DEFAULT_TIMEOUT, MILLISECONDS);

    final String stringFromStdout = new String(bytesEchoedToStdout.get()).trim();

    assertThat(stringFromStdout).isEqualTo("a,b,c,d"); // From the input fixture
}
 
Example 7
@Test
@DisplayName("Exactly 1/3 consensus")
void oneThirdConsensus() throws Exception {
    // Remove last node from current 4 node address book
    byte[] addressBook = Files.readAllBytes(mirrorProperties.getAddressBookPath());
    int index = Bytes.lastIndexOf(addressBook, (byte) '\n');
    addressBook = Arrays.copyOfRange(addressBook, 0, index);
    networkAddressBook.update(addressBook);

    fileCopier.filterDirectories("*0.0.3").copy();
    downloader.download();
    verify(applicationStatusRepository).updateStatusValue(
            ApplicationStatusCode.LAST_VALID_DOWNLOADED_BALANCE_FILE, "2019-08-30T18_30_00.010147001Z_Balances" +
                    ".csv");
    assertValidFiles(List
            .of("2019-08-30T18_15_00.016002001Z_Balances.csv", "2019-08-30T18_30_00.010147001Z_Balances.csv"));
}
 
Example 8
@Test
@DisplayName("Exactly 1/3 consensus")
void oneThirdConsensus() throws Exception {
    // Remove last node from current 4 node address book
    byte[] addressBook = Files.readAllBytes(mirrorProperties.getAddressBookPath());
    int index = Bytes.lastIndexOf(addressBook, (byte) '\n');
    addressBook = Arrays.copyOfRange(addressBook, 0, index);
    networkAddressBook.update(addressBook);

    fileCopier.filterDirectories("*0.0.3").copy();
    downloader.download();

    verify(applicationStatusRepository).updateStatusValue(
            ApplicationStatusCode.LAST_VALID_DOWNLOADED_RECORD_FILE, "2019-08-30T18_10_00.419072Z.rcd");
    verify(applicationStatusRepository).updateStatusValue(
            ApplicationStatusCode.LAST_VALID_DOWNLOADED_RECORD_FILE, "2019-08-30T18_10_05.249678Z.rcd");
    verify(applicationStatusRepository, times(2)).updateStatusValue(
            eq(ApplicationStatusCode.LAST_VALID_DOWNLOADED_RECORD_FILE_HASH), any());
    assertValidFiles(List.of("2019-08-30T18_10_05.249678Z.rcd", "2019-08-30T18_10_00.419072Z.rcd"));
}
 
Example 9
private SignatureData getServerSignature(ByteString clientNonce,
                                         ByteString clientCertificate,
                                         SecurityPolicy securityPolicy,
                                         KeyPair keyPair) throws UaException {

    if (clientNonce.isNull() || clientCertificate.isNull() || keyPair == null) {
        return new SignatureData(null, null);
    }

    try {
        SecurityAlgorithm algorithm = securityPolicy.getAsymmetricSignatureAlgorithm();

        byte[] data = Bytes.concat(clientCertificate.bytes(), clientNonce.bytes());

        byte[] signature = SignatureUtil.sign(
                algorithm,
                keyPair.getPrivate(),
                ByteBuffer.wrap(data)
        );

        return new SignatureData(algorithm.getUri(), ByteString.of(signature));
    } catch (UaRuntimeException e) {
        throw new UaException(StatusCodes.Bad_SecurityChecksFailed);
    }
}
 
Example 10
Source Project: grpc-java   Source File: ApplicationThreadDeframerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void messagesAvailableDrainsToMessageReadQueue_returnedByInitializingMessageProducer()
    throws Exception {
  byte[][] messageBytes = {{1, 2, 3}, {4}, {5, 6}};
  Queue<InputStream> messages = new LinkedList<>();
  for (int i = 0; i < messageBytes.length; i++) {
    messages.add(new ByteArrayInputStream(messageBytes[i]));
  }
  MultiMessageProducer messageProducer = new MultiMessageProducer(messages);
  applicationThreadDeframer.getAppListener().messagesAvailable(messageProducer);
  applicationThreadDeframer.request(1 /* value is ignored */);
  for (int i = 0; i < messageBytes.length; i++) {
    InputStream message = listener.storedProducer.next();
    assertNotNull(message);
    assertEquals(Bytes.asList(messageBytes[i]), Bytes.asList(ByteStreams.toByteArray(message)));
  }
  assertNull(listener.storedProducer.next());
}
 
Example 11
Source Project: onos   Source File: NetworkLsa.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets LSA body as byte array.
 *
 * @return LSA body as byte array
 * @throws OspfParseException might throws exception while parsing packet
 */
public byte[] getLsaBodyAsByteArray() throws OspfParseException {
    List<Byte> bodyLst = new ArrayList<>();

    try {
        bodyLst.addAll(Bytes.asList(this.networkMask().toOctets()));
        //add each attachedRouters details
        for (Ip4Address attachedRouter : attachedRouters) {
            //attached router
            bodyLst.addAll(Bytes.asList(attachedRouter.toOctets()));
        }
    } catch (Exception e) {
        log.debug("Error::NetworkLSA::getLsrBodyAsByteArray {}", e.getMessage());
        throw new OspfParseException(OspfErrorType.OSPF_MESSAGE_ERROR, OspfErrorType.BAD_MESSAGE);
    }

    return Bytes.toArray(bodyLst);
}
 
Example 12
@Test
public void encryptWhenSerializing() throws Exception {
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);
    SecretKey key = keyGen.generateKey();
    TransformedRecordSerializer<Message> serializer = TransformedRecordSerializerJCE.newDefaultBuilder()
            .setEncryptWhenSerializing(true)
            .setEncryptionKey(key)
            .build();

    MySimpleRecord mediumRecord = MySimpleRecord.newBuilder().setRecNo(1066L).setStrValueIndexed(SONNET_108).build();
    assertTrue(Bytes.indexOf(mediumRecord.toByteArray(), "brain".getBytes()) >= 0, "should contain clear text");
    byte[] serialized = serialize(serializer, mediumRecord);
    assertEquals(TransformedRecordSerializer.ENCODING_ENCRYPTED, serialized[0]);
    assertFalse(Bytes.indexOf(serialized, "brain".getBytes()) >= 0, "should not contain clear text");
    Message deserialized = deserialize(serializer, Tuple.from(1066L), serialized);
    assertEquals(mediumRecord, deserialized);
}
 
Example 13
Source Project: grpc-java   Source File: MessageDeframerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void emptyPayload() {
  deframer.request(1);
  deframer.deframe(buffer(new byte[]{0, 0, 0, 0, 0}));
  verify(listener).messagesAvailable(producer.capture());
  assertEquals(Bytes.asList(), bytes(producer.getValue().next()));
  verify(listener, atLeastOnce()).bytesRead(anyInt());
  verifyNoMoreInteractions(listener);
  checkStats(tracer, transportTracer.getStats(), fakeClock, 0, 0);
}
 
Example 14
Source Project: grpc-nebula-java   Source File: MessageDeframerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void simplePayload() {
  deframer.request(1);
  fakeClock.forwardTime(10, TimeUnit.MILLISECONDS);
  deframer.deframe(buffer(new byte[]{0, 0, 0, 0, 2, 3, 14}));
  verify(listener).messagesAvailable(producer.capture());
  assertEquals(Bytes.asList(new byte[]{3, 14}), bytes(producer.getValue().next()));
  verify(listener, atLeastOnce()).bytesRead(anyInt());
  verifyNoMoreInteractions(listener);
  checkStats(tracer, transportTracer.getStats(), fakeClock, 2, 2);
}
 
Example 15
Source Project: james-project   Source File: InternalDateExtraFieldTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void parseFromLocalFileDataShouldHandleOffset() throws Exception {
    InternalDateExtraField testee = new InternalDateExtraField();

    byte[] input = Bytes.concat(UNUSED, _123456789ABCDEF0_AS_LE_BYTE_ARRAY);
    testee.parseFromLocalFileData(input, 2, 8);
    assertThat(testee.getValue())
        .contains(0x123456789ABCDEF0L);
}
 
Example 16
Source Project: GreenBits   Source File: GATx.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static byte[] createInScript(final List<byte[]> sigs, final byte[] outScript,
                              final int scriptType) {
    if (scriptType == P2SH_FORTIFIED_OUT || scriptType == REDEEM_P2SH_FORTIFIED)
        // FIXME: investigate P2SH_ vs REDEEM_P2SH_ and ideally make it consistent here
        return ScriptBuilder.createMultiSigInputScriptBytes(sigs, outScript).getProgram();
    // REDEEM_P2SH_P2WSH_FORTIFIED: PUSH(OP_0 PUSH(sha256(outScript)))
    return Bytes.concat(Wally.hex_to_bytes("220020"), Wally.sha256(outScript));
}
 
Example 17
Source Project: geowave   Source File: RedisUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Iterator<GeoWaveMetadata> groupByIds(final Iterable<GeoWaveMetadata> result) {
  final ListMultimap<ByteArray, GeoWaveMetadata> multimap =
      MultimapBuilder.hashKeys().arrayListValues().build();
  result.forEach(
      r -> multimap.put(new ByteArray(Bytes.concat(r.getPrimaryId(), r.getSecondaryId())), r));
  return multimap.values().iterator();
}
 
Example 18
Source Project: xtext-lib   Source File: Conversions.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @throws NullPointerException
 *             if the wrapped array was <code>null</code>.
 */
@Override
public boolean contains(Object o) {
	// Will make the method fail if array is null.
	if (size() < 1) {
		return false;
	}
	if (o instanceof Byte) {
		return Bytes.contains(array, ((Byte) o).byteValue());
	}
	return false;
}
 
Example 19
Source Project: onos   Source File: LspEntriesTlv.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public byte[] asBytes() {
    byte[] bytes = null;
    byte[] tlvHeader = tlvHeaderAsByteArray();
    byte[] tlvBody = tlvBodyAsBytes();
    tlvHeader[1] = (byte) tlvBody.length;
    bytes = Bytes.concat(tlvHeader, tlvBody);
    return bytes;
}
 
Example 20
Source Project: onos   Source File: OpaqueLsa11.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns instance as bytes.
 *
 * @return instance as bytes
 */
public byte[] asBytes() {
    byte[] lsaMessage = null;

    byte[] lsaHeader = getOpaqueLsaHeaderAsByteArray();
    byte[] lsaBody = getLsaBodyAsByteArray();
    lsaMessage = Bytes.concat(lsaHeader, lsaBody);

    return lsaMessage;
}
 
Example 21
Source Project: Qora   Source File: Crypto.java    License: MIT License 5 votes vote down vote up
public String getAddress(byte[] publicKey)
{
	//SHA256 PUBLICKEY FOR PROTECTION
	byte[] publicKeyHash = this.digest(publicKey);
	
	//RIPEMD160 TO CREATE A SHORTER ADDRESS
	RIPEMD160 ripEmd160 = new RIPEMD160();
	publicKeyHash = ripEmd160.digest(publicKeyHash);
	
	//CONVERT TO LIST
	List<Byte> addressList = new ArrayList<Byte>();
	
	//ADD VERSION BYTE
	Byte versionByte = Byte.valueOf(ADDRESS_VERSION);
	addressList.add(versionByte);
	
	addressList.addAll(Bytes.asList(publicKeyHash));
	
	//GENERATE CHECKSUM
	byte[] checkSum = this.doubleDigest(Bytes.toArray(addressList));
	
	//ADD FIRST 4 BYTES OF CHECKSUM TO ADDRESS
	addressList.add(checkSum[0]);
	addressList.add(checkSum[1]);
	addressList.add(checkSum[2]);
	addressList.add(checkSum[3]);
	
	//BASE58 ENCODE ADDRESS
	String address = Base58.encode(Bytes.toArray(addressList));
	
	return address;
}
 
Example 22
Source Project: james-project   Source File: DataChunkerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void chunkShouldReturnSeveralArrayWhenInputBiggerThanChunkSize() {
    byte[] part1 = "1234567890".getBytes(StandardCharsets.UTF_8);
    byte[] part2 = "12345".getBytes(StandardCharsets.UTF_8);
    Assumptions.assumeThat(part1.length).isEqualTo(CHUNK_SIZE);
    byte[] data = Bytes.concat(part1, part2);

    Flux<ByteBuffer> chunks = testee.chunkStream(new ByteArrayInputStream(data), CHUNK_SIZE);

    assertThat(chunks.map(DataChunkerTest::read).toStream()).containsExactly(part1, part2);
}
 
Example 23
Source Project: rya   Source File: CustomDatatypeResolver.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public byte[][] serializeType(final RyaType ryaType) throws RyaTypeResolverException {
    final StringBuilder dataBuilder = new StringBuilder();
    dataBuilder.append(ryaType.getData());
    final String validatedLanguage = LiteralLanguageUtils.validateLanguage(ryaType.getLanguage(), ryaType.getDataType());
    if (validatedLanguage != null) {
        dataBuilder.append(LiteralLanguageUtils.LANGUAGE_DELIMITER);
        dataBuilder.append(validatedLanguage);
    }
    // Combine data and language
    final byte[] bytes = serializeData(dataBuilder.toString()).getBytes(StandardCharsets.UTF_8);
    return new byte[][]{bytes, Bytes.concat(TYPE_DELIM_BYTES, ryaType.getDataType().stringValue().getBytes(StandardCharsets.UTF_8), TYPE_DELIM_BYTES, markerBytes)};
}
 
Example 24
Source Project: Qora   Source File: CancelSellNameTransaction.java    License: MIT License 5 votes vote down vote up
public static byte[] generateSignature(DBSet db, PrivateKeyAccount creator, String name, BigDecimal fee, long timestamp) 
{
	byte[] data = new byte[0];
	
	//WRITE TYPE
	byte[] typeBytes = Ints.toByteArray(CANCEL_SELL_NAME_TRANSACTION);
	typeBytes = Bytes.ensureCapacity(typeBytes, TYPE_LENGTH, 0);
	data = Bytes.concat(data, typeBytes);
	
	//WRITE TIMESTAMP
	byte[] timestampBytes = Longs.toByteArray(timestamp);
	timestampBytes = Bytes.ensureCapacity(timestampBytes, TIMESTAMP_LENGTH, 0);
	data = Bytes.concat(data, timestampBytes);
	
	//WRITE REFERENCE
	data = Bytes.concat(data, creator.getLastReference(db));
	
	//WRITE OWNER
	data = Bytes.concat(data, creator.getPublicKey());
	
	//WRITE NAME SIZE
	byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8);
	int nameLength = nameBytes.length;
	byte[] nameLengthBytes = Ints.toByteArray(nameLength);
	data = Bytes.concat(data, nameLengthBytes);
			
	//WRITE NAME
	data = Bytes.concat(data, nameBytes);
	
	//WRITE FEE
	byte[] feeBytes = fee.unscaledValue().toByteArray();
	byte[] fill = new byte[FEE_LENGTH - feeBytes.length];
	feeBytes = Bytes.concat(fill, feeBytes);
	data = Bytes.concat(data, feeBytes);
	
	return Crypto.getInstance().sign(creator, data);
}
 
Example 25
Source Project: Qora   Source File: ArbitraryTransaction.java    License: MIT License 5 votes vote down vote up
public static byte[] generateSignature(DBSet db, PrivateKeyAccount creator, int service, byte[] arbitraryData, BigDecimal fee, long timestamp) 
{
	byte[] data = new byte[0];
	
	//WRITE TYPE
	byte[] typeBytes = Ints.toByteArray(ARBITRARY_TRANSACTION);
	typeBytes = Bytes.ensureCapacity(typeBytes, TYPE_LENGTH, 0);
	data = Bytes.concat(data, typeBytes);
	
	//WRITE TIMESTAMP
	byte[] timestampBytes = Longs.toByteArray(timestamp);
	timestampBytes = Bytes.ensureCapacity(timestampBytes, TIMESTAMP_LENGTH, 0);
	data = Bytes.concat(data, timestampBytes);
	
	//WRITE REFERENCE
	data = Bytes.concat(data, creator.getLastReference(db));
	
	//WRITE CREATOR
	data = Bytes.concat(data, creator.getPublicKey());
	
	//WRITE SERVICE
	byte[] serviceBytes = Ints.toByteArray(service);
	data = Bytes.concat(data, serviceBytes);
	
	//WRITE DATA SIZE
	byte[] dataSizeBytes = Ints.toByteArray(arbitraryData.length);
	data = Bytes.concat(data, dataSizeBytes);
	
	//WRITE DATA
	data = Bytes.concat(data, arbitraryData);
	
	//WRITE FEE
	byte[] feeBytes = fee.unscaledValue().toByteArray();
	byte[] fill = new byte[FEE_LENGTH - feeBytes.length];
	feeBytes = Bytes.concat(fill, feeBytes);
	data = Bytes.concat(data, feeBytes);
	
	return Crypto.getInstance().sign(creator, data);
}
 
Example 26
Source Project: james-project   Source File: UidValidityExtraFieldTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void parseFromLocalFileDataShouldHandleOffset() throws Exception {
    UidValidityExtraField testee = new UidValidityExtraField();

    byte[] input = Bytes.concat(UNUSED, _123456789ABCDEF0_AS_LE_BYTE_ARRAY);
    testee.parseFromLocalFileData(input, 2, 8);
    assertThat(testee.getValue())
        .contains(0x123456789ABCDEF0L);
}
 
Example 27
Source Project: geowave   Source File: FileSystemDataFormatter.java    License: Apache License 2.0 5 votes vote down vote up
public byte[] getSortOrderKey() {
  if (timeMillis.isPresent()) {
    return Bytes.concat(sortKey, dataId, Longs.toByteArray(timeMillis.get()));
  } else {
    return Bytes.concat(sortKey, dataId);
  }
}
 
Example 28
Source Project: shardingsphere   Source File: MySQLAuthPluginDataTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void assertGetAuthPluginData() {
    byte[] actualPart1 = {106, 105, 55, 122, 117, 98, 115, 109};
    byte[] actualPart2 = {68, 102, 53, 122, 65, 49, 84, 79, 85, 115, 116, 113};
    MySQLAuthPluginData actual = new MySQLAuthPluginData(actualPart1, actualPart2);
    assertThat(actual.getAuthPluginDataPart1(), is(actualPart1));
    assertThat(actual.getAuthPluginDataPart2(), is(actualPart2));
    assertThat(actual.getAuthPluginData(), is(Bytes.concat(actualPart1, actualPart2)));
}
 
Example 29
Source Project: james-project   Source File: SizeExtraFieldTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void parseFromLocalFileDataShouldHandleOffset() throws Exception {
    byte[] input = Bytes.concat(UNUSED, _123456789ABCDEF0_AS_LE_BYTE_ARRAY);
    testee.parseFromLocalFileData(input, 2, 8);
    assertThat(testee.getValue())
        .contains(0x123456789ABCDEF0L);
}
 
Example 30
Source Project: onos   Source File: DdPacket.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets DD body as byte array.
 *
 * @return DD body
 */
public byte[] getDdBodyAsByteArray() {
    List<Byte> bodyLst = new ArrayList<>();

    try {
        bodyLst.addAll(Bytes.asList(OspfUtil.convertToTwoBytes(this.imtu())));
        bodyLst.add((byte) this.options());

        StringBuilder sb = new StringBuilder();
        sb.append(this.isInitialize());
        sb.append(this.isMore());
        sb.append(this.isMaster());

        bodyLst.add((byte) Integer.parseInt(sb.toString(), 2));
        bodyLst.addAll(Bytes.asList(OspfUtil.convertToFourBytes(this.sequenceNo()))); // passing long value

        for (LsaHeader lsaHeader : lsaHeaderList) {
            if (lsaHeader.lsType() == OspfParameters.LINK_LOCAL_OPAQUE_LSA ||
                    lsaHeader.lsType() == OspfParameters.AREA_LOCAL_OPAQUE_LSA ||
                    lsaHeader.lsType() == OspfParameters.AS_OPAQUE_LSA) {
                OpaqueLsaHeader header = (OpaqueLsaHeader) lsaHeader;
                bodyLst.addAll(Bytes.asList(header.getOpaqueLsaHeaderAsByteArray()));
            } else {
                bodyLst.addAll(Bytes.asList(lsaHeader.getLsaHeaderAsByteArray()));
            }
        }
    } catch (Exception e) {
        log.debug("Error::getLsrBodyAsByteArray {}", e.getMessage());
        return Bytes.toArray(bodyLst);
    }

    return Bytes.toArray(bodyLst);
}