下面列出了怎么用org.apache.commons.lang3.RandomUtils的API类实例代码及写法,或者点击链接到github查看源代码。
@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();
}
@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());
}
@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);
}
@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);
}
@Test
public void should_generate_jwt_token_with_refresh_type() throws Exception {
// Create payload
Long userId = RandomUtils.nextLong(10, 1000);
Set<Integer> actions = new HashSet<>();
actions.add(0);
Set<String> networkIds = new HashSet<>();
networkIds.add("string");
Set<String> deviceTypeIds = new HashSet<>();
deviceTypeIds.add("string");
Set<String> deviceIds = new HashSet<>();
deviceIds.add("string");
JwtUserPayload.JwtUserPayloadBuilder jwtUserPayloadBuilder = new JwtUserPayload.JwtUserPayloadBuilder();
JwtUserPayload payload = jwtUserPayloadBuilder.withPublicClaims(userId, actions, networkIds, deviceTypeIds).buildPayload();
String token = jwtClientService.generateJwtRefreshToken(payload, true);
JwtUserPayload resultPayload = jwtClientService.getUserPayload(token);
assertEquals(resultPayload.getTokenType(), TokenType.REFRESH.getId());
}
@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();
}
/**
* 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();
}
}
@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());
}
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);
}
@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();
}
@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);
}
}
@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());
}
@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());
}
@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());
}
@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)));
}
}
}
}
@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));*/
}
@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());
}
@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);
}
@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();
}
/**
* 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;
}
@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());
}
/**
* 获取商品价格(异步)
*/
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;
}
/**
* Sets a key-value pair with a zero value via cache.setStorage() and ensures that null is
* returned when called on that same key.
*/
private void doSetZeroValueViaStorageTest(ContractDetails cache) {
Map<ByteArrayWrapper, ByteArrayWrapper> storage = new HashMap<>();
ByteArrayWrapper key =
new DataWord(RandomUtils.nextBytes(DataWord.BYTES)).toWrapper();
storage.put(key, null);
setStorage(cache, storage);
checkGetNonExistentPairing(cache, key);
}
private void prepareFile(final Path path, final SwiftRegionService regionService, final SwiftSegmentService segmentService) throws BackgroundException {
final SwiftLargeUploadWriteFeature upload = new SwiftLargeUploadWriteFeature(session, regionService, segmentService);
final OutputStream out = upload.write(path, new TransferStatus(), new DisabledConnectionCallback());
final byte[] content = RandomUtils.nextBytes(1024 * 1024);
final ByteArrayInputStream in = new ByteArrayInputStream(content);
final TransferStatus progress = new TransferStatus();
new StreamCopier(new TransferStatus(), progress).transfer(in, out);
}
@Test
public void testCopyFileIntoVault() 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 cleartextFile = new Path(home, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
final SwiftWriteFeature write = new SwiftWriteFeature(session, new SwiftRegionService(session));
final byte[] content = RandomUtils.nextBytes(40500);
new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), write.write(cleartextFile, new TransferStatus().length(content.length), new DisabledConnectionCallback()));
assertTrue(new SwiftFindFeature(session).find(cleartextFile));
final Path encryptedFolder = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
final Path encryptedFile = new Path(encryptedFolder, 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);
cryptomator.getFeature(session, Directory.class, new SwiftDirectoryFeature(session)).mkdir(encryptedFolder, null, new TransferStatus());
assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(encryptedFolder));
// copy file into vault
final CopyWorker worker = new CopyWorker(Collections.singletonMap(cleartextFile, encryptedFile), new SessionPool.SingleSessionPool(session, registry), PathCache.empty(), new DisabledProgressListener(), new DisabledConnectionCallback());
worker.run(session);
assertTrue(new SwiftFindFeature(session).find(cleartextFile));
assertTrue(new CryptoFindFeature(session, new SwiftFindFeature(session), cryptomator).find(encryptedFile));
final ByteArrayOutputStream out = new ByteArrayOutputStream(content.length);
assertEquals(content.length, IOUtils.copy(new CryptoReadFeature(session, new SwiftReadFeature(session, new SwiftRegionService(session)), cryptomator).read(encryptedFile, 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();
registry.clear();
}
@Test
public void testReadRange() throws Exception {
final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new IRODSProtocol())));
final Profile profile = new ProfilePlistReader(factory).read(
new Local("../profiles/iRODS (iPlant Collaborative).cyberduckprofile"));
final Host host = new Host(profile, profile.getDefaultHostname(), new Credentials(
System.getProperties().getProperty("irods.key"), System.getProperties().getProperty("irods.secret")
));
final IRODSSession session = new IRODSSession(host);
session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback());
session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback());
final Path test = new Path(new IRODSHomeFinderService(session).find(), UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
new IRODSTouchFeature(session).touch(test, new TransferStatus());
final Local local = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
final byte[] content = RandomUtils.nextBytes(2048);
final OutputStream out = local.getOutputStream(false);
assertNotNull(out);
IOUtils.write(content, out);
out.close();
new DefaultUploadFeature<Integer>(new IRODSWriteFeature(session)).upload(
test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(),
new TransferStatus().length(content.length),
new DisabledConnectionCallback());
final TransferStatus status = new TransferStatus();
status.setLength(content.length);
status.setAppend(true);
status.setOffset(100L);
final InputStream in = new IRODSReadFeature(session).read(test, status, new DisabledConnectionCallback());
assertNotNull(in);
final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length - 100);
new StreamCopier(status, status).transfer(in, buffer);
final byte[] reference = new byte[content.length - 100];
System.arraycopy(content, 100, reference, 0, content.length - 100);
assertArrayEquals(reference, buffer.toByteArray());
in.close();
new IRODSDeleteFeature(session).delete(Collections.<Path>singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
session.close();
}
@RepeatedTest(3)
public void testGetKeyNew() {
long startTime = Utils.now();
int i = 500;
while (i-- >=0) {
lastPriceCacheNew.getLastPrice(RandomUtils.nextInt(1, 3));
}
System.out.println("testGetKeyNew:" + Utils.diff(startTime));
}
public String randomCanadianOrUsFiveOrNineDigitPostalCode() {
if (RandomUtils.nextBoolean()) {
return randomCanadianPostalCode();
} else if (RandomUtils.nextBoolean()) {
return randomUsZipCode();
}
return randomUsZipCodeNineDigit();
}
/**
* Create a {@link PictureProject} with some example data.
*
* @return created example object
*/
protected static PictureProject createPicture() {
PictureProject pic = FACTORY.createPictureProject();
pic.setPosition(BigInteger.valueOf(RandomUtils.nextLong(0, 100)));
pic.setValue("image-" + RandomUtils.nextInt(0, 999) + ".jpg");
return pic;
}
@Override
protected void doCommit() {
try {
Thread.sleep(20 * RandomUtils.nextInt(10, 15));
} catch (InterruptedException e) {
e.printStackTrace();
}
}