org.apache.commons.lang3.RandomUtils Java Examples

The following examples show how to use org.apache.commons.lang3.RandomUtils. 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 File: DetailsDataStoreTest.java    From aion with MIT License 6 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testDecodingWithIncorrectSize() {
    AionAddress address = new AionAddress(RandomUtils.nextBytes(AionAddress.LENGTH));
    byte[] code = RandomUtils.nextBytes(512);

    // create old encoding
    byte[] rlpAddress = RLP.encodeElement(address.toByteArray());
    byte[] rlpIsExternalStorage = RLP.encodeByte((byte) 1);
    byte[] rlpStorageRoot = RLP.encodeElement(RandomUtils.nextBytes(32));
    byte[] rlpStorageTrie = RLP.encodeElement(EMPTY_BYTE_ARRAY);
    byte[] rlpCode = RLP.encodeList(RLP.encodeElement(code));

    byte[] oldEncoding =
            RLP.encodeList(
                    rlpAddress,
                    rlpIsExternalStorage,
                    rlpStorageRoot,
                    rlpStorageTrie,
                    rlpCode,
                    RLP.encodeByte(InternalVmType.AVM.getCode()));

    // create object using encoding
    // throws exception due to the illegal size of the encoding above
    DetailsDataStore.fromEncoding(oldEncoding);
}
 
Example #2
Source File: S3ReadFeatureTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testReadCloseReleaseEntity() throws Exception {
    final Path container = new Path("test-us-east-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final Path file = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final int length = 2048;
    final byte[] content = RandomUtils.nextBytes(length);
    final TransferStatus status = new TransferStatus().length(content.length);
    status.setChecksum(new SHA256ChecksumCompute().compute(new ByteArrayInputStream(content), status));
    final OutputStream out = new S3WriteFeature(session).write(file, status, new DisabledConnectionCallback());
    new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), out);
    out.close();
    final CountingInputStream in = new CountingInputStream(new S3ReadFeature(session).read(file, status, new DisabledConnectionCallback()));
    in.close();
    assertEquals(0L, in.getByteCount(), 0L);
    new S3DefaultDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example #3
Source File: SDSReadFeatureTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testReadCloseReleaseEntity() throws Exception {
    final TransferStatus status = new TransferStatus();
    final byte[] content = RandomUtils.nextBytes(32769);
    final TransferStatus writeStatus = new TransferStatus();
    writeStatus.setLength(content.length);
    final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session).withCache(cache);
    final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(
        new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume, Path.Type.triplecrypt)), null, new TransferStatus());
    final Path test = new Path(room, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final SDSWriteFeature writer = new SDSWriteFeature(session, nodeid);
    final HttpResponseOutputStream<VersionId> out = writer.write(test, writeStatus, new DisabledConnectionCallback());
    assertNotNull(out);
    new StreamCopier(writeStatus, writeStatus).transfer(new ByteArrayInputStream(content), out);
    final CountingInputStream in = new CountingInputStream(new SDSReadFeature(session, nodeid).read(test, status, new DisabledConnectionCallback()));
    in.close();
    assertEquals(0L, in.getByteCount(), 0L);
    new SDSDeleteFeature(session, nodeid).delete(Collections.singletonList(room), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example #4
Source File: MoveWorkerTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testMoveSameFolderCryptomator() throws Exception {
    final Path home = DriveHomeFinderService.MYDRIVE_FOLDER;
    final CryptoVault cryptomator = new CryptoVault(
        new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)));
    final Path vault = cryptomator.create(session, null, new VaultCredentials("test"), new DisabledPasswordStore(), vaultVersion);
    final Path source = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final Path target = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    session.withRegistry(new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator));
    final byte[] content = RandomUtils.nextBytes(40500);
    final TransferStatus status = new TransferStatus();
    final DriveFileidProvider fileid = new DriveFileidProvider(session).withCache(cache);
    new CryptoBulkFeature<>(session, new DisabledBulkFeature(), new DriveDeleteFeature(session, fileid), cryptomator).pre(Transfer.Type.upload, Collections.singletonMap(new TransferItem(source), status), new DisabledConnectionCallback());
    new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), new CryptoWriteFeature<>(session, new DriveWriteFeature(session, fileid), cryptomator).write(source, status.length(content.length), new DisabledConnectionCallback()));
    assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).withCache(cache).find(source));
    final MoveWorker worker = new MoveWorker(Collections.singletonMap(source, target), new SessionPool.SingleSessionPool(session), cache, new DisabledProgressListener(), new DisabledLoginCallback());
    worker.run(session);
    assertFalse(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(source));
    assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(target));
    final ByteArrayOutputStream out = new ByteArrayOutputStream(content.length);
    assertEquals(content.length, IOUtils.copy(new CryptoReadFeature(session, new DriveReadFeature(session, fileid), cryptomator).read(target, new TransferStatus().length(content.length), new DisabledConnectionCallback()), out));
    assertArrayEquals(content, out.toByteArray());
    cryptomator.getFeature(session, Delete.class, new DriveDeleteFeature(session, fileid)).delete(Arrays.asList(target, vault), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example #5
Source File: InnerContractDetailsTest.java    From aion with MIT License 6 votes vote down vote up
@Test
public void testCommitToStored_withCodeOnAvm() {
    AionAddress address = mock(AionAddress.class);
    ByteArrayKeyValueStore db = mock(XorDataSource.class);
    AvmContractDetails parent = new AvmContractDetails(address, db, db);

    byte[] code = RandomUtils.nextBytes(100);
    InnerContractDetails child = new InnerContractDetails(null);
    child.setCode(code);
    assertThat(child.isDirty()).isTrue();

    assertThat(parent.getVmType()).isEqualTo(InternalVmType.AVM);

    child.commitTo(parent);

    assertThat(parent.getVmType()).isEqualTo(InternalVmType.AVM);
    assertThat(parent.getCode(h256(code))).isEqualTo(code);
    assertThat(parent.isDirty()).isTrue();
}
 
Example #6
Source File: SDSMultipartWriteFeatureTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testWriteZeroSingleByte() throws Exception {
    final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session).withCache(cache);
    final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(
        new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.volume, Path.Type.triplecrypt)), null, new TransferStatus());
    final byte[] content = RandomUtils.nextBytes(1);
    final TransferStatus status = new TransferStatus().length(content.length);
    final Path test = new Path(room, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final SDSMultipartWriteFeature writer = new SDSMultipartWriteFeature(session, nodeid);
    final HttpResponseOutputStream<VersionId> out = writer.write(test, status, new DisabledConnectionCallback());
    assertNotNull(out);
    new StreamCopier(status, status).transfer(new ByteArrayInputStream(content), out);
    final VersionId version = out.getStatus();
    assertNotNull(version);
    assertTrue(new DefaultFindFeature(session).find(test));
    new SDSDeleteFeature(session, nodeid).delete(Collections.singletonList(room), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example #7
Source File: CopyWorkerTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testCopyFile() throws Exception {
    final Path home = new Path("/test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final Path vault = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
    final Path source = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final Path target = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final CryptoVault cryptomator = new CryptoVault(vault);
    cryptomator.create(session, null, new VaultCredentials("test"), new DisabledPasswordStore(), vaultVersion);
    final DefaultVaultRegistry registry = new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator);
    session.withRegistry(registry);
    final byte[] content = RandomUtils.nextBytes(40500);
    final TransferStatus status = new TransferStatus();
    final B2FileidProvider fileid = new B2FileidProvider(session).withCache(cache);
    new CryptoBulkFeature<>(session, new DisabledBulkFeature(), new B2DeleteFeature(session, fileid), cryptomator).pre(Transfer.Type.upload, Collections.singletonMap(new TransferItem(source), status), new DisabledConnectionCallback());
    new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), new CryptoWriteFeature<>(session, new B2WriteFeature(session, fileid), cryptomator).write(source, status.length(content.length), new DisabledConnectionCallback()));
    assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(source));
    final CopyWorker worker = new CopyWorker(Collections.singletonMap(source, target), new SessionPool.SingleSessionPool(session, registry), PathCache.empty(), new DisabledProgressListener(), new DisabledConnectionCallback());
    worker.run(session);
    assertTrue(new CryptoFindFeature(session, new B2FindFeature(session, fileid), cryptomator).find(source));
    assertTrue(new CryptoFindFeature(session, new B2FindFeature(session, fileid), cryptomator).find(target));
    final ByteArrayOutputStream out = new ByteArrayOutputStream(content.length);
    assertEquals(content.length, IOUtils.copy(new CryptoReadFeature(session, new B2ReadFeature(session, fileid), cryptomator).read(target, new TransferStatus().length(content.length), new DisabledConnectionCallback()), out));
    assertArrayEquals(content, out.toByteArray());
    new DeleteWorker(new DisabledLoginCallback(), Collections.singletonList(vault), PathCache.empty(), new DisabledProgressListener()).run(session);
}
 
Example #8
Source File: CopyWorkerTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testCopyFile() throws Exception {
    final Path home = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.volume, Path.Type.directory));
    final Path vault = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
    final Path source = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final Path target = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final CryptoVault cryptomator = new CryptoVault(vault);
    cryptomator.create(session, null, new VaultCredentials("test"), new DisabledPasswordStore(), vaultVersion);
    final DefaultVaultRegistry registry = new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator);
    session.withRegistry(registry);
    final byte[] content = RandomUtils.nextBytes(40500);
    final TransferStatus status = new TransferStatus();
    new CryptoBulkFeature<>(session, new DisabledBulkFeature(), new SwiftDeleteFeature(session), cryptomator).pre(Transfer.Type.upload, Collections.singletonMap(new TransferItem(source), status), new DisabledConnectionCallback());
    new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), new CryptoWriteFeature<>(session, new SwiftWriteFeature(session, new SwiftRegionService(session)), cryptomator).write(source, status.length(content.length), new DisabledConnectionCallback()));
    assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(source));
    final CopyWorker worker = new CopyWorker(Collections.singletonMap(source, target), new SessionPool.SingleSessionPool(session, registry), PathCache.empty(), new DisabledProgressListener(), new DisabledConnectionCallback());
    worker.run(session);
    assertTrue(new CryptoFindFeature(session, new SwiftFindFeature(session), cryptomator).find(source));
    assertTrue(new CryptoFindFeature(session, new SwiftFindFeature(session), cryptomator).find(target));
    final ByteArrayOutputStream out = new ByteArrayOutputStream(content.length);
    assertEquals(content.length, IOUtils.copy(new CryptoReadFeature(session, new SwiftReadFeature(session, new SwiftRegionService(session)), cryptomator).read(target, new TransferStatus().length(content.length), new DisabledConnectionCallback()), out));
    assertArrayEquals(content, out.toByteArray());
    new DeleteWorker(new DisabledLoginCallback(), Collections.singletonList(vault), PathCache.empty(), new DisabledProgressListener()).run(session);
    session.close();
}
 
Example #9
Source File: AddDataMessageTest.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void toProtoBuf() throws Exception {
    SealedAndSigned sealedAndSigned = new SealedAndSigned(RandomUtils.nextBytes(10), RandomUtils.nextBytes(10), RandomUtils.nextBytes(10), keyRing1.getPubKeyRing().getSignaturePubKey());
    PrefixedSealedAndSignedMessage prefixedSealedAndSignedMessage = new PrefixedSealedAndSignedMessage(new NodeAddress("host", 1000), sealedAndSigned, RandomUtils.nextBytes(10),
            UUID.randomUUID().toString());
    MailboxStoragePayload mailboxStoragePayload = new MailboxStoragePayload(prefixedSealedAndSignedMessage,
            keyRing1.getPubKeyRing().getSignaturePubKey(), keyRing1.getPubKeyRing().getSignaturePubKey());
    ProtectedStorageEntry protectedStorageEntry = new ProtectedMailboxStorageEntry(mailboxStoragePayload,
            keyRing1.getSignatureKeyPair().getPublic(), 1, RandomUtils.nextBytes(10), keyRing1.getPubKeyRing().getSignaturePubKey(), Clock.systemDefaultZone());
    AddDataMessage dataMessage1 = new AddDataMessage(protectedStorageEntry);
    protobuf.NetworkEnvelope envelope = dataMessage1.toProtoNetworkEnvelope();

    //TODO Use NetworkProtoResolver, PersistenceProtoResolver or ProtoResolver which are all in io.bisq.common.
  /*  AddDataMessage dataMessage2 = (AddDataMessage) ProtoBufferUtilities.getAddDataMessage(envelope);

    assertTrue(dataMessage1.protectedStorageEntry.getStoragePayload().equals(dataMessage2.protectedStorageEntry.getStoragePayload()));
    assertTrue(dataMessage1.protectedStorageEntry.equals(dataMessage2.protectedStorageEntry));
    assertTrue(dataMessage1.equals(dataMessage2));*/
}
 
Example #10
Source File: IdStore.java    From janusgraph-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Get a random integer except the one(s) in the the ex
 * @param vType vertex label
 * @param ex unsorted list of unique numbers to exclude
 * @return an integer not in the exclude list or -1 if not found
 */
public int getRandomIdWithException(String vType, List<Integer> ex) {
    int start = idBean.getMinId(vType);
    int end = idBean.getMaxId(vType);
    boolean found = false;
    int rnd = -1;
    if (ex.size() > (end - start))
        return rnd;
    while (!found) {
        rnd = RandomUtils.nextInt(start, end + 1);
        if (false == ex.contains(rnd)) {
            found = true;
        }
    }
    return rnd;
}
 
Example #11
Source File: StoregateReadFeatureTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testReadCloseReleaseEntity() throws Exception {
    final TransferStatus status = new TransferStatus();
    final byte[] content = RandomUtils.nextBytes(32769);
    final TransferStatus writeStatus = new TransferStatus();
    writeStatus.setLength(content.length);
    final StoregateIdProvider nodeid = new StoregateIdProvider(session).withCache(cache);
    final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir(
        new Path(String.format("/My files/%s", new AlphanumericRandomStringService().random()),
            EnumSet.of(Path.Type.directory, Path.Type.volume)), null, new TransferStatus());
    final Path test = new Path(room, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final StoregateWriteFeature writer = new StoregateWriteFeature(session, nodeid);
    final HttpResponseOutputStream<VersionId> out = writer.write(test, writeStatus, new DisabledConnectionCallback());
    assertNotNull(out);
    new StreamCopier(writeStatus, writeStatus).transfer(new ByteArrayInputStream(content), out);
    final CountingInputStream in = new CountingInputStream(new StoregateReadFeature(session, nodeid).read(test, status, new DisabledConnectionCallback()));
    in.close();
    assertEquals(0L, in.getByteCount(), 0L);
    new StoregateDeleteFeature(session, nodeid).delete(Collections.singletonList(room), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example #12
Source File: HKDFTest.java    From hkdf with Apache License 2.0 6 votes vote down vote up
@Test
public void testExpand() {
    int[] lengthsPrk = {1, 16, 20, 32, 64};
    int[] lengthsOut = {1, 4, 7, 8, 16, 20, 24, 36, 48, 64, 69, 72, 96, 128, 256, 512};
    byte[] prk;
    byte[] info;
    for (int lengthPrk : lengthsPrk) {
        for (int lengthOut : lengthsOut) {
            prk = RandomUtils.nextBytes(lengthPrk);
            info = RandomUtils.nextBytes(lengthPrk);
            checkLength(HKDF.fromHmacSha256().expand(prk, info, lengthOut), lengthOut);
            checkLength(HKDF.fromHmacSha256().expand(prk, null, lengthOut), lengthOut);
            checkLength(HKDF.fromHmacSha256().expand(prk, new byte[0], lengthOut), lengthOut);
            checkLength(HKDF.fromHmacSha512().expand(prk, info, lengthOut), lengthOut);
            checkLength(HKDF.fromHmacSha512().expand(prk, null, lengthOut), lengthOut);
            checkLength(HKDF.from(HkdfMacFactory.Default.hmacSha1()).expand(prk, info, lengthOut), lengthOut);
            checkLength(HKDF.from(new HkdfMacFactory.Default("HmacMD5")).expand(prk, info, lengthOut), lengthOut);

            if (lengthOut > 4) {
                assertFalse(Arrays.equals(HKDF.fromHmacSha256().expand(prk, info, lengthOut), HKDF.fromHmacSha512().expand(prk, info, lengthOut)));
                assertFalse(Arrays.equals(HKDF.fromHmacSha256().expand(prk, info, lengthOut), HKDF.from(HkdfMacFactory.Default.hmacSha1()).expand(prk, info, lengthOut)));
            }
        }
    }
}
 
Example #13
Source File: DetailsDataStoreTest.java    From aion with MIT License 6 votes vote down vote up
@Test
public void testDecodingWithSizeFiveExternal() {
    AionAddress address = new AionAddress(RandomUtils.nextBytes(AionAddress.LENGTH));
    byte[] code = RandomUtils.nextBytes(512);

    // create encoding
    byte[] rlpAddress = RLP.encodeElement(address.toByteArray());
    byte[] rlpIsExternalStorage = RLP.encodeByte((byte) 1);
    byte[] root = RandomUtils.nextBytes(32);
    byte[] rlpStorageRoot = RLP.encodeElement(root);
    byte[] rlpStorageTrie = RLP.encodeElement(EMPTY_BYTE_ARRAY);
    byte[] rlpCode = RLP.encodeElement(code);

    byte[] encoding = RLP.encodeList(rlpAddress, rlpIsExternalStorage, rlpStorageRoot, rlpStorageTrie, rlpCode);

    // decode
    RLPContractDetails details = DetailsDataStore.fromEncoding(encoding);

    assertThat(details.address).isEqualTo(address);
    assertThat(details.isExternalStorage).isTrue();
    assertThat(details.storageRoot.getRLPData()).isEqualTo(root);
    assertThat(details.storageTrie.getRLPData()).isEqualTo(EMPTY_BYTE_ARRAY);
    assertThat(details.code.getRLPData()).isEqualTo(code);
}
 
Example #14
Source File: TestOzoneNativeAuthorizer.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
public TestOzoneNativeAuthorizer(String keyName, String prefixName,
    ACLType userRight,
    ACLType groupRight, boolean expectedResult) throws IOException {
  int randomInt = RandomUtils.nextInt();
  vol = "vol" + randomInt;
  buck = "bucket" + randomInt;
  key = keyName + randomInt;
  prefix = prefixName + randomInt + OZONE_URI_DELIMITER;
  parentDirUserAcl = userRight;
  parentDirGroupAcl = groupRight;
  expectedAclResult = expectedResult;

  createVolume(vol);
  createBucket(vol, buck);
  createKey(vol, buck, key);
}
 
Example #15
Source File: StoregateMultipartWriteFeatureTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testWriteUnknownLength() throws Exception {
    final StoregateIdProvider nodeid = new StoregateIdProvider(session).withCache(cache);
    final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir(
        new Path(String.format("/My files/%s", new AlphanumericRandomStringService().random()),
            EnumSet.of(Path.Type.directory, Path.Type.volume)), null, new TransferStatus());
    final byte[] content = RandomUtils.nextBytes(1);
    final TransferStatus status = new TransferStatus().length(-1L);
    final Path test = new Path(room, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final StoregateMultipartWriteFeature writer = new StoregateMultipartWriteFeature(session, nodeid);
    final HttpResponseOutputStream<VersionId> out = writer.write(test, status, new DisabledConnectionCallback());
    assertNotNull(out);
    new StreamCopier(status, status).transfer(new ByteArrayInputStream(content), out);
    final VersionId version = out.getStatus();
    assertNotNull(version);
    assertTrue(new DefaultFindFeature(session).find(test));
    new StoregateDeleteFeature(session, nodeid).delete(Collections.singletonList(room), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example #16
Source File: GraphWriteFeatureTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testWriteUmlaut() throws Exception {
    final GraphWriteFeature feature = new GraphWriteFeature(session);
    final Path container = new OneDriveHomeFinderService(session).find();
    final byte[] content = RandomUtils.nextBytes(2048);
    final TransferStatus status = new TransferStatus();
    status.setLength(content.length);
    final Path file = new Path(container, String.format("%sä", new AlphanumericRandomStringService().random()), EnumSet.of(Path.Type.file));
    final HttpResponseOutputStream<Void> out = feature.write(file, status, new DisabledConnectionCallback());
    final ByteArrayInputStream in = new ByteArrayInputStream(content);
    assertEquals(content.length, IOUtils.copyLarge(in, out));
    in.close();
    out.close();
    assertNull(out.getStatus());
    assertTrue(new DefaultFindFeature(session).find(file));
    final byte[] compare = new byte[content.length];
    final InputStream stream = new GraphReadFeature(session).read(file, new TransferStatus().length(content.length), new DisabledConnectionCallback());
    IOUtils.readFully(stream, compare);
    stream.close();
    assertArrayEquals(content, compare);
    new GraphDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example #17
Source File: InnerContractDetailsTest.java    From aion with MIT License 6 votes vote down vote up
@Test
public void testCommitToInner_withCode() {
    InnerContractDetails parent = new InnerContractDetails(null);

    byte[] code = RandomUtils.nextBytes(100);
    InnerContractDetails child = new InnerContractDetails(null);
    child.setCode(code);
    assertThat(child.isDirty()).isTrue();

    assertThat(parent.getVmType()).isEqualTo(InternalVmType.EITHER);

    child.commitTo(parent);

    assertThat(parent.getVmType()).isEqualTo(InternalVmType.EITHER);
    assertThat(parent.getCode(h256(code))).isEqualTo(code);
    assertThat(parent.isDirty()).isTrue();
}
 
Example #18
Source File: Shop.java    From java-master with Apache License 2.0 6 votes vote down vote up
/**
 * 获取商品价格(异步)
 */
public Future<Double> getPriceAsync(String product) {
    // 创建CompletableFuture对象,它会包含计算的结果
    CompletableFuture<Double> futurePrice = new CompletableFuture<>();
    new Thread(() -> {
        try {
            TimeUnit.MILLISECONDS.sleep(500 + RandomUtils.nextInt(10, 1000));
            // 模拟价格
            double price = RandomUtils.nextDouble(1, 10) * product.charAt(0) + product.charAt(1);
            // 需长时间计算的任务结束并得出结果时,设置Future的返回值
            futurePrice.complete(price);
        } catch (Exception ex) {
            // 抛出导致失败的异常,完成这次Future操作
            futurePrice.completeExceptionally(ex);
        }
    }).start();
    // 无需等待还没结束的计算,直接返回Future对象
    return futurePrice;
}
 
Example #19
Source File: CompactMobAction.java    From hbase with Apache License 2.0 6 votes vote down vote up
@Override
public void perform() throws Exception {
  HBaseTestingUtility util = context.getHBaseIntegrationTestingUtility();
  Admin admin = util.getAdmin();
  boolean major = RandomUtils.nextInt(0, 100) < majorRatio;

  // Don't try the modify if we're stopping
  if (context.isStopping()) {
    return;
  }

  getLogger().info("Performing action: Compact mob of table " + tableName + ", major=" + major);
  try {
    if (major) {
      admin.majorCompact(tableName, CompactType.MOB);
    } else {
      admin.compact(tableName, CompactType.MOB);
    }
  } catch (Exception ex) {
    getLogger().warn("Mob Compaction failed, might be caused by other chaos: " + ex.getMessage());
  }
  if (sleepTime > 0) {
    Thread.sleep(sleepTime);
  }
}
 
Example #20
Source File: CopyWorkerTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testCopyFile() throws Exception {
    final Path home = new DropboxHomeFinderFeature(session).find();
    final Path vault = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
    final Path source = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final Path target = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final CryptoVault cryptomator = new CryptoVault(vault);
    cryptomator.create(session, null, new VaultCredentials("test"), new DisabledPasswordStore(), vaultVersion);
    final DefaultVaultRegistry registry = new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator);
    session.withRegistry(registry);
    final byte[] content = RandomUtils.nextBytes(40500);
    final TransferStatus status = new TransferStatus();
    new CryptoBulkFeature<>(session, new DisabledBulkFeature(), new DropboxDeleteFeature(session), cryptomator).pre(Transfer.Type.upload, Collections.singletonMap(new TransferItem(source), status), new DisabledConnectionCallback());
    new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), new CryptoWriteFeature<>(session, new DropboxWriteFeature(session), cryptomator).write(source, status.length(content.length), new DisabledConnectionCallback()));
    assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(source));
    final CopyWorker worker = new CopyWorker(Collections.singletonMap(source, target), new SessionPool.SingleSessionPool(session, registry), PathCache.empty(), new DisabledProgressListener(), new DisabledConnectionCallback());
    worker.run(session);
    assertTrue(new CryptoFindFeature(session, new DropboxFindFeature(session), cryptomator).find(source));
    assertTrue(new CryptoFindFeature(session, new DropboxFindFeature(session), cryptomator).find(target));
    final ByteArrayOutputStream out = new ByteArrayOutputStream(content.length);
    assertEquals(content.length, IOUtils.copy(new CryptoReadFeature(session, new DropboxReadFeature(session), cryptomator).read(target, new TransferStatus().length(content.length), new DisabledConnectionCallback()), out));
    assertArrayEquals(content, out.toByteArray());
    new DeleteWorker(new DisabledLoginCallback(), Collections.singletonList(vault), PathCache.empty(), new DisabledProgressListener()).run(session);
    session.close();
}
 
Example #21
Source File: SubscribeToShardIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Puts a random record to the stream.
 *
 * @param len The number of bytes to generate for the record.
 * @return Record data that was put.
 */
private Optional<SdkBytes> putRecord(int len) {
    try {
        SdkBytes data = SdkBytes.fromByteArray(RandomUtils.nextBytes(len));
        asyncClient.putRecord(PutRecordRequest.builder()
                                              .streamName(streamName)
                                              .data(data)
                                              .partitionKey(UUID.randomUUID().toString())
                                              .build())
                   .join();
        return Optional.of(data);
    } catch (Exception e) {
        e.printStackTrace();
        return Optional.empty();
    }
}
 
Example #22
Source File: InboundParamMatchServiceImpl.java    From smockin with Apache License 2.0 5 votes vote down vote up
String processRandomNumber(final int matchStartingPosition, final String responseBody) {

        final String randomNumberContent = extractArgName(matchStartingPosition, ParamMatchTypeEnum.randomNumber, responseBody, false);

        if (logger.isDebugEnabled()) {
            logger.debug("Random number params: " + randomNumberContent);
        }

        if (randomNumberContent == null) {
            throw new IllegalArgumentException(ParamMatchTypeEnum.randomNumber.name() + " is missing args");
        }

        final String[] randomNumberContentParams = StringUtils.split(randomNumberContent, ",");

        if (randomNumberContentParams.length == 0) {
            throw new IllegalArgumentException(ParamMatchTypeEnum.randomNumber.name() + " is missing args");
        }

        if (randomNumberContentParams.length > 2) {
            throw new IllegalArgumentException(ParamMatchTypeEnum.randomNumber.name() + " has too many args");
        }

        final int startInc = (randomNumberContentParams.length == 2) ? Integer.parseInt(randomNumberContentParams[0].trim()) : 0;
        final int endExcl = (randomNumberContentParams.length == 2) ? Integer.parseInt(randomNumberContentParams[1].trim()) : Integer.parseInt(randomNumberContentParams[0].trim());
        final int randomValue = RandomUtils.nextInt(startInc, endExcl);

        if (logger.isDebugEnabled()) {
            logger.debug("Random number value: " + randomValue);
        }

        return StringUtils.replaceIgnoreCase(responseBody,
                ParamMatchTypeEnum.PARAM_PREFIX + ParamMatchTypeEnum.randomNumber + "(" + randomNumberContent + ")",
                String.valueOf(randomValue),
                1);
    }
 
Example #23
Source File: Shop.java    From java-master with Apache License 2.0 5 votes vote down vote up
public Future<Double> getPriceAsync1(String product) {
    return CompletableFuture.supplyAsync(() -> {
        try {
            TimeUnit.MILLISECONDS.sleep(500 + RandomUtils.nextInt(10, 1000));
        } catch (InterruptedException ignored) {
        }
        // 模拟价格
        return RandomUtils.nextDouble(1, 10) * product.charAt(0) + product.charAt(1);
    });
}
 
Example #24
Source File: RightDigging.java    From java-master with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        System.out.println("右边队伍任务挖掘中...");
        int time = RandomUtils.nextInt(3, 8);
        TimeUnit.SECONDS.sleep(time);
        System.out.println("右边队伍到达汇合点(即栅栏处),耗时" + time + "秒,等待中...");
        // 线程完成了其任务,停留在栅栏处,即线程阻塞在这一行.一旦所有线程都到达这个栅栏,那么栅栏就会被撤销,线程就可以继续运行了
        cyclicBarrier.await();
        System.out.println("栅栏被撤销,右边队伍线程继续运行");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #25
Source File: Request.java    From YuRPC with Apache License 2.0 5 votes vote down vote up
/**
 * 创建请求体
 *
 * @param requestType
 * @param method
 * @param params
 * @return
 */
public static Request createRequest(Boolean requestType, String method, Object... params) {
    Request request = new Request();
    request.setRequestType(requestType);
    request.setEventType(false);
    request.setId(COUNTER.getAndIncrement());
    request.setMethod(method);
    request.setParams(params);
    request.setCreateTime(System.currentTimeMillis());
    Pair<String, Integer> pair = ClientConfig.serverList.get(RandomUtils.nextInt(0, ClientConfig.serverList.size()));
    request.setHost(pair.getO1());
    request.setPort(pair.getO2());
    return request;
}
 
Example #26
Source File: CustomerServiceTest.java    From POC with Apache License 2.0 5 votes vote down vote up
@Test
void testGetCustomer() throws EntityNotFoundException {
	Customer customer = this.customerService.getCustomer(RandomUtils.nextLong());
	assertThat(customer).isNotNull();
	assertThat(customer.getFirstName()).isEqualTo("firstName");

	try {
		this.customerService.getCustomer(0L);
	}
	catch (EntityNotFoundException ex) {
		assertThat(ex).isExactlyInstanceOf(EntityNotFoundException.class);
	}
}
 
Example #27
Source File: DropboxWriteFeatureTest.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected = AccessDeniedException.class)
public void testWriteLibreOfficeLock() throws Exception {
    final DropboxWriteFeature write = new DropboxWriteFeature(session);
    final TransferStatus status = new TransferStatus();
    final byte[] content = RandomUtils.nextBytes(0);
    status.setLength(content.length);
    final Path test = new Path(new DropboxHomeFinderFeature(session).find(), ".~lock." + new AsciiRandomStringService().random(), EnumSet.of(Path.Type.file));
    final OutputStream out = write.write(test, status, new DisabledConnectionCallback());
    new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), out);
}
 
Example #28
Source File: DeallocatorService.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
/**
 * This method adds Deallocatable object instance to tracking system
 *
 * @param deallocatable object to track
 */
public void pickObject(@NonNull Deallocatable deallocatable) {
    val desiredDevice = deallocatable.targetDevice();
    val map = deviceMap.get(desiredDevice);
    val reference = new DeallocatableReference(deallocatable, map.get(RandomUtils.nextInt(0, map.size())));
    referenceMap.put(deallocatable.getUniqueId(), reference);
}
 
Example #29
Source File: LeftDigging.java    From java-master with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        System.out.println("左边队伍任务挖掘中...");
        int time = RandomUtils.nextInt(3, 8);
        TimeUnit.SECONDS.sleep(time);
        System.out.println("左边队伍到达汇合点(即栅栏处),耗时" + time + "秒,等待中...");
        // 线程完成了其任务,停留在栅栏处,即线程阻塞在这一行.一旦所有线程都到达这个栅栏,那么栅栏就会被撤销,线程就可以继续运行了
        cyclicBarrier.await();
        System.out.println("栅栏被撤销,左边队伍线程继续运行");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #30
Source File: RoutingTable.java    From dht-spider with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    RoutingTable routingTable = new RoutingTable();
    Map<Integer, PriorityQueue<Node>> tableMap = routingTable.getTableMap();
    tableMap.put(0,new PriorityQueue<>());
    byte[] bytes = RandomUtils.nextBytes(26);
    Node node = new Node(bytes);
    node.setRank(1);
    for(int i=0;i<100;i++)
        routingTable.put(node);

}