Example usage for java.util Random nextLong

List of usage examples for java.util Random nextLong

Introduction

In this page you can find the example usage for java.util Random nextLong.

Prototype

public long nextLong() 

Source Link

Document

Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence.

Usage

From source file:sf.net.experimaestro.scheduler.SchedulerTest.java

@Test(description = "Run jobs generated at random", dataProvider = "complexDependenciesTestProvider")
public void test_complex_dependencies(ComplexDependenciesParameters p)
        throws ExperimaestroCannotOverwrite, IOException {
    Random random = new Random();
    long seed = p.seed == null ? random.nextLong() : p.seed;
    LOGGER.info("Seed is %d", seed);
    random.setSeed(seed);//from   w w  w  .ja va 2  s  .co  m

    // Prepares directory and counter
    File jobDirectory = mkTestDir();
    ThreadCount counter = new ThreadCount();

    // Our set of jobs
    WaitingJob[] jobs = new WaitingJob[p.nbJobs];

    // --- Generate the dependencies

    // Number of potential dependencies
    int nbCouples = p.nbJobs * (p.nbJobs - 1) / 2;

    // Maximum number of dependencies
    final int maxDependencies = min(p.maxDeps, nbCouples);

    // The list of dependencies
    TreeSet<Link> dependencies = new TreeSet<>();

    // Number of generated dependencies
    int n = min(min((int) (long) (nbCouples * p.dependencyRatio * random.nextDouble()), Integer.MAX_VALUE),
            maxDependencies);
    long[] values = new long[n];
    // Draw n dependencies among nbCouples possible
    RandomSampler.sample(n, nbCouples, n, 0, values, 0, random);

    LOGGER.debug("Sampling %d values from %d", n, nbCouples);
    for (long v : values) {
        final Link link = new Link(v);
        dependencies.add(link);
        LOGGER.debug("LINK %d status %d [%d]", link.from, link.to, v);
        assert link.from < p.nbJobs;
        assert link.to < p.nbJobs;
        assert link.from < link.to;
    }

    // --- Select the jobs that will fail
    ResourceState[] states = new ResourceState[jobs.length];
    for (int i = 0; i < states.length; i++)
        states[i] = ResourceState.DONE;
    n = (int) max(p.minFailures, random.nextDouble() * p.failureRatio * jobs.length);
    long[] values2 = new long[n];
    RandomSampler.sample(n, jobs.length - p.minFailureId, n, p.minFailureId, values2, 0, random);
    for (int i = 0; i < n; i++)
        states[((int) values2[i])] = ResourceState.ERROR;

    // --- Generate token resource
    final TokenResource token;
    if (p.token > 0) {
        token = Transaction.evaluate((em, t) -> {
            final String path = format("scheduler_test/test_complex_dependency/%s", p.name);
            final TokenResource _token = new TokenResource(path, p.token);
            _token.save(t);
            return _token;
        });
    } else {
        token = null;
    }

    final MutableLong totalTime = new MutableLong();

    // --- Generate new jobs
    for (int i = 0; i < jobs.length; i++) {
        final int j = i;

        Transaction.run((em, t) -> {
            int waitingTime = random.nextInt(p.maxExecutionTime - p.minExecutionTime) + p.minExecutionTime;
            jobs[j] = new WaitingJob(counter, jobDirectory, "job" + j,
                    new Action(waitingTime, states[j] == ResourceState.DONE ? 0 : 1, 0));

            totalTime.add(jobs[j].totalTime() + JOB_PROCESSING_TIME);

            ArrayList<String> deps = new ArrayList<>();
            for (Link link : dependencies.subSet(new Link(j, 0), true, new Link(j, Integer.MAX_VALUE), true)) {
                assert j == link.to;
                jobs[j].addDependency(jobs[link.from].createDependency(null));
                if (states[link.from].isBlocking())
                    states[j] = ResourceState.ON_HOLD;
                deps.add(jobs[link.from].toString());
            }

            if (token != null) {
                jobs[j].addDependency(em.find(TokenResource.class, token.getId()).createDependency(null));
            }

            jobs[j].save(t);
            LOGGER.debug("Job [%s] created: final=%s, deps=%s", jobs[j], states[j],
                    Output.toString(", ", deps));
        });
    }

    LOGGER.info("Waiting for jobs status finish (%d remaining) / total time = %dms", counter.getCount(),
            totalTime.longValue());

    waitToFinish(0, counter, jobs, totalTime.longValue(), 5);

    waitBeforeCheck();

    int count = counter.getCount();

    LOGGER.info("Finished waiting [%d]: %d jobs remaining", System.currentTimeMillis(), counter.getCount());

    if (count > 0) {
        LOGGER.error("Time out: %d jobs were not processed", count);
    }

    // --- Check
    LOGGER.info("Checking job states");
    int errors = 0;
    for (int i = 0; i < jobs.length; i++)
        errors += checkState(EnumSet.of(states[i]), jobs[i]);

    LOGGER.info("Checking job dependencies");
    for (Link link : dependencies) {
        if (states[link.from] == ResourceState.DONE && jobs[link.to].getState() == ResourceState.DONE)
            errors += checkSequence(false, true, jobs[link.from], jobs[link.to]);
    }

    Assert.assertTrue(errors == 0, "Detected " + errors + " errors after running jobs");
}

From source file:org.jenkinsci.remoting.protocol.impl.ConnectionHeadersFilterLayerTest.java

@Theory
public void headerExchange(NetworkLayerFactory serverFactory, NetworkLayerFactory clientFactory)
        throws Exception {
    Random entropy = new Random();
    final SettableFuture<Map<String, String>> serverActualHeaders = SettableFuture.create();
    Map<String, String> clientExpectedHeaders = new HashMap<String, String>();
    for (int i = 1 + entropy.nextInt(50); i > 0; i--) {
        clientExpectedHeaders.put(Long.toHexString(entropy.nextLong()), Long.toHexString(entropy.nextLong()));
    }/*from  w  w  w  .  j  ava2s.  c o  m*/
    ProtocolStack<IOBufferMatcher> client = ProtocolStack
            .on(clientFactory.create(selector.hub(), serverToClient.source(), clientToServer.sink()))
            .filter(new ConnectionHeadersFilterLayer(clientExpectedHeaders,
                    new ConnectionHeadersFilterLayer.Listener() {
                        @Override
                        public void onReceiveHeaders(Map<String, String> headers)
                                throws ConnectionRefusalException {
                            serverActualHeaders.set(headers);
                        }
                    }))
            .build(new IOBufferMatcherLayer());

    final SettableFuture<Map<String, String>> clientActualHeaders = SettableFuture.create();
    Map<String, String> serverExpectedHeaders = new HashMap<String, String>();
    for (int i = 1 + entropy.nextInt(50); i > 0; i--) {
        serverExpectedHeaders.put(Long.toHexString(entropy.nextLong()), Long.toHexString(entropy.nextLong()));
    }
    ProtocolStack<IOBufferMatcher> server = ProtocolStack
            .on(serverFactory.create(selector.hub(), clientToServer.source(), serverToClient.sink()))
            .filter(new ConnectionHeadersFilterLayer(serverExpectedHeaders,
                    new ConnectionHeadersFilterLayer.Listener() {
                        @Override
                        public void onReceiveHeaders(Map<String, String> headers)
                                throws ConnectionRefusalException {
                            clientActualHeaders.set(headers);
                        }
                    }))
            .build(new IOBufferMatcherLayer());

    byte[] expected = "Here is some sample data".getBytes("UTF-8");
    ByteBuffer data = ByteBuffer.allocate(expected.length);
    data.put(expected);
    data.flip();
    server.get().send(data);
    client.get().awaitByteContent(is(expected));
    assertThat(client.get().asByteArray(), is(expected));

    assertThat(serverActualHeaders.get(1000, TimeUnit.MICROSECONDS), is(serverExpectedHeaders));
    assertThat(clientActualHeaders.get(1000, TimeUnit.MICROSECONDS), is(clientExpectedHeaders));
}

From source file:rapture.blob.BlobApiTests.java

@Test(groups = { "blob", "mongo", "nightly" })
public void testBlobPut() {
    long maxContentSize = 10000L;

    Random rand = new Random();
    RaptureURI repo = helper.getRandomAuthority(Scheme.BLOB);
    helper.configureTestRepo(repo, "MONGODB");
    String repoName = new RaptureURI.Builder(repo).docPath("").build().toString();
    String blobUri = repoName + "testblob" + System.nanoTime();

    long content_size = Math.abs(rand.nextLong() % maxContentSize);
    String currBlobURI = blobUri + Thread.currentThread().getId() + "_" + content_size + "_"
            + System.nanoTime();//from  w  w w. ja v a  2 s. c o  m
    Reporter.log("Creating URI " + currBlobURI + " with content size= " + content_size, true);
    String currContent = "";
    for (int i = 0; i < content_size; i++)
        currContent = currContent + "a";
    Reporter.log("Storing to blob: " + currBlobURI, true);
    try {
        blobApi.putBlob(currBlobURI, currContent.getBytes(), "application/text");
    } catch (Exception e) {
        Reporter.log("Exception thrown: " + e, true);
    }
    Assert.assertEquals(blobApi.getBlobSize(currBlobURI).longValue(), content_size);
    Assert.assertEquals(blobApi.getBlobMetaData(currBlobURI).get("Content-Type"), "application/text");
}

From source file:org.apache.syncope.core.logic.NotificationTest.java

@Test
public void notifyByMailEmptyAbout() throws Exception {
    // 1. create suitable notification for subsequent tests
    Notification notification = entityFactory.newEntity(Notification.class);
    notification.getEvents().add("[REST]:[UserLogic]:[]:[create]:[SUCCESS]");
    notification.setRecipients(new UserFiqlSearchConditionBuilder().inGroups(8L).query());
    notification.setSelfAsRecipient(true);

    notification.setRecipientAttrName("email");
    notification.setRecipientAttrType(IntMappingType.UserPlainSchema);

    Random random = new Random(System.currentTimeMillis());
    String sender = "syncopetest-" + random.nextLong() + "@syncope.apache.org";
    notification.setSender(sender);/* w  w w .  jav a2 s .  c  o  m*/
    String subject = "Test notification " + random.nextLong();
    notification.setSubject(subject);
    notification.setTemplate("optin");

    Notification actual = notificationDAO.save(notification);
    assertNotNull(actual);

    notificationDAO.flush();

    // 2. create user
    UserTO userTO = getSampleTO(MAIL_ADDRESS);
    MembershipTO membershipTO = new MembershipTO();
    membershipTO.setRightKey(7);
    userTO.getMemberships().add(membershipTO);

    userLogic.create(userTO, true);

    // 3. force Quartz job execution and verify e-mail
    notificationJob.execute(null);
    assertTrue(verifyMail(sender, subject));

    // 4. get NotificationTask id
    Long taskId = null;
    for (NotificationTask task : taskDAO.<NotificationTask>findAll(TaskType.NOTIFICATION)) {
        if (sender.equals(task.getSender())) {
            taskId = task.getKey();
        }
    }
    assertNotNull(taskId);

    // 5. execute Notification task and verify e-mail
    taskLogic.execute(taskId, false);
    assertTrue(verifyMail(sender, subject));
}

From source file:org.apache.syncope.core.logic.NotificationTest.java

@Test
public void issueSYNCOPE492() throws Exception {
    // 1. create suitable disabled notification for subsequent tests
    Notification notification = entityFactory.newEntity(Notification.class);
    notification.getEvents().add("[REST]:[UserLogic]:[]:[create]:[SUCCESS]");

    AnyAbout about = entityFactory.newEntity(AnyAbout.class);
    about.setNotification(notification);
    notification.add(about);//from  ww  w  .  j  av a 2s .c  o m
    about.setAnyType(anyTypeDAO.findUser());
    about.set(new UserFiqlSearchConditionBuilder().inGroups(7L).query());

    notification.setSelfAsRecipient(true);

    notification.setRecipientAttrName("email");
    notification.setRecipientAttrType(IntMappingType.UserPlainSchema);

    notification.getStaticRecipients().add("syncope492@syncope.apache.org");

    Random random = new Random(System.currentTimeMillis());
    String sender = "syncopetest-" + random.nextLong() + "@syncope.apache.org";
    notification.setSender(sender);
    String subject = "Test notification " + random.nextLong();
    notification.setSubject(subject);
    notification.setTemplate("optin");
    notification.setActive(false);

    Notification actual = notificationDAO.save(notification);
    assertNotNull(actual);

    notificationDAO.flush();

    final int tasksNumberBefore = taskDAO.findAll(TaskType.NOTIFICATION).size();

    // 2. create user
    UserTO userTO = getUniqueSampleTO(MAIL_ADDRESS);
    MembershipTO membershipTO = new MembershipTO();
    membershipTO.setRightKey(7);
    userTO.getMemberships().add(membershipTO);

    userLogic.create(userTO, true);

    // 3. force Quartz job execution
    notificationJob.execute(null);

    // 4. check if number of tasks is not incremented
    assertEquals(tasksNumberBefore, taskDAO.findAll(TaskType.NOTIFICATION).size());
}

From source file:com.linkedin.pinot.core.data.readers.PinotSegmentRecordReaderTest.java

private List<GenericRow> createTestData() {
    List<GenericRow> rows = new ArrayList<>();
    Random random = new Random();

    Map<String, Object> fields;
    for (int i = 0; i < 10000; i++) {
        fields = new HashMap<>();
        fields.put(D_SV_1, D_SV_1 + "_" + RandomStringUtils.randomAlphabetic(2));
        Object[] d2Array = new Object[5];
        for (int j = 0; j < 5; j++) {
            d2Array[j] = D_MV_1 + "_" + j + "_" + RandomStringUtils.randomAlphabetic(2);
        }//from  w w w .j  a v  a 2  s .  c o  m
        fields.put(D_MV_1, d2Array);
        fields.put(M1, Math.abs(random.nextInt()));
        fields.put(M2, Math.abs(random.nextFloat()));
        fields.put(TIME, Math.abs(random.nextLong()));

        GenericRow row = new GenericRow();
        row.init(fields);
        rows.add(row);
    }
    return rows;
}

From source file:org.apache.syncope.core.logic.NotificationTest.java

@Test
public void issueSYNCOPE192() throws Exception {
    // 1. create suitable notification for subsequent tests
    Notification notification = entityFactory.newEntity(Notification.class);
    notification.getEvents().add("[REST]:[UserLogic]:[]:[create]:[SUCCESS]");

    AnyAbout about = entityFactory.newEntity(AnyAbout.class);
    about.setNotification(notification);
    notification.add(about);/*  w  w w.  j  a v a  2s.c  om*/
    about.setAnyType(anyTypeDAO.findUser());
    about.set(new UserFiqlSearchConditionBuilder().inGroups(7L).query());

    notification.setRecipients(new UserFiqlSearchConditionBuilder().inGroups(8L).query());
    notification.setSelfAsRecipient(true);

    notification.setRecipientAttrName("email");
    notification.setRecipientAttrType(IntMappingType.UserPlainSchema);

    Random random = new Random(System.currentTimeMillis());
    String sender = "syncope192-" + random.nextLong() + "@syncope.apache.org";
    notification.setSender(sender);
    String subject = "Test notification " + random.nextLong();
    notification.setSubject(subject);
    notification.setTemplate("optin");
    notification.setTraceLevel(TraceLevel.NONE);

    Notification actual = notificationDAO.save(notification);
    assertNotNull(actual);

    // 2. create user
    UserTO userTO = getSampleTO(MAIL_ADDRESS);
    MembershipTO membershipTO = new MembershipTO();
    membershipTO.setRightKey(7);
    userTO.getMemberships().add(membershipTO);

    userLogic.create(userTO, true);

    // 3. force Quartz job execution and verify e-mail
    notificationJob.execute(null);
    assertTrue(verifyMail(sender, subject));

    // 4. get NotificationTask id
    Long taskId = null;
    for (NotificationTask task : taskDAO.<NotificationTask>findAll(TaskType.NOTIFICATION)) {
        if (sender.equals(task.getSender())) {
            taskId = task.getKey();
        }
    }
    assertNotNull(taskId);

    // 5. verify that last exec status was updated
    NotificationTaskTO task = (NotificationTaskTO) taskLogic.read(taskId);
    assertNotNull(task);
    assertTrue(task.getExecutions().isEmpty());
    assertTrue(task.isExecuted());
    assertTrue(StringUtils.isNotBlank(task.getLatestExecStatus()));
}

From source file:rapture.blob.BlobApiGoogleTests.java

@Test(groups = { "blob", "mongo", "nightly" })
public void testBlobPut() {
    long maxContentSize = 10000L;

    Random rand = new Random();
    RaptureURI repo = helper.getRandomAuthority(Scheme.BLOB);
    helper.configureTestRepo(repo, "GCP_STORAGE");
    String repoName = new RaptureURI.Builder(repo).docPath("").build().toString();
    String blobUri = repoName + "testblob" + System.nanoTime();

    long content_size = Math.abs(rand.nextLong() % maxContentSize);
    String currBlobURI = blobUri + Thread.currentThread().getId() + "_" + content_size + "_"
            + System.nanoTime();//from   ww  w .  j av  a  2s .co  m
    Reporter.log("Creating URI " + currBlobURI + " with content size= " + content_size, true);
    String currContent = "";
    for (int i = 0; i < content_size; i++)
        currContent = currContent + "a";
    Reporter.log("Storing to blob: " + currBlobURI, true);
    try {
        blobApi.putBlob(currBlobURI, currContent.getBytes(), "application/text");
    } catch (Exception e) {
        Reporter.log("Exception thrown: " + e, true);
    }
    Assert.assertEquals(blobApi.getBlobSize(currBlobURI).longValue(), content_size);
    Assert.assertEquals(blobApi.getBlobMetaData(currBlobURI).get("Content-Type"), "application/text");
}

From source file:org.apache.syncope.core.logic.NotificationTest.java

@Test
public void notifyByMail() throws Exception {
    // 1. create suitable notification for subsequent tests
    Notification notification = entityFactory.newEntity(Notification.class);
    notification.getEvents().add("[REST]:[UserLogic]:[]:[create]:[SUCCESS]");

    AnyAbout about = entityFactory.newEntity(AnyAbout.class);
    about.setNotification(notification);
    notification.add(about);/*from www .  ja v  a 2 s .c  om*/
    about.setAnyType(anyTypeDAO.findUser());
    about.set(new UserFiqlSearchConditionBuilder().inGroups(7L).query());

    notification.setRecipients(new UserFiqlSearchConditionBuilder().inGroups(8L).query());
    notification.setSelfAsRecipient(true);

    notification.setRecipientAttrName("email");
    notification.setRecipientAttrType(IntMappingType.UserPlainSchema);

    Random random = new Random(System.currentTimeMillis());
    String sender = "syncopetest-" + random.nextLong() + "@syncope.apache.org";
    notification.setSender(sender);
    String subject = "Test notification " + random.nextLong();
    notification.setSubject(subject);
    notification.setTemplate("optin");

    Notification actual = notificationDAO.save(notification);
    assertNotNull(actual);

    notificationDAO.flush();

    // 2. create user
    UserTO userTO = getSampleTO(MAIL_ADDRESS);
    MembershipTO membershipTO = new MembershipTO();
    membershipTO.setRightKey(7);
    userTO.getMemberships().add(membershipTO);

    userLogic.create(userTO, true);

    // 3. force Quartz job execution and verify e-mail
    notificationJob.execute(null);
    assertTrue(verifyMail(sender, subject));

    // 4. get NotificationTask id and text body
    Long taskId = null;
    String textBody = null;
    for (NotificationTask task : taskDAO.<NotificationTask>findAll(TaskType.NOTIFICATION)) {
        if (sender.equals(task.getSender())) {
            taskId = task.getKey();
            textBody = task.getTextBody();
        }
    }
    assertNotNull(taskId);
    assertNotNull(textBody);
    assertTrue("Notification mail text doesn't contain expected content.",
            textBody.contains("Your email address is notificationtest@syncope.apache.org."));
    assertTrue("Notification mail text doesn't contain expected content.",
            textBody.contains("Your email address inside a link: "
                    + "http://localhost/?email=notificationtest%40syncope.apache.org ."));

    // 5. execute Notification task and verify e-mail
    taskLogic.execute(taskId, false);
    assertTrue(verifyMail(sender, subject));
}

From source file:org.apache.syncope.core.logic.NotificationTest.java

@Test
public void issueSYNCOPE446() throws Exception {
    // 1. create suitable notification for subsequent tests
    Notification notification = entityFactory.newEntity(Notification.class);
    notification.getEvents().add("[REST]:[GroupLogic]:[]:[create]:[SUCCESS]");

    AnyAbout about = entityFactory.newEntity(AnyAbout.class);
    about.setNotification(notification);
    notification.add(about);// ww w.  j ava  2s . com
    about.setAnyType(anyTypeDAO.findGroup());
    about.set(new GroupFiqlSearchConditionBuilder().is("name").equalTo("group446").query());

    notification.setSelfAsRecipient(false);

    notification.setRecipientAttrName("email");
    notification.setRecipientAttrType(IntMappingType.UserPlainSchema);

    notification.getStaticRecipients().add(MAIL_ADDRESS);

    Random random = new Random(System.currentTimeMillis());
    String sender = "syncopetest-" + random.nextLong() + "@syncope.apache.org";
    notification.setSender(sender);
    String subject = "Test notification " + random.nextLong();
    notification.setSubject(subject);
    notification.setTemplate("optin");

    Notification actual = notificationDAO.save(notification);
    assertNotNull(actual);

    notificationDAO.flush();

    // 2. create group
    GroupTO groupTO = new GroupTO();
    groupTO.setName("group446");
    groupTO.setRealm("/even/two");

    GroupTO createdGroup = groupLogic.create(groupTO);
    assertNotNull(createdGroup);

    // 3. force Quartz job execution and verify e-mail
    notificationJob.execute(null);
    assertTrue(verifyMail(sender, subject));

    // 4. get NotificationTask id and text body
    Long taskId = null;
    String textBody = null;
    Set<String> recipients = null;
    for (NotificationTask task : taskDAO.<NotificationTask>findAll(TaskType.NOTIFICATION)) {
        if (sender.equals(task.getSender())) {
            taskId = task.getKey();
            textBody = task.getTextBody();
            recipients = task.getRecipients();
        }
    }

    assertNotNull(taskId);
    assertNotNull(textBody);
    assertTrue(recipients != null && recipients.contains(MAIL_ADDRESS));

    // 5. execute Notification task and verify e-mail
    taskLogic.execute(taskId, false);
    assertTrue(verifyMail(sender, subject));
}