Java Code Examples for java.util.Random#nextBoolean()

The following examples show how to use java.util.Random#nextBoolean() . 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: TestIntPivot.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void testIntPivotLarge(){
  Random r = new Random();
  final int count = 6000;
  final Integer[] vectA = new Integer[count];
  final Integer[] vectB = new Integer[count];

  for(int i =0; i < count; i++){
    if(r.nextBoolean()){
      vectA[i] = r.nextInt();
    }

    if(r.nextBoolean()){
      vectB[i] = r.nextInt();
    }
  }
  testDualIntVectors(count, vectA, vectB);

}
 
Example 2
Source File: ServerTest.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
@Test
public void testInt()
{
  Server.writeInt(array, 0, Integer.MAX_VALUE);
  Assert.assertEquals("Max Integer", Integer.MAX_VALUE, Server.readInt(array, 0));

  Server.writeInt(array, 0, Integer.MIN_VALUE);
  Assert.assertEquals("Min Integer", Integer.MIN_VALUE, Server.readInt(array, 0));

  Server.writeInt(array, 0, 0);
  Assert.assertEquals("Zero Integer", 0, Server.readInt(array, 0));

  Random rand = new Random();
  for (int i = 0; i < 128; i++) {
    int n = rand.nextInt();
    if (rand.nextBoolean()) {
      n = -n;
    }
    Server.writeInt(array, 0, n);
    Assert.assertEquals("Random Integer", n, Server.readInt(array, 0));
  }
}
 
Example 3
Source File: RangeSetTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the performance of {@link RangeSet} implementation. This test is not executed
 * in normal SIS build. We run this test only when the {@link RangeSet} implementation
 * changed, and we want to test the impact of that change on the performance.
 *
 * @throws InterruptedException if the test has been interrupted.
 */
@Performance
public void stress() throws InterruptedException {
    final PrintWriter out = TestCase.out;
    final Random r = TestUtilities.createRandomNumberGenerator();
    for (int p=0; p<10; p++) {
        final long start = System.nanoTime();
        final RangeSet<Integer> set = RangeSet.create(Integer.class, true, false);
        for (int i=0; i<100000; i++) {
            final int lower = r.nextInt(1000000) - 500;
            final int upper = lower + r.nextInt(100) + 1;
            if (r.nextBoolean()) {
                set.add(lower, upper);
            } else {
                set.remove(lower, upper);
            }
        }
        out.print((System.nanoTime() - start) / (float) NANOS_PER_SECOND);
        out.print(" seconds for a size of ");
        out.println(set.size());
        Thread.sleep(1000);
    }
}
 
Example 4
Source File: UpdateTest.java    From mongodb-async-driver with Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link Update#validateSize(int)} .
 */
@Test
public void testValidateSize() {
    final Random random = new Random(System.currentTimeMillis());

    final String databaseName = "db";
    final String collectionName = "collection";
    final Document query = BuilderFactory.start().build();
    final Document update = BuilderFactory.start().build();
    final boolean multiUpdate = random.nextBoolean();
    final boolean upsert = random.nextBoolean();
    final Update message = new Update(databaseName, collectionName, query,
            update, multiUpdate, upsert);

    message.validateSize(1024);

    // Should be able to call again without visitor since size is cached.
    message.validateSize(1024);
}
 
Example 5
Source File: JobDetailsInfoTest.java    From flink with Apache License 2.0 5 votes vote down vote up
private JobDetailsInfo.JobVertexDetailsInfo createJobVertexDetailsInfo(Random random) {
	final Map<ExecutionState, Integer> tasksPerState = new HashMap<>(ExecutionState.values().length);
	final IOMetricsInfo jobVertexMetrics = new IOMetricsInfo(
		random.nextLong(),
		random.nextBoolean(),
		random.nextLong(),
		random.nextBoolean(),
		random.nextLong(),
		random.nextBoolean(),
		random.nextLong(),
		random.nextBoolean());

	for (ExecutionState executionState : ExecutionState.values()) {
		tasksPerState.put(executionState, random.nextInt());
	}

	return new JobDetailsInfo.JobVertexDetailsInfo(
		new JobVertexID(),
		"jobVertex" + random.nextLong(),
		random.nextInt(),
		ExecutionState.values()[random.nextInt(ExecutionState.values().length)],
		random.nextLong(),
		random.nextLong(),
		random.nextLong(),
		tasksPerState,
		jobVertexMetrics);
}
 
Example 6
Source File: RandomTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Repeated calls to nextBoolean produce at least two distinct results
 */
public void testNextBoolean() {
    Random r = new Random();
    boolean f = r.nextBoolean();
    int i = 0;
    while (i < NCALLS && r.nextBoolean() == f)
        ++i;
    assertTrue(i < NCALLS);
}
 
Example 7
Source File: AssessmentMetaRelations.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
private static LearningObjectiveMeta getOrCreateLearningObjective() {
    LearningObjectiveMeta learningObjectiveMeta = null;

    Random random = new Random(31);

    if (random.nextBoolean()) {
        learningObjectiveMeta = getRandomLearningObjectiveMeta();
    }

    if (learningObjectiveMeta == null) {
        learningObjectiveMeta = createLearningObjective();
    }
    return learningObjectiveMeta;
}
 
Example 8
Source File: SortingTests.java    From morpheus-core with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a frame for sort testing containing all data types
 * @param parallel      true for parallel version
 * @param rowCount      the row count
 * @return              the newly created DataFrame
 */
private DataFrame<LocalDate,String> createRowTestFrame(boolean parallel, int rowCount) {
    final Random random = new Random();
    final LocalDate startDate = LocalDate.of(1990,1,1);
    final Index<LocalDate> rowKeys = Index.of(LocalDate.class, rowCount);
    final Index<String> colKeys = Index.of(String.class, 10);
    final DataFrame<LocalDate,String> frame = DataFrame.ofObjects(rowKeys, colKeys);
    frame.rows().addAll(Range.of(0, rowCount).map(startDate::plusDays));
    frame.cols().add("Booleans", Array.of(Boolean.class, rowCount));
    frame.cols().add("Integers", Array.of(Integer.class, rowCount));
    frame.cols().add("Longs", Array.of(Long.class, rowCount));
    frame.cols().add("Doubles", Array.of(Double.class, rowCount));
    frame.cols().add("Strings", Array.of(String.class, rowCount));
    frame.cols().add("Dates", Array.of(LocalDate.class, rowCount));

    boolean booleanValue = random.nextBoolean();
    int intValue = random.nextInt();
    long longValue = random.nextLong();
    double doubleValue = random.nextDouble();
    String stringValue = "XYZ-" + random.nextDouble();
    LocalDate dateValue = startDate.plusDays(random.nextInt(500));

    for (int rowIndex=0; rowIndex<rowCount; ++rowIndex) {
        frame.data().setBoolean(rowIndex, 0, booleanValue);
        frame.data().setInt(rowIndex, 1, intValue);
        frame.data().setLong(rowIndex, 2, longValue);
        frame.data().setDouble(rowIndex, 3, doubleValue);
        frame.data().setValue(rowIndex, 4, stringValue);
        frame.data().setValue(rowIndex, 5, dateValue);
        if (rowIndex % 60 == 0) booleanValue = random.nextBoolean();
        if (rowIndex % 50 == 0) intValue = random.nextInt();
        if (rowCount % 40 == 0) longValue = random.nextLong();
        if (rowCount % 30 == 0) doubleValue = random.nextDouble();
        if (rowCount % 20 == 0) stringValue = "XYZ-" + random.nextDouble();
        if (rowCount % 10 == 0) dateValue = startDate.plusDays(random.nextInt(500));
    }
    return parallel ? frame.parallel() : frame.sequential();
}
 
Example 9
Source File: TestUtil.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a String thats "regexpish" (contains lots of operators typically found in regular expressions)
 * If you call this enough times, you might get a valid regex!
 * 
 * <P>Note: to avoid practically endless backtracking patterns we replace asterisk and plus
 * operators with bounded repetitions. See LUCENE-4111 for more info.
 * 
 * @param maxLength A hint about maximum length of the regexpish string. It may be exceeded by a few characters.
 */
public static String randomRegexpishString(Random r, int maxLength) {
  final StringBuilder regexp = new StringBuilder(maxLength);
  for (int i = nextInt(r, 0, maxLength); i > 0; i--) {
    if (r.nextBoolean()) {
      regexp.append((char) RandomNumbers.randomIntBetween(r, 'a', 'z'));
    } else {
      regexp.append(RandomPicks.randomFrom(r, ops));
    }
  }
  return regexp.toString();
}
 
Example 10
Source File: RandomTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Repeated calls to nextBoolean produce at least two distinct results
 */
public void testNextBoolean() {
    Random r = new Random();
    boolean f = r.nextBoolean();
    int i = 0;
    while (i < NCALLS && r.nextBoolean() == f)
        ++i;
    assertTrue(i < NCALLS);
}
 
Example 11
Source File: RandomTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Repeated calls to nextBoolean produce at least two distinct results
 */
public void testNextBoolean() {
    Random r = new Random();
    boolean f = r.nextBoolean();
    int i = 0;
    while (i < NCALLS && r.nextBoolean() == f)
        ++i;
    assertTrue(i < NCALLS);
}
 
Example 12
Source File: RMF_Motor.java    From PowerSwitch_Android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public String getSignal(Gateway gateway, String action) throws GatewayNotSupportedException, ActionNotSupportedException {
    String lo = "4,";
    String hi = "8,";
    String seqLo = lo + hi;
    String seqFl = hi + lo;
    String h = seqFl;
    String l = seqLo;
    String up = l + l + l + h + l + l + l;
    String stop = l + h + l + h + l + h + l;
    String down = l + l + h + h + l + l + h;

    Random ran = new Random(seed);

    String signal = "";
    if (gateway instanceof ConnAir || gateway instanceof BrematicGWY433) {
        signal += headAutoPairConnAir;
    } else if (gateway instanceof ITGW433) {
        signal += headAutoPairITGW;
    } else {
        throw new GatewayNotSupportedException();
    }

    // action
    if (action.equals(context.getString(R.string.pair))) {
        for (int i = 0; i < 32; i++) {
            if (ran.nextBoolean()) {
                signal += h;
            } else {
                signal += l;
            }
        }

        signal += h + h + l + l + h + h + l;
        if (gateway instanceof ConnAir || gateway instanceof BrematicGWY433) {
            signal += "4,61;";
            return signal;
        } else if (gateway instanceof ITGW433) {
            signal += "4,120,0";
            return signal;
        } else {
            throw new GatewayNotSupportedException();
        }

    } else if (action.equals(context.getString(R.string.up))) {
        for (int i = 0; i < 32; i++) {
            if (ran.nextBoolean()) {
                signal += h;
            } else {
                signal += l;
            }
        }

        signal += up;
    } else if (action.equals(context.getString(R.string.stop))) {
        for (int i = 0; i < 32; i++) {
            if (ran.nextBoolean()) {
                signal += h;
            } else {
                signal += l;
            }
        }

        signal += stop;
    } else if (action.equals(context.getString(R.string.down))) {
        for (int i = 0; i < 32; i++) {
            if (ran.nextBoolean()) {
                signal += h;
            } else {
                signal += l;
            }
        }

        signal += down;
    } else {
        throw new ActionNotSupportedException(action);
    }

    if (gateway instanceof ConnAir || gateway instanceof BrematicGWY433) {
        signal += tailAutoPairConnAir;
    } else if (gateway instanceof ITGW433) {
        signal += tailAutoPairITGW;
    }

    return signal;
}
 
Example 13
Source File: Sorting.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
void build(int[] a, int m, Random random) {
    int x = 0, y = 0;
    for (int i = 0; i < a.length; i++) {
        a[i] = random.nextBoolean() ? (x += 2) : (y += 2);
    }
}
 
Example 14
Source File: RBTree.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) {
  int treeSize = 10000;
  int maxVal = treeSize;
  System.err.println("Building tree...");
  RBTree tree = new RBTree(new Comparator() {
      public int compare(Object o1, Object o2) {
        Integer i1 = (Integer) o1;
        Integer i2 = (Integer) o2;
        if (i1.intValue() < i2.intValue()) {
          return -1;
        } else if (i1.intValue() == i2.intValue()) {
          return 0;
        }
        return 1;
      }
    });
  Random rand = new Random(System.currentTimeMillis());
  for (int i = 0; i < treeSize; i++) {
    Integer val = new Integer(rand.nextInt(maxVal) + 1);
    try {
      tree.insertNode(new RBNode(val));
      if ((i > 0) && (i % 100 == 0)) {
        System.err.print(i + "...");
        System.err.flush();
      }
    }
    catch (Exception e) {
      e.printStackTrace();
      System.err.println("While inserting value " + val);
      tree.printOn(System.err);
      System.exit(1);
    }
  }
  // Now churn data in tree by deleting and inserting lots of nodes
  System.err.println();
  System.err.println("Churning tree...");
  for (int i = 0; i < treeSize; i++) {
    if (DEBUGGING && VERBOSE) {
      System.err.println("Iteration " + i + ":");
      tree.printOn(System.err);
    }
    // Pick a random value to remove (NOTE that this is not
    // uniformly distributed)
    RBNode xParent = null;
    RBNode x = tree.getRoot();
    int depth = 0;
    while (x != null) {
      // Traverse path down to leaf
      xParent = x;
      if (rand.nextBoolean()) {
        x = x.getLeft();
      } else {
        x = x.getRight();
      }
      ++depth;
    }
    // Pick a random height at which to remove value
    int height = rand.nextInt(depth);
    if (DEBUGGING) {
      if (height >= depth) {
        throw new RuntimeException("bug in java.util.Random");
      }
    }
    // Walk that far back up (FIXME: off by one?)
    while (height > 0) {
      xParent = xParent.getParent();
      --height;
    }
    // Tell the tree to remove this node
    if (DEBUGGING && VERBOSE) {
      System.err.println("(Removing value " + tree.getNodeValue(xParent) + ")");
    }
    tree.deleteNode(xParent);

    // Now create and insert a new value
    Integer newVal = new Integer(rand.nextInt(maxVal) + 1);
    if (DEBUGGING && VERBOSE) {
      System.err.println("(Inserting value " + newVal + ")");
    }
    tree.insertNode(new RBNode(newVal));
  }
  System.err.println("All tests passed.");
}
 
Example 15
Source File: RBTree.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) {
  int treeSize = 10000;
  int maxVal = treeSize;
  System.err.println("Building tree...");
  RBTree tree = new RBTree(new Comparator() {
      public int compare(Object o1, Object o2) {
        Integer i1 = (Integer) o1;
        Integer i2 = (Integer) o2;
        if (i1.intValue() < i2.intValue()) {
          return -1;
        } else if (i1.intValue() == i2.intValue()) {
          return 0;
        }
        return 1;
      }
    });
  Random rand = new Random(System.currentTimeMillis());
  for (int i = 0; i < treeSize; i++) {
    Integer val = new Integer(rand.nextInt(maxVal) + 1);
    try {
      tree.insertNode(new RBNode(val));
      if ((i > 0) && (i % 100 == 0)) {
        System.err.print(i + "...");
        System.err.flush();
      }
    }
    catch (Exception e) {
      e.printStackTrace();
      System.err.println("While inserting value " + val);
      tree.printOn(System.err);
      System.exit(1);
    }
  }
  // Now churn data in tree by deleting and inserting lots of nodes
  System.err.println();
  System.err.println("Churning tree...");
  for (int i = 0; i < treeSize; i++) {
    if (DEBUGGING && VERBOSE) {
      System.err.println("Iteration " + i + ":");
      tree.printOn(System.err);
    }
    // Pick a random value to remove (NOTE that this is not
    // uniformly distributed)
    RBNode xParent = null;
    RBNode x = tree.getRoot();
    int depth = 0;
    while (x != null) {
      // Traverse path down to leaf
      xParent = x;
      if (rand.nextBoolean()) {
        x = x.getLeft();
      } else {
        x = x.getRight();
      }
      ++depth;
    }
    // Pick a random height at which to remove value
    int height = rand.nextInt(depth);
    if (DEBUGGING) {
      if (height >= depth) {
        throw new RuntimeException("bug in java.util.Random");
      }
    }
    // Walk that far back up (FIXME: off by one?)
    while (height > 0) {
      xParent = xParent.getParent();
      --height;
    }
    // Tell the tree to remove this node
    if (DEBUGGING && VERBOSE) {
      System.err.println("(Removing value " + tree.getNodeValue(xParent) + ")");
    }
    tree.deleteNode(xParent);

    // Now create and insert a new value
    Integer newVal = new Integer(rand.nextInt(maxVal) + 1);
    if (DEBUGGING && VERBOSE) {
      System.err.println("(Inserting value " + newVal + ")");
    }
    tree.insertNode(new RBNode(newVal));
  }
  System.err.println("All tests passed.");
}
 
Example 16
Source File: QueryTest.java    From mongodb-async-driver with Apache License 2.0 4 votes vote down vote up
/**
 * Test method for number to return determination logic.
 */
@Test
public void testNumberToReturnWhenNoBatchAndSmallishLimit() {
    final Random random = new Random(System.currentTimeMillis());

    final Document doc1 = BuilderFactory.start().addInteger("1", 0).build();
    final Document doc2 = BuilderFactory.start().addInteger("1", 1).build();
    final String databaseName = "db";
    final String collectionName = "collection";
    final Document query = doc1;
    final Document returnFields = doc2;
    final int numberToSkip = random.nextInt();
    final boolean tailable = random.nextBoolean();
    final ReadPreference readPreference = random.nextBoolean() ? ReadPreference.PRIMARY
            : ReadPreference.SECONDARY;
    final boolean noCursorTimeout = random.nextBoolean();
    final boolean awaitData = random.nextBoolean();
    final boolean exhaust = random.nextBoolean();
    final boolean partial = random.nextBoolean();

    final int batchSize = 0;
    final int limit = 5;

    final Query message = new Query(databaseName, collectionName, query,
            returnFields, batchSize, limit, numberToSkip, tailable,
            readPreference, noCursorTimeout, awaitData, exhaust, partial);

    assertEquals(databaseName, message.getDatabaseName());
    assertEquals(collectionName, message.getCollectionName());
    assertEquals(numberToSkip, message.getNumberToSkip());
    assertEquals(query, message.getQuery());
    assertEquals(returnFields, message.getReturnFields());
    assertEquals(Boolean.valueOf(awaitData),
            Boolean.valueOf(message.isAwaitData()));
    assertEquals(Boolean.valueOf(exhaust),
            Boolean.valueOf(message.isExhaust()));
    assertEquals(Boolean.valueOf(noCursorTimeout),
            Boolean.valueOf(message.isNoCursorTimeout()));
    assertEquals(Boolean.valueOf(partial),
            Boolean.valueOf(message.isPartial()));
    assertSame(readPreference, message.getReadPreference());
    assertEquals(Boolean.valueOf(tailable),
            Boolean.valueOf(message.isTailable()));

    assertEquals(batchSize, message.getBatchSize());
    assertEquals(limit, message.getLimit());
    assertEquals(-5, message.getNumberToReturn());

}
 
Example 17
Source File: JobVertexDetailsInfoTest.java    From flink with Apache License 2.0 4 votes vote down vote up
@Override
protected JobVertexDetailsInfo getTestResponseInstance() throws Exception {
	final Random random = new Random();
	final IOMetricsInfo jobVertexMetrics = new IOMetricsInfo(
		random.nextLong(),
		random.nextBoolean(),
		random.nextLong(),
		random.nextBoolean(),
		random.nextLong(),
		random.nextBoolean(),
		random.nextLong(),
		random.nextBoolean());
	List<JobVertexDetailsInfo.VertexTaskDetail> vertexTaskDetailList = new ArrayList<>();
	vertexTaskDetailList.add(new JobVertexDetailsInfo.VertexTaskDetail(
		0,
		ExecutionState.CREATED,
		random.nextInt(),
		"local1",
		System.currentTimeMillis(),
		System.currentTimeMillis(),
		1L,
		jobVertexMetrics));
	vertexTaskDetailList.add(new JobVertexDetailsInfo.VertexTaskDetail(
		1,
		ExecutionState.FAILED,
		random.nextInt(),
		"local2",
		System.currentTimeMillis(),
		System.currentTimeMillis(),
		1L,
		jobVertexMetrics));
	vertexTaskDetailList.add(new JobVertexDetailsInfo.VertexTaskDetail(
		2,
		ExecutionState.FINISHED,
		random.nextInt(),
		"local3",
		System.currentTimeMillis(),
		System.currentTimeMillis(),
		1L,
		jobVertexMetrics));

	return new JobVertexDetailsInfo(
		new JobVertexID(),
		"jobVertex" + random.nextLong(),
		random.nextInt(),
		System.currentTimeMillis(),
		vertexTaskDetailList);
}
 
Example 18
Source File: MixingBijectionTest.java    From Whitebox-crypto-AES-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Test of invP method, of class MixingBijection.
 */
public void testInvP() {
    System.out.println("invP");
    Random rnd = new Random();
    
    // probabilistic testing case - random matrix size, rank
    for(int it=0; it<500; it++){
        final int     N        = 2 + rnd.nextInt(66);  // matrix rank
        final boolean fullRank = rnd.nextBoolean();    // should matrix have full rank?
        final int     rank     = fullRank ? N : 2 + rnd.nextInt(N-1); 
        
        // Generate invertible matrix of given size
        MixingBijection instance = new MixingBijection();
        GF2MatrixEx A = instance.generateInvertiblePM(N);
        NormalGF2MatrixHolder h = new NormalGF2MatrixHolder();
        
        // Rank fixing
        if (!fullRank){
            final int srcRow = rnd.nextInt(N);
            
            int[][] Ai = A.getIntArray();
            for(int i=0,r=N; i<N; i++){
                if (r==rank || i==srcRow) {
                    continue;
                }
                
                Ai[i] = IntUtils.clone(Ai[srcRow]);
                r-=1;
            }   
        }

        long result = MixingBijection.invP(h, A);
        
        /*
        System.out.println("Matrix2invert: N="+N+"; rank="+rank+"\n" + A.toString());
        System.out.println("After inversion... Rank=" + h.getRank() 
                + "; Determinant=" + h.getDetetrminant()
                + "; Inversion matrix: \n" + h.getP()
                + "; Q matrix: \n" + h.getQ());
        */

        
        GF2MatrixEx PA  = (GF2MatrixEx) h.getP().rightMultiply(A);
        GF2MatrixEx PAQ = (GF2MatrixEx) PA.rightMultiply(h.getQ());

        /*
        System.out.println("P*A:   \n" + PA);
        System.out.println("P*A*Q: \n" + PAQ);
        */
        
        assertEquals(rank, h.getRank());
        assertEquals(rank == N ? 1 : 0, h.getDetetrminant());
        
        // test resulting normal matrix for correct form
        assertEquals("Normalized matrix has invalid form", true, NTLUtils.isNormalizedRank(PAQ, rank));
    }
}
 
Example 19
Source File: RandomObjects.java    From crate with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a tuple containing random stored field values and their corresponding expected values once printed out
 * via {@link org.elasticsearch.common.xcontent.ToXContent#toXContent(XContentBuilder, ToXContent.Params)} and parsed back via
 * {@link org.elasticsearch.common.xcontent.XContentParser#objectText()}.
 * Generates values based on what can get printed out. Stored fields values are retrieved from lucene and converted via
 * {@link org.elasticsearch.index.mapper.MappedFieldType#valueForDisplay(Object)} to either strings, numbers or booleans.
 *
 * @param random Random generator
 * @param xContentType the content type, used to determine what the expected values are for float numbers.
 */
public static Tuple<List<Object>, List<Object>> randomStoredFieldValues(Random random, XContentType xContentType) {
    int numValues = randomIntBetween(random, 1, 5);
    List<Object> originalValues = new ArrayList<>();
    List<Object> expectedParsedValues = new ArrayList<>();
    int dataType = randomIntBetween(random, 0, 8);
    for (int i = 0; i < numValues; i++) {
        switch(dataType) {
            case 0:
                long randomLong = random.nextLong();
                originalValues.add(randomLong);
                expectedParsedValues.add(randomLong);
                break;
            case 1:
                int randomInt = random.nextInt();
                originalValues.add(randomInt);
                expectedParsedValues.add(randomInt);
                break;
            case 2:
                Short randomShort = (short) random.nextInt();
                originalValues.add(randomShort);
                expectedParsedValues.add(randomShort.intValue());
                break;
            case 3:
                Byte randomByte = (byte)random.nextInt();
                originalValues.add(randomByte);
                expectedParsedValues.add(randomByte.intValue());
                break;
            case 4:
                double randomDouble = random.nextDouble();
                originalValues.add(randomDouble);
                expectedParsedValues.add(randomDouble);
                break;
            case 5:
                Float randomFloat = random.nextFloat();
                originalValues.add(randomFloat);
                if (xContentType == XContentType.SMILE) {
                    //with SMILE we get back a double (this will change in Jackson 2.9 where it will return a Float)
                    expectedParsedValues.add(randomFloat.doubleValue());
                } else {
                    //with JSON AND YAML we get back a double, but with float precision.
                    expectedParsedValues.add(Double.parseDouble(randomFloat.toString()));
                }
                break;
            case 6:
                boolean randomBoolean = random.nextBoolean();
                originalValues.add(randomBoolean);
                expectedParsedValues.add(randomBoolean);
                break;
            case 7:
                String randomString = random.nextBoolean() ? RandomStrings.randomAsciiLettersOfLengthBetween(random, 3, 10) :
                        randomUnicodeOfLengthBetween(random, 3, 10);
                originalValues.add(randomString);
                expectedParsedValues.add(randomString);
                break;
            case 8:
                byte[] randomBytes = RandomStrings.randomUnicodeOfLengthBetween(random, 10, 50).getBytes(StandardCharsets.UTF_8);
                BytesArray randomBytesArray = new BytesArray(randomBytes);
                originalValues.add(randomBytesArray);
                if (xContentType == XContentType.JSON || xContentType == XContentType.YAML) {
                    //JSON and YAML write the base64 format
                    expectedParsedValues.add(Base64.getEncoder().encodeToString(randomBytes));
                } else {
                    //SMILE and CBOR write the original bytes as they support binary format
                    expectedParsedValues.add(randomBytesArray);
                }
                break;
            default:
                throw new UnsupportedOperationException();
        }
    }
    return Tuple.tuple(originalValues, expectedParsedValues);
}
 
Example 20
Source File: RandomUtils.java    From DevUtils with Apache License 2.0 2 votes vote down vote up
/**
 * 获取伪随机 boolean 值
 * @param random Random
 * @return 随机 boolean 值
 */
public static boolean nextBoolean(final Random random) {
    return random != null ? random.nextBoolean() : new Random().nextBoolean();
}