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:org.apache.syncope.core.logic.NotificationTest.java

@Test
public void issueSYNCOPE445() 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);//ww  w.  j av a 2  s  .co  m
    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);

    notification.getStaticRecipients().add("syncope445@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 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;
    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.contains("syncope445@syncope.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 notifyByMailWithRetry() 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);/*from w  ww . j a  v  a 2  s  .  com*/
    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. Set number of retries
    CPlainAttr maxRetries = entityFactory.newEntity(CPlainAttr.class);
    maxRetries.setSchema(plainSchemaDAO.find("notification.maxRetries"));
    CPlainAttrValue maxRetriesValue = entityFactory.newEntity(CPlainAttrValue.class);
    maxRetries.add("5", maxRetriesValue);
    confDAO.save(maxRetries);
    confDAO.flush();

    // 4. Stop mail server to force error sending mail
    stopGreenMail();

    // 5. force Quartz job execution multiple times
    for (int i = 0; i < 10; i++) {
        notificationJob.execute(null);
    }

    // 6. get NotificationTask, count number of executions
    NotificationTask foundTask = null;
    for (NotificationTask task : taskDAO.<NotificationTask>findAll(TaskType.NOTIFICATION)) {
        if (sender.equals(task.getSender())) {
            foundTask = task;
        }
    }
    assertNotNull(foundTask);
    assertEquals(6, notificationManager.countExecutionsWithStatus(foundTask.getKey(),
            NotificationJob.Status.NOT_SENT.name()));

    // 7. start mail server again
    startGreenMail();

    // 8. reset number of retries
    maxRetries = entityFactory.newEntity(CPlainAttr.class);
    maxRetries.setSchema(plainSchemaDAO.find("notification.maxRetries"));
    maxRetriesValue = entityFactory.newEntity(CPlainAttrValue.class);
    maxRetries.add("0", maxRetriesValue);
    confDAO.save(maxRetries);
    confDAO.flush();
}

From source file:dremel.common.AvroTest.java

@SuppressWarnings(value = "unchecked")
private static Object generateRandomDataRecursive(Schema schema, Random random, int size) {
    switch (schema.getType()) {
    case RECORD://  w  w  w  . ja  va  2 s.  co m
        GenericRecord record = new GenericData.Record(schema);
        boolean isFieldsEmpty = true;
        for (Schema.Field field : schema.getFields()) {
            Object o = generateRandomDataRecursive(field.schema(), random, size);
            if (o != null) {
                record.put(field.name(), o);
                isFieldsEmpty = isFieldsEmpty && o instanceof GenericArray
                        && ((GenericArray<Object>) o).size() == 0;
            }
        }
        return isFieldsEmpty ? null : record;
    case ARRAY:
        int length = size + (random.nextInt(10));
        GenericArray<Object> array = new GenericData.Array<Object>(length <= 0 ? 0 : length, schema);
        Object o;
        for (int i = 0; i < length; i++) {
            o = generateRandomDataRecursive(schema.getElementType(), random, size > 0 ? size - 1 : 0);
            if (o != null)
                array.add(o);
        }
        return array;
    case STRING:
        return generateRandomUtf8(random, 40);
    case INT:
        return random.nextInt();
    case LONG:
        return random.nextLong();
    case FLOAT:
        return random.nextFloat();
    case DOUBLE:
        return random.nextDouble();
    case BOOLEAN:
        return random.nextBoolean();
    default:
        throw new RuntimeException("Unknown type: " + schema);
    }
}

From source file:com.yahoo.glimmer.indexing.preprocessor.ResourceRecordWriterTest.java

@Test
public void bySubjectsTest()
        throws IOException, InterruptedException, NoSuchAlgorithmException, BySubjectRecordException {
    FSDataOutputStream bySubjectOs = new FSDataOutputStream(
            new FileOutputStream(new File(tempDirPath.toUri().getPath(), "bySubject.bz2")), null);
    FSDataOutputStream bySubjectOffsetsOs = new FSDataOutputStream(
            new FileOutputStream(new File(tempDirPath.toUri().getPath(), "bySubject.blockOffsets")), null);

    e.one(fs).create(e.with(new Path(tempDirPath, "bySubject.bz2")), e.with(false));
    e.will(Expectations.returnValue(bySubjectOs));
    e.one(fs).create(e.with(new Path(tempDirPath, "bySubject.blockOffsets")), e.with(false));
    e.will(Expectations.returnValue(bySubjectOffsetsOs));

    e.allowing(subjectOs).write(e.with(new ByteMatcher()), e.with(0), e.with(Expectations.any(Integer.class)));

    e.allowing(allOs).write(e.with(new ByteMatcher("all\nall\n", true)), e.with(0),
            e.with(Expectations.any(Integer.class)));

    context.checking(e);/*from  ww  w. j  a  v  a2  s.com*/
    System.out.println("tempDirPath:" + tempDirPath);
    ResourceRecordWriter writer = new ResourceRecordWriter(fs, tempDirPath, null);

    BySubjectRecord record = new BySubjectRecord();
    Random random = new Random();
    for (long l = 100000; l < 200000; l += (random.nextInt(19) + 2)) {
        record.setId(l);
        record.setSubject("Subject:" + Integer.toString(random.nextInt()));
        for (int i = 0; i < random.nextInt() % 100; i++) {
            record.addRelation("a relation " + Long.toString(random.nextLong()));
        }

        writer.write(null, record);

        record.setPreviousId(l);
        record.clearRelations();
    }

    BySubjectRecord beforeBigRecord = new BySubjectRecord();
    beforeBigRecord.setId(200200l);
    beforeBigRecord.setPreviousId(record.getId());
    beforeBigRecord.setSubject("Before Big Test Record");
    writer.write(null, beforeBigRecord);

    // Write a big record that will span multiple blocks of 100000 bytes.
    BySubjectRecord bigRecord = new BySubjectRecord();
    bigRecord.setId(200201l);
    bigRecord.setPreviousId(beforeBigRecord.getId());
    bigRecord.setSubject("Big Test Record");

    MessageDigest md5Digest = MessageDigest.getInstance("MD5");
    StringBuilder sb = new StringBuilder();
    // 8k x 128 byte relations.  The relation here is just a 128 byte hex string without delimiters.
    for (int i = 0; i < 8192; i++) {
        md5Digest.update((byte) ((i * 1299299) & 0xFF));
        byte[] digest = md5Digest.digest();
        sb.append(Hex.encodeHex(digest));

        md5Digest.update(digest);
        digest = md5Digest.digest();
        sb.append(Hex.encodeHex(digest));

        md5Digest.update(digest);
        digest = md5Digest.digest();
        sb.append(Hex.encodeHex(digest));

        md5Digest.update(digest);
        digest = md5Digest.digest();
        sb.append(Hex.encodeHex(digest));

        bigRecord.addRelation(sb.toString());
        sb.setLength(0);
    }

    writer.write(null, bigRecord);

    BySubjectRecord afterBigRecord = new BySubjectRecord();
    afterBigRecord.setId(200202l);
    afterBigRecord.setPreviousId(bigRecord.getId());
    afterBigRecord.setSubject("After Big Test Record");
    writer.write(null, afterBigRecord);

    OutputCount outputCount = new OutputCount();
    outputCount.output = OUTPUT.ALL;
    outputCount.count = 1;
    Text key = new Text("all");
    for (int i = 0; i < 200205; i++) {
        writer.write(key, outputCount);
    }
    writer.write(new Text("http://a/key1"), outputCount);

    writer.close(null);

    BlockCompressedDocumentCollection collection = new BlockCompressedDocumentCollection("bySubject", null, 10);
    String indexBaseName = new File(tempDirPath.toUri().getPath(), "bySubject").getCanonicalPath();
    collection.filename(indexBaseName);

    assertEquals(-1, collection.stream(99999).read());

    InputStream documentInputStream = collection.stream(100000);
    record.readFrom(new InputStreamReader(documentInputStream));
    assertEquals(100000, record.getId());

    documentInputStream = collection.stream(record.getId());
    record.readFrom(new InputStreamReader(documentInputStream));
    assertEquals(record.getId(), record.getId());

    record.setPreviousId(3);
    record.setSubject(null);
    documentInputStream = collection.stream(record.getId() + 1);
    assertEquals(-1, documentInputStream.read());

    documentInputStream = collection.stream(beforeBigRecord.getId());
    record.readFrom(new InputStreamReader(documentInputStream));
    assertEquals(beforeBigRecord, record);

    documentInputStream = collection.stream(afterBigRecord.getId());
    record.readFrom(new InputStreamReader(documentInputStream));
    assertEquals(afterBigRecord, record);

    documentInputStream = collection.stream(bigRecord.getId());
    record.readFrom(new InputStreamReader(documentInputStream));
    System.out.println("BigRecord Relation count:" + bigRecord.getRelationsCount());
    System.out.println("First:" + bigRecord.getRelation(0));
    System.out.println("Last:" + bigRecord.getRelation(bigRecord.getRelationsCount() - 1));
    System.out.println("Record Relation count:" + record.getRelationsCount());
    System.out.println("First:" + record.getRelation(0));
    System.out.println("Last:" + record.getRelation(record.getRelationsCount() - 1));

    int limit = bigRecord.getRelationsCount() > record.getRelationsCount() ? record.getRelationsCount()
            : bigRecord.getRelationsCount();
    for (int i = 0; i < limit; i++) {
        assertEquals("At index " + i, bigRecord.getRelation(i), record.getRelation(i));
    }

    assertEquals(bigRecord.getRelationsCount(), record.getRelationsCount());
    assertEquals(bigRecord, record);

    assertEquals(-1, collection.stream(afterBigRecord.getId() + 1).read());

    collection.close();
}

From source file:org.nuxeo.duoweb.authentication.DuoFactorsAuthenticator.java

public Principal createIdentity(String username) throws LoginException {
    UserManager manager = Framework.getService(UserManager.class);
    Random random = new Random(System.currentTimeMillis());
    log.debug("createIdentity: " + username);
    try {/* w  w  w.j av  a2  s . c  om*/
        NuxeoPrincipal principal;
        if (manager == null) {
            principal = new NuxeoPrincipalImpl(username);
        } else {
            principal = manager.getPrincipal(username);
            if (principal == null) {
                throw new LoginException(String.format("principal %s does not exist", username));
            }
        }
        String principalId = String.valueOf(random.nextLong());
        principal.setPrincipalId(principalId);
        return principal;
    } catch (LoginException | ClientException e) {
        log.error("createIdentity failed", e);
        LoginException le = new LoginException("createIdentity failed for" + " user " + username);
        le.initCause(e);
        throw le;
    }
}

From source file:com.linkedin.pinot.integration.tests.BaseClusterIntegrationTest.java

private static void generateRandomRecord(GenericRecord genericRecord, Schema avroSchema, Random random) {
    for (Schema.Field field : avroSchema.getFields()) {
        Schema.Type fieldType = field.schema().getType();

        // Non-nullable single value?
        if (fieldType != Schema.Type.ARRAY && fieldType != Schema.Type.UNION) {
            switch (fieldType) {
            case INT:
                genericRecord.put(field.name(), random.nextInt(100000));
                break;
            case LONG:
                genericRecord.put(field.name(), random.nextLong() % 1000000L);
                break;
            case STRING:
                genericRecord.put(field.name(), "potato" + random.nextInt(1000));
                break;
            default:
                throw new RuntimeException("Unimplemented random record generation for field " + field);
            }//from w  w  w.  ja  va  2  s  .c o m
        } else if (fieldType == Schema.Type.UNION) { // Nullable field?
            // Use first type of union to determine actual data type
            switch (field.schema().getTypes().get(0).getType()) {
            case INT:
                genericRecord.put(field.name(), random.nextInt(100000));
                break;
            case LONG:
                genericRecord.put(field.name(), random.nextLong() % 1000000L);
                break;
            case STRING:
                genericRecord.put(field.name(), "potato" + random.nextInt(1000));
                break;
            default:
                throw new RuntimeException("Unimplemented random record generation for field " + field);
            }
        } else {
            // Multivalue field
            final int MAX_MULTIVALUES = 5;
            int multivalueCount = random.nextInt(MAX_MULTIVALUES);
            List<Object> values = new ArrayList<>(multivalueCount);

            switch (field.schema().getElementType().getType()) {
            case INT:
                for (int i = 0; i < multivalueCount; i++) {
                    values.add(random.nextInt(100000));
                }
                break;
            case LONG:
                for (int i = 0; i < multivalueCount; i++) {
                    values.add(random.nextLong() % 1000000L);
                }
                break;
            case STRING:
                for (int i = 0; i < multivalueCount; i++) {
                    values.add("potato" + random.nextInt(1000));
                }
                break;
            default:
                throw new RuntimeException("Unimplemented random record generation for field " + field);
            }

            genericRecord.put(field.name(), values);
        }
    }
}

From source file:com.cloudera.science.ml.kmeans.parallel.KMeansParallel.java

/**
 * Main constructor that includes the option to uses a fixed {@code Random} instance
 * for running the k-means algorithm for testing purposes.
 *//*  w w w.ja  v  a  2 s. co m*/
public KMeansParallel(Random random, int projectionBits, int projectionSamples) {
    this.projectionBits = projectionBits;
    this.projectionSamples = projectionSamples;
    if (random == null) {
        this.seed = System.currentTimeMillis();
    } else {
        this.seed = random.nextLong();
    }
    this.random = random;
}

From source file:org.apache.hadoop.dfs.TestBlockReplacement.java

public void testBlockReplacement() throws IOException {
    final Configuration CONF = new Configuration();
    final String[] INITIAL_RACKS = { "/RACK0", "/RACK1", "/RACK2" };
    final String[] NEW_RACKS = { "/RACK2" };

    final short REPLICATION_FACTOR = (short) 3;
    final int DEFAULT_BLOCK_SIZE = 1024;
    final Random r = new Random();

    CONF.setLong("dfs.block.size", DEFAULT_BLOCK_SIZE);
    CONF.setInt("io.bytes.per.checksum", DEFAULT_BLOCK_SIZE / 2);
    CONF.setLong("dfs.blockreport.intervalMsec", 500);
    cluster = new MiniDFSCluster(CONF, REPLICATION_FACTOR, true, INITIAL_RACKS);
    try {//from  w  w w  .  jav  a 2s.c  o m
        cluster.waitActive();

        FileSystem fs = cluster.getFileSystem();
        Path fileName = new Path("/tmp.txt");

        // create a file with one block
        DFSTestUtil.createFile(fs, fileName, DEFAULT_BLOCK_SIZE, REPLICATION_FACTOR, r.nextLong());
        DFSTestUtil.waitReplication(fs, fileName, REPLICATION_FACTOR);

        // get all datanodes
        InetSocketAddress addr = new InetSocketAddress("localhost", cluster.getNameNodePort());
        DFSClient client = new DFSClient(addr, CONF);
        List<LocatedBlock> locatedBlocks = client.namenode.getBlockLocations("/tmp.txt", 0, DEFAULT_BLOCK_SIZE)
                .getLocatedBlocks();
        assertEquals(1, locatedBlocks.size());
        LocatedBlock block = locatedBlocks.get(0);
        DatanodeInfo[] oldNodes = block.getLocations();
        assertEquals(oldNodes.length, 3);
        Block b = block.getBlock();

        // add a new datanode to the cluster
        cluster.startDataNodes(CONF, 1, true, null, NEW_RACKS);
        cluster.waitActive();

        DatanodeInfo[] datanodes = client.datanodeReport(DatanodeReportType.ALL);

        // find out the new node
        DatanodeInfo newNode = null;
        for (DatanodeInfo node : datanodes) {
            Boolean isNewNode = true;
            for (DatanodeInfo oldNode : oldNodes) {
                if (node.equals(oldNode)) {
                    isNewNode = false;
                    break;
                }
            }
            if (isNewNode) {
                newNode = node;
                break;
            }
        }

        assertTrue(newNode != null);
        DatanodeInfo source = null;
        ArrayList<DatanodeInfo> proxies = new ArrayList<DatanodeInfo>(2);
        for (DatanodeInfo node : datanodes) {
            if (node != newNode) {
                if (node.getNetworkLocation().equals(newNode.getNetworkLocation())) {
                    source = node;
                } else {
                    proxies.add(node);
                }
            }
        }
        assertTrue(source != null && proxies.size() == 2);

        // start to replace the block
        // case 1: proxySource does not contain the block
        LOG.info("Testcase 1: Proxy " + newNode.getName() + " does not contain the block " + b.getBlockName());
        assertFalse(replaceBlock(b, source, newNode, proxies.get(0)));
        // case 2: destination contains the block
        LOG.info("Testcase 2: Destination " + proxies.get(1).getName() + " contains the block "
                + b.getBlockName());
        assertFalse(replaceBlock(b, source, proxies.get(0), proxies.get(1)));
        // case 3: correct case
        LOG.info("Testcase 3: Proxy=" + source.getName() + " source=" + proxies.get(0).getName()
                + " destination=" + newNode.getName());
        assertTrue(replaceBlock(b, source, proxies.get(0), newNode));
        // block locations should contain two proxies and newNode
        checkBlocks(new DatanodeInfo[] { newNode, proxies.get(0), proxies.get(1) }, fileName.toString(),
                DEFAULT_BLOCK_SIZE, REPLICATION_FACTOR, client);
        // case 4: proxies.get(0) is not a valid del hint
        LOG.info("Testcase 4: invalid del hint " + proxies.get(0).getName());
        assertTrue(replaceBlock(b, proxies.get(1), proxies.get(0), source));
        /* block locations should contain two proxies,
         * and either of source or newNode
         */
        checkBlocks(proxies.toArray(new DatanodeInfo[proxies.size()]), fileName.toString(), DEFAULT_BLOCK_SIZE,
                REPLICATION_FACTOR, client);
    } finally {
        cluster.shutdown();
    }
}

From source file:io.selendroid.server.model.DefaultSelendroidDriver.java

@Override
public String initializeSession(JSONObject desiredCapabilities) {
    if (this.session != null) {
        session.getKnownElements().clear();
        return session.getSessionId();
    }/* w  ww .  ja va  2 s.c o m*/
    activeWindowType = WindowType.NATIVE_APP.name();
    Random random = new Random();
    this.session = new Session(desiredCapabilities, new UUID(random.nextLong(), random.nextLong()).toString());
    nativeSearchScope = new NativeSearchScope(serverInstrumentation, getSession().getKnownElements());

    selendroidNativeDriver = new SelendroidNativeDriver(serverInstrumentation,
            (NativeSearchScope) nativeSearchScope);
    SelendroidLogger.info("new s: " + session.getSessionId());

    nativeExecuteScriptMap.put("invokeMenuActionSync", new InvokeMenuAction(session, serverInstrumentation));
    nativeExecuteScriptMap.put("findRId", new FindRId(serverInstrumentation));
    nativeExecuteScriptMap.put("getL10nKeyTranslation", new GetL10nKeyTranslation(serverInstrumentation));
    nativeExecuteScriptMap.put("findElementByAndroidTag",
            new FindElementByAndroidTag(session.getKnownElements(), serverInstrumentation, keySender));
    nativeExecuteScriptMap.put("isElementDisplayedInViewport",
            new IsElementDisplayedInViewport(session.getKnownElements(), serverInstrumentation));

    return session.getSessionId();
}

From source file:org.jbpm.workbench.pr.client.editors.instance.list.ProcessInstanceListPresenterTest.java

@Test
public void abortProcessInstancesTest() {
    final Random random = new Random();

    final Map<String, List<Long>> containerInstance = singletonMap("container",
            Arrays.asList(random.nextLong(), random.nextLong(), random.nextLong()));

    presenter.abortProcessInstances(containerInstance);

    verify(processService).abortProcessInstances(anyString(), eq(containerInstance));
}