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:com.sfs.beans.EmailAttachmentBean.java

/**
 * Gets the file name.//ww w .j a  v a 2  s  . c  o m
 *
 * @return the file name
 */
public final String getFileName() {
    if (this.fileName == null) {
        this.fileName = "";
    }
    if (StringUtils.isBlank(this.fileName)) {
        // Generate new filename based on an 13 letter random string
        Random r = new Random();
        final int maxLength = 36;
        this.fileName = Long.toString(Math.abs(r.nextLong()), maxLength);
    }
    return this.fileName;
}

From source file:org.onlab.util.ImmutableByteSequenceTest.java

@Test
public void testBitwiseOperations() {
    Random random = new Random();
    long long1 = random.nextLong();
    long long2 = random.nextLong();

    ImmutableByteSequence bs1 = ImmutableByteSequence.copyFrom(long1);
    ImmutableByteSequence bs2 = ImmutableByteSequence.copyFrom(long2);

    ImmutableByteSequence andBs = bs1.bitwiseAnd(bs2);
    ImmutableByteSequence orBs = bs1.bitwiseOr(bs2);
    ImmutableByteSequence xorBs = bs1.bitwiseXor(bs2);

    assertThat("Invalid bitwise AND result", andBs.asReadOnlyBuffer().getLong(), is(long1 & long2));
    assertThat("Invalid bitwise OR result", orBs.asReadOnlyBuffer().getLong(), is(long1 | long2));
    assertThat("Invalid bitwise XOR result", xorBs.asReadOnlyBuffer().getLong(), is(long1 ^ long2));
}

From source file:org.apache.hadoop.mapreduce.lib.output.TestMRSequenceFileAsBinaryOutputFormat.java

public void testBinary() throws IOException, InterruptedException {
    Configuration conf = new Configuration();
    Job job = new Job(conf);

    Path outdir = new Path(System.getProperty("test.build.data", "/tmp"), "outseq");
    Random r = new Random();
    long seed = r.nextLong();
    r.setSeed(seed);//from w ww.  j  a  v a  2  s .c o  m

    FileOutputFormat.setOutputPath(job, outdir);

    SequenceFileAsBinaryOutputFormat.setSequenceFileOutputKeyClass(job, IntWritable.class);
    SequenceFileAsBinaryOutputFormat.setSequenceFileOutputValueClass(job, DoubleWritable.class);

    SequenceFileAsBinaryOutputFormat.setCompressOutput(job, true);
    SequenceFileAsBinaryOutputFormat.setOutputCompressionType(job, CompressionType.BLOCK);

    BytesWritable bkey = new BytesWritable();
    BytesWritable bval = new BytesWritable();

    TaskAttemptContext context = MapReduceTestUtil.createDummyMapTaskAttemptContext(job.getConfiguration());
    OutputFormat<BytesWritable, BytesWritable> outputFormat = new SequenceFileAsBinaryOutputFormat();
    OutputCommitter committer = outputFormat.getOutputCommitter(context);
    committer.setupJob(job);
    RecordWriter<BytesWritable, BytesWritable> writer = outputFormat.getRecordWriter(context);

    IntWritable iwritable = new IntWritable();
    DoubleWritable dwritable = new DoubleWritable();
    DataOutputBuffer outbuf = new DataOutputBuffer();
    LOG.info("Creating data by SequenceFileAsBinaryOutputFormat");
    try {
        for (int i = 0; i < RECORDS; ++i) {
            iwritable = new IntWritable(r.nextInt());
            iwritable.write(outbuf);
            bkey.set(outbuf.getData(), 0, outbuf.getLength());
            outbuf.reset();
            dwritable = new DoubleWritable(r.nextDouble());
            dwritable.write(outbuf);
            bval.set(outbuf.getData(), 0, outbuf.getLength());
            outbuf.reset();
            writer.write(bkey, bval);
        }
    } finally {
        writer.close(context);
    }
    committer.commitTask(context);
    committer.commitJob(job);

    InputFormat<IntWritable, DoubleWritable> iformat = new SequenceFileInputFormat<IntWritable, DoubleWritable>();
    int count = 0;
    r.setSeed(seed);
    SequenceFileInputFormat.setInputPaths(job, outdir);
    LOG.info("Reading data by SequenceFileInputFormat");
    for (InputSplit split : iformat.getSplits(job)) {
        RecordReader<IntWritable, DoubleWritable> reader = iformat.createRecordReader(split, context);
        MapContext<IntWritable, DoubleWritable, BytesWritable, BytesWritable> mcontext = new MapContext<IntWritable, DoubleWritable, BytesWritable, BytesWritable>(
                job.getConfiguration(), context.getTaskAttemptID(), reader, null, null,
                MapReduceTestUtil.createDummyReporter(), split);
        reader.initialize(split, mcontext);
        try {
            int sourceInt;
            double sourceDouble;
            while (reader.nextKeyValue()) {
                sourceInt = r.nextInt();
                sourceDouble = r.nextDouble();
                iwritable = reader.getCurrentKey();
                dwritable = reader.getCurrentValue();
                assertEquals("Keys don't match: " + "*" + iwritable.get() + ":" + sourceInt + "*", sourceInt,
                        iwritable.get());
                assertTrue("Vals don't match: " + "*" + dwritable.get() + ":" + sourceDouble + "*",
                        Double.compare(dwritable.get(), sourceDouble) == 0);
                ++count;
            }
        } finally {
            reader.close();
        }
    }
    assertEquals("Some records not found", RECORDS, count);
}

From source file:org.kiji.examples.phonebook.IntegrationTestPhonebookImporter.java

/**
 * Generates a random HDFS path.//from w ww  . j  a va  2s  . c o m
 *
 * @param prefix Prefix for the random file name.
 * @return a random HDFS path.
 * @throws Exception on error.
 */
private Path makeRandomHdfsPath(String prefix) throws Exception {
    Preconditions.checkNotNull(mFS);
    final Path base = new Path(FileSystem.getDefaultUri(mConf));
    final Random random = new Random(System.nanoTime());
    return new Path(base, String.format("/%s-%s", prefix, random.nextLong()));
}

From source file:org.apache.hadoop.mapred.TestSequenceFileAsBinaryOutputFormat.java

public void testBinary() throws IOException {
    JobConf job = new JobConf();
    FileSystem fs = FileSystem.getLocal(job);

    Path dir = new Path(
            new Path(new Path(System.getProperty("test.build.data", ".")), FileOutputCommitter.TEMP_DIR_NAME),
            "_" + attempt);
    Path file = new Path(dir, "testbinary.seq");
    Random r = new Random();
    long seed = r.nextLong();
    r.setSeed(seed);/*from w w  w .  j a v  a 2 s  .  com*/

    fs.delete(dir, true);
    if (!fs.mkdirs(dir)) {
        fail("Failed to create output directory");
    }

    job.set("mapred.task.id", attempt);
    FileOutputFormat.setOutputPath(job, dir.getParent().getParent());
    FileOutputFormat.setWorkOutputPath(job, dir);

    SequenceFileAsBinaryOutputFormat.setSequenceFileOutputKeyClass(job, IntWritable.class);
    SequenceFileAsBinaryOutputFormat.setSequenceFileOutputValueClass(job, DoubleWritable.class);

    SequenceFileAsBinaryOutputFormat.setCompressOutput(job, true);
    SequenceFileAsBinaryOutputFormat.setOutputCompressionType(job, CompressionType.BLOCK);

    BytesWritable bkey = new BytesWritable();
    BytesWritable bval = new BytesWritable();

    RecordWriter<BytesWritable, BytesWritable> writer = new SequenceFileAsBinaryOutputFormat()
            .getRecordWriter(fs, job, file.toString(), Reporter.NULL);

    IntWritable iwritable = new IntWritable();
    DoubleWritable dwritable = new DoubleWritable();
    DataOutputBuffer outbuf = new DataOutputBuffer();
    LOG.info("Creating data by SequenceFileAsBinaryOutputFormat");
    try {
        for (int i = 0; i < RECORDS; ++i) {
            iwritable = new IntWritable(r.nextInt());
            iwritable.write(outbuf);
            bkey.set(outbuf.getData(), 0, outbuf.getLength());
            outbuf.reset();
            dwritable = new DoubleWritable(r.nextDouble());
            dwritable.write(outbuf);
            bval.set(outbuf.getData(), 0, outbuf.getLength());
            outbuf.reset();
            writer.write(bkey, bval);
        }
    } finally {
        writer.close(Reporter.NULL);
    }

    InputFormat<IntWritable, DoubleWritable> iformat = new SequenceFileInputFormat<IntWritable, DoubleWritable>();
    int count = 0;
    r.setSeed(seed);
    DataInputBuffer buf = new DataInputBuffer();
    final int NUM_SPLITS = 3;
    SequenceFileInputFormat.addInputPath(job, file);
    LOG.info("Reading data by SequenceFileInputFormat");
    for (InputSplit split : iformat.getSplits(job, NUM_SPLITS)) {
        RecordReader<IntWritable, DoubleWritable> reader = iformat.getRecordReader(split, job, Reporter.NULL);
        try {
            int sourceInt;
            double sourceDouble;
            while (reader.next(iwritable, dwritable)) {
                sourceInt = r.nextInt();
                sourceDouble = r.nextDouble();
                assertEquals("Keys don't match: " + "*" + iwritable.get() + ":" + sourceInt + "*", sourceInt,
                        iwritable.get());
                assertTrue("Vals don't match: " + "*" + dwritable.get() + ":" + sourceDouble + "*",
                        Double.compare(dwritable.get(), sourceDouble) == 0);
                ++count;
            }
        } finally {
            reader.close();
        }
    }
    assertEquals("Some records not found", RECORDS, count);
}

From source file:io.cloudslang.engine.queue.services.QueueListenerImplTest.java

private Execution createBranchExecution() {
    SystemContext systemContext = new SystemContext();
    systemContext.setBranchId(UUID.randomUUID().toString());
    Random random = new Random();
    return new Execution(random.nextLong(), random.nextLong(), 0L, new HashMap<String, String>(0),
            systemContext);//from   ww w.ja v a  2  s  .c om
}

From source file:com.ms.commons.lang.RangeBuilderTest.java

@Test
public void testPrimitive() {
    List<Person> data = new ArrayList<Person>();
    for (int i = 0; i < 5; i++) {
        Random r = new Random(System.nanoTime());
        Person p = new Person();
        p.setSalary(r.nextFloat());//  w  ww  .j  a  va 2  s. co m
        p.setAge((r.nextInt(10)));
        p.setId(r.nextLong());
        p.setSex(r.nextInt(10));
        p.setName("name" + r.nextInt(10));
        data.add(p);
    }
    println(data);
    Range range = RangeBuilder.data(data).property("age").range();
    println(range);
    range = RangeBuilder.data(data).property("name").keyName("newName").range();
    println(range);
    range = RangeBuilder.data(data).property("salary").desc().range();
    println(range);
    range = RangeBuilder.data(data).property("id").asc().range();
    println(range);
}

From source file:io.seldon.recommendation.VariationTestingClientStrategyTest.java

@Test
public void testSampling() {
    List<Variation> variations = new ArrayList<Variation>();
    int max = 4;/*from  w ww  .  j  ava 2 s.c o  m*/
    double ratio = 1 / (max * 1.0);
    for (int i = 1; i <= max; i++) {
        ClientStrategy s = new TestStrategy("" + i);
        Variation v = new Variation(s, new BigDecimal(ratio));
        variations.add(v);
    }
    VariationTestingClientStrategy v = VariationTestingClientStrategy.build(variations);
    Random r = new Random();
    int[] sTot = new int[max];
    int sampleSize = 10000000;
    for (int i = 0; i < sampleSize; i++) {
        String userId = "u" + r.nextLong();
        ClientStrategy s = v.sample(userId);
        Assert.assertNotNull(s);
        int index = Integer.parseInt(s.getName(null, null)) - 1;
        sTot[index] += 1;
    }
    Assert.assertEquals(1 / (max * 1.0), sTot[0] / (sampleSize * 1.0), 0.001);
}

From source file:io.selendroid.standalone.server.model.SelendroidStandaloneDriverTest.java

private void createTestSession(SelendroidConfiguration conf, SelendroidCapabilities caps) throws Exception {
    // Setting up driver with test app and device stub
    SelendroidStandaloneDriver driver = getSelendroidStandaloneDriver();
    driver.initApplicationsUnderTest(conf);
    DeviceStore store = new DeviceStore(EMULATOR_PORT, getDeviceManager());

    DeviceForTest emulator = new DeviceForTest(DeviceTargetPlatform.ANDROID16);
    Random random = new Random();
    final UUID definedSessionId = new UUID(random.nextLong(), random.nextLong());

    emulator.testSessionListener = new TestSessionListener(definedSessionId.toString(), "test") {
        @Override/*from w w w  .j a  v  a 2s. c  om*/
        public SelendroidResponse executeSelendroidRequest(Properties params) {
            return null;
        }
    };
    store.addDeviceToStore(emulator);
    driver.setDeviceStore(store);

    // testing new session creation
    caps.setPlatformVersion(DeviceTargetPlatform.ANDROID16);
    try {
        String sessionId = driver.createNewTestSession(new JSONObject(caps.asMap()), 0);
        Assert.assertNotNull(UUID.fromString(sessionId));
    } finally {
        // this will also stop the http server
        emulator.stop();
    }
}