List of usage examples for java.util.concurrent ThreadLocalRandom current
public static ThreadLocalRandom current()
From source file:com.jql.gcmccsmock.GCMMessageHandler.java
@Override protected Stanza executeMessageLogic(MessageStanza stanza, ServerRuntimeContext serverRuntimeContext, SessionContext sessionContext) { try {/*from w ww .ja v a 2 s .c o m*/ String incomingMessage = stanza.getInnerElements().get(0).getSingleInnerText().getText(); logger.info("Received message. stanza.gcm={}", incomingMessage); Entity from = extractSenderJID(stanza, sessionContext); MessageStanzaType type = stanza.getMessageType(); if (!MessageStanzaType.NORMAL.equals(type)) return null; // no immediate response GCMMessage gcmMessage = GCMMessage.fromStanza(stanza); JSONObject jsonObject = gcmMessage.getJsonObject(); if (jsonObject.get(JSON_TO).equals(badRegistrationTag)) { Stanza outboundStanza = createNackBadRegIdMessageStanza(stanza, jsonObject); MessageRelayJobImpl messageRelayJob = new MessageRelayJobImpl( ThreadLocalRandom.current().nextLong(ACK_DELAY_MS), from, outboundStanza, serverRuntimeContext); serviceContext.getMessageRelayManager().addJob(messageRelayJob); return null; } Stanza outboundStanza = createAckMessageStanza(stanza, jsonObject); MessageRelayJobImpl messageRelayJob = new MessageRelayJobImpl( ThreadLocalRandom.current().nextLong(ACK_DELAY_MS), from, outboundStanza, serverRuntimeContext); serviceContext.getMessageRelayManager().addJob(messageRelayJob); outboundStanza = createDeliveryReceiptMessageStanza(stanza, jsonObject); messageRelayJob = new MessageRelayJobImpl( ThreadLocalRandom.current().nextLong(DELIVERY_RECEIPT_DELAY_MS), from, outboundStanza, serverRuntimeContext, (String) jsonObject.get(JSON_TO), incomingMessage); serviceContext.getMessageRelayManager().addJob(messageRelayJob); // draining control message test if (jsonObject.get(JSON_TO).equals(drainingTag)) { outboundStanza = createDrainingMessageStanza(stanza, jsonObject); messageRelayJob = new MessageRelayJobImpl(500, from, outboundStanza, serverRuntimeContext, (String) jsonObject.get(JSON_TO), incomingMessage); serviceContext.getMessageRelayManager().addJob(messageRelayJob); } } catch (Exception ex) { logger.error("got exception: ", ex); } return null; }
From source file:org.wso2.carbon.sample.isanalyticsclient.Client.java
private static Object[] getEventDataObject() { String[] usernames = { "admin", "thisaru", "LordVoldemort", "ProfMoriyarty", "Menaka", "Ruwangika", "Irunika", "Ninada", "Tharinda", "Dilanka", "Namodaya", "StrongArm", "Karl", "Neil", "Aravinda", "Sanath", "Mahela", "Sangakkara", "Muvindu", "Shihan", "Kasun", "Sanuka", "Indrachapa", "Chithral", "Shehan" }; String[] localUsernames = { "admin", "sam", "TomRiddle", "TheOne", "Mana", "Ru", "Iru", "Nin", "Thari", "Dila", "Namo", "Gun", "Scientist", "Atheist", "Silva", "Jayasooriya", "Jayawardana", "Sanga", "Binoy", "Bennet", "Kalhara", "Wicky", "Chapa", "Chitty", "Kaushalya" }; String[] userRoles = { "admin", "user", "admin, user", "restricted", "user, restricted" }; String[] ipAddresses = { "152.101.145.121", "8.89.153.229", "167.72.51.148", "35.155.233.154", "165.211.184.166", "150.88.129.200", "164.28.204.222", "75.177.7.40", "66.124.5.23", "254.107.47.83", "213.138.26.248", "185.168.135.92", "45.1.8.19", "30.47.231.32", "65.208.246.181", "98.22.73.94", "120.31.229.94", "75.238.156.179", "140.247.144.183", "149.203.141.172", "175.225.166.25", "114.85.215.55", "110.231.12.1", "194.105.181.134", "97.42.32.147" }; String[] eventTypes = { "step", "overall", "test-type" }; String[] userStoreDomains = { "user-store-1", "default-store", "testing-user-store" }; String[] tenantDomains = { "tenant-domain-1", "custom-tenant", "sample-tenant" }; String[] inboundAuthTypes = { "inbound-auth-1", "sample-inbound-auth", "custom-inbound-auth" }; String[] serviceProviders = { "travelocity.com", "harrypotter.com", "sherlock.org" }; String[] authenticationSteps = { "general", "2-step-auth", "SAML" }; String[] identityProviders = { "google.com", "facebook.com", "amazon.com" }; String[] stepAuthenticators = { "email", "totp", "motp" }; String[] identityProviderTypes = { "LOCAL", "FEDERATED" }; String contextId, eventId, eventType, username, localUsername, userStoreDomain, tenantDomain, remoteIp, inboundAuth, serviceProvider, rolesCommaSeparated, authenticationStep, identityProvider, stepAuthenticator, identityProviderType; Boolean authenticationSuccess, rememberMeEnabled, forceAuthEnabled, passiveAuthEnabled, authStepSuccess, isFirstLogin;/*from w w w . ja v a2s. c o m*/ int index = ThreadLocalRandom.current().nextInt(0, 25); contextId = UUID.randomUUID().toString(); eventId = UUID.randomUUID().toString(); eventType = eventTypes[index % 3]; authenticationSuccess = ThreadLocalRandom.current().nextBoolean(); username = usernames[index]; localUsername = localUsernames[index]; userStoreDomain = userStoreDomains[index % 3]; tenantDomain = tenantDomains[index % 3]; inboundAuth = inboundAuthTypes[index % 3]; remoteIp = ipAddresses[index]; serviceProvider = serviceProviders[index % 3]; rememberMeEnabled = ThreadLocalRandom.current().nextBoolean(); forceAuthEnabled = ThreadLocalRandom.current().nextBoolean(); passiveAuthEnabled = ThreadLocalRandom.current().nextBoolean(); rolesCommaSeparated = userRoles[index % 5]; authenticationStep = authenticationSteps[index % 3]; identityProvider = identityProviders[index % 3]; authStepSuccess = authenticationSuccess; stepAuthenticator = stepAuthenticators[index % 3]; identityProviderType = identityProviderTypes[index % 2]; isFirstLogin = ThreadLocalRandom.current().nextBoolean(); Long timestamp = new Timestamp(System.currentTimeMillis()).getTime(); return (new Object[] { contextId, eventId, eventType, authenticationSuccess, username, localUsername, userStoreDomain, tenantDomain, remoteIp, "N/A", inboundAuth, serviceProvider, rememberMeEnabled, forceAuthEnabled, passiveAuthEnabled, rolesCommaSeparated, authenticationStep, identityProvider, authStepSuccess, stepAuthenticator, isFirstLogin, identityProviderType, timestamp }); }
From source file:org.apache.drill.exec.planner.fragment.Wrapper.java
public void assignEndpoints(Collection<DrillbitEndpoint> allPossible) throws PhysicalOperatorSetupException { Preconditions.checkState(!endpointsAssigned); endpointsAssigned = true;/*from w ww .j a v a 2 s .c o m*/ List<EndpointAffinity> values = Lists.newArrayList(); values.addAll(endpointAffinity.values()); if (values.size() == 0) { List<DrillbitEndpoint> all = Lists.newArrayList(allPossible); final int div = allPossible.size(); int start = ThreadLocalRandom.current().nextInt(div); // round robin with random start. for (int i = start; i < start + width; i++) { Preconditions.checkNotNull(all.get(i % div)); endpoints.add(all.get(i % div)); } } else { // get nodes with highest affinity. Collections.sort(values); values = Lists.reverse(values); for (int i = 0; i < width; i++) { Preconditions.checkNotNull(values.get(i % values.size()).getEndpoint()); endpoints.add(values.get(i % values.size()).getEndpoint()); } } // Set scan and store endpoints. AssignEndpointsToScanAndStore visitor = new AssignEndpointsToScanAndStore(); node.getRoot().accept(visitor, endpoints); // Set the endpoints for this (one at most) sending exchange. if (node.getSendingExchange() != null) { node.getSendingExchange().setupSenders(majorFragmentId, endpoints); } // Set the endpoints for each incoming exchange within this fragment. for (ExchangeFragmentPair e : node.getReceivingExchangePairs()) { e.getExchange().setupReceivers(majorFragmentId, endpoints); } }
From source file:org.apache.bookkeeper.common.conf.ConfigKeyTest.java
@Test public void testGetShort() { String keyName = runtime.getMethodName(); short defaultValue = (short) ThreadLocalRandom.current().nextInt(10000); ConfigKey key = ConfigKey.builder(keyName).required(true).type(Type.SHORT).defaultValue(defaultValue) .build();//from w w w.jav a 2s.c om Configuration conf = new ConcurrentConfiguration(); // get default value assertEquals(defaultValue, key.getShort(conf)); assertEquals(defaultValue, key.get(conf)); // set value short newValue = (short) (defaultValue * 2); key.set(conf, newValue); assertEquals(newValue, key.getShort(conf)); assertEquals(newValue, key.get(conf)); }
From source file:com.linkedin.pinot.core.segment.index.creator.SegmentGenerationWithTimeColumnTest.java
private Object getRandomValueForTimeColumn(boolean isSimpleDate) { long randomMs = ThreadLocalRandom.current().nextLong(startTime); long dateColVal = randomMs; Object result;/* w w w . j a va 2 s .c om*/ if (isSimpleDate) { DateTime dateTime = new DateTime(randomMs); LocalDateTime localDateTime = dateTime.toLocalDateTime(); int year = localDateTime.getYear(); int month = localDateTime.getMonthOfYear(); int day = localDateTime.getDayOfMonth(); String dateColStr = String.format("%04d%02d%02d", year, month, day); dateColVal = Integer.valueOf(dateColStr); result = new Integer(Integer.valueOf(dateColStr)); } else { result = new Long(dateColVal); } if (dateColVal < minTime) { minTime = dateColVal; } if (dateColVal > maxTime) { maxTime = dateColVal; } return result; }
From source file:com.graphaware.neo4j.graphgen.faker.FakerService.java
public long unixTime() { long now = System.currentTimeMillis(); long diff = ThreadLocalRandom.current().nextLong(now); return ThreadLocalRandom.current().nextLong((now - diff), now); }
From source file:cc.mallet.types.PolyaUrnDirichlet.java
protected double nextStandardExponential() { for (;;) {//from w w w. ja v a2 s . c o m double u = ThreadLocalRandom.current().nextDouble(); double e = -FastMath.log(u); if (e > 0 && e < Double.MAX_VALUE && e == e) { // check for zero, positive infinity, and NaN return e; } } }
From source file:org.briljantframework.data.dataframe.DataFrames.java
/** * Same as {@link #permuteRecords(DataFrame, java.util.Random)} with a static random number * generator.//from w ww . j a va 2 s. c o m * * @param in the input data frame * @return a permuted copy of {@code in} */ public static DataFrame permuteRecords(DataFrame in) { return permuteRecords(in, ThreadLocalRandom.current()); }
From source file:org.apache.hadoop.hbase.io.asyncfs.TestFanOutOneBlockAsyncDFSOutput.java
@Test public void testRecover() throws IOException, InterruptedException, ExecutionException { Path f = new Path("/" + name.getMethodName()); EventLoop eventLoop = EVENT_LOOP_GROUP.next(); final FanOutOneBlockAsyncDFSOutput out = FanOutOneBlockAsyncDFSOutputHelper.createOutput(FS, f, true, false, (short) 3, FS.getDefaultBlockSize(), eventLoop); final byte[] b = new byte[10]; ThreadLocalRandom.current().nextBytes(b); final FanOutOneBlockAsyncDFSOutputFlushHandler handler = new FanOutOneBlockAsyncDFSOutputFlushHandler(); eventLoop.execute(new Runnable() { @Override// w w w .j a v a 2 s . c om public void run() { out.write(b, 0, b.length); out.flush(null, handler, false); } }); handler.get(); // restart one datanode which causes one connection broken TEST_UTIL.getDFSCluster().restartDataNode(0); try { handler.reset(); eventLoop.execute(new Runnable() { @Override public void run() { out.write(b, 0, b.length); out.flush(null, handler, false); } }); try { handler.get(); fail("flush should fail"); } catch (ExecutionException e) { // we restarted one datanode so the flush should fail LOG.info("expected exception caught", e); } out.recoverAndClose(null); assertEquals(b.length, FS.getFileStatus(f).getLen()); byte[] actual = new byte[b.length]; try (FSDataInputStream in = FS.open(f)) { in.readFully(actual); } assertArrayEquals(b, actual); } finally { ensureAllDatanodeAlive(); } }
From source file:ffx.algorithms.mc.RosenbluthCBMC.java
public boolean cbmcStep() { numMovesProposed++;/*from w ww.ja v a 2s.c o m*/ boolean accepted; double temperature; if (thermostat != null) { temperature = thermostat.getCurrentTemperature(); } else { temperature = 298.15; } double beta = 1.0 / (BOLTZMANN * temperature); // Select a target residue. int which = ThreadLocalRandom.current().nextInt(targets.size()); Residue target = targets.get(which); RosenbluthChiAllMove cbmcMove = new RosenbluthChiAllMove(mola, target, trialSetSize, ffe, temperature, writeSnapshots, numMovesProposed, true); if (cbmcMove.getMode() == RosenbluthChiAllMove.MODE.CHEAP) { if (cbmcMove.wasAccepted()) { numMovesAccepted++; } return cbmcMove.wasAccepted(); } double Wn = cbmcMove.getWn(); double Wo = cbmcMove.getWo(); double criterion = Math.min(1, Wn / Wo); double rng = ThreadLocalRandom.current().nextDouble(); logger.info(String.format(" rng: %5.2f", rng)); if (rng < criterion) { cbmcMove.move(); numMovesAccepted++; logger.info(String.format(" Accepted! Energy: %.4f\n", cbmcMove.finalEnergy)); accepted = true; write(); } else { logger.info(String.format(" Denied.\n")); accepted = false; } return accepted; }