List of usage examples for java.util Random nextLong
public long nextLong()
From source file:org.eclipse.tracecompass.statesystem.core.tests.perf.historytree.HistoryTreeBackendBenchmark.java
/** * Benchmarks creating, single querying and full querying the state system *//*from w w w.j a v a2 s .c o m*/ @Test public void testBenchmark() { /* Check arguments */ long totalTime = this.fNbAvgIntervals * INTERVAL_AVG_TIME; Performance perf = Performance.getDefault(); PerformanceMeter pmBuild = perf.createPerformanceMeter(TEST_PREFIX + TEST_BUILDING_ID + fName); perf.tagAsSummary(pmBuild, TEST_BUILDING_ID + fShortName, Dimension.CPU_TIME); PerformanceMeter pmSingleQuery = perf.createPerformanceMeter(TEST_PREFIX + TEST_SINGLE_QUERY_ID + fName); perf.tagAsSummary(pmSingleQuery, TEST_SINGLE_QUERY_ID + fShortName, Dimension.CPU_TIME); PerformanceMeter pmFullQuery = perf.createPerformanceMeter(TEST_PREFIX + TEST_FULL_QUERY_ID + fName); perf.tagAsSummary(pmFullQuery, TEST_FULL_QUERY_ID + fShortName, Dimension.CPU_TIME); PerformanceMeter pmRangeQuery = perf.createPerformanceMeter(TEST_PREFIX + TEST_QUERY_RANGE_ID + fName); perf.tagAsSummary(pmRangeQuery, TEST_QUERY_RANGE_ID + fShortName, Dimension.CPU_TIME); for (int i = 0; i < fNbLoops; i++) { try { /* Create the state system */ createFile(); IStateHistoryBackend backend = StateHistoryBackendFactory.createHistoryTreeBackendNewFile( TEST_BUILDING_ID, NonNullUtils.checkNotNull(fTempFile), 1, 1, QUEUE_SIZE); ITmfStateSystemBuilder ss = StateSystemFactory.newStateSystem(backend); /* Initialize the attributes */ Queue<QuarkEvent> quarkEvents = new PriorityQueue<>(fNbAttrib); Random randomGenerator = new Random(SEED); int rootQuark = ss.getQuarkAbsoluteAndAdd(ROOT_NODE); /* Create all attributes before testing */ for (int j = 0; j < fNbAttrib; j++) { int quark = ss.getQuarkRelativeAndAdd(rootQuark, String.valueOf(j)); quarkEvents.add(new QuarkEvent(quark, (Math.abs(randomGenerator.nextLong()) % INTERVAL_AVG_TIME) + 1, fValues.getValues())); } /* Adds random intervals to the state system */ pmBuild.start(); while (true) { QuarkEvent quarkEvent = quarkEvents.poll(); if (quarkEvent == null) { break; } long eventTime = quarkEvent.getNextEventTime(); ss.modifyAttribute(eventTime, quarkEvent.getNextValue(), quarkEvent.getQuark()); long nextDelta = fDistributionMethod.getNextEndTime(randomGenerator, INTERVAL_AVG_TIME); long nextEndTime = eventTime + nextDelta; if (nextEndTime <= totalTime) { quarkEvent.setNextEventTime(nextEndTime); quarkEvents.add(quarkEvent); } } ss.closeHistory(totalTime); pmBuild.stop(); /* * Benchmark the single queries: for each random timestamp, * query a random attribute */ List<Integer> subAttributes = ss.getSubAttributes(rootQuark, false); pmSingleQuery.start(); for (int j = 0; j < QUERY_COUNT; j++) { long ts = getNextRandomValue(randomGenerator, totalTime); int attrib = (int) getNextRandomValue(randomGenerator, subAttributes.size()); ss.querySingleState(ts, attrib); } pmSingleQuery.stop(); /* Benchmark the history range query of 10 attributes */ pmRangeQuery.start(); for (int j = 0; j < 10; j++) { int attrib = (int) getNextRandomValue(randomGenerator, subAttributes.size()); StateSystemUtils.queryHistoryRange(ss, attrib, ss.getStartTime(), ss.getCurrentEndTime()); } pmRangeQuery.stop(); /* Benchmark the full queries */ pmFullQuery.start(); for (int j = 0; j < QUERY_COUNT; j++) { long ts = getNextRandomValue(randomGenerator, totalTime); ss.queryFullState(ts); } pmFullQuery.stop(); /* Output some data on the file */ if (i == 0) { if (backend instanceof HistoryTreeBackend) { HistoryTreeBackend htBackend = (HistoryTreeBackend) backend; System.out.println("History tree file size: " + FileUtils.byteCountToDisplaySize(htBackend.getFileSize())); System.out.println("Average node usage: " + htBackend.getAverageNodeUsage()); } } deleteFile(); } catch (IOException | StateValueTypeException | AttributeNotFoundException | StateSystemDisposedException e) { fail(e.getMessage()); } finally { deleteFile(); } } pmBuild.commit(); pmSingleQuery.commit(); pmFullQuery.commit(); pmRangeQuery.commit(); }
From source file:org.apache.solr.core.OpenCloseCoreStressTest.java
public Indexer(OpenCloseCoreStressTest OCCST, String url, List<HttpSolrClient> clients, int numThreads, int secondsToRun, Random random) { stopTimeout = new TimeOut(secondsToRun, TimeUnit.SECONDS); nextTimeout = new TimeOut(60, TimeUnit.SECONDS); docsThisCycle.set(0);//from w w w . ja va 2 s. co m qTimesAccum.set(0); updateCounts.set(0); for (int idx = 0; idx < numThreads; ++idx) { OneIndexer one = new OneIndexer(OCCST, url, clients.get(idx), random.nextLong()); _threads.add(one); one.start(); } }
From source file:com.facebook.LinkBench.LinkBenchDriver.java
void sendrequests() throws IOException, InterruptedException, Throwable { if (!doRequest) { logger.info("Skipping request phase per the cmdline arg"); return;/* w w w .j a v a 2 s . c om*/ } // config info for requests int nrequesters = ConfigUtil.getInt(props, Config.NUM_REQUESTERS); if (nrequesters == 0) { logger.info("NO REQUEST PHASE CONFIGURED. "); return; } LatencyStats latencyStats = new LatencyStats(nrequesters); List<LinkBenchRequest> requesters = new LinkedList<LinkBenchRequest>(); RequestProgress progress = LinkBenchRequest.createProgress(logger, props); Random masterRandom = createMasterRNG(props, Config.REQUEST_RANDOM_SEED); // create requesters for (int i = 0; i < nrequesters; i++) { Stores stores = initStores(); LinkBenchRequest l = new LinkBenchRequest(stores.linkStore, stores.nodeStore, props, latencyStats, csvStreamFile, progress, new Random(masterRandom.nextLong()), i, nrequesters); requesters.add(l); } progress.startTimer(); // run requesters concurrentExec(requesters); long finishTime = System.currentTimeMillis(); // Calculate duration accounting for warmup time long benchmarkTime = finishTime - progress.getBenchmarkStartTime(); long requestsdone = 0; int abortedRequesters = 0; // wait for requesters for (LinkBenchRequest requester : requesters) { requestsdone += requester.getRequestsDone(); if (requester.didAbort()) { abortedRequesters++; } } latencyStats.displayLatencyStats(); if (csvStatsFile != null) { latencyStats.printCSVStats(csvStatsFile, true); } logger.info("REQUEST PHASE COMPLETED. " + requestsdone + " requests done in " + (benchmarkTime / 1000) + " seconds." + " Requests/second = " + (1000 * requestsdone) / benchmarkTime); if (abortedRequesters > 0) { logger.error(String.format( "Benchmark did not complete cleanly: %d/%d " + "request threads aborted. See error log entries for details.", abortedRequesters, nrequesters)); } }
From source file:de.mpg.escidoc.services.exportmanager.Export.java
private String generateTmpFileName() { Random r = new Random(); return Long.toString(Math.abs(r.nextLong()), 36); }
From source file:org.apache.hadoop.hbase.client.TestMaxResponseSize.java
/** * Test from client side for scans that are cross multiple regions * @throws Exception/*from ww w. j a va2 s.c om*/ */ @Test public void testScanCrossRegion() throws Exception { byte[] TABLE = Bytes.toBytes("testScanCrossRegion"); byte[][] FAMILIES = { Bytes.toBytes("MyCF1") }; List<KeyValue> kvListExp = new ArrayList<KeyValue>(); HTable ht = TEST_UTIL.createTable(TABLE, FAMILIES, NUM_VERSION, Bytes.toBytes("row0"), Bytes.toBytes("row99"), NUM_REGION); TEST_UTIL.waitUntilAllRegionsAssigned(NUM_REGION); Random rand = new Random(System.currentTimeMillis()); for (int iRow = 0; iRow < 100; ++iRow) { final byte[] row = Bytes.toBytes(String.format("row%02d", iRow)); Put put = new Put(row); final long ts = System.currentTimeMillis(); for (int iCol = 0; iCol < 10; ++iCol) { final byte[] cf = FAMILIES[0]; final byte[] qual = Bytes.toBytes("col" + iCol); final byte[] value = Bytes.toBytes("value_for_row_" + iRow + "_cf_" + Bytes.toStringBinary(cf) + "_col_" + iCol + "_ts_" + ts + "_random_" + rand.nextLong()); KeyValue kv = new KeyValue(row, cf, qual, ts, value); put.add(kv); kvListExp.add(kv); } ht.put(put); ht.flushCommits(); } boolean toLog = true; Scan scan = new Scan(); Result result; // each region have 10 rows, we fetch 5 rows at a time scan.setCaching(5); ResultScanner scanner; List<KeyValue> kvListScan = new ArrayList<KeyValue>(); scanner = ht.getScanner(scan); kvListScan.clear(); // do a full scan of the table that is split among multiple regions while ((result = scanner.next()) != null) { for (KeyValue kv : result.list()) { kvListScan.add(kv); } } scanner.close(); result = new Result(kvListScan); verifyResult(result, kvListExp, toLog, "testScanCrossRegion"); }
From source file:org.apache.hadoop.io.TestArrayOutputStream.java
private void runComparison(ArrayOutputStream aos, DataOutputStream dos, ByteArrayOutputStream bos) throws IOException { Random r = new Random(); // byte/*from w w w. j a v a 2s . c o m*/ int b = r.nextInt(128); aos.write(b); dos.write(b); // byte[] byte[] bytes = new byte[10]; r.nextBytes(bytes); aos.write(bytes, 0, 10); dos.write(bytes, 0, 10); // Byte aos.writeByte(b); dos.writeByte(b); // boolean boolean bool = r.nextBoolean(); aos.writeBoolean(bool); dos.writeBoolean(bool); // short short s = (short) r.nextInt(); aos.writeShort(s); dos.writeShort(s); // char int c = r.nextInt(); aos.writeChar(c); dos.writeChar(c); // int int i = r.nextInt(); aos.writeInt(i); dos.writeInt(i); // long long l = r.nextLong(); aos.writeLong(l); dos.writeLong(l); // float float f = r.nextFloat(); aos.writeFloat(f); dos.writeFloat(f); // double double d = r.nextDouble(); aos.writeDouble(d); dos.writeDouble(d); // strings String str = RandomStringUtils.random(20); aos.writeBytes(str); aos.writeChars(str); aos.writeUTF(str); dos.writeBytes(str); dos.writeChars(str); dos.writeUTF(str); byte[] expected = bos.toByteArray(); assertEquals(expected.length, aos.size()); byte[] actual = new byte[aos.size()]; System.arraycopy(aos.getBytes(), 0, actual, 0, actual.length); // serialized bytes should be the same assertTrue(Arrays.equals(expected, actual)); }
From source file:com.toughra.mlearnplayer.EXEStrMgr.java
/** * Make a UUIID/* w w w . j ava 2 s .c om*/ */ public String makeUUID() { Random r = new Random(System.currentTimeMillis()); String uuid = String.valueOf(Math.abs(r.nextLong())); return uuid; }
From source file:org.galicaster.dashboard.DashboardService.java
@SuppressWarnings("unchecked") protected void activate(ComponentContext cc) throws URISyntaxException { // Initialize the object to hold the agent's properties agentPasswords = new Properties(); if ((cc == null) || (cc.getProperties() == null)) { mode = MODE_DEFAULT;//from ww w. j a v a 2 s .co m logger.debug("Setting default functioning mode: {}", mode.toString()); pingTimeout = PING_TIMEOUT_DEFAULT; logger.debug("Setting default ping timeout: {}", pingTimeout); snapshotTimeout = SNAPSHOT_TIMEOUT_DEFAULT; logger.debug("Setting default snapshot timeout: {}", snapshotTimeout); snapshotPeriod = SNAPSHOT_PERIOD_DEFAULT; logger.debug("Setting default snapshot period: {}", snapshotPeriod); maxConcurrentSnapshots = MAX_CONCURRENT_DEFAULT; logger.debug("Setting default maximum concurrent snapshots: {}", maxConcurrentSnapshots); defaultPassword = DEFAULT_PASSWORD_DEFAULT; logger.debug("Setting default VNC password default: {}", DEFAULT_PASSWORD_DEFAULT); } else { // Get the component properties Dictionary<String, Object> properties = cc.getProperties(); // Get the functioning mode. String strMode = (String) properties.get(MODE_PROPERTY); if (strMode != null) { try { mode = Mode.valueOf(strMode.toUpperCase()); } catch (IllegalArgumentException iae) { logger.warn("Invalid functioning mode found in configuration file: {}", strMode); mode = MODE_DEFAULT; logger.debug("Setting default functioning mode: {}", mode.toString()); } } // Read the properties that control the "snapshot taking" process try { pingTimeout = Integer.parseInt((String) properties.get(PING_TIMEOUT_PROPERTY)); } catch (Exception e) { pingTimeout = PING_TIMEOUT_DEFAULT; } try { snapshotTimeout = Integer.parseInt((String) properties.get(SNAPSHOT_TIMEOUT_PROPERTY)); } catch (Exception e) { pingTimeout = SNAPSHOT_TIMEOUT_DEFAULT; } try { snapshotPeriod = Long.parseLong((String) properties.get(SNAPSHOT_PERIOD_PROPERTY)); } catch (Exception e) { snapshotPeriod = SNAPSHOT_PERIOD_DEFAULT; } try { maxConcurrentSnapshots = Integer.parseInt((String) properties.get(MAX_CONCURRENT_PROPERTY)); } catch (Exception e) { maxConcurrentSnapshots = MAX_CONCURRENT_DEFAULT; } // Get the default VNC password, if it is defined in the config file defaultPassword = (String) properties.get(DEFAULT_PASSWORD_PROPERTY); if (defaultPassword == null) defaultPassword = DEFAULT_PASSWORD_DEFAULT; // Get the passwords per agent, if specified in the config file Pattern propertyPattern = Pattern.compile(PASSWORD_REGEXP); for (Enumeration<String> keys = properties.keys(); keys.hasMoreElements();) { String key = keys.nextElement(); Matcher match = propertyPattern.matcher(key); if (match.matches()) { agentPasswords.setProperty(match.group(1), (String) properties.get(match.group())); } } } // If the mode is PULL, set the security information and start the snapshot threads accordingly if (mode == Mode.PULL) { // Set security information this.systemAccount = cc.getBundleContext().getProperty("org.opencastproject.security.digest.user"); DefaultOrganization defaultOrg = new DefaultOrganization(); securityService.setOrganization(defaultOrg); securityService .setUser(new JaxbUser(systemAccount, defaultOrg, new JaxbRole(GLOBAL_ADMIN_ROLE, defaultOrg))); // Start the threads that take the snapshots periodicSnapshots = Executors.newScheduledThreadPool(maxConcurrentSnapshots); Map<String, Agent> knownAgents = captureAgentStateService.getKnownAgents(); Random randGen = new Random(); for (Map.Entry<String, Agent> entry : knownAgents.entrySet()) { SnapshotWithDeadline task = new SnapshotWithDeadline(entry.getValue(), tempDir, agentPasswords.getProperty(entry.getKey(), defaultPassword), snapshotTimeout, TimeUnit.SECONDS); periodicSnapshots.scheduleAtFixedRate(task, randGen.nextLong() % snapshotPeriod, snapshotPeriod, TimeUnit.SECONDS); } } logger.info("Galicaster Service activated"); }
From source file:hsa.awp.campaign.facade.CampaignFacadeTest.java
/** * Creates and persists a newly created {@link PriorityList} with random items. * * @return persisted PriorityList./*from ww w . ja v a 2s .c o m*/ */ private PriorityList createAndPersistRandomPriorityList() { Random random = new Random(); PriorityList list = PriorityList.getInstance(0L); list.setInitiator(random.nextLong()); list.setParticipant(random.nextLong()); for (int i = 1; i < 10; i++) { list.addItem(random.nextLong(), i); } return campFac.savePriorityList(list); }
From source file:io.druid.hll.HyperLogLogCollectorTest.java
@Test public void testSparseEstimation() throws Exception { final Random random = new Random(0); HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector(); for (int i = 0; i < 100; ++i) { collector.add(fn.hashLong(random.nextLong()).asBytes()); }//from w w w. j a v a 2 s.co m Assert.assertEquals(collector.estimateCardinality(), HyperLogLogCollector.estimateByteBuffer(collector.toByteBuffer()), 0.0d); }