下面列出了java.util.Random#nextLong ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* test get find token from stream
* @throws java.io.IOException if an IO exception happens during deserialization
*/
@Test
public void getFindTokenTest() throws IOException {
short version = 0;
Random random = new Random();
long latestBlobUpdateTime = random.nextLong();
long bytesRead = random.nextLong();
Set<String> lastReadBlobIds = new HashSet<>();
lastReadBlobIds.add("blobid1");
lastReadBlobIds.add("blobid2");
CosmosUpdateTimeFindToken cosmosUpdateTimeFindToken1 =
new CosmosUpdateTimeFindToken(version, latestBlobUpdateTime, bytesRead, lastReadBlobIds);
DataInputStream stream = new DataInputStream(new ByteArrayInputStream(cosmosUpdateTimeFindToken1.toBytes()));
CosmosUpdateTimeFindToken cosmosUpdateTimeFindToken2 =
(CosmosUpdateTimeFindToken) new CosmosUpdateTimeFindTokenFactory().getFindToken(stream);
assertEquals("incorrect token returned from factory", cosmosUpdateTimeFindToken1, cosmosUpdateTimeFindToken2);
}
/**
* Create's a new Simplex-Noise instance, that can be used for pseudorandom number-generation.
*
* @param seed The seed for this SimplexNoise generator. (Cannot be changed)
**/
public SimplexNoise(long seed)
{
// Shuffle array by using random number generator made from the given seed.
Random rnd = new Random(seed);
for(int r = this.p.length; r > 1; r--)
{
swap(this.p, r - 1, rnd.nextInt(r));
}
// Copy Permutations
for(int i = 0; i < 512; i++)
{
this.perm[i] = this.p[i & 255];
this.permMod12[i] = (short) (this.perm[i] % 12);
}
octaveDepthPositionPermutationTable = new double[64];
for(int i = 0; i < octaveDepthPositionPermutationTable.length; i++)
{
octaveDepthPositionPermutationTable[i] = rnd.nextFloat() * (int) (rnd.nextLong() & 0xFFFFFFFF);
}
}
private long findNewFreeOrRemoved() {
long free = KolobokeLongIntHashMap.this.freeValue;
Random random = ThreadLocalRandom.current();
long newFree;
{
do {
newFree = ((long) (random.nextLong()));
} while ((newFree == free) || ((index(newFree)) >= 0) );
}
return newFree;
}
public Unitec_EIM_209_48110(Context context, Long id, String name, long seed, Long roomId) {
super(context, id, name, BRAND, MODEL, Type.AUTOPAIR, roomId);
buttons.add(new OnButton(context, id));
buttons.add(new OffButton(context, id));
if (seed == -1) {
// init seed for this receiver instance, to always generate the same codes from now on
Random ran = new Random();
this.seed = ran.nextLong();
} else {
this.seed = seed;
}
}
@Test
public void testSplitMerge63() {
Random rnd = new Random();
for (int i = 0; i < 1000; i++) {
long[] l = new long[]{rnd.nextLong()>>>1, rnd.nextLong()>>>1};
int[] x = BitTools.merge(63, l);
long[] l2 = BitTools.split(2, 63, x);
assertArrayEquals(l, l2);
}
}
/**
* Gets a long number between two values
*
* @param rnd
* @param range
*
* @return long
*/
static long betweenPositive(Random rnd, Range<Long> range) {
if (range.getLower().equals(range.getUpper())) {
return range.getLower();
}
long nextRnd = rnd.nextLong();
long normRange = (range.getUpper() - range.getLower() + 1);
return Math.abs(nextRnd % normRange) + range.getLower();
}
public BaseImpl() {
values = new long[N];
final Random random = new Random(657483918);
for (int i = 0; i < N; i++) {
values[i] = random.nextLong();
}
}
@Test
public void subtractionVersusAdditionWithRandomAddresses()
{
final Random random = new Random();
final int randomInt = random.nextInt();
final IPv6Address randomAddress = new IPv6Address(random.nextLong(), random.nextLong());
assertEquals(randomAddress, randomAddress.add(randomInt).subtract(randomInt));
}
@Override
protected LongValue[] getTestData() {
Random rnd = new Random(874597969123412341L);
long rndLong = rnd.nextLong();
return new LongValue[] {new LongValue(0L), new LongValue(1L), new LongValue(-1L),
new LongValue(Long.MAX_VALUE), new LongValue(Long.MIN_VALUE),
new LongValue(rndLong), new LongValue(-rndLong)};
}
@Test
public void testAbortProcedureFail() throws Exception {
Random randomGenerator = new Random();
long procId = randomGenerator.nextLong();
boolean abortResult = ADMIN.abortProcedure(procId, true);
assertFalse(abortResult);
}
public static SimpleAllPrimitiveCreator newRandom() {
final Random r = new Random();
return new AutoValue_SimpleAllPrimitiveCreator(
0L,
r.nextBoolean(),
(byte) r.nextInt(),
(short) r.nextInt(),
r.nextInt(),
r.nextLong(),
r.nextFloat(),
r.nextDouble()
);
}
@Test
public void testLongStream() {
final long seed = System.currentTimeMillis();
final Random r1 = new Random(seed);
final long[] a = new long[SIZE];
for (int i=0; i < SIZE; i++) {
a[i] = r1.nextLong();
}
final Random r2 = new Random(seed); // same seed
final long[] b = r2.longs().limit(SIZE).toArray();
assertEquals(a, b);
}
public RMF_Motor(Context context, Long id, String name, long seed, Long roomId) {
super(context, id, name, BRAND, MODEL, Type.AUTOPAIR, roomId);
buttons.add(new UpButton(context, id));
buttons.add(new StopButton(context, id));
buttons.add(new DownButton(context, id));
if (seed == -1) {
// init seed for this receiver instance, to always generate the same codes from now on
Random ran = new Random();
this.seed = ran.nextLong();
} else {
this.seed = seed;
}
}
public void testBinary() throws IOException {
JobConf job = new JobConf();
FileSystem fs = FileSystem.getLocal(job);
Path dir = new Path(System.getProperty("test.build.data",".") + "/mapred");
Path file = new Path(dir, "testbinary.seq");
Random r = new Random();
long seed = r.nextLong();
r.setSeed(seed);
fs.delete(dir, true);
FileInputFormat.setInputPaths(job, dir);
Text tkey = new Text();
Text tval = new Text();
SequenceFile.Writer writer =
new SequenceFile.Writer(fs, job, file, Text.class, Text.class);
try {
for (int i = 0; i < RECORDS; ++i) {
tkey.set(Integer.toString(r.nextInt(), 36));
tval.set(Long.toString(r.nextLong(), 36));
writer.append(tkey, tval);
}
} finally {
writer.close();
}
InputFormat<BytesWritable,BytesWritable> bformat =
new SequenceFileAsBinaryInputFormat();
int count = 0;
r.setSeed(seed);
BytesWritable bkey = new BytesWritable();
BytesWritable bval = new BytesWritable();
Text cmpkey = new Text();
Text cmpval = new Text();
DataInputBuffer buf = new DataInputBuffer();
final int NUM_SPLITS = 3;
FileInputFormat.setInputPaths(job, file);
for (InputSplit split : bformat.getSplits(job, NUM_SPLITS)) {
RecordReader<BytesWritable,BytesWritable> reader =
bformat.getRecordReader(split, job, Reporter.NULL);
try {
while (reader.next(bkey, bval)) {
tkey.set(Integer.toString(r.nextInt(), 36));
tval.set(Long.toString(r.nextLong(), 36));
buf.reset(bkey.getBytes(), bkey.getLength());
cmpkey.readFields(buf);
buf.reset(bval.getBytes(), bval.getLength());
cmpval.readFields(buf);
assertTrue(
"Keys don't match: " + "*" + cmpkey.toString() + ":" +
tkey.toString() + "*",
cmpkey.toString().equals(tkey.toString()));
assertTrue(
"Vals don't match: " + "*" + cmpval.toString() + ":" +
tval.toString() + "*",
cmpval.toString().equals(tval.toString()));
++count;
}
} finally {
reader.close();
}
}
assertEquals("Some records not found", RECORDS, count);
}
public ClientUserAuths(int clientProxyHashcode)
{
m_seed = clientProxyHashcode;
uniqueIdGenerator = new Random(m_seed + System.currentTimeMillis());
m_firstId = uniqueIdGenerator.nextLong();
}
@Test( timeout = 10000)
@SuppressWarnings("unchecked") // mocked generics
public void testLocalizerRunnerException() throws Exception {
DrainDispatcher dispatcher = new DrainDispatcher();
dispatcher.init(conf);
dispatcher.start();
EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
dispatcher.register(ApplicationEventType.class, applicationBus);
EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
dispatcher.register(ContainerEventType.class, containerBus);
ContainerExecutor exec = mock(ContainerExecutor.class);
LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
LocalDirsHandlerService dirsHandlerSpy = spy(dirsHandler);
dirsHandlerSpy.init(conf);
DeletionService delServiceReal = new DeletionService(exec);
DeletionService delService = spy(delServiceReal);
delService.init(new Configuration());
delService.start();
ResourceLocalizationService rawService =
new ResourceLocalizationService(dispatcher, exec, delService,
dirsHandlerSpy, nmContext);
ResourceLocalizationService spyService = spy(rawService);
doReturn(mockServer).when(spyService).createServer();
try {
spyService.init(conf);
spyService.start();
// init application
final Application app = mock(Application.class);
final ApplicationId appId =
BuilderUtils.newApplicationId(314159265358979L, 3);
when(app.getUser()).thenReturn("user0");
when(app.getAppId()).thenReturn(appId);
spyService.handle(new ApplicationLocalizationEvent(
LocalizationEventType.INIT_APPLICATION_RESOURCES, app));
dispatcher.await();
Random r = new Random();
long seed = r.nextLong();
System.out.println("SEED: " + seed);
r.setSeed(seed);
final Container c = getMockContainer(appId, 42, "user0");
final LocalResource resource1 = getPrivateMockedResource(r);
System.out.println("Here 4");
final LocalResourceRequest req1 = new LocalResourceRequest(resource1);
Map<LocalResourceVisibility, Collection<LocalResourceRequest>> rsrcs =
new HashMap<LocalResourceVisibility,
Collection<LocalResourceRequest>>();
List<LocalResourceRequest> privateResourceList =
new ArrayList<LocalResourceRequest>();
privateResourceList.add(req1);
rsrcs.put(LocalResourceVisibility.PRIVATE, privateResourceList);
final Constructor<?>[] constructors =
FSError.class.getDeclaredConstructors();
constructors[0].setAccessible(true);
FSError fsError =
(FSError) constructors[0].newInstance(new IOException("Disk Error"));
Mockito
.doThrow(fsError)
.when(dirsHandlerSpy)
.getLocalPathForWrite(isA(String.class));
spyService.handle(new ContainerLocalizationRequestEvent(c, rsrcs));
Thread.sleep(1000);
dispatcher.await();
// Verify if ContainerResourceFailedEvent is invoked on FSError
verify(containerBus).handle(isA(ContainerResourceFailedEvent.class));
} finally {
spyService.stop();
dispatcher.stop();
delService.stop();
}
}
@Test
public void testCheckpointing() throws Exception {
source.autoAck = false;
StreamSource<String, RMQSource<String>> src = new StreamSource<>(source);
AbstractStreamOperatorTestHarness<String> testHarness =
new AbstractStreamOperatorTestHarness<>(src, 1, 1, 0);
testHarness.open();
sourceThread.start();
Thread.sleep(5);
final Random random = new Random(System.currentTimeMillis());
int numSnapshots = 50;
long previousSnapshotId;
long lastSnapshotId = 0;
long totalNumberOfAcks = 0;
for (int i = 0; i < numSnapshots; i++) {
long snapshotId = random.nextLong();
OperatorSubtaskState data;
synchronized (DummySourceContext.lock) {
data = testHarness.snapshot(snapshotId, System.currentTimeMillis());
previousSnapshotId = lastSnapshotId;
lastSnapshotId = messageId;
}
// let some time pass
Thread.sleep(5);
// check if the correct number of messages have been snapshotted
final long numIds = lastSnapshotId - previousSnapshotId;
RMQTestSource sourceCopy = new RMQTestSource();
StreamSource<String, RMQTestSource> srcCopy = new StreamSource<>(sourceCopy);
AbstractStreamOperatorTestHarness<String> testHarnessCopy =
new AbstractStreamOperatorTestHarness<>(srcCopy, 1, 1, 0);
testHarnessCopy.setup();
testHarnessCopy.initializeState(data);
testHarnessCopy.open();
ArrayDeque<Tuple2<Long, Set<String>>> deque = sourceCopy.getRestoredState();
Set<String> messageIds = deque.getLast().f1;
assertEquals(numIds, messageIds.size());
if (messageIds.size() > 0) {
assertTrue(messageIds.contains(Long.toString(lastSnapshotId)));
}
// check if the messages are being acknowledged and the transaction committed
synchronized (DummySourceContext.lock) {
source.notifyCheckpointComplete(snapshotId);
}
totalNumberOfAcks += numIds;
}
Mockito.verify(source.channel, Mockito.times((int) totalNumberOfAcks)).basicAck(Mockito.anyLong(), Mockito.eq(false));
Mockito.verify(source.channel, Mockito.times(numSnapshots)).txCommit();
}
@Test
public void testTuple5CustomObjects() {
Random rnd = new Random(807346528946L);
SimpleTypes a = new SimpleTypes();
SimpleTypes b = new SimpleTypes(rnd.nextInt(), rnd.nextLong(), (byte) rnd.nextInt(),
StringUtils.getRandomString(rnd, 10, 100), (short) rnd.nextInt(), rnd.nextDouble());
SimpleTypes c = new SimpleTypes(rnd.nextInt(), rnd.nextLong(), (byte) rnd.nextInt(),
StringUtils.getRandomString(rnd, 10, 100), (short) rnd.nextInt(), rnd.nextDouble());
SimpleTypes d = new SimpleTypes(rnd.nextInt(), rnd.nextLong(), (byte) rnd.nextInt(),
StringUtils.getRandomString(rnd, 10, 100), (short) rnd.nextInt(), rnd.nextDouble());
SimpleTypes e = new SimpleTypes(rnd.nextInt(), rnd.nextLong(), (byte) rnd.nextInt(),
StringUtils.getRandomString(rnd, 10, 100), (short) rnd.nextInt(), rnd.nextDouble());
SimpleTypes f = new SimpleTypes(rnd.nextInt(), rnd.nextLong(), (byte) rnd.nextInt(),
StringUtils.getRandomString(rnd, 10, 100), (short) rnd.nextInt(), rnd.nextDouble());
SimpleTypes g = new SimpleTypes(rnd.nextInt(), rnd.nextLong(), (byte) rnd.nextInt(),
StringUtils.getRandomString(rnd, 10, 100), (short) rnd.nextInt(), rnd.nextDouble());
ComplexNestedObject1 o1 = new ComplexNestedObject1(5626435);
ComplexNestedObject1 o2 = new ComplexNestedObject1(76923);
ComplexNestedObject1 o3 = new ComplexNestedObject1(-1100);
ComplexNestedObject1 o4 = new ComplexNestedObject1(0);
ComplexNestedObject1 o5 = new ComplexNestedObject1(44);
ComplexNestedObject2 co1 = new ComplexNestedObject2(rnd);
ComplexNestedObject2 co2 = new ComplexNestedObject2();
ComplexNestedObject2 co3 = new ComplexNestedObject2(rnd);
ComplexNestedObject2 co4 = new ComplexNestedObject2(rnd);
Book b1 = new Book(976243875L, "The Serialization Odysse", 42);
Book b2 = new Book(0L, "Debugging byte streams", 1337);
Book b3 = new Book(-1L, "Low level interfaces", 0xC0FFEE);
Book b4 = new Book(Long.MAX_VALUE, "The joy of bits and bytes", 0xDEADBEEF);
Book b5 = new Book(Long.MIN_VALUE, "Winnign a prize for creative test strings", 0xBADF00);
Book b6 = new Book(-2L, "Distributed Systems", 0xABCDEF0123456789L);
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
BookAuthor ba1 = new BookAuthor(976243875L, list, "Arno Nym");
ArrayList<String> list2 = new ArrayList<String>();
BookAuthor ba2 = new BookAuthor(987654321L, list2, "The Saurus");
@SuppressWarnings("unchecked")
Tuple5<SimpleTypes, Book, ComplexNestedObject1, BookAuthor, ComplexNestedObject2>[] testTuples = new Tuple5[] {
new Tuple5<SimpleTypes, Book, ComplexNestedObject1, BookAuthor, ComplexNestedObject2>(a, b1, o1, ba1, co1),
new Tuple5<SimpleTypes, Book, ComplexNestedObject1, BookAuthor, ComplexNestedObject2>(b, b2, o2, ba2, co2),
new Tuple5<SimpleTypes, Book, ComplexNestedObject1, BookAuthor, ComplexNestedObject2>(c, b3, o3, ba1, co3),
new Tuple5<SimpleTypes, Book, ComplexNestedObject1, BookAuthor, ComplexNestedObject2>(d, b2, o4, ba1, co4),
new Tuple5<SimpleTypes, Book, ComplexNestedObject1, BookAuthor, ComplexNestedObject2>(e, b4, o5, ba2, co4),
new Tuple5<SimpleTypes, Book, ComplexNestedObject1, BookAuthor, ComplexNestedObject2>(f, b5, o1, ba2, co4),
new Tuple5<SimpleTypes, Book, ComplexNestedObject1, BookAuthor, ComplexNestedObject2>(g, b6, o4, ba1, co2)
};
runTests(-1, testTuples);
}
/**
* Test we can invoke an SPL operator with various parameter types.
*/
private void testOpParams(String testName, OpParamAdder opParamAdder) throws Exception {
Topology topology = new Topology(testName);
opParamAdder.init(topology, getConfig());
StreamSchema schema = Type.Factory.getStreamSchema(
"tuple<"
+ "rstring r"
+ ", ustring u"
+ ", boolean b"
+ ", int8 i8, int16 i16, int32 i32, int64 i64"
+ ", uint8 ui8, uint16 ui16, uint32 ui32, uint64 ui64"
+ ", float32 f32, float64 f64"
+ " >");
Map<String,Object> expectedValues = new HashMap<>();
Random rand = new Random();
String r = "test X\tY\"Lit\nerals\\nX\\tY " + rand.nextInt();
opParamAdder.put("r", r);
String u = "test X\tY\"Lit\nerals\\nX\\tY " + rand.nextInt();
opParamAdder.put("u", SPL.createValue(u, MetaType.USTRING));
expectedValues.put("r", new RString(r));
expectedValues.put("u", u);
boolean b = rand.nextBoolean();
opParamAdder.put("b", b);
expectedValues.put("b", b);
byte i8 = (byte) rand.nextInt();
short i16 = (short) rand.nextInt();
int i32 = rand.nextInt();
long i64 = rand.nextLong();
opParamAdder.put("i8", i8);
opParamAdder.put("i16", i16);
opParamAdder.put("i32", i32);
opParamAdder.put("i64", i64);
expectedValues.put("i8", i8);
expectedValues.put("i16", i16);
expectedValues.put("i32", i32);
expectedValues.put("i64", i64);
byte ui8 = (byte) 0xFF; // 255 => -1
short ui16 = (short) 0xFFFE; // 65534 => -2
int ui32 = 0xFFFFFFFD; // 4294967293 => -3
long ui64 = 0xFFFFFFFFFFFFFFFCL; // 18446744073709551612 => -4
opParamAdder.put("ui8", SPL.createValue(ui8, MetaType.UINT8));
opParamAdder.put("ui16", SPL.createValue(ui16, MetaType.UINT16));
opParamAdder.put("ui32", SPL.createValue(ui32, MetaType.UINT32));
opParamAdder.put("ui64", SPL.createValue(ui64, MetaType.UINT64));
expectedValues.put("ui8", ui8);
expectedValues.put("ui16", ui16);
expectedValues.put("ui32", ui32);
expectedValues.put("ui64", ui64);
float f32 = 4.0f;
double f64 = 32.0;
opParamAdder.put("f32", f32);
opParamAdder.put("f64", f64);
expectedValues.put("f32", f32);
expectedValues.put("f64", f64);
SPL.addToolkit(topology, new File(getTestRoot(), "spl/testtk"));
SPLStream paramTuple = SPL.invokeSource(topology, "testgen::TypeLiteralTester", opParamAdder.getParams(), schema);
Tuple expectedTuple = schema.getTuple(expectedValues);
Tester tester = topology.getTester();
Condition<Long> expectedCount = tester.tupleCount(paramTuple, 1);
Condition<?> contents = tester.tupleContents(paramTuple, expectedTuple);;
complete(tester, expectedCount.and(contents), 10, TimeUnit.SECONDS);
assertTrue(contents.valid());
assertTrue(expectedCount.valid());
}
/**
* Generate a new device identity using a provided random number generator
* class. This is used for testing.
*
* @param rng random number generator to retrieve the next long from
* @return verifier device identity based on the input from the provided
* random number generator
*/
@VisibleForTesting
static VerifierDeviceIdentity generate(Random rng) {
long identity = rng.nextLong();
return new VerifierDeviceIdentity(identity);
}