Example usage for java.util Random nextBoolean

List of usage examples for java.util Random nextBoolean

Introduction

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

Prototype

public boolean nextBoolean() 

Source Link

Document

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

Usage

From source file:es.emergya.bbdd.dao.test.UsuarioHomeTest.java

@Test
public void testMuchosThreadsALaVezYCruzaLosDedos() {
    Hilo hilo1 = new Hilo();
    hilo1.start();//from  ww w. ja va 2s  . c  o  m

    Hilo hilo2 = new Hilo();
    hilo2.start();

    Hilo hilo3 = new Hilo();
    hilo3.start();

    Hilo hilo4 = new Hilo();
    hilo4.start();

    Random r = new Random();
    for (int i = 0; i < 20; i++) {
        System.out.println("Vuelta numero " + i + " con " + getTotal() + " usuarios.");
        try {
            Thread.sleep((int) (500));
        } catch (InterruptedException e) {
            fail(e.toString());
        }
        synchronized (total) {
            List<Usuario> usuarios = usuarioHome.getAll();
            for (Usuario u : usuarios)
                if (r.nextBoolean())
                    if (!u.getNombreUsuario().equals("emergya"))
                        usuarioHome.delete(u);

            for (int j = 0; j < 3; j++) {
                Usuario u = new Usuario();
                u.setNombre("usuario " + System.currentTimeMillis());
                u.setNombreUsuario("nombre " + System.currentTimeMillis());
                u.setApellidos("apellidos");
                u.setHabilitado(r.nextBoolean());
                u.setAdministrador(r.nextBoolean());
                usuarioHome.saveOrUpdate(u);
            }

            total = usuarioHome.getTotal();
        }
    }

    if (error)
        fail("error en la concurrencia");
    System.out.println(contador + " comprobaciones.");
}

From source file:org.ballerinalang.langserver.command.testgen.ValueSpaceGenerator.java

/**
 * Returns value space for a given BTypeSymbol.
 *
 * @param tSymbol  BTypeSymbol to evaluate
 * @param template templates to be modified
 * @return {@link String}  modified templates
 *//*w ww  . j a v a2  s . com*/
public static String[] getValueSpaceByTypeSymbol(BTypeSymbol tSymbol, String[] template) {
    if (tSymbol == null) {
        String[] result = new String[] { "()" };
        populateValueSpace(result, template, () -> "()");
        return template;
    }
    Random random = new Random();
    switch (tSymbol.name.getValue()) {
    case "int":
    case "any":
        String[] resultInt = new String[] { "-1", "0", "1" };
        populateValueSpace(resultInt, template, () -> String.valueOf(random.nextInt((template.length))));
        break;
    case "string":
        String[] resultStr = new String[] { "\"\"", "\"foo\"", "\"bar\"" };
        populateValueSpace(resultStr, template,
                () -> "\"" + RandomStringUtils.randomAlphabetic(RANDOM_WORDS_LENGTH) + "\"");
        break;
    case "float":
        String[] resultFloat = new String[] { "-1.0", "0.0", "1.0" };
        populateValueSpace(resultFloat, template, () -> String.format("%.1f", random.nextDouble()));
        break;
    case "json":
        String[] resultJson = new String[] { "{\"key\": \"value\"}", "{}", "{\"foo\": \"bar\"}" };
        populateValueSpace(resultJson, template, () -> {
            String key = RandomStringUtils.randomAlphabetic(RANDOM_WORDS_LENGTH);
            String value = RandomStringUtils.randomAlphabetic(RANDOM_WORDS_LENGTH);
            return "{\"" + key + "\": \"" + value + "\"}";
        });
        break;
    case "boolean":
        String[] resultBool = new String[] { "false", "true" };
        populateValueSpace(resultBool, template, () -> String.valueOf(random.nextBoolean()));
        break;
    case "xml":
        String[] resultXml = new String[] { "xml `<msg>hello</msg>`", "xml `<foo>bar</foo>`",
                "xml `<bar>foo</bar>`" };
        populateValueSpace(resultXml, template, () -> {
            String key = RandomStringUtils.randomAlphabetic(RANDOM_WORDS_LENGTH);
            String value = RandomStringUtils.randomAlphabetic(RANDOM_WORDS_LENGTH);
            return "xml `<" + key + ">" + value + "</" + key + ">`";
        });
        break;
    case "byte":
        String[] resultBlob = new String[] { "0" };
        populateValueSpace(resultBlob, template, () -> String.valueOf("0"));
        break;
    default:
        String[] result = new String[] { "()" };
        populateValueSpace(result, template, () -> "()");
        break;
    }
    return template;
}

From source file:org.apache.flink.table.codegen.SortCodeGeneratorTest.java

@Test
public void testOneKey() throws Exception {
    for (int time = 0; time < 100; time++) {
        Random rnd = new Random();
        fields = new int[rnd.nextInt(9) + 1];
        for (int i = 0; i < fields.length; i++) {
            fields[i] = rnd.nextInt(types.length);
        }/*from   w w w.j  a v a  2 s .co  m*/

        keys = new int[] { 0 };
        orders = new boolean[] { rnd.nextBoolean() };
        nullsIsLast = SortUtil.getNullDefaultOrders(orders);
        testInner();
    }
}

From source file:org.apache.tinkerpop.gremlin.structure.util.star.StarGraphTest.java

@Test
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexPropertyFeatures.FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_PROPERTY)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_META_PROPERTIES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_MULTI_PROPERTIES)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_PROPERTY)
public void shouldAttachWithCreateMethod() {
    final Random random = new Random(234335l);
    StarGraph starGraph = StarGraph.open();
    Vertex starVertex = starGraph.addVertex(T.label, "person", "name", "stephen", "name", "spmallete");
    starVertex.property("acl", true, "timestamp", random.nextLong(), "creator", "marko");
    for (int i = 0; i < 100; i++) {
        starVertex.addEdge("knows", starGraph.addVertex("person", "name",
                new UUID(random.nextLong(), random.nextLong()), "since", random.nextLong()));
        starGraph.addVertex(T.label, "project").addEdge("developedBy", starVertex, "public",
                random.nextBoolean());
    }/*  w  ww  .j a  va2s  .  c o m*/
    final Vertex createdVertex = starGraph.getStarVertex().attach(Attachable.Method.create(graph));
    starGraph.getStarVertex().edges(Direction.BOTH).forEachRemaining(edge -> ((Attachable<Edge>) edge)
            .attach(Attachable.Method.create(random.nextBoolean() ? graph : createdVertex)));
    TestHelper.validateEquality(starVertex, createdVertex);
}

From source file:org.apache.solr.response.transform.TestSubQueryTransformer.java

@Test
public void testMultiValue() throws Exception {

    String[] happyPathAsserts = new String[] {
            "count(//result/doc/str[@name='name_s_dv'][.='dave']/../result[@name='subq1']/doc/str[@name='text_t'][.='These guys develop stuff'])="
                    + (peopleMultiplier * deptMultiplier),
            "count(//result/doc/str[@name='name_s_dv'][.='dave']/../result[@name='subq1']/doc/str[@name='text_t'][.='These guys help customers'])="
                    + (peopleMultiplier * deptMultiplier),
            "//result[@numFound=" + peopleMultiplier + "]" };
    Random random1 = random();

    assertQ("dave works at both, whether we set a  default separator or both",
            req(new String[] { "q", "name_s:dave", "indent", "true", "fl",
                    (random().nextBoolean() ? "name_s_dv,dept_ss_dv" : "*") + ",subq1:[subquery "
                            + ((random1.nextBoolean() ? "" : "separator=,")) + "]",
                    "rows", "" + peopleMultiplier, "subq1.q",
                    "{!terms f=dept_id_s v=$row.dept_ss_dv " + ((random1.nextBoolean() ? "" : "separator=,"))
                            + "}",
                    "subq1.fl", "text_t", "subq1.indent", "true", "subq1.rows", "" + (deptMultiplier * 2),
                    "subq1.logParamsList", "q,fl,rows,row.dept_ss_dv" }),
            happyPathAsserts);/*from  w ww.  j  a  v a2s  .  c  o m*/

    assertQ("even via numbers",
            req("q", "name_s:dave", "indent", "true", "fl", "dept_is_dv,name_s_dv,subq1:[subquery]", "rows",
                    "" + (peopleMultiplier), "subq1.q", "{!terms f=dept_id_i v=$row.dept_is_dv}", "subq1.fl",
                    "text_t", "subq1.indent", "true", "subq1.rows", "" + (deptMultiplier * 2)),
            happyPathAsserts);

    assertQ("even if we set a separator both", req("q", "name_s:dave", "indent", "true", "fl",
            "dept_ss_dv,name_s_dv,name_s_dv,subq1:[subquery separator=\" \"]", "rows", "" + (peopleMultiplier),
            "subq1.q", "{!terms f=dept_id_s v=$row.dept_ss_dv separator=\" \"}", "subq1.fl", "text_t",
            "subq1.indent", "true", "subq1.rows", "" + (deptMultiplier * 2)), happyPathAsserts);

    String[] noMatchAtSubQ = new String[] {
            "count(//result/doc/str[@name='name_s_dv'][.='dave']/../result[@name='subq1'][@numFound=0])="
                    + (peopleMultiplier),
            "//result[@numFound=" + peopleMultiplier + "]" };

    assertQ("different separators, no match",
            req("q", "name_s:dave", "indent", "true", "fl", "dept_ss_dv,name_s_dv,subq1:[subquery]", "rows",
                    "" + (peopleMultiplier), "subq1.q",
                    "{!terms f=dept_id_s v=$row.dept_ss_dv separator=\" \"}", "subq1.fl", "text_t",
                    "subq1.indent", "true", "subq1.rows", "" + (deptMultiplier * 2)),
            noMatchAtSubQ);

    assertQ("and no matter where",
            req("q", "name_s:dave", "indent", "true", "fl",
                    "dept_ss_dv,name_s_dv,subq1:[subquery separator=\" \"]", "rows", "" + (peopleMultiplier),
                    "subq1.q", "{!terms f=dept_id_s v=$row.dept_ss_dv}", "subq1.fl", "text_t", "subq1.indent",
                    "true", "subq1.rows", "" + (deptMultiplier * 2)),
            noMatchAtSubQ);

    assertQ("setting a wrong parser gets you nowhere",
            req("q", "name_s:dave", "indent", "true", "fl", "dept_ss_dv,name_s_dv,subq1:[subquery]", "rows",
                    "" + (peopleMultiplier), "subq1.q", "{!term f=dept_id_s v=$row.dept_ss_dv}", "subq1.fl",
                    "text_t", "subq1.indent", "true", "subq1.rows", "" + (deptMultiplier * 2)),
            noMatchAtSubQ);

    assertQ("but it luckily works with default query parser, but it's not really reliable",
            req("q", "name_s:dave", "indent", "true", "fl",
                    "dept_ss_dv,name_s_dv,subq1:[subquery separator=\" \"]", "rows", "" + (peopleMultiplier),
                    "subq1.q", "{!lucene df=dept_id_s v=$row.dept_ss_dv}", "subq1.fl", "text_t", "subq1.indent",
                    "true", "subq1.rows", "" + (deptMultiplier * 2)),
            happyPathAsserts);

    assertQ("even lucene qp can't help at any separator but space",
            req("q", "name_s:dave", "indent", "true", "fl",
                    "dept_ss_dv,name_s_dv," + "subq1:[subquery "
                            + (random().nextBoolean() ? ""
                                    : "separator=" + ((random().nextBoolean() ? "" : ",")))
                            + "]",
                    "rows", "" + (peopleMultiplier), "subq1.q", "{!lucene df=dept_id_s v=$row.dept_ss_dv}",
                    "subq1.fl", "text_t", "subq1.indent", "true", "subq1.rows", "" + (deptMultiplier * 2)),
            noMatchAtSubQ);
}

From source file:org.diorite.impl.world.generator.structures.tree.SmallTreeStructure.java

@SuppressWarnings("PointlessArithmeticExpression") // it looks better, java should simplify that on compilation time
protected boolean genTree(final ChunkPos chunkPos, final Random random, final BlockLocation c, final int size) {
    for (int i = 0; i < size; i++) {
        this.setBlock(c, 0 * 0, 0 + i, 0 * 0, this.logMat);
    }//from w ww.j a  va  2s  .c  o m
    this.setBlock(c, 0 * 0, size, 0 * 0, this.leavesMat);
    int k = 0;
    for (int i = size, h = (size - 4); i > h; i--, k++) {
        this.setBlock(c, 0 + 1, i, 0 * 0, this.leavesMat);
        this.setBlock(c, 0 * 0, i, 0 + 1, this.leavesMat);
        this.setBlock(c, 0 - 1, i, 0 * 0, this.leavesMat);
        this.setBlock(c, 0 * 0, i, 0 - 1, this.leavesMat);
        if (k == 1) {
            // corners are set randomly
            if (random.nextBoolean()) {
                this.setBlock(c, 0 + 1, i, 0 + 1, this.leavesMat);
            }
            if (random.nextBoolean()) {
                this.setBlock(c, 0 + 1, i, 0 - 1, this.leavesMat);
            }
            if (random.nextBoolean()) {
                this.setBlock(c, 0 - 1, i, 0 + 1, this.leavesMat);
            }
            if (random.nextBoolean()) {
                this.setBlock(c, 0 - 1, i, 0 - 1, this.leavesMat);
            }
        } else if (k >= 2) {
            this.setBlock(c, 0 + 1, i, 0 + 1, this.leavesMat);
            this.setBlock(c, 0 + 1, i, 0 - 1, this.leavesMat);
            this.setBlock(c, 0 - 1, i, 0 + 1, this.leavesMat);
            this.setBlock(c, 0 - 1, i, 0 - 1, this.leavesMat);

            this.setBlock(c, 0 + 2, i, 0 + 1, this.leavesMat);
            this.setBlock(c, 0 + 2, i, 0 * 0, this.leavesMat);
            this.setBlock(c, 0 + 2, i, 0 - 1, this.leavesMat);

            this.setBlock(c, 0 - 2, i, 0 + 1, this.leavesMat);
            this.setBlock(c, 0 - 2, i, 0 * 0, this.leavesMat);
            this.setBlock(c, 0 - 2, i, 0 - 1, this.leavesMat);

            this.setBlock(c, 0 + 1, i, 0 + 2, this.leavesMat);
            this.setBlock(c, 0 * 0, i, 0 + 2, this.leavesMat);
            this.setBlock(c, 0 - 1, i, 0 + 2, this.leavesMat);

            this.setBlock(c, 0 + 1, i, 0 - 2, this.leavesMat);
            this.setBlock(c, 0 * 0, i, 0 - 2, this.leavesMat);
            this.setBlock(c, 0 - 1, i, 0 - 2, this.leavesMat);

            // corners are set randomly
            if (random.nextBoolean()) {
                this.setBlock(c, 0 + 2, i, 0 + 2, this.leavesMat);
            }
            if (random.nextBoolean()) {
                this.setBlock(c, 0 + 2, i, 0 - 2, this.leavesMat);
            }
            if (random.nextBoolean()) {
                this.setBlock(c, 0 - 2, i, 0 + 2, this.leavesMat);
            }
            if (random.nextBoolean()) {
                this.setBlock(c, 0 - 2, i, 0 - 2, this.leavesMat);
            }
        }
    }
    return true;
}

From source file:org.jumpmind.symmetric.io.data.DbFill.java

private BigDecimal randomBigDecimal(int size, int digits) {
    if (size == 0 && digits == 0) {
        // set the values to something reasonable
        size = 10;/*from  w ww  .ja v  a 2  s  . c o m*/
        digits = 6;
    }
    Random rnd = getRand();
    StringBuilder str = new StringBuilder();
    if (size > 0 && rnd.nextBoolean()) {
        str.append("-");
    }
    for (int i = 0; i < size; i++) {
        if (i == size - digits)
            str.append(".");
        str.append(rnd.nextInt(10));
    }
    return new BigDecimal(str.toString());
}

From source file:org.apache.hadoop.hdfs.server.blockmanagement.TestDatanodeManager.java

/**
 * This test sends a random sequence of node registrations and node removals
 * to the DatanodeManager (of nodes with different IDs and versions), and
 * checks that the DatanodeManager keeps a correct count of different software
 * versions at all times.//from   w w w .ja  v a 2 s  .c  om
 */
@Test
public void testNumVersionsReportedCorrect() throws IOException {
    //Create the DatanodeManager which will be tested
    FSNamesystem fsn = Mockito.mock(FSNamesystem.class);
    Mockito.when(fsn.hasWriteLock()).thenReturn(true);
    DatanodeManager dm = mockDatanodeManager(fsn, new Configuration());

    //Seed the RNG with a known value so test failures are easier to reproduce
    Random rng = new Random();
    int seed = rng.nextInt();
    rng = new Random(seed);
    LOG.info("Using seed " + seed + " for testing");

    //A map of the Storage IDs to the DN registration it was registered with
    HashMap<String, DatanodeRegistration> sIdToDnReg = new HashMap<String, DatanodeRegistration>();

    for (int i = 0; i < NUM_ITERATIONS; ++i) {

        //If true, remove a node for every 3rd time (if there's one)
        if (rng.nextBoolean() && i % 3 == 0 && sIdToDnReg.size() != 0) {
            //Pick a random node.
            int randomIndex = rng.nextInt() % sIdToDnReg.size();
            //Iterate to that random position 
            Iterator<Map.Entry<String, DatanodeRegistration>> it = sIdToDnReg.entrySet().iterator();
            for (int j = 0; j < randomIndex - 1; ++j) {
                it.next();
            }
            DatanodeRegistration toRemove = it.next().getValue();
            LOG.info("Removing node " + toRemove.getDatanodeUuid() + " ip " + toRemove.getXferAddr()
                    + " version : " + toRemove.getSoftwareVersion());

            //Remove that random node
            dm.removeDatanode(toRemove);
            it.remove();
        }

        // Otherwise register a node. This node may be a new / an old one
        else {
            //Pick a random storageID to register.
            String storageID = "someStorageID" + rng.nextInt(5000);

            DatanodeRegistration dr = Mockito.mock(DatanodeRegistration.class);
            Mockito.when(dr.getDatanodeUuid()).thenReturn(storageID);

            //If this storageID had already been registered before
            if (sIdToDnReg.containsKey(storageID)) {
                dr = sIdToDnReg.get(storageID);
                //Half of the times, change the IP address
                if (rng.nextBoolean()) {
                    dr.setIpAddr(dr.getIpAddr() + "newIP");
                }
            } else { //This storageID has never been registered
                //Ensure IP address is unique to storageID
                String ip = "someIP" + storageID;
                Mockito.when(dr.getIpAddr()).thenReturn(ip);
                Mockito.when(dr.getXferAddr()).thenReturn(ip + ":9000");
                Mockito.when(dr.getXferPort()).thenReturn(9000);
            }
            //Pick a random version to register with
            Mockito.when(dr.getSoftwareVersion()).thenReturn("version" + rng.nextInt(5));

            LOG.info("Registering node storageID: " + dr.getDatanodeUuid() + ", version: "
                    + dr.getSoftwareVersion() + ", IP address: " + dr.getXferAddr());

            //Register this random node
            dm.registerDatanode(dr);
            sIdToDnReg.put(storageID, dr);
        }

        //Verify DatanodeManager still has the right count
        Map<String, Integer> mapToCheck = dm.getDatanodesSoftwareVersions();

        //Remove counts from versions and make sure that after removing all nodes
        //mapToCheck is empty
        for (Entry<String, DatanodeRegistration> it : sIdToDnReg.entrySet()) {
            String ver = it.getValue().getSoftwareVersion();
            if (!mapToCheck.containsKey(ver)) {
                throw new AssertionError(
                        "The correct number of datanodes of a " + "version was not found on iteration " + i);
            }
            mapToCheck.put(ver, mapToCheck.get(ver) - 1);
            if (mapToCheck.get(ver) == 0) {
                mapToCheck.remove(ver);
            }
        }
        for (Entry<String, Integer> entry : mapToCheck.entrySet()) {
            LOG.info("Still in map: " + entry.getKey() + " has " + entry.getValue());
        }
        assertEquals("The map of version counts returned by DatanodeManager was"
                + " not what it was expected to be on iteration " + i, 0, mapToCheck.size());
    }
}

From source file:org.apache.hadoop.hbase.master.TestRegionStateOnMasterFailure.java

/**
 * Writes some data to the table./* ww  w  .  j  av a  2 s .c o m*/
 * @throws InterruptedException
 */
private void fillTable() throws IOException, InterruptedException {
    Random rand = new Random(19387129L);
    HTable table = testUtil.createTable(TABLE_NAME, FAMILIES);
    for (int iStoreFile = 0; iStoreFile < 4; ++iStoreFile) {
        for (int iRow = 0; iRow < 100; ++iRow) {
            final byte[] row = Bytes.toBytes("row" + iRow);
            Put put = new Put(row);
            Delete del = new Delete(row);
            for (int iCol = 0; iCol < 10; ++iCol) {
                final byte[] cf = rand.nextBoolean() ? CF1 : CF2;
                final long ts = rand.nextInt();
                final byte[] qual = Bytes.toBytes("col" + iCol);
                if (rand.nextBoolean()) {
                    final byte[] value = Bytes
                            .toBytes("value_for_row_" + iRow + "_cf_" + Bytes.toStringBinary(cf) + "_col_"
                                    + iCol + "_ts_" + ts + "_random_" + rand.nextLong());
                    put.add(cf, qual, ts, value);
                } else if (rand.nextDouble() < 0.8) {
                    del.deleteColumn(cf, qual, ts);
                } else {
                    del.deleteColumns(cf, qual, ts);
                }
            }
            table.put(put);
            table.delete(del);
            table.flushCommits();
        }
    }
    testUtil.waitUntilAllRegionsAssigned(1);
}