Java Code Examples for org.apache.commons.lang3.RandomUtils#nextBytes()

The following examples show how to use org.apache.commons.lang3.RandomUtils#nextBytes() . 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: TestOzoneFSInputStream.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
private static void testReadToByteBuffer(
    IntFunction<ByteBuffer> bufferConstructor,
    int streamLength, int bufferCapacity,
    int bufferPosition) throws IOException {
  final byte[] source = RandomUtils.nextBytes(streamLength);
  final InputStream input = new ByteArrayInputStream(source);
  final OzoneFSInputStream subject = createTestSubject(input);

  final int expectedReadLength = Math.min(bufferCapacity - bufferPosition,
      input.available());
  final byte[] expectedContent = Arrays.copyOfRange(source, 0,
      expectedReadLength);

  final ByteBuffer buf = bufferConstructor.apply(bufferCapacity);
  buf.position(bufferPosition);

  final int bytesRead = subject.read(buf);

  assertEquals(expectedReadLength, bytesRead);

  final byte[] content = new byte[bytesRead];
  buf.position(bufferPosition);
  buf.get(content);
  assertArrayEquals(expectedContent, content);
}
 
Example 2
Source File: HtltExample.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
    String yourPrivateKey = "";
    Wallet wallet =
            new Wallet(yourPrivateKey,
                    BinanceDexEnvironment.TEST_NET);
    BinanceDexApiRestClient client =
            BinanceDexApiClientFactory.newInstance().newRestClient(BinanceDexEnvironment.TEST_NET.getBaseUrl());

    HtltReq htltReq = new HtltReq();
    htltReq.setRecipient(""); // the recipient
    long timestamp = Instant.now().getEpochSecond();
    byte[] randomNumber = RandomUtils.nextBytes(32); // remember your randomNumber
    byte[] originData = ArrayUtils.addAll(randomNumber, EncodeUtils.long2Bytes(timestamp));
    htltReq.setRandomNumberHash(EncodeUtils.hashBySHA256(originData));
    htltReq.setTimestamp(timestamp);
    Token token = new Token();
    token.setDenom("BNB");
    token.setAmount(100L);
    htltReq.setOutAmount(Collections.singletonList(token));
    htltReq.setExpectedIncome("100:CNN-210");
    htltReq.setHeightSpan(1000);
    htltReq.setCrossChain(false);
    TransactionOption options = TransactionOption.DEFAULT_INSTANCE;
    List<TransactionMetadata> resp = client.htlt(htltReq,wallet,options,true);
    System.out.println(resp.get(0).toString());
}
 
Example 3
Source File: S3MultipartWriteFeatureTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testWrite() throws Exception {
    final S3MultipartWriteFeature feature = new S3MultipartWriteFeature(session);
    final Path container = new Path("test-eu-central-1-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final TransferStatus status = new TransferStatus();
    status.setLength(-1L);
    final Path file = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final HttpResponseOutputStream<VersionId> out = feature.write(file, status, new DisabledConnectionCallback());
    final byte[] content = RandomUtils.nextBytes(6 * 1024 * 1024);
    final ByteArrayInputStream in = new ByteArrayInputStream(content);
    final TransferStatus progress = new TransferStatus();
    new StreamCopier(new TransferStatus(), progress).transfer(in, out);
    assertEquals(content.length, progress.getOffset());
    in.close();
    out.close();
    assertNotNull(out.getStatus());
    assertTrue(new S3FindFeature(session).find(file));
    final byte[] compare = new byte[content.length];
    final InputStream stream = new S3ReadFeature(session).read(file, new TransferStatus().length(content.length), new DisabledConnectionCallback());
    IOUtils.readFully(stream, compare);
    stream.close();
    assertArrayEquals(content, compare);
    new S3DefaultDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example 4
Source File: InnerContractDetailsTest.java    From aion with MIT License 6 votes vote down vote up
@Test
public void testCommitToStored_withCodeOnFvm() {
    AionAddress address = mock(AionAddress.class);
    ByteArrayKeyValueStore db = mock(XorDataSource.class);
    FvmContractDetails parent = new FvmContractDetails(address, db);

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

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

    child.commitTo(parent);

    assertThat(parent.getVmType()).isEqualTo(InternalVmType.FVM);
    assertThat(parent.getCode(h256(code))).isEqualTo(code);
    assertThat(parent.isDirty()).isTrue();
}
 
Example 5
Source File: MantaWriteFeatureTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testWriteUnknownLength() throws Exception {
    final MantaWriteFeature feature = new MantaWriteFeature(session);
    final Path container = randomDirectory();
    new MantaDirectoryFeature(session).mkdir(container, "", new TransferStatus());
    final byte[] content = RandomUtils.nextBytes(5 * 1024 * 1024);

    final TransferStatus status = new TransferStatus();
    status.setLength(-1L);
    final Path file = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final HttpResponseOutputStream<Void> out = feature.write(file, status, new DisabledConnectionCallback());
    final ByteArrayInputStream in = new ByteArrayInputStream(content);
    final int alloc = 1024;
    final byte[] buffer = new byte[alloc];
    assertEquals(content.length, IOUtils.copyLarge(in, out, buffer));
    out.close();
    final PathAttributes found = new MantaAttributesFinderFeature(session).find(file);
    assertEquals(found.getSize(), content.length);
    new MantaDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example 6
Source File: StoregateMultipartWriteFeatureTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testReadWrite() throws Exception {
    final StoregateIdProvider nodeid = new StoregateIdProvider(session).withCache(cache);
    final Path folder = 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(524289);
    final TransferStatus status = new TransferStatus();
    status.setLength(-1L);
    final Path test = new Path(folder, 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));
    final byte[] compare = new byte[content.length];
    final InputStream stream = new StoregateReadFeature(session, nodeid).read(test, new TransferStatus().length(content.length), new DisabledConnectionCallback());
    IOUtils.readFully(stream, compare);
    stream.close();
    assertArrayEquals(content, compare);
    new StoregateDeleteFeature(session, nodeid).delete(Collections.singletonList(folder), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example 7
Source File: HtltExample.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
    String yourPrivateKey = "";
    Wallet wallet =
            new Wallet(yourPrivateKey,
                    BinanceDexEnvironment.TEST_NET);
    BinanceDexApiRestClient client =
            BinanceDexApiClientFactory.newInstance().newRestClient(BinanceDexEnvironment.TEST_NET.getBaseUrl());

    HtltReq htltReq = new HtltReq();
    htltReq.setRecipient(""); // the recipient
    long timestamp = Instant.now().getEpochSecond();
    byte[] randomNumber = RandomUtils.nextBytes(32); // remember your randomNumber
    byte[] originData = ArrayUtils.addAll(randomNumber, EncodeUtils.long2Bytes(timestamp));
    htltReq.setRandomNumberHash(EncodeUtils.hashBySHA256(originData));
    htltReq.setTimestamp(timestamp);
    Token token = new Token();
    token.setDenom("BNB");
    token.setAmount(100L);
    htltReq.setOutAmount(Collections.singletonList(token));
    htltReq.setExpectedIncome("100:CNN-210");
    htltReq.setHeightSpan(1000);
    htltReq.setCrossChain(false);
    TransactionOption options = TransactionOption.DEFAULT_INSTANCE;
    List<TransactionMetadata> resp = client.htlt(htltReq,wallet,options,true);
    System.out.println(resp.get(0).toString());
}
 
Example 8
Source File: MemorySegementingOutputStreamTest.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testCopy1() throws Exception {
    final ByteArrayOutputStream proxy = new ByteArrayOutputStream(20);
    final MemorySegementingOutputStream out = new MemorySegementingOutputStream(proxy, 32768);
    final byte[] content = RandomUtils.nextBytes(40500);
    out.write(content, 0, 32800);
    assertEquals(32768, proxy.toByteArray().length);
    out.write(content, 32800, 7700);
    out.close();
    assertArrayEquals(content, proxy.toByteArray());
}
 
Example 9
Source File: AionTransactionTest.java    From aion with MIT License 5 votes vote down vote up
@Test
public void testBeaconHashAbsent() {
    byte[] nonce = RandomUtils.nextBytes(16);
    AionAddress to = new AionAddress(RandomUtils.nextBytes(32));
    byte[] value = RandomUtils.nextBytes(16);
    byte[] data = RandomUtils.nextBytes(64);
    long nrg = 0;
    long nrgPrice = 0;
    byte type = 0;

    AionTransaction tx =
            AionTransaction.create(
                    key,
                    nonce,
                    to,
                    value,
                    data,
                    nrg,
                    nrgPrice,
                    type,
                    null);

    assertNull("beacon hash should be null", tx.getBeaconHash());

    RLPList decoded = (RLPList) RLP.decode2(tx.getEncoded()).get(0);
    assertEquals("wrong number of elements in RLP encoding of AionTransaction without beacon hash",
            TxUtil.RLP_TX_SIG,
            decoded.size() - 1
    );

    AionTransaction tx2 = TxUtil.decode(tx.getEncoded());
    assertNotNull(tx2);
    assertTransactionEquals(tx, tx2);
}
 
Example 10
Source File: GraphReadFeatureTest.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testReadRange() throws Exception {
    final Path drive = new OneDriveHomeFinderService(session).find();
    final Path test = new Path(drive, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    new GraphTouchFeature(session).touch(test, new TransferStatus());

    final Local local = new Local(System.getProperty("java.io.tmpdir"), new AlphanumericRandomStringService().random());
    final byte[] content = RandomUtils.nextBytes(1000);
    final OutputStream out = local.getOutputStream(false);
    assertNotNull(out);
    IOUtils.write(content, out);
    out.close();
    new DefaultUploadFeature<Void>(new GraphWriteFeature(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 GraphReadFeature read = new GraphReadFeature(session);
    assertTrue(read.offset(test));
    final InputStream in = read.read(test, status.length(content.length - 100), 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 GraphDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example 11
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 testWriteMSOfficeLock() 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(), "~$" + 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 12
Source File: MemorySegementingOutputStreamTest.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testCopy3() throws Exception {
    final ByteArrayOutputStream proxy = new ByteArrayOutputStream(40500);
    final MemorySegementingOutputStream out = new MemorySegementingOutputStream(proxy, 32768);
    final byte[] content = RandomUtils.nextBytes(40500);
    out.write(content, 0, 32767);
    assertEquals(0, proxy.toByteArray().length);
    out.write(content, 32767, 2);
    assertEquals(32768, proxy.toByteArray().length);
    out.write(content, 32769, 7731);
    out.close();
    assertArrayEquals(content, proxy.toByteArray());
}
 
Example 13
Source File: Benchmark.java    From aion with MIT License 5 votes vote down vote up
private static MiningBlock createDummyBlock() {
    byte[] parentHash = new byte[32];
    byte[] coinbase = RandomUtils.nextBytes(AionAddress.LENGTH);
    byte[] logsBloom = new byte[0];
    byte[] difficulty = new DataWord(0x1000000L).getData();
    long number = 1;
    long timestamp = System.currentTimeMillis() / 1000;
    byte[] extraData = new byte[0];
    byte[] nonce = new byte[32];
    byte[] receiptsRoot = new byte[32];
    byte[] transactionsRoot = new byte[32];
    byte[] stateRoot = new byte[32];
    List<AionTransaction> transactionsList = Collections.emptyList();
    byte[] solutions = new byte[0];

    // TODO: set a dummy limit of 5000000 for now
    return new MiningBlock(
            parentHash,
            new AionAddress(coinbase),
            logsBloom,
            difficulty,
            number,
            timestamp,
            extraData,
            nonce,
            receiptsRoot,
            transactionsRoot,
            stateRoot,
            transactionsList,
            solutions,
            0,
            5000000);
}
 
Example 14
Source File: FvmContractDetailsTest.java    From aion with MIT License 5 votes vote down vote up
@Test
public void testDecode_withExternalStorageAndMultiCode() {
    AionAddress address = new AionAddress(RandomUtils.nextBytes(AionAddress.LENGTH));

    byte[] storageHash = RandomUtils.nextBytes(32);
    RLPElement root = mock(RLPItem.class);
    when(root.getRLPData()).thenReturn(storageHash);

    byte[] codeBytes1 = RandomUtils.nextBytes(100);
    byte[] codeBytes2 = RandomUtils.nextBytes(100);
    RLPList code = new RLPList();
    code.add(new RLPItem(codeBytes1));
    code.add(new RLPItem(codeBytes2));

    RLPContractDetails input = new RLPContractDetails(address, true, root, null, code);
    FvmContractDetails details = FvmContractDetails.decodeAtRoot(input, mockDatabase, storageHash);
    assertThat(details.address).isEqualTo(address);
    assertThat(details.isDirty()).isTrue(); // because it uses the setCodes method
    assertThat(details.isDeleted()).isFalse();

    assertThat(details.getCodes().size()).isEqualTo(2);
    assertThat(details.getCodes().values()).contains(ByteArrayWrapper.wrap(codeBytes1));
    assertThat(details.getCodes().values()).contains(ByteArrayWrapper.wrap(codeBytes2));
    assertThat(details.getCode(h256(codeBytes1))).isEqualTo(codeBytes1);
    assertThat(details.getCode(h256(codeBytes2))).isEqualTo(codeBytes2);

    assertThat(details.getStorageHash()).isEqualTo(storageHash);
}
 
Example 15
Source File: ApiAion0Test.java    From aion with MIT License 5 votes vote down vote up
public ApiAion0Test() {
    msg = "test message".getBytes();
    socketId = RandomUtils.nextBytes(5);
    hash = RandomUtils.nextBytes(ApiUtil.HASH_LEN);
    System.out.println("socketId set to " + ByteUtil.toHexString(socketId));
    System.out.println("hash set to " + ByteUtil.toHexString(hash));
    rsp = null;
}
 
Example 16
Source File: AzureWriteFeatureTest.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testWrite() throws Exception {
    final Host host = new Host(new AzureProtocol(), "kahy9boj3eib.blob.core.windows.net", new Credentials(
        System.getProperties().getProperty("azure.account"), System.getProperties().getProperty("azure.key")
    ));
    final AzureSession session = new AzureSession(host);
    session.open(Proxy.DIRECT, new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(Proxy.DIRECT, new DisabledLoginCallback(), new DisabledCancelCallback());
    final TransferStatus status = new TransferStatus();
    final byte[] content = RandomUtils.nextBytes(1048576);
    status.setLength(content.length);
    final Path home = new Path("cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory));
    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);
    session.withRegistry(new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator));
    final CryptoWriteFeature<Void> writer = new CryptoWriteFeature<>(session, new AzureWriteFeature(session, null), cryptomator);
    final FileHeader header = cryptomator.getFileHeaderCryptor().create();
    status.setHeader(cryptomator.getFileHeaderCryptor().encryptHeader(header));
    status.setNonces(new RotatingNonceGenerator(cryptomator.numberOfChunks(content.length)));
    final Path test = new Path(vault, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    status.setChecksum(writer.checksum(test, status).compute(new ByteArrayInputStream(content), status));
    final OutputStream out = writer.write(test, status, new DisabledConnectionCallback());
    assertNotNull(out);
    new StreamCopier(status, status).transfer(new ByteArrayInputStream(content), out);
    out.close();
    final OperationContext context = new OperationContext();
    assertTrue(new CryptoFindFeature(session, new AzureFindFeature(session, context), cryptomator).find(test));
    assertEquals(content.length, new CryptoListService(session, new AzureListService(session, context), cryptomator).list(test.getParent(), new DisabledListProgressListener()).get(test).attributes().getSize());
    assertEquals(content.length, new CryptoWriteFeature<>(session, new AzureWriteFeature(session, context, new DefaultFindFeature(session), new DefaultAttributesFinderFeature(session)), cryptomator).append(test, status.getLength(), PathCache.empty()).size, 0L);
    assertEquals(content.length, new CryptoWriteFeature<>(session, new AzureWriteFeature(session, context, new AzureFindFeature(session, context), new AzureAttributesFinderFeature(session, context)), cryptomator).append(test, status.getLength(), PathCache.empty()).size, 0L);
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length);
    final InputStream in = new CryptoReadFeature(session, new AzureReadFeature(session, context), cryptomator).read(test, new TransferStatus().length(content.length), new DisabledConnectionCallback());
    new StreamCopier(status, status).transfer(in, buffer);
    assertArrayEquals(content, buffer.toByteArray());
    cryptomator.getFeature(session, Delete.class, new AzureDeleteFeature(session, context)).delete(Arrays.asList(test, vault), new DisabledLoginCallback(), new Delete.DisabledCallback());
    session.close();
}
 
Example 17
Source File: StoregateReadFeatureTest.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testReadRangeUnknownLength() 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 Path test = new Path(room, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    new StoregateTouchFeature(session, nodeid).touch(test, new TransferStatus());
    final Local local = new Local(System.getProperty("java.io.tmpdir"), new AlphanumericRandomStringService().random());
    final byte[] content = RandomUtils.nextBytes(1000);
    final OutputStream out = local.getOutputStream(false);
    assertNotNull(out);
    IOUtils.write(content, out);
    out.close();
    final TransferStatus upload = new TransferStatus().length(content.length);
    upload.setExists(true);
    new DefaultUploadFeature<VersionId>(new StoregateWriteFeature(session, nodeid)).upload(
        test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(), upload,
        new DisabledConnectionCallback());
    final TransferStatus status = new TransferStatus();
    status.setLength(-1L);
    status.setAppend(true);
    status.setOffset(100L);
    final InputStream in = new StoregateReadFeature(session, nodeid).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 StoregateDeleteFeature(session, nodeid).delete(Collections.singletonList(room), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example 18
Source File: DdiArtifactDownloadTest.java    From hawkbit with Eclipse Public License 1.0 4 votes vote down vote up
@Test
@Description("Tests non allowed requests on the artifact ressource, e.g. invalid URI, wrong if-match, wrong command.")
public void invalidRequestsOnArtifactResource() throws Exception {
    // create target
    final Target target = testdataFactory.createTarget();
    final List<Target> targets = Arrays.asList(target);

    // create ds
    final DistributionSet ds = testdataFactory.createDistributionSet("");
    assignDistributionSet(ds, targets);

    // create artifact
    final int artifactSize = 5 * 1024;
    final byte random[] = RandomUtils.nextBytes(artifactSize);
    final Artifact artifact = artifactManagement.create(new ArtifactUpload(new ByteArrayInputStream(random),
            ds.findFirstModuleByType(osType).get().getId(), "file1", false, artifactSize));

    // no artifact available
    mvc.perform(get("/controller/v1/{controllerId}/softwaremodules/{softwareModuleId}/artifacts/123455",
            target.getControllerId(), getOsModule(ds))).andExpect(status().isNotFound());
    mvc.perform(get("/controller/v1/{controllerId}/softwaremodules/{softwareModuleId}/artifacts/123455.MD5SUM",
            target.getControllerId(), getOsModule(ds))).andExpect(status().isNotFound());

    // SM does not exist
    mvc.perform(get("/controller/v1/{controllerId}/softwaremodules/1234567890/artifacts/{filename}",
            target.getControllerId(), artifact.getFilename())).andExpect(status().isNotFound());
    mvc.perform(get("/controller/v1/{controllerId}/softwaremodules/1234567890/artifacts/{filename}.MD5SUM",
            target.getControllerId(), artifact.getFilename())).andExpect(status().isNotFound());

    // test now consistent data to test allowed methods
    mvc.perform(get("/{tenant}/controller/v1/{controllerId}/softwaremodules/{smId}/artifacts/{filename}",
            tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename())
                    .header(HttpHeaders.IF_MATCH, artifact.getSha1Hash()))
            .andExpect(status().isOk());
    mvc.perform(get("/{tenant}/controller/v1/{controllerId}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM",
            tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()))
            .andExpect(status().isOk());

    // test failed If-match
    mvc.perform(get("/{tenant}/controller/v1/{controllerId}/softwaremodules/{smId}/artifacts/{filename}",
            tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename())
                    .header(HttpHeaders.IF_MATCH, "fsjkhgjfdhg"))
            .andExpect(status().isPreconditionFailed());

    // test invalid range
    mvc.perform(get("/{tenant}/controller/v1/{controllerId}/softwaremodules/{smId}/artifacts/{filename}",
            tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename())
                    .header("Range", "bytes=1-10,hdsfjksdh"))
            .andExpect(header().string("Content-Range", "bytes */" + 5 * 1024))
            .andExpect(status().isRequestedRangeNotSatisfiable());

    mvc.perform(get("/{tenant}/controller/v1/{controllerId}/softwaremodules/{smId}/artifacts/{filename}",
            tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename())
                    .header("Range", "bytes=100-10"))
            .andExpect(header().string("Content-Range", "bytes */" + 5 * 1024))
            .andExpect(status().isRequestedRangeNotSatisfiable());

    // not allowed methods
    mvc.perform(put("/{tenant}/controller/v1/{controllerId}/softwaremodules/{smId}/artifacts/{filename}",
            tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()))
            .andExpect(status().isMethodNotAllowed());

    mvc.perform(delete("/{tenant}/controller/v1/{controllerId}/softwaremodules/{smId}/artifacts/{filename}",
            tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()))
            .andExpect(status().isMethodNotAllowed());

    mvc.perform(post("/{tenant}/controller/v1/{controllerId}/softwaremodules/{smId}/artifacts/{filename}",
            tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()))
            .andExpect(status().isMethodNotAllowed());

    mvc.perform(put("/{tenant}/controller/v1/{controllerId}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM",
            tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()))
            .andExpect(status().isMethodNotAllowed());

    mvc.perform(delete("/{tenant}/controller/v1/{controllerId}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM",
            tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()))
            .andExpect(status().isMethodNotAllowed());

    mvc.perform(post("/{tenant}/controller/v1/{controllerId}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM",
            tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()))
            .andExpect(status().isMethodNotAllowed());
}
 
Example 19
Source File: DHTUtil.java    From dht-spider with MIT License 4 votes vote down vote up
public static String generateNodeIdString() {
    return new String(RandomUtils.nextBytes(20), CharsetUtil.ISO_8859_1);
}
 
Example 20
Source File: DdiArtifactDownloadTest.java    From hawkbit with Eclipse Public License 1.0 4 votes vote down vote up
@Test
@WithUser(principal = "4712", authorities = "ROLE_CONTROLLER", allSpPermissions = true)
@Description("Tests valid downloads through the artifact resource by identifying the artifact not by ID but file name.")
public void downloadArtifactThroughFileName() throws Exception {
    downLoadProgress = 1;
    shippedBytes = 0;
    assertThat(softwareModuleManagement.findAll(PAGE)).hasSize(0);

    // create target
    final Target target = testdataFactory.createTarget();
    final List<Target> targets = Arrays.asList(target);

    // create ds
    final DistributionSet ds = testdataFactory.createDistributionSet("");

    // create artifact
    final int artifactSize = 5 * 1024 * 1024;
    final byte random[] = RandomUtils.nextBytes(artifactSize);
    final Artifact artifact = artifactManagement.create(new ArtifactUpload(new ByteArrayInputStream(random),
            ds.findFirstModuleByType(osType).get().getId(), "file1", false, artifactSize));

    // download fails as artifact is not yet assigned
    mvc.perform(get("/controller/v1/{controllerId}/softwaremodules/{softwareModuleId}/artifacts/{filename}",
            target.getControllerId(), getOsModule(ds), artifact.getFilename())).andExpect(status().isNotFound());

    // now assign and download successful
    assignDistributionSet(ds, targets);
    final MvcResult result = mvc.perform(get(
            "/{tenant}/controller/v1/{controllerId}/softwaremodules/{softwareModuleId}/artifacts/{filename}",
            tenantAware.getCurrentTenant(), target.getControllerId(), getOsModule(ds), artifact.getFilename()))
            .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM))
            .andExpect(header().string("Accept-Ranges", "bytes"))
            .andExpect(header().string("Last-Modified", dateFormat.format(new Date(artifact.getCreatedAt()))))
            .andExpect(header().string("Content-Disposition", "attachment;filename=" + artifact.getFilename()))
            .andReturn();

    assertTrue("The same file that was uploaded is expected when downloaded",
            Arrays.equals(result.getResponse().getContentAsByteArray(), random));

    // download complete
    assertThat(downLoadProgress).isEqualTo(10);
    assertThat(shippedBytes).isEqualTo(artifactSize);
}