Java Examples for java.util.concurrent.ThreadLocalRandom
The following java examples will help you to understand the usage of java.util.concurrent.ThreadLocalRandom. These source code samples are taken from different open source projects.
Example 1
| Project: intellij-community-master File: SharedThreadLocalRandomInspectionBase.java View source code |
@Override
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
super.visitMethodCallExpression(expression);
final PsiReferenceExpression methodExpression = expression.getMethodExpression();
@NonNls final String name = methodExpression.getReferenceName();
if (!"current".equals(name)) {
return;
}
final PsiMethod method = expression.resolveMethod();
if (method == null) {
return;
}
final PsiClass aClass = method.getContainingClass();
if (!InheritanceUtil.isInheritor(aClass, "java.util.concurrent.ThreadLocalRandom")) {
return;
}
if (isArgumentToMethodCall(expression)) {
registerMethodCallError(expression);
} else {
final PsiVariable variable = assignedToVariable(expression);
if (variable instanceof PsiField) {
registerMethodCallError(expression);
} else if (variable instanceof PsiLocalVariable) {
final PsiCodeBlock context = PsiTreeUtil.getParentOfType(variable, PsiCodeBlock.class);
final boolean passed = VariableAccessUtils.variableIsPassedAsMethodArgument(variable, context, myMethodMatcher::matches);
if (passed || VariableAccessUtils.variableIsUsedInInnerClass(variable, context)) {
registerMethodCallError(expression);
}
}
}
}Example 2
| Project: SkypeBot-master File: Swear.java View source code |
@Command(name = "swear")
public static void cmdSwear(ReceivedMessage chat) throws Exception {
SwearType[] combination = combinations[ThreadLocalRandom.current().nextInt(combinations.length)];
String output = "";
for (SwearType s : combination) {
if (!output.equals("")) {
output += " ";
}
output += s.getRandomWord();
}
Resource.sendMessage(chat, output.toUpperCase());
}Example 3
| Project: cattle-master File: StorageDriverDaoImpl.java View source code |
@Override
public Volume createSecretsVolume(Instance instance, StorageDriver storageDriver, String token) {
Map<String, Object> dataVolumesMounts = DataAccessor.fieldMap(instance, InstanceConstants.FIELD_DATA_VOLUME_MOUNTS);
Object volumeId = dataVolumesMounts.get(VolumeConstants.SECRETS_PATH);
if (volumeId != null) {
return objectManager.loadResource(Volume.class, volumeId.toString());
}
byte[] bytes = new byte[32];
ThreadLocalRandom.current().nextBytes(bytes);
String name = Hex.encodeHexString(bytes);
Map<String, Object> tokenMap = CollectionUtils.asMap("value", token);
Volume volume;
try {
volume = resourceDao.create(Volume.class, VOLUME.NAME, name, VOLUME.ACCOUNT_ID, instance.getAccountId(), VOLUME.STORAGE_DRIVER_ID, storageDriver.getId(), VolumeConstants.FIELD_VOLUME_DRIVER, storageDriver.getName(), VolumeConstants.FIELD_VOLUME_DRIVER_OPTS, CollectionUtils.asMap(VolumeConstants.SECRETS_OPT_KEY, jsonMapper.writeValueAsString(tokenMap)));
} catch (IOException e) {
throw new IllegalStateException(e);
}
dataVolumesMounts.put(VolumeConstants.SECRETS_PATH, volume.getId());
objectManager.setFields(instance, InstanceConstants.FIELD_DATA_VOLUME_MOUNTS, dataVolumesMounts);
return volume;
}Example 4
| Project: keycloak-master File: KeyUtilsTest.java View source code |
@Test
public void loadSecretKey() throws Exception {
byte[] secretBytes = new byte[32];
ThreadLocalRandom.current().nextBytes(secretBytes);
SecretKeySpec expected = new SecretKeySpec(secretBytes, "HmacSHA256");
SecretKey actual = KeyUtils.loadSecretKey(secretBytes);
assertEquals(expected.getAlgorithm(), actual.getAlgorithm());
assertArrayEquals(expected.getEncoded(), actual.getEncoded());
}Example 5
| Project: Assignments-master File: Simulation.java View source code |
private long generateHour() {
int hour = ThreadLocalRandom.current().nextInt(simulationInput.getHoursFieldMin(), simulationInput.getHoursFieldMax() + 1);
int minute = ThreadLocalRandom.current().nextInt(0, 61);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date d = null;
try {
d = sdf.parse("15/04/2016 " + hour + ":" + minute + ":00");
} catch (ParseException e) {
e.printStackTrace();
}
return d.getTime();
}Example 6
| Project: metastone-master File: CardCollection.java View source code |
public Card getRandomOfType(CardType cardType) {
List<Card> relevantCards = new ArrayList<>();
for (Card card : cards) {
if (card.getCardType().isCardType(cardType)) {
relevantCards.add(card);
}
}
if (relevantCards.isEmpty()) {
return null;
}
return relevantCards.get(ThreadLocalRandom.current().nextInt(relevantCards.size()));
}Example 7
| Project: scalecube-master File: NetworkLinkSettings.java View source code |
/** Delays are emulated using exponential distribution of probabilities. */
public long evaluateDelay() {
if (meanDelay > 0) {
// Network delays (network delays). Delays should be emulated using exponential distribution of probabilities.
// log(1-x)/(1/mean)
Double x0 = ThreadLocalRandom.current().nextDouble();
Double y0 = -Math.log(1 - x0) * meanDelay;
return y0.longValue();
}
return 0;
}Example 8
| Project: jstorm-master File: RandomNumberGeneratorSpout.java View source code |
@Override
public void emitBatch(long batchId, TridentCollector collector) {
List<List<Object>> values = null;
if (batches.containsKey(batchId)) {
values = batches.get(batchId);
} else {
values = new ArrayList<>();
for (int i = 0; i < batchSize; i++) {
List<Object> numbers = new ArrayList<>();
for (int x = 0; x < fields.size(); x++) {
numbers.add(ThreadLocalRandom.current().nextInt(0, maxNumber + 1));
}
values.add(numbers);
}
batches.put(batchId, values);
}
for (List<Object> value : values) {
collector.emit(value);
}
}Example 9
| Project: mssql-jdbc-master File: SqlDecimal.java View source code |
public Object createdata() {
double lowerBound = 0;
double upperBound = 1;
/**
* value to add for Math.random() to include upperBound - to choose random value between 0 to 1 (inclusive of both)
*/
double incrementValue = 0.1d;
Boolean inValidData = true;
BigDecimal randomValue = null;
while (inValidData) {
randomValue = new BigDecimal(ThreadLocalRandom.current().nextDouble(lowerBound, upperBound + incrementValue));
Boolean isNegative = (0 == ThreadLocalRandom.current().nextInt(2)) ? true : false;
// i.e., if the precision is say 5, then get unscaledRandom%10^5
if (randomValue.compareTo(new BigDecimal("1")) >= 0) {
randomValue = randomValue.movePointRight(precision - scale - 1);
} else {
randomValue = randomValue.movePointRight(precision - scale);
}
randomValue = randomValue.setScale(scale, RoundingMode.FLOOR);
randomValue = (isNegative) ? randomValue.multiply(new BigDecimal("-1")) : randomValue;
// must be 0 or -ve
int exceedsMax = randomValue.compareTo((BigDecimal) maxvalue);
// must be 0 or +ve
int exceedsMin = randomValue.compareTo((BigDecimal) minvalue);
// than max bigdecimal
if (!((exceedsMin < 0) || (exceedsMax > 0))) {
inValidData = false;
}
}
return randomValue;
}Example 10
| Project: ostrich-master File: ExponentialBackoffHealthCheckRetryDelay.java View source code |
@Override
public long getDelay(int numAttempts, HealthCheckResult result) {
checkArgument(numAttempts >= 1);
checkNotNull(result);
// Pick a random number between baseDelay*2^(n-1) and baseDelay*2^n (inclusive), subject
// to the upper bound.
long rangeMax = Math.min(_baseDelay * (1 << numAttempts), _maxDelayMillis);
long rangeMin = rangeMax / 2;
return rangeMin + ThreadLocalRandom.current().nextLong(rangeMax - rangeMin + 1);
}Example 11
| Project: parfait-master File: ProductBuilder.java View source code |
private void build() {
// emulate the work of building this product, by sleeping
Integer elapsed = ThreadLocalRandom.current().nextInt(0, this.bound);
try {
sleep(elapsed);
// increase counters for this product, another completed!
totalTime.inc(elapsed);
completed.inc();
} catch (InterruptedException e) {
failures.inc();
}
}Example 12
| Project: z-stack-master File: ThroughputStressTestForGenericHL.java View source code |
private void runHyperLoopStress(String label) {
System.out.println("=====in Round " + label);
int numRunnings0 = numOfRunningThreads();
CountDownLatch endLatch = new CountDownLatch(1);
String[] values = new String[RUNS];
ThreadLocalRandom rnd = ThreadLocalRandom.current();
for (int i = 0; i < RUNS; i++) {
values[i] = String.valueOf(rnd.nextLong());
}
System.out.println("start stress...");
Thread t = new Thread(() -> {
Affinity.bindTo(Topology.socket(0).physicalCore(3).virtualCore(0));
String v;
for (int i = 0; i < RUNS; i++) {
while (out.notReceivable()) {
}
v = out.tryReceive();
// if (!v.equals(values[i])) {
// //DEBUG
// for (int j = 0; j < values.length; j++) {
// if (v.equals(j))
// System.out.println("i:"+i+",j:"+j);
// }
// System.out.println("======#####=====");
// }
assertThat("happend when i=" + i, v, is(values[i]));
}
endLatch.countDown();
});
t.setDaemon(true);
t.start();
try {
long s = System.nanoTime();
//XXX: producer is in main thread
for (int i = 0; i < RUNS; i++) {
while (!loop.trySend(values[i])) {
}
}
endLatch.await();
long time = System.nanoTime() - s;
System.out.printf("done with costed time: %,d\n", time);
assertThat(numOfRunningThreads(), is(numRunnings0));
} catch (Exception e) {
e.printStackTrace();
}
}Example 13
| Project: find-sec-bugs-master File: PredictableRandomDetector.java View source code |
@Override
public void sawOpcode(int seen) {
if (seen == Constants.INVOKESPECIAL && getClassConstantOperand().equals("java/util/Random") && getNameConstantOperand().equals("<init>")) {
bugReporter.reportBug(//
new BugInstance(this, PREDICTABLE_RANDOM_TYPE, Priorities.NORMAL_PRIORITY).addClass(this).addMethod(this).addSourceLine(//
this).addString("java.util.Random"));
} else if (seen == Constants.INVOKESTATIC && getClassConstantOperand().equals("java/lang/Math") && getNameConstantOperand().equals("random")) {
bugReporter.reportBug(//
new BugInstance(this, PREDICTABLE_RANDOM_TYPE, Priorities.NORMAL_PRIORITY).addClass(this).addMethod(this).addSourceLine(//
this).addString("java.lang.Math.random()"));
} else if (seen == Constants.INVOKESTATIC && getClassConstantOperand().equals("java/util/concurrent/ThreadLocalRandom") && getNameConstantOperand().equals("current")) {
bugReporter.reportBug(//
new BugInstance(this, PREDICTABLE_RANDOM_TYPE, Priorities.NORMAL_PRIORITY).addClass(this).addMethod(this).addSourceLine(//
this).addString("java.util.concurrent.ThreadLocalRandom"));
} else if (seen == Constants.INVOKESPECIAL && getClassConstantOperand().equals("scala/util/Random") && getNameConstantOperand().equals("<init>")) {
bugReporter.reportBug(//
new BugInstance(this, PREDICTABLE_RANDOM_SCALA_TYPE, Priorities.NORMAL_PRIORITY).addClass(this).addMethod(this).addSourceLine(//
this).addString("scala.util.Random"));
} else if (seen == Constants.INVOKEVIRTUAL && RANDOM_NEXT_METHODS.matches(this)) {
bugReporter.reportBug(//
new BugInstance(this, PREDICTABLE_RANDOM_SCALA_TYPE, Priorities.NORMAL_PRIORITY).addClass(this).addMethod(this).addSourceLine(//
this).addString("scala.util.Random." + getNameConstantOperand() + "()"));
}
}Example 14
| Project: beam-master File: GenerateShardedTable.java View source code |
@ProcessElement
public void processElement(ProcessContext context, BoundedWindow window) throws IOException {
ThreadLocalRandom randomGenerator = ThreadLocalRandom.current();
// We output on keys 0-numShards.
String tableSpec = context.element().getKey().getTableSpec();
context.output(KV.of(ShardedKey.of(tableSpec, randomGenerator.nextInt(0, numShards)), context.element().getValue()));
}Example 15
| Project: blynk-server-master File: ActiveHardwareClient.java View source code |
public void start(String token) {
super.start();
send("login " + token);
nioEventLoopGroup.scheduleAtFixedRate(() -> {
send(makeCommand("vw 4 " + ThreadLocalRandom.current().nextInt(100)));
send(makeCommand("dw 3 " + ThreadLocalRandom.current().nextInt(255)));
send(makeCommand("dw 0 " + buttonVal));
send(makeCommand("vw 5 " + (buttonVal == 1 ? 255 : 0)));
send(makeCommand("vw 6 " + ledVal));
send(makeCommand("aw 6 " + ledVal));
send(makeCommand("vw 10 p 0 0 ledVal:" + ledVal));
if (buttonVal == 1) {
buttonVal = 0;
} else {
buttonVal = 1;
}
if (ledVal > 255) {
ledVal = 0;
send(makeCommand("vw 10 clr"));
} else {
ledVal += 20;
}
}, 1, 1, TimeUnit.SECONDS);
}Example 16
| Project: camel-master File: RandomServiceChooser.java View source code |
@Override
public ServiceDefinition choose(List<ServiceDefinition> definitions) {
// Fail if the service definition list is null or empty
if (ObjectHelper.isEmpty(definitions)) {
throw new IllegalArgumentException("The ServiceDefinition list should not be empty");
}
int size = definitions.size();
if (size == 1) {
return definitions.get(0);
} else {
return definitions.get(ThreadLocalRandom.current().nextInt(size));
}
}Example 17
| Project: Glowstone-master File: BlockOre.java View source code |
public Collection<ItemStack> getDrops(GlowBlock block, ItemStack tool) {
ThreadLocalRandom random = ThreadLocalRandom.current();
int count = minCount;
if (maxCount > minCount) {
count += random.nextInt(maxCount - minCount);
}
ItemStack stack = new ItemStack(dropType, count, (short) data);
if (tool == null) {
return Collections.unmodifiableList(Arrays.asList(stack));
}
Collection<ItemStack> drops = super.getDrops(block, tool);
if (drops.size() == 0) {
return drops;
}
if (tool.containsEnchantment(Enchantment.LOOT_BONUS_BLOCKS)) {
stack.setAmount(count * getMultiplicator(random, tool.getEnchantmentLevel(Enchantment.LOOT_BONUS_BLOCKS)));
}
return Collections.unmodifiableList(Arrays.asList(stack));
}Example 18
| Project: idnadrev-master File: SampleApp.java View source code |
private void getNextEntries(LocalDate begin, LocalDate end, Consumer<List<WeekViewAppointment<Object>>> consumer) {
ThreadLocalRandom random = ThreadLocalRandom.current();
LinkedList<WeekViewAppointment<Object>> retval = new LinkedList<>();
LocalDate firstDayOfWeek = begin;
for (int i = 0; i < 7; i++) {
LocalDate current = firstDayOfWeek.plusDays(i);
LocalTime time = LocalTime.of(random.nextInt(6, 18), random.nextInt(3) * 15);
int minutes = Math.max(15, random.nextInt(12) * 15);
Duration duration = Duration.ofMinutes(minutes);
LocalDateTime localDateTime = LocalDateTime.of(current, time);
BiPredicate<LocalDate, LocalTime> newTimePossiblePredicate = ( newDate, newTime) -> {
if (newTime == null) {
return true;
}
if (newTime.getHour() > 6 && newTime.getHour() < 22) {
return true;
} else {
log.info("Wrong time {}", newTime);
return false;
}
};
WeekViewAppointment<Object> timedAppointment = new WeekViewAppointment<>("test entry" + i + " " + minutes + "m", localDateTime, duration);
timedAppointment.setChangeStartCallback(( newDate, newTime) -> {
log.info("{} now starts on {} {}", timedAppointment.getTitle(), newDate, newTime);
});
timedAppointment.setNewTimePossiblePredicate(newTimePossiblePredicate);
retval.add(timedAppointment);
for (int j = 0; j < random.nextInt(1, 4); j++) {
WeekViewAppointment<Object> dayAppointment = new WeekViewAppointment<>(j + " test day spanning entry" + i + " " + minutes + "m", localDateTime.toLocalDate(), duration);
dayAppointment.setChangeStartCallback(( newDate, newTime) -> {
log.info("{} now starts on {} {}", dayAppointment.getTitle(), newDate, newTime);
});
dayAppointment.setNewTimePossiblePredicate(newTimePossiblePredicate);
retval.add(dayAppointment);
}
}
consumer.accept(retval);
}Example 19
| Project: ignite-master File: IgniteSqlQueryJoinBenchmark.java View source code |
/** {@inheritDoc} */
@Override
public boolean test(Map<Object, Object> ctx) throws Exception {
double salary = ThreadLocalRandom.current().nextDouble() * args.range() * 1000;
double maxSalary = salary + 1000;
Collection<List<?>> lists = executeQueryJoin(salary, maxSalary);
for (List<?> l : lists) {
double sal = (Double) l.get(4);
if (sal < salary || sal > maxSalary) {
Person p = new Person();
p.setId((Integer) l.get(0));
p.setOrganizationId((Integer) l.get(1));
p.setFirstName((String) l.get(2));
p.setLastName((String) l.get(3));
p.setSalary(sal);
throw new Exception("Invalid person retrieved [min=" + salary + ", max=" + maxSalary + ", person=" + p + ']');
}
}
return true;
}Example 20
| Project: Java_MVVM_with_Swing_and_RxJava_Examples-master File: Example_8_Model.java View source code |
public Observable<LogRow> getLogs() {
SerializedSubject<LogRow, LogRow> subject = new SerializedSubject<>(PublishSubject.create());
ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat(Example_8_Model.class.getSimpleName() + "-thread-%d").build();
final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), threadFactory);
IntStream.range(1, Runtime.getRuntime().availableProcessors() + 1).forEach( value -> {
executorService.submit(() -> {
SysOutUtils.sysout(Thread.currentThread().getName() + " will briefly start creating lots of log rows...");
VariousUtils.sleep(1000);
long incrementingNumber = 1;
while (true) {
subject.onNext(new LogRow(DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.now()), "Status " + Integer.toString(ThreadLocalRandom.current().nextInt(1, 5)), "Action " + incrementingNumber + " from " + Thread.currentThread().getName()));
}
});
});
return subject;
}Example 21
| Project: jst-master File: RandomNumberGeneratorSpout.java View source code |
@Override
public void emitBatch(long batchId, TridentCollector collector) {
List<List<Object>> values = null;
if (batches.containsKey(batchId)) {
values = batches.get(batchId);
} else {
values = new ArrayList<>();
for (int i = 0; i < batchSize; i++) {
List<Object> numbers = new ArrayList<>();
for (int x = 0; x < fields.size(); x++) {
numbers.add(ThreadLocalRandom.current().nextInt(0, maxNumber + 1));
}
values.add(numbers);
}
batches.put(batchId, values);
}
for (List<Object> value : values) {
collector.emit(value);
}
}Example 22
| Project: MaritimeCloud-master File: OldContinuesReconnectTest.java View source code |
public void run() {
int latestId = 0;
Integer ackIt = null;
while (received.size() < NUMBER_OF_MESSAGES) {
Message tm = t.take(Message.class);
if (tm instanceof Broadcast) {
Broadcast bs = (Broadcast) tm;
try {
BroadcastTestMessage hw = (BroadcastTestMessage) MmsMessage.tryRead(bs);
int id = hw.getId();
assertEquals(latestId++, id);
received.add(id);
} catch (Exception e) {
e.printStackTrace();
}
ackIt = null;
} else {
if (ackIt == null) {
ackIt = ThreadLocalRandom.current().nextInt(ack.get(), latestId + 1);
}
ack.set(ackIt);
latestId = ackIt;
t.send(new Connected().setSessionId(BIN1).setLastReceivedMessageId((long) ackIt));
}
}
}Example 23
| Project: mldht-master File: DHTLifeCycleTest.java View source code |
/**
* Test that startup doesn't throw exceptions
*
* things not covered:
* - routing table loading
* - delayed tasks
* - bootstrap name resolution
* - bootstrap ping attempts
*/
@Test
public void testStartup() throws Exception {
int port = ThreadLocalRandom.current().nextInt(1024, 65535);
CompletableFuture<Boolean> exceptionCanary = new CompletableFuture<>();
ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
exceptionCanary.completeExceptionally(e);
}
});
return t;
}
});
DHT dhtInstance = new DHT(DHTtype.IPV4_DHT);
// TODO: refactor to per-instance logger
DHT.setLogger(new DHTLogger() {
@Override
public void log(Throwable t, LogLevel l) {
// allow bootstrap node resolution to fail in test environment
if (t instanceof UnknownHostException)
return;
exceptionCanary.completeExceptionally(t);
}
@Override
public void log(String message, LogLevel l) {
}
});
dhtInstance.setScheduler(scheduler);
Path storagePath = Paths.get(".", "does", "not", "exist");
dhtInstance.start(new DHTConfiguration() {
@Override
public boolean noRouterBootstrap() {
return true;
}
@Override
public boolean isPersistingID() {
return false;
}
@Override
public Path getStoragePath() {
return storagePath;
}
@Override
public int getListeningPort() {
return port;
}
@Override
public boolean allowMultiHoming() {
return false;
}
});
assertEquals(DHTStatus.Initializing, dhtInstance.getStatus());
// bootstrap is called synchronously during startup and should fall straight through, thus reset the state
assertEquals(DHT.BootstrapState.NONE, dhtInstance.bootstrapping.get());
assertEquals(1, dhtInstance.getServerManager().getServerCount());
CompletableFuture<Boolean> wasEmpty = new CompletableFuture<>();
// single-threaded executor -> we can let startup tasks complete and then stop the DHT from the pool itself
// thus there should be no pending tasks on the executor
scheduler.execute(() -> {
dhtInstance.stop();
scheduler.purge();
wasEmpty.complete(scheduler.getQueue().isEmpty());
});
assertTrue("no tasks should remain queued after stop()", wasEmpty.get());
assertEquals(DHTStatus.Stopped, dhtInstance.getStatus());
assertEquals("no messages should have been sent on a bootstrapless startup", 0, dhtInstance.getStats().getNumSentPackets());
scheduler.shutdown();
assertTrue("all tasks terminated", scheduler.awaitTermination(10, TimeUnit.MILLISECONDS));
exceptionCanary.complete(true);
// check for async exceptions
exceptionCanary.get();
assertFalse("should not create storage path, that's the caller's duty", Files.isDirectory(storagePath));
}Example 24
| Project: motan-master File: ActiveWeightLoadBalance.java View source code |
@Override
protected Referer<T> doSelect(Request request) {
List<Referer<T>> referers = getReferers();
int refererSize = referers.size();
int startIndex = ThreadLocalRandom.current().nextInt(refererSize);
int currentCursor = 0;
int currentAvailableCursor = 0;
Referer<T> referer = null;
while (currentAvailableCursor < MAX_REFERER_COUNT && currentCursor < refererSize) {
Referer<T> temp = referers.get((startIndex + currentCursor) % refererSize);
currentCursor++;
if (!temp.isAvailable()) {
continue;
}
currentAvailableCursor++;
if (referer == null) {
referer = temp;
} else {
if (compare(referer, temp) > 0) {
referer = temp;
}
}
}
return referer;
}Example 25
| Project: netflix-commons-master File: ConcurrentUUIDFactory.java View source code |
@Override
public UUID generateRandomUuid() {
final Random rnd = ThreadLocalRandom.current();
long mostSig = rnd.nextLong();
long leastSig = rnd.nextLong();
// Identify this as a version 4 UUID, that is one based on a random value.
mostSig &= 0xffffffffffff0fffL;
mostSig |= 0x0000000000004000L;
// Set the variant identifier as specified for version 4 UUID values. The two
// high order bits of the lower word are required to be one and zero, respectively.
leastSig &= 0x3fffffffffffffffL;
leastSig |= 0x8000000000000000L;
return new UUID(mostSig, leastSig);
}Example 26
| Project: pinot-master File: ExponentialBackoffRetryPolicy.java View source code |
@Override
public boolean attempt(Callable<Boolean> operation) {
try {
ThreadLocalRandom random = ThreadLocalRandom.current();
int remainingAttempts = _maximumAttemptCount - 1;
long minimumSleepTime = _minimumMilliseconds;
long maximumSleepTime = (long) (minimumSleepTime * _retryScaleFactor);
boolean result = operation.call();
while ((!result) && (0 < remainingAttempts)) {
long sleepTime = random.nextLong(minimumSleepTime, maximumSleepTime);
Uninterruptibles.sleepUninterruptibly(sleepTime, TimeUnit.MILLISECONDS);
result = operation.call();
remainingAttempts--;
minimumSleepTime *= _retryScaleFactor;
maximumSleepTime *= _retryScaleFactor;
}
return result;
} catch (Exception e) {
Utils.rethrowException(e);
return false;
}
}Example 27
| Project: Polyphemus-master File: GameMapBuilder.java View source code |
private GameMapBuilder createRiver(Tile tile, int size) {
int randomNum = ThreadLocalRandom.current().nextInt(0, height - size);
for (int z = 0; z < depth; z++) {
for (int x = 0; x < width; x++) {
for (int y = 0; y < size; y++) {
tiles.put(new Point(x, (y + randomNum), z), tile);
}
}
}
return this;
}Example 28
| Project: presto-master File: TestShowPartitions.java View source code |
private static TableDefinition generateTableDefinition() {
StringBuilder createTableDdl = new StringBuilder();
createTableDdl.append("CREATE EXTERNAL TABLE %NAME%(");
createTableDdl.append(" col INT");
createTableDdl.append(") ");
createTableDdl.append("PARTITIONED BY (part_col INT) ");
createTableDdl.append(" STORED AS ORC");
HiveDataSource dataSource = createResourceDataSource(TABLE_NAME, String.valueOf(ThreadLocalRandom.current().nextLong(Long.MAX_VALUE)), "com/facebook/presto/tests/hive/data/single_int_column/data.orc");
HiveDataSource invalidData = createStringDataSource(TABLE_NAME, String.valueOf(ThreadLocalRandom.current().nextLong(Long.MAX_VALUE)), "INVALID DATA");
return HiveTableDefinition.builder(TABLE_NAME).setCreateTableDDLTemplate(createTableDdl.toString()).addPartition("part_col = 1", invalidData).addPartition("part_col = 2", dataSource).build();
}Example 29
| Project: red5-websocket-master File: IdGenerator.java View source code |
/**
* Returns a cryptographically generated id.
*
* @return id
*/
public static final long generateId() {
long id = 0;
// add new seed material from current time
random.addSeedMaterial(ThreadLocalRandom.current().nextLong());
// get a new id
byte[] bytes = new byte[16];
// get random bytes
random.nextBytes(bytes);
for (int i = 0; i < bytes.length; i++) {
id += ((long) bytes[i] & 0xffL) << (8 * i);
}
//System.out.println("Id: " + id);
return id;
}Example 30
| Project: scylla-tools-java-master File: MemoryTest.java View source code |
@Test
public void testByteBuffers() {
byte[] bytes = new byte[1000];
ThreadLocalRandom.current().nextBytes(bytes);
final Memory memory = Memory.allocate(bytes.length);
memory.setBytes(0, bytes, 0, bytes.length);
ByteBuffer canon = ByteBuffer.wrap(bytes).order(ByteOrder.nativeOrder());
test(canon, memory);
memory.setBytes(0, new byte[1000], 0, 1000);
memory.setBytes(0, canon.duplicate());
test(canon, memory);
memory.close();
}Example 31
| Project: airlift-master File: TestHyperLogLog.java View source code |
@Test
public void testEstimates() throws Exception {
int trials = 1000;
for (int indexBits = 4; indexBits <= 13; indexBits++) {
Map<Integer, Stats> errors = new HashMap<>();
int numberOfBuckets = 1 << indexBits;
int maxCardinality = numberOfBuckets * 2;
for (int trial = 0; trial < trials; trial++) {
HyperLogLog hll = HyperLogLog.newInstance(numberOfBuckets);
for (int cardinality = 1; cardinality <= maxCardinality; cardinality++) {
hll.add(ThreadLocalRandom.current().nextLong());
if (cardinality % (numberOfBuckets / 10) == 0) {
// only do this a few times, since computing the cardinality is currently not
// as cheap as it should be
double error = (hll.cardinality() - cardinality) * 1.0 / cardinality;
Stats stats = errors.get(cardinality);
if (stats == null) {
stats = new Stats();
errors.put(cardinality, stats);
}
stats.add(error);
}
}
}
double expectedStandardError = 1.04 / Math.sqrt(1 << indexBits);
for (Map.Entry<Integer, Stats> entry : errors.entrySet()) {
// Give an extra error margin. This is mostly a sanity check to catch egregious errors
assertTrue(entry.getValue().stdev() <= expectedStandardError * 1.1, String.format("Failed at p = %s, cardinality = %s. Expected std error = %s, actual = %s", indexBits, entry.getKey(), expectedStandardError, entry.getValue().stdev()));
}
}
}Example 32
| Project: cassa-master File: PredefinedOperation.java View source code |
ColumnSelection select() {
if (settings.columns.slice) {
int count = (int) columnCount.next();
int start;
if (count == settings.columns.maxColumnsPerKey)
start = 0;
else
start = 1 + ThreadLocalRandom.current().nextInt(settings.columns.maxColumnsPerKey - count);
return new ColumnSelection(null, start, start + count);
}
int count = (int) columnCount.next();
int totalCount = settings.columns.names.size();
if (count == settings.columns.names.size())
return new ColumnSelection(null, 0, count);
ThreadLocalRandom rnd = ThreadLocalRandom.current();
int[] indices = new int[count];
int c = 0, o = 0;
while (c < count && count + o < totalCount) {
int leeway = totalCount - (count + o);
int spreadover = count - c;
o += Math.round(rnd.nextDouble() * (leeway / (double) spreadover));
indices[c] = o + c;
c++;
}
while (c < count) {
indices[c] = o + c;
c++;
}
return new ColumnSelection(indices, 0, 0);
}Example 33
| Project: cassandra-master File: PredefinedOperation.java View source code |
ColumnSelection select() {
if (settings.columns.slice) {
int count = (int) columnCount.next();
int start;
if (count == settings.columns.maxColumnsPerKey)
start = 0;
else
start = 1 + ThreadLocalRandom.current().nextInt(settings.columns.maxColumnsPerKey - count);
return new ColumnSelection(null, start, start + count);
}
int count = (int) columnCount.next();
int totalCount = settings.columns.names.size();
if (count == settings.columns.names.size())
return new ColumnSelection(null, 0, count);
ThreadLocalRandom rnd = ThreadLocalRandom.current();
int[] indices = new int[count];
int c = 0, o = 0;
while (c < count && count + o < totalCount) {
int leeway = totalCount - (count + o);
int spreadover = count - c;
o += Math.round(rnd.nextDouble() * (leeway / (double) spreadover));
indices[c] = o + c;
c++;
}
while (c < count) {
indices[c] = o + c;
c++;
}
return new ColumnSelection(indices, 0, 0);
}Example 34
| Project: Chronicle-Map-master File: MarkTest.java View source code |
private static void test(Function<ChronicleMapBuilder<Integer, Integer>, ChronicleMap<Integer, Integer>> createMap) {
long ms = System.currentTimeMillis();
try (ChronicleMap<Integer, Integer> map = createMap.apply(ChronicleMapBuilder.of(Integer.class, Integer.class).entries(ENTRIES).entriesPerSegment((1 << 15) / 3).checksumEntries(false).putReturnsNull(true).removeReturnsNull(true))) {
Random r = ThreadLocalRandom.current();
for (int i = 0; i < ENTRIES; i++) {
map.put(r.nextInt(), r.nextInt());
}
}
System.out.println(System.currentTimeMillis() - ms);
}Example 35
| Project: cloudconductor-server-master File: AuthTokenGenerator.java View source code |
private String shuffleWithFisherYates(String tokenStringToShuffle) {
char[] shuffleArray = tokenStringToShuffle.toCharArray();
int tokenLength = tokenStringToShuffle.length();
for (int i = 0; i < (tokenLength - 2); i++) {
int j = ThreadLocalRandom.current().nextInt(i, tokenLength);
shuffleArray = this.swap(shuffleArray, i, j);
}
return new String(shuffleArray);
}Example 36
| Project: dropwizard-master File: RequestIdFilter.java View source code |
/**
* Generate a random UUID v4 that will perform reasonably when used by
* multiple threads under load.
*
* @see https://github.com/Netflix/netflix-commons/blob/v0.3.0/netflix-commons-util/src/main/java/com/netflix/util/concurrent/ConcurrentUUIDFactory.java
* @return random UUID
*/
private static UUID generateRandomUuid() {
final Random rnd = ThreadLocalRandom.current();
long mostSig = rnd.nextLong();
long leastSig = rnd.nextLong();
// Identify this as a version 4 UUID, that is one based on a random value.
mostSig &= 0xffffffffffff0fffL;
mostSig |= 0x0000000000004000L;
// Set the variant identifier as specified for version 4 UUID values. The two
// high order bits of the lower word are required to be one and zero, respectively.
leastSig &= 0x3fffffffffffffffL;
leastSig |= 0x8000000000000000L;
return new UUID(mostSig, leastSig);
}Example 37
| Project: dropwizardry-master File: LoggingDebugExceptionMapper.java View source code |
@Override
public Response toResponse(E exception) {
if (exception instanceof WebApplicationException) {
return ((WebApplicationException) exception).getResponse();
}
boolean debuggable = isDebuggable();
final long id = ThreadLocalRandom.current().nextLong();
/*
* If we are a BaseWebApplicationException then we will use its data to build a
* response.
*/
if (exception instanceof BaseWebApplicationException) {
ResponseBuilder builder = ((BaseWebApplicationException) exception).createResponseBuilder();
if (!debuggable) {
return builder.entity(new ErrorMessage(exception.getMessage())).build();
} else {
builder.entity(new DebugErrorMessage(id, exception));
debugLogException(id, exception);
return builder.build();
}
}
//here we have an unexpected exception of some kind (its not a BaseWebApplicationException)
//we must sanitize the exception message we send back to the client
//unless its debuggable
logException(id, exception);
if (debuggable) {
return Response.serverError().entity(new DebugErrorMessage(id, exception)).build();
} else {
return Response.serverError().entity(new ErrorMessage(formatErrorMessage(id))).build();
}
}Example 38
| Project: event-based-shopping-system-master File: MoviesController.java View source code |
@RequestMapping(value = "{id}/order", method = RequestMethod.GET)
public String orderMovie(@PathVariable UUID id, Model model) {
log.info("orderMovie with id " + id);
Movie movie = movieService.getMovieById(id);
// Create some default shipping details
Address address = new Address(Locale.GERMANY.getDisplayCountry(), "Cologne", "50667", "Domkloster", "4");
Recipient recipient = new Recipient("Alexander", "Mustermann", address, address);
Integer amount = ThreadLocalRandom.current().nextInt(1, 15);
Order order = new Order(amount, movie.getId().toString(), recipient);
BigDecimal totalPrice = movie.getPrice().multiply(BigDecimal.valueOf(amount));
model.addAttribute("movie", movie);
model.addAttribute("order", order);
model.addAttribute("totalPrice", totalPrice);
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
try {
String orderAsJson = ow.writeValueAsString(order);
messageChannel.send(new GenericMessage<String>(orderAsJson));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return "order";
}Example 39
| Project: fast-object-pool-master File: ObjectPoolPartition.java View source code |
// set the scavenge interval carefully
public synchronized void scavenge() throws InterruptedException {
int delta = this.totalCount - config.getMinSize();
if (delta <= 0)
return;
int removed = 0;
long now = System.currentTimeMillis();
Poolable<T> obj;
while (delta-- > 0 && (obj = objectQueue.poll()) != null) {
// so it could take several intervals to shrink the pool to the configured min value.
if (Log.isDebug())
Log.debug("obj=", obj, ", now-last=", now - obj.getLastAccessTs(), ", max idle=", config.getMaxIdleMilliseconds());
if (now - obj.getLastAccessTs() > config.getMaxIdleMilliseconds() && ThreadLocalRandom.current().nextDouble(1) < config.getScavengeRatio()) {
// shrink the pool size if the object reaches max idle time
decreaseObject(obj);
removed++;
} else {
//put it back
objectQueue.put(obj);
}
}
if (removed > 0)
Log.debug(removed, " objects were scavenged.");
}Example 40
| Project: flink-master File: CustomKvStateProgram.java View source code |
public static void main(String[] args) throws Exception {
final int parallelism = Integer.parseInt(args[0]);
final String checkpointPath = args[1];
final int checkpointingInterval = Integer.parseInt(args[2]);
final String outputPath = args[3];
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(parallelism);
env.getConfig().disableSysoutLogging();
env.enableCheckpointing(checkpointingInterval);
env.setStateBackend(new FsStateBackend(checkpointPath));
DataStream<Integer> source = env.addSource(new InfiniteIntegerSource());
source.map(new MapFunction<Integer, Tuple2<Integer, Integer>>() {
private static final long serialVersionUID = 1L;
@Override
public Tuple2<Integer, Integer> map(Integer value) throws Exception {
return new Tuple2<>(ThreadLocalRandom.current().nextInt(parallelism), value);
}
}).keyBy(new KeySelector<Tuple2<Integer, Integer>, Integer>() {
private static final long serialVersionUID = 1L;
@Override
public Integer getKey(Tuple2<Integer, Integer> value) throws Exception {
return value.f0;
}
}).flatMap(new ReducingStateFlatMap()).writeAsText(outputPath);
env.execute();
}Example 41
| Project: ggp-base-master File: RandomGamer.java View source code |
@Override
public Move stateMachineSelectMove(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException {
long start = System.currentTimeMillis();
List<Move> moves = getStateMachine().getLegalMoves(getCurrentState(), getRole());
Move selection = (moves.get(ThreadLocalRandom.current().nextInt(moves.size())));
long stop = System.currentTimeMillis();
notifyObservers(new GamerSelectedMoveEvent(moves, selection, stop - start));
return selection;
}Example 42
| Project: hbase-master File: TestSwitchToStreamRead.java View source code |
@BeforeClass
public static void setUp() throws IOException {
UTIL.getConfiguration().setLong(StoreScanner.STORESCANNER_PREAD_MAX_BYTES, 2048);
StringBuilder sb = new StringBuilder(256);
for (int i = 0; i < 255; i++) {
sb.append((char) ThreadLocalRandom.current().nextInt('A', 'z' + 1));
}
VALUE_PREFIX = sb.append("-").toString();
REGION = UTIL.createLocalHRegion(new HTableDescriptor(TABLE_NAME).addFamily(new HColumnDescriptor(FAMILY).setBlocksize(1024)), null, null);
for (int i = 0; i < 900; i++) {
REGION.put(new Put(Bytes.toBytes(i)).addColumn(FAMILY, QUAL, Bytes.toBytes(VALUE_PREFIX + i)));
}
REGION.flush(true);
for (int i = 900; i < 1000; i++) {
REGION.put(new Put(Bytes.toBytes(i)).addColumn(FAMILY, QUAL, Bytes.toBytes(VALUE_PREFIX + i)));
}
}Example 43
| Project: hibernate-redis-master File: Stresser.java View source code |
@Override
public void run() {
for (int i = 0; i < ITERATIONS; i++) {
limiter.acquire();
ThreadLocalRandom random = ThreadLocalRandom.current();
int playerId = random.nextInt(ENTITIES);
if (random.nextDouble() < 0.7) {
playerDao.update(playerId, i);
} else {
playerDao.get(playerId);
}
}
}Example 44
| Project: incubator-atlas-master File: AtlasBaseExceptionMapper.java View source code |
@Override
public Response toResponse(AtlasBaseException exception) {
final long id = ThreadLocalRandom.current().nextLong();
// Only log the exception is there's an internal error
if (exception.getAtlasErrorCode().getHttpCode() == Response.Status.INTERNAL_SERVER_ERROR) {
ExceptionMapperUtil.logException(id, exception);
}
return buildAtlasBaseExceptionResponse(exception);
}Example 45
| Project: infinispan-master File: SoftIndexFileStoreStressTest.java View source code |
@Override
public void run() {
ThreadLocalRandom random = ThreadLocalRandom.current();
InternalCacheEntry ice;
while (!terminate) {
long lifespan;
String key = key(random);
switch(random.nextInt(3)) {
case 0:
lifespan = random.nextInt(3) == 0 ? random.nextInt(10) : -1;
ice = TestInternalCacheEntryFactory.<Object, Object>create(factory, key(random), String.valueOf(random.nextInt()), lifespan);
store.write(TestingUtil.marshalledEntry(ice, marshaller));
break;
case 1:
store.delete(key);
break;
case 2:
store.load(key);
}
}
}Example 46
| Project: infinite-scroll-gwt-master File: DudeGenerator.java View source code |
public String random5to10Name() {
int randLength = 5 + ThreadLocalRandom.current().nextInt(6);
StringBuilder sb = new StringBuilder(randLength);
sb.append(firstLetter.charAt(ThreadLocalRandom.current().nextInt(firstLetter.length())));
for (int i = 0; i < randLength - 1; i++) sb.append(numsAndLetters.charAt(ThreadLocalRandom.current().nextInt(numsAndLetters.length())));
return sb.toString();
}Example 47
| Project: injector-master File: SimpleCollectionBurnTest.java View source code |
public void run() {
ThreadLocalRandom rand = ThreadLocalRandom.current();
List<SimpleCollection.Node> items = new ArrayList<>();
while (System.nanoTime() < until) {
int targetSize = rand.nextInt(maxSignalsPerThread);
while (items.size() < targetSize) items.add(c.add(new Object()));
while (items.size() > targetSize) items.remove(rand.nextInt(items.size())).remove();
if (!present(c, items.iterator()))
System.err.println("fail");
}
latch.countDown();
}Example 48
| Project: mocha-mvc-master File: InvokeTargetResolverTest.java View source code |
private long doBenchmark(InvokeTargetResolver resolver, Collection<String> keys) {
long ret = 0;
long begin = System.nanoTime();
for (String key : keys) {
int hash = resolver.resolve(key, "GET").hashCode();
ret += hash;
}
long dur = System.nanoTime() - begin;
if (ThreadLocalRandom.current().nextInt(100000) == 1) {
System.out.println("Please ignore: " + ret);
}
return dur;
}Example 49
| Project: modeshape-master File: DbLockingService.java View source code |
@Override
public boolean tryLock(long time, TimeUnit unit, String... names) throws InterruptedException {
long start = System.currentTimeMillis();
boolean result;
long timeInMills = TimeUnit.MILLISECONDS.convert(time, unit);
while (!(result = db.lockForWriting(names)) && System.currentTimeMillis() - start <= timeInMills) {
//wait a bit (between 50 and 300 ms)
long sleepDurationMillis = 50 + ThreadLocalRandom.current().nextInt(251);
Thread.sleep(sleepDurationMillis);
}
return result;
}Example 50
| Project: monitoring-master File: ResponseTimeChartGroupTest.java View source code |
private List<SampledResponseTime> createSampledResponseTimeList(TimeWindow timeWindow) {
List<SampledResponseTime> sampledResponseTimeList = new ArrayList<>();
int maxConnectionSize = ThreadLocalRandom.current().nextInt(MIN_VALUE_OF_MAX_CONNECTION_SIZE) + MIN_VALUE_OF_MAX_CONNECTION_SIZE;
long from = timeWindow.getWindowRange().getFrom();
long to = timeWindow.getWindowRange().getTo();
for (long i = from; i < to; i += timeWindow.getWindowSlotSize()) {
sampledResponseTimeList.add(createSampledResponseTime(i, maxConnectionSize));
}
return sampledResponseTimeList;
}Example 51
| Project: multiway-pool-master File: EliminationProfile.java View source code |
Runnable newEliminationStackRunner() {
final EliminationStack<Integer> stack = new EliminationStack<>();
return new Runnable() {
@Override
public void run() {
final ThreadLocalRandom random = ThreadLocalRandom.current();
for (; ; ) {
if (random.nextBoolean()) {
stack.push(ELEMENT);
} else {
stack.pop();
}
calls.increment();
}
}
};
}Example 52
| Project: PalletTown-master File: RandomDetails.java View source code |
static String randomBirthday() {
long minDay = LocalDate.of(1950, 1, 1).toEpochDay();
long maxDay = LocalDate.of(2002, 12, 31).toEpochDay();
long randomDay = ThreadLocalRandom.current().nextLong(minDay, maxDay);
LocalDate randomDate = LocalDate.ofEpochDay(randomDay);
DateTimeFormatter yearlyFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return randomDate.format(yearlyFormat);
}Example 53
| Project: pinpoint-master File: ResponseTimeChartGroupTest.java View source code |
private List<SampledResponseTime> createSampledResponseTimeList(TimeWindow timeWindow) {
List<SampledResponseTime> sampledResponseTimeList = new ArrayList<>();
int maxConnectionSize = ThreadLocalRandom.current().nextInt(MIN_VALUE_OF_MAX_CONNECTION_SIZE) + MIN_VALUE_OF_MAX_CONNECTION_SIZE;
long from = timeWindow.getWindowRange().getFrom();
long to = timeWindow.getWindowRange().getTo();
for (long i = from; i < to; i += timeWindow.getWindowSlotSize()) {
sampledResponseTimeList.add(createSampledResponseTime(i, maxConnectionSize));
}
return sampledResponseTimeList;
}Example 54
| Project: Pixelitor-master File: DiffuseFilter.java View source code |
@Override
protected void transformInverse(int x, int y, float[] out) {
// int angle = (int) (Math.random() * 255);
// faster than Math.random
int angle = ThreadLocalRandom.current().nextInt(255);
// float distance = (float) Math.random();
// faster than Math.random
float distance = ThreadLocalRandom.current().nextFloat();
out[0] = x + distance * sinTable[angle];
out[1] = y + distance * cosTable[angle];
}Example 55
| Project: quasar-master File: FiberOverheadJMHBenchmark.java View source code |
@Setup
public void preapre() {
rands = new long[(DEPTH + 1) * 4];
Random rnd = ThreadLocalRandom.current();
for (int i = 0; i < rands.length; i++) rands[i] = rnd.nextLong();
runnable = new Runnable() {
@Override
public void run() {
res = recursive1(DEPTH);
}
};
fiber = new Fiber((String) null, null, STACK, new SuspendableRunnable() {
@Override
public void run() throws SuspendExecution {
res = recursive2(DEPTH);
}
});
fiber2 = new Fiber((String) null, null, STACK, new SuspendableRunnable() {
@Override
public void run() throws SuspendExecution {
res = recursive3(DEPTH);
}
});
}Example 56
| Project: rce-master File: IdGenerator.java View source code |
/**
* Generates a random String of hex characters. The requested String length must be even and must not exceed
* {@link #MAX_RANDOM_STRING_LENGTH}. The {@link IdGeneratorType} parameter select between computationally cheap or cryptographically
* secure random generation.
*
* @param length the requested string length
* @param generatorType whether to prioritize speed {@link IdGeneratorType#FAST} or security ( {@link IdGeneratorType#SECURE})
* @return the generated string
*/
public static String createRandomHexString(int length, IdGeneratorType generatorType) {
validateRequestedLength(length);
byte[] bytes = new byte[length / 2];
switch(generatorType) {
case FAST:
ThreadLocalRandom.current().nextBytes(bytes);
break;
case SECURE:
sharedSecureRandom.nextBytes(bytes);
break;
default:
throw new IllegalArgumentException();
}
String string = endodeBytesAsHexAndValidateLength(bytes, length);
return string;
}Example 57
| Project: redisson-master File: RedissonLockHeavyTest.java View source code |
@Override
public void run() {
for (int j = 0; j < loops; j++) {
RLock lock = redisson.getLock("RLOCK_" + j);
try {
if (lock.tryLock(ThreadLocalRandom.current().nextInt(10), TimeUnit.MILLISECONDS)) {
try {
RBucket<String> bucket = redisson.getBucket("RBUCKET_" + j);
bucket.set("TEST", 30, TimeUnit.SECONDS);
RSemaphore semaphore = redisson.getSemaphore("SEMAPHORE_" + j);
semaphore.release();
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
} finally {
lock.unlock();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}Example 58
| Project: rpc4j-master File: ServiceDiscovery.java View source code |
public String discover() {
String data = null;
int size = dataList.size();
if (size > 0) {
if (size == 1) {
data = dataList.get(0);
Logger.debug("using only data: {}", data);
} else {
data = dataList.get(ThreadLocalRandom.current().nextInt(size));
Logger.debug("using random data: {}", data);
}
}
return data;
}Example 59
| Project: web-framework-master File: RequestIdFilter.java View source code |
/**
* Generate a random UUID v4 that will perform reasonably when used by
* multiple threads under load.
*
* @see https://github.com/Netflix/netflix-commons/blob/v0.3.0/netflix-commons-util/src/main/java/com/netflix/util/concurrent/ConcurrentUUIDFactory.java
* @return random UUID
*/
private static UUID generateRandomUuid() {
final Random rnd = ThreadLocalRandom.current();
long mostSig = rnd.nextLong();
long leastSig = rnd.nextLong();
// Identify this as a version 4 UUID, that is one based on a random value.
mostSig &= 0xffffffffffff0fffL;
mostSig |= 0x0000000000004000L;
// Set the variant identifier as specified for version 4 UUID values. The two
// high order bits of the lower word are required to be one and zero, respectively.
leastSig &= 0x3fffffffffffffffL;
leastSig |= 0x8000000000000000L;
return new UUID(mostSig, leastSig);
}Example 60
| Project: wildfly-elytron-master File: PasswordFileKeyStoreTest.java View source code |
@Test
public void testGetPut() throws Exception {
final PasswordFactory passwordFactory = PasswordFactory.getInstance(UnixMD5CryptPassword.ALGORITHM_CRYPT_MD5);
byte[] b = new byte[16];
ThreadLocalRandom.current().nextBytes(b);
final Password password = passwordFactory.generatePassword(new EncryptablePasswordSpec("swordfish".toCharArray(), new SaltedPasswordAlgorithmSpec(b)));
KeyStore keyStore = KeyStore.getInstance("PasswordFile");
keyStore.load(new InputStream() {
public int read() throws IOException {
return -1;
}
}, null);
keyStore.setEntry("bob", new PasswordEntry(password), null);
final KeyStore.Entry entry = keyStore.getEntry("bob", null);
assertNotNull("Missing entry", entry);
assertTrue("Wrong entry type", entry instanceof PasswordEntry);
final Password storedPassword = ((PasswordEntry) entry).getPassword();
assertNotNull(storedPassword);
assertSame(password, storedPassword);
}Example 61
| Project: wildfly-security-master File: PasswordFileKeyStoreTest.java View source code |
@Test
public void testGetPut() throws Exception {
final PasswordFactory passwordFactory = PasswordFactory.getInstance(UnixMD5CryptPassword.ALGORITHM_CRYPT_MD5);
byte[] b = new byte[16];
ThreadLocalRandom.current().nextBytes(b);
final Password password = passwordFactory.generatePassword(new EncryptablePasswordSpec("swordfish".toCharArray(), new SaltedPasswordAlgorithmSpec(b)));
KeyStore keyStore = KeyStore.getInstance("PasswordFile");
keyStore.load(new InputStream() {
public int read() throws IOException {
return -1;
}
}, null);
keyStore.setEntry("bob", new PasswordEntry(password), null);
final KeyStore.Entry entry = keyStore.getEntry("bob", null);
assertNotNull("Missing entry", entry);
assertTrue("Wrong entry type", entry instanceof PasswordEntry);
final Password storedPassword = ((PasswordEntry) entry).getPassword();
assertNotNull(storedPassword);
assertSame(password, storedPassword);
}Example 62
| Project: ambry-master File: CostBenefitInfoTest.java View source code |
/**
* Tests {@link CostBenefitInfo} for comparisons
*/
@Test
public void testCostBenefitInfoComparison() {
List<String> randomSegments = CompactionPolicyTest.generateRandomStrings(3);
long cost = getRandomCost();
int benefit = 1 + TestUtils.RANDOM.nextInt(Integer.MAX_VALUE - 1);
CostBenefitInfo one = new CostBenefitInfo(randomSegments, cost, benefit);
// generate a CostBenefitInfo with cost = 1 + one's cost
compareAndTest(one, 1, 0, -1);
// generate a CostBenefitInfo with cost = 1 - one's cost
compareAndTest(one, -1, 0, 1);
// generate a CostBenefitInfo with same cost as one
compareAndTest(one, 0, 0, 0);
// generate a CostBenefitInfo with benefit = 1 + one's benefit
compareAndTest(one, 0, 1, 1);
// generate a CostBenefitInfo with benefit = 1 - one's benefit
compareAndTest(one, 0, -1, -1);
// test a case where costBenefitRatio is same, but diff cost and benefit.
cost = ThreadLocalRandom.current().nextLong(Integer.MAX_VALUE / 2);
benefit = 2 + TestUtils.RANDOM.nextInt(Integer.MAX_VALUE / 2 - 2);
if (cost % 2 != 0) {
cost++;
}
if (benefit % 2 != 0) {
benefit++;
}
one = new CostBenefitInfo(randomSegments, cost, benefit);
// generate a CostBenefitInfo with cost = half of one and benefit = half of one. CostBenefit is same, but one'e
// benefit is more
compareAndTest(one, (cost / 2) * (-1), (benefit / 2) * (-1), -1);
}Example 63
| Project: armeria-master File: SlidingWindowCounterTest.java View source code |
@Test
public void testConcurrentAccess() throws InterruptedException {
SlidingWindowCounter counter = new SlidingWindowCounter(Ticker.systemTicker(), Duration.ofMinutes(5), Duration.ofMillis(1));
int worker = 6;
int batch = 100000;
AtomicLong success = new AtomicLong();
AtomicLong failure = new AtomicLong();
CyclicBarrier barrier = new CyclicBarrier(worker);
List<Thread> threads = new ArrayList<>(worker);
for (int i = 0; i < worker; i++) {
Thread t = new Thread(() -> {
try {
barrier.await();
long s = 0;
long f = 0;
for (int j = 0; j < batch; j++) {
double r = ThreadLocalRandom.current().nextDouble();
if (r > 0.6) {
counter.onSuccess();
s++;
} else if (r > 0.2) {
counter.onFailure();
f++;
}
}
success.addAndGet(s);
failure.addAndGet(f);
} catch (Exception e) {
e.printStackTrace();
}
});
threads.add(t);
t.start();
}
for (Thread thread : threads) {
thread.join();
}
await().untilAsserted(() -> assertThat(counter.onFailure()).isPresent());
assertThat(counter.count()).isEqualTo(new EventCount(success.get(), failure.get()));
}Example 64
| Project: botula-master File: ButtBotListener.java View source code |
@Override
public void onMessage(MessageEvent event) throws Exception {
if (botName.equals(event.getUser().getNick()) || Math.abs(ThreadLocalRandom.current().nextDouble()) >= BUTT_MESSAGE_RATIO) {
return;
}
StringBuilder butted = new StringBuilder();
if (buttifyMessage(event.getMessage(), butted)) {
event.respondChannel(butted.toString());
}
}Example 65
| Project: cas-master File: MockTicketGrantingTicketCreatedEventProducer.java View source code |
private static GeoLocationRequest getMockGeoLocation() {
final int index = ThreadLocalRandom.current().nextInt(ALL_GEOLOCS.size());
final GeoLocationRequest location = new GeoLocationRequest();
final Pair<String, String> pair = ALL_GEOLOCS.get(index);
location.setLatitude(pair.getKey());
location.setLongitude(pair.getValue());
location.setAccuracy("50");
location.setTimestamp(String.valueOf(new Date().getTime()));
return location;
}Example 66
| Project: cloudeventbus-master File: EncoderDecoderTest.java View source code |
@Test
public void greetingFrame() {
final int version = 1;
final String agent = "test-0.1-SNAPSHOT";
final long id = ThreadLocalRandom.current().nextLong();
final GreetingFrame frame = new GreetingFrame(version, agent, id);
final GreetingFrame recodedFrame = recode(frame);
assertEquals(recodedFrame.getVersion(), version);
assertEquals(recodedFrame.getAgent(), agent);
assertEquals(recodedFrame.getId(), id);
}Example 67
| Project: controller-master File: ConnectionEntryTest.java View source code |
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
doNothing().when(mockCallback).accept(any(MockFailure.class));
ticker = new FakeTicker();
ticker.advance(ThreadLocalRandom.current().nextLong());
mockActor = TestProbe.apply(actorSystem);
mockRequest = new MockRequest(mockIdentifier, mockReplyTo);
mockResponse = mockRequest.toRequestFailure(mockCause);
entry = new ConnectionEntry(mockRequest, mockCallback, ticker.read());
}Example 68
| Project: CraftBook-master File: Bookshelf.java View source code |
@Listener
public void onPlayerInteract(InteractBlockEvent.Secondary.MainHand event, @Named(NamedCause.SOURCE) Player player) {
event.getTargetBlock().getLocation().filter((this::isValid)).ifPresent( location -> {
if (!sneakState.getValue().doesPass(player.get(Keys.IS_SNEAKING).orElse(false) || !usePermissions.hasPermission(player))) {
return;
}
if (!readWhenHoldingBlock.getValue()) {
ItemStack stack = player.getItemInHand(HandTypes.MAIN_HAND).filter(( itemStack -> itemStack.getItem().getBlock().isPresent())).orElse(null);
if (stack != null)
return;
}
String line = bookLines[ThreadLocalRandom.current().nextInt(bookLines.length)];
player.sendMessage(Text.of(TextColors.YELLOW, "You pick up a book..."));
player.sendMessage(Text.of(line));
});
}Example 69
| Project: Europeana-Cloud-master File: FileUploadResourceTest.java View source code |
@Test
public void shouldUploadFileForNonExistingRepresentation() {
//given
String providerId = "providerId";
byte[] content = new byte[1000];
ThreadLocalRandom.current().nextBytes(content);
String contentMd5 = Hashing.md5().hashBytes(content).toString();
FormDataMultiPart multipart = new FormDataMultiPart().field(ParamConstants.F_PROVIDER, providerId).field(ParamConstants.F_FILE_MIME, file.getMimeType()).field(ParamConstants.F_FILE_DATA, new ByteArrayInputStream(content), MediaType.APPLICATION_OCTET_STREAM_TYPE).field(ParamConstants.F_FILE_NAME, file.getFileName());
//when
Response uploadFileResponse = fileWebTarget.request().post(Entity.entity(multipart, multipart.getMediaType()));
//then
assertThat("Unexpected status code", uploadFileResponse.getStatus(), is(201));
assertThat("File content tag does not match", uploadFileResponse.getEntityTag().getValue(), is(contentMd5));
}Example 70
| Project: hadoop-release-2.6.0-master File: InternalDataNodeTestUtils.java View source code |
/**
* Starts an instance of DataNode with NN mocked. Called should ensure to
* shutdown the DN
*
* @throws IOException
*/
public static DataNode startDNWithMockNN(Configuration conf, final InetSocketAddress nnSocketAddr, final String dnDataDir) throws IOException {
FileSystem.setDefaultUri(conf, "hdfs://" + nnSocketAddr.getHostName() + ":" + nnSocketAddr.getPort());
ArrayList<StorageLocation> locations = new ArrayList<StorageLocation>();
File dataDir = new File(dnDataDir);
FileUtil.fullyDelete(dataDir);
dataDir.mkdirs();
StorageLocation location = StorageLocation.parse(dataDir.getPath());
locations.add(location);
final DatanodeProtocolClientSideTranslatorPB namenode = mock(DatanodeProtocolClientSideTranslatorPB.class);
Mockito.doAnswer(new Answer<DatanodeRegistration>() {
@Override
public DatanodeRegistration answer(InvocationOnMock invocation) throws Throwable {
return (DatanodeRegistration) invocation.getArguments()[0];
}
}).when(namenode).registerDatanode(Mockito.any(DatanodeRegistration.class));
when(namenode.versionRequest()).thenReturn(new NamespaceInfo(1, TEST_CLUSTER_ID, TEST_POOL_ID, 1L));
when(namenode.sendHeartbeat(Mockito.any(DatanodeRegistration.class), Mockito.any(StorageReport[].class), Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt(), Mockito.any(VolumeFailureSummary.class), Mockito.anyBoolean(), Mockito.any(SlowPeerReports.class))).thenReturn(new HeartbeatResponse(new DatanodeCommand[0], new NNHAStatusHeartbeat(HAServiceState.ACTIVE, 1), null, ThreadLocalRandom.current().nextLong() | 1L));
DataNode dn = new DataNode(conf, locations, null, null) {
@Override
DatanodeProtocolClientSideTranslatorPB connectToNN(InetSocketAddress nnAddr) throws IOException {
Assert.assertEquals(nnSocketAddr, nnAddr);
return namenode;
}
};
// Trigger a heartbeat so that it acknowledges the NN as active.
dn.getAllBpOs()[0].triggerHeartbeatForTests();
return dn;
}Example 71
| Project: hive-master File: TestTimestampTZWritable.java View source code |
@Test
@Repeating(repetition = 10)
public void testSeconds() {
// just 1 VInt
long seconds = ThreadLocalRandom.current().nextLong(Integer.MAX_VALUE);
TimestampTZ tstz = new TimestampTZ(seconds, 0);
verifyConversion(tstz);
// 2 VInt
seconds = ThreadLocalRandom.current().nextLong(Integer.MAX_VALUE) + Integer.MAX_VALUE + 1;
if (ThreadLocalRandom.current().nextBoolean()) {
seconds = -seconds;
}
tstz.set(seconds, 0);
verifyConversion(tstz);
}Example 72
| Project: java-loggregator-master File: MessageSigner.java View source code |
public byte[] sign(Messages.LogMessage message) {
try {
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
final byte[] hash = digest.digest(message.getMessage().toByteArray());
final byte[] iv = new byte[BLOCK_SIZE];
ThreadLocalRandom.current().nextBytes(iv);
final Cipher cipher = createCipher(Cipher.ENCRYPT_MODE, iv);
byte[] cipherText = cipher.doFinal(pad(hash));
byte[] signature = new byte[iv.length + cipherText.length];
System.arraycopy(iv, 0, signature, 0, iv.length);
System.arraycopy(cipherText, 0, signature, iv.length, cipherText.length);
return signature;
} catch (GeneralSecurityException e) {
throw new LoggregatorException(e);
}
}Example 73
| Project: jinjava-master File: RandomFilter.java View source code |
@Override
public Object filter(Object object, JinjavaInterpreter interpreter, String... arg) {
if (object == null) {
return null;
}
// collection
if (object instanceof Collection) {
Collection<?> clt = (Collection<?>) object;
Iterator<?> it = clt.iterator();
int size = clt.size();
if (size == 0) {
return null;
}
int index = ThreadLocalRandom.current().nextInt(size);
while (index-- > 0) {
it.next();
}
return it.next();
}
// array
if (object.getClass().isArray()) {
int size = Array.getLength(object);
if (size == 0) {
return null;
}
int index = ThreadLocalRandom.current().nextInt(size);
return Array.get(object, index);
}
// map
if (object instanceof Map) {
Map<?, ?> map = (Map<?, ?>) object;
Iterator<?> it = map.values().iterator();
int size = map.size();
if (size == 0) {
return null;
}
int index = ThreadLocalRandom.current().nextInt(size);
while (index-- > 0) {
it.next();
}
return it.next();
}
// number
if (object instanceof Number) {
return ThreadLocalRandom.current().nextLong(((Number) object).longValue());
}
// string
if (object instanceof String) {
try {
return ThreadLocalRandom.current().nextLong(new BigDecimal((String) object).longValue());
} catch (Exception e) {
return 0;
}
}
return object;
}Example 74
| Project: jmeter-master File: Random.java View source code |
/** {@inheritDoc} */
@Override
public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException {
long min = Long.parseLong(minimum.execute().trim());
long max = Long.parseLong(maximum.execute().trim());
long rand = ThreadLocalRandom.current().nextLong(min, max + 1);
String randString = Long.toString(rand);
if (varName != null) {
JMeterVariables vars = getVariables();
final String varTrim = varName.execute().trim();
if (vars != null && varTrim.length() > 0) {
// vars will be null on TestPlan
vars.put(varTrim, randString);
}
}
return randString;
}Example 75
| Project: kafka-master File: DefaultPartitioner.java View source code |
private int nextValue(String topic) {
AtomicInteger counter = topicCounterMap.get(topic);
if (null == counter) {
counter = new AtomicInteger(ThreadLocalRandom.current().nextInt());
AtomicInteger currentCounter = topicCounterMap.putIfAbsent(topic, counter);
if (currentCounter != null) {
counter = currentCounter;
}
}
return counter.getAndIncrement();
}Example 76
| Project: Kite-master File: FlexibleBoundedExponentialBackoffRetry.java View source code |
private long getSleepTime(int retryCount) {
if (retryCount < retriesLimit) {
long low = baseSleepTimeNanos * (1L << retryCount);
long high = 2 * low;
long sleepTimeNanos = ThreadLocalRandom.current().nextLong(low, high);
return Math.min(maxSleepTimeNanos, sleepTimeNanos);
} else {
return maxSleepTimeNanos;
}
}Example 77
| Project: milib-master File: RandomAccessFastaReaderTest.java View source code |
public static <S extends Sequence<S>> void assertRA(List<FastaRecord<S>> seqs, Path path, Alphabet<S> alphabet, boolean allowReverse) throws Exception {
try (RandomAccessFastaReader<S> raReader = new RandomAccessFastaReader<>(path, alphabet)) {
ThreadLocalRandom r = ThreadLocalRandom.current();
for (int i = 0; i < 1000; i++) {
FastaRecord<S> rec = seqs.get(r.nextInt(seqs.size()));
int from = r.nextInt(rec.getSequence().size() - 1);
int to = allowReverse ? r.nextInt(rec.getSequence().size() - 1) : r.nextInt(from, rec.getSequence().size());
Range range = new Range(from, to);
Assert.assertEquals(rec.getSequence().getRange(range), raReader.getSequence((int) rec.getId(), range));
Assert.assertEquals(rec.getSequence().getRange(range), raReader.getSequence(rec.getDescription(), range));
}
}
}Example 78
| Project: MyApps-master File: FlowPusherTask.java View source code |
@Override
public void run() {
ForwardingObjective forwardingObjective = DefaultForwardingObjective.builder().withSelector(FlowPusherTask.this.selectorBuilder.build()).withTreatment(FlowPusherTask.this.treatment).withPriority(ThreadLocalRandom.current().nextInt(100, 4000 + 1)).withFlag(ForwardingObjective.Flag.VERSATILE).fromApp(FlowPusherTask.this.appId).makeTemporary(/*.makePermanent()*/
ThreadLocalRandom.current().nextInt(100, 4000 + 1)).add(new TimerObjectiveContext());
//FlowRuleOperations operations = builder.build(flowRuleOperationsContext);
//flowRuleService.apply(operations);
log.info("Starting the Flowpusher task for " + FlowPusherTask.this.appId.name() + " on device " + FlowPusherTask.this.device.id() + "with id => " + forwardingObjective.id());
flowObjectiveService.forward(FlowPusherTask.this.device.id(), forwardingObjective);
}Example 79
| Project: pgjdbc-master File: FinalizeStatement.java View source code |
@Benchmark
public Statement createAndLeak() throws SQLException {
Statement statement = connection.createStatement();
Random rnd;
//#if mvn.project.property.current.jdk < "1.7"
rnd = random;
//#else
rnd = java.util.concurrent.ThreadLocalRandom.current();
//#endif
if (rnd.nextFloat() >= leakPctFloat) {
statement.close();
}
return statement;
}Example 80
| Project: quartz-scheduler-hazelcast-jobstore-master File: HazelcastJobStoreUngracefulShutdownTest.java View source code |
@Test
public void testOneOfTwoInstancesCrashing() throws Exception {
// Build node 1
HazelcastInstance hazelcast1 = createHazelcastInstance("testOneOfTwoInstancesCrashing");
HazelcastJobStore.setHazelcastClient(hazelcast1);
HazelcastJobStore jobstore1 = createJobStore("jobstore1");
jobstore1.setTriggerReleaseThreshold(450);
jobstore1.setShutdownHazelcastOnShutdown(false);
jobstore1.initialize(null, new SampleSignaler());
// Build node 2
HazelcastInstance hazelcast2 = createHazelcastInstance("testOneOfTwoInstancesCrashing");
HazelcastJobStore.setHazelcastClient(hazelcast2);
HazelcastJobStore jobstore2 = createJobStore("jobstore2");
jobstore2.setShutdownHazelcastOnShutdown(false);
jobstore2.setTriggerReleaseThreshold(450);
jobstore2.initialize(null, new SampleSignaler());
// Add a job and its trigger to the scheduler
JobDetail job = JobBuilder.newJob(TestSlowJob.class).withIdentity("job1", "jobGroup1").build();
OperableTrigger trigger = buildAndComputeTrigger("trigger1", "triggerGroup1", job, new Date().getTime());
trigger.setMisfireInstruction(MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY);
jobstore1.storeJobAndTrigger(job, (OperableTrigger) trigger);
long firstFireTime = new Date(trigger.getNextFireTime().getTime()).getTime();
// Create a thread for acquiring next triggers on node 1
Thread acquireThread = new Thread(() -> {
try {
List<OperableTrigger> triggers1 = jobstore1.acquireNextTriggers(firstFireTime + 150, 1, 0L);
triggers1.forEach(jobstore1::releaseAcquiredTrigger);
} catch (JobPersistenceException e) {
throw new RuntimeException(e);
}
}, "acquireThread");
// Create a thread for terminating Hazelcast on node 1
Thread terminateThread = new Thread(hazelcast1.getLifecycleService()::terminate, "terminateThread");
// Start acquiring next triggers and right after start terminating Hazelcast
acquireThread.start();
long waitTime = ThreadLocalRandom.current().nextInt(1, 51);
Thread.sleep(waitTime);
terminateThread.start();
// Wait a bit
Thread.sleep(500);
// Acquire next triggers on node 2, we should get our trigger here!
List<OperableTrigger> triggers2 = jobstore2.acquireNextTriggers(firstFireTime + 150 + 6000, 10, 0L);
System.err.println("-------------------------> VAL " + triggers2.size());
assertEquals(triggers2.size(), 1, "Should find 1 trigger on node 2 after node 1 crashed when failing after " + waitTime + "ms");
}Example 81
| Project: rhq-master File: MeasurementReader.java View source code |
@Override
public void run() {
Timer.Context context = metrics.totalReadTime.time();
Stopwatch stopwatch = new Stopwatch().start();
try {
log.info("Running metrics queries");
ThreadLocalRandom random = ThreadLocalRandom.current();
int bound = startingSchedule + batchSize;
findResourceDataForPast24Hours(random.nextInt(startingSchedule, bound));
findResourceDataForPastWeek(random.nextInt(startingSchedule, bound));
findResourceDataForPast2Weeks(random.nextInt(startingSchedule, bound));
findResourceDataForPast31Days(random.nextInt(startingSchedule, bound));
findResourceDataForPastYear(random.nextInt(startingSchedule, bound));
} finally {
stopwatch.stop();
log.info("Finished running metrics queries in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
context.stop();
}
}Example 82
| Project: RxNetty-master File: AbstractP2CStrategy.java View source code |
@Override
public Observable<Connection<R, W>> newConnectionRequest() {
HostHolder<W, R> selected = null;
if (hosts.isEmpty()) {
noUsableHostsFound();
return Observable.error(NoHostsAvailableException.EMPTY_INSTANCE);
} else if (hosts.size() == 1) {
HostHolder<W, R> holder = hosts.get(0);
@SuppressWarnings("unchecked") L eventListener = (L) holder.getEventListener();
double weight = getWeight(eventListener);
if (isUnusable(weight)) {
noUsableHostsFound();
return Observable.error(new NoHostsAvailableException("No usable hosts found."));
}
selected = holder;
} else {
ThreadLocalRandom rand = ThreadLocalRandom.current();
for (int i = 0; i < 5; i++) {
int pos = rand.nextInt(hosts.size());
HostHolder<W, R> first = hosts.get(pos);
int pos2 = (rand.nextInt(hosts.size() - 1) + pos + 1) % hosts.size();
HostHolder<W, R> second = hosts.get(pos2);
@SuppressWarnings("unchecked") double w1 = getWeight((L) first.getEventListener());
@SuppressWarnings("unchecked") double w2 = getWeight((L) second.getEventListener());
if (w1 > w2) {
selected = first;
break;
} else if (w1 < w2) {
selected = second;
break;
} else if (!isUnusable(w1)) {
selected = first;
break;
}
foundTwoUnusableHosts();
}
if (null == selected) {
noUsableHostsFound();
return Observable.error(new NoHostsAvailableException("No usable hosts found after 5 tries."));
}
}
return selected.getConnector().getConnectionProvider().newConnectionRequest();
}Example 83
| Project: sulong-master File: LLVM80BitGetShortTest.java View source code |
@Test
public void testRandomInt() {
for (int i = 0; i < NR_RANDOM_NUMBERS; i++) {
byte[] bytes = new byte[1];
ThreadLocalRandom.current().nextBytes(bytes);
byte nextByte = bytes[0];
assertEquals(nextByte, LLVM80BitFloat.fromShort(nextByte).getShortValue());
assertEquals(nextByte, LLVM80BitFloat.fromShort(nextByte).getShortValue());
}
}Example 84
| Project: t-digest-benchmark-master File: TDigestBench.java View source code |
@Setup
public void setUp() {
random = ThreadLocalRandom.current();
tdigest = tdigestFactory.create(compression);
distribution = distributionFactory.create(random);
// first values are cheap to add, so pre-fill the t-digest to have more realistic results
for (int i = 0; i < 10000; ++i) {
tdigest.add(distribution.nextDouble());
}
for (int i = 0; i < data.length; ++i) {
data[i] = distribution.nextDouble();
}
}Example 85
| Project: async-google-pubsub-client-master File: PublisherBenchmark.java View source code |
public static void main(final String... args) throws IOException {
final String project = Util.defaultProject();
GoogleCredential credential;
// Use credentials from file if available
try {
credential = GoogleCredential.fromStream(new FileInputStream("credentials.json")).createScoped(PubsubScopes.all());
} catch (IOException e) {
credential = GoogleCredential.getApplicationDefault().createScoped(PubsubScopes.all());
}
final Pubsub pubsub = Pubsub.builder().credential(credential).compressionLevel(Deflater.BEST_SPEED).enabledCipherSuites(nonGcmCiphers()).build();
final Publisher publisher = Publisher.builder().pubsub(pubsub).concurrency(128).project(project).build();
LoggingConfigurator.configureDefaults("benchmark", WARN);
final String topicPrefix = TEST_NAME_PREFIX + ThreadLocalRandom.current().nextInt();
final List<String> topics = IntStream.range(0, 100).mapToObj( i -> topicPrefix + "-" + i).collect(toList());
topics.stream().map( topic -> pubsub.createTopic(project, topic)).collect(toList()).forEach(Futures::getUnchecked);
final List<Message> messages = IntStream.range(0, 1000).mapToObj( i -> {
final StringBuilder s = new StringBuilder();
while (s.length() < MESSAGE_SIZE) {
s.append(ThreadLocalRandom.current().nextInt());
}
return Message.ofEncoded(s.toString());
}).collect(toList());
final ProgressMeter meter = new ProgressMeter();
final ProgressMeter.Metric requests = meter.group("operations").metric("publishes", "messages");
for (int i = 0; i < 100000; i++) {
benchSend(publisher, messages, topics, requests);
}
}Example 86
| Project: Blazar-master File: GitBranchUpdaterTest.java View source code |
private GitInfo buildGitInfo(String uri) {
GitInfo gitInfo = GitInfo.fromString(uri);
return new GitInfo(Optional.absent(), gitInfo.getHost(), gitInfo.getOrganization(), gitInfo.getRepository(), ThreadLocalRandom.current().nextInt(1337, 100000), gitInfo.getBranch(), true, System.currentTimeMillis(), System.currentTimeMillis());
}Example 87
| Project: build-properties-maven-plugin-master File: GitIntegrationTest.java View source code |
@Before
public void setUp() throws Exception {
// generate unique sandbox for this test
File sandbox;
do {
currSandbox = SANDBOX_DIR + "sandbox" + Integer.toString(ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE));
sandbox = new File(currSandbox);
} while (sandbox.exists());
mavenSandbox = new FileSystemMavenSandbox(currSandbox);
mojo = new GitCommitIdMojo();
initializeMojoWithDefaults(mojo);
}Example 88
| Project: caffeine-master File: Threads.java View source code |
@Override
public void run() {
int id = index.getAndIncrement();
for (Integer e : sets.get(id)) {
BiConsumer<A, Integer> operation = operations.get(ThreadLocalRandom.current().nextInt(operations.size()));
try {
operation.accept(collection, e);
} catch (Throwable t) {
failures.add(String.format("Failed: key %s on operation %s%n%s", e, operation, Throwables.getStackTraceAsString(t)));
throw t;
}
}
}Example 89
| Project: cf-java-component-master File: CfComponentConfiguration.java View source code |
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
final MultiValueMap<String, Object> attributes = importMetadata.getAllAnnotationAttributes(CfComponent.class.getName());
type = evaluate(attributes, "type");
index = Integer.valueOf(evaluate(attributes, "index"));
uuid = evaluate(attributes, "uuid");
if (StringUtils.isEmpty(uuid)) {
uuid = UUID.randomUUID().toString();
}
host = evaluate(attributes, "host");
port = Integer.valueOf(evaluate(attributes, "port"));
username = evaluate(attributes, "username");
password = evaluate(attributes, "password");
if (StringUtils.isEmpty(password)) {
password = new BigInteger(256, ThreadLocalRandom.current()).toString(32);
}
}Example 90
| Project: dbeaver-master File: LockGeneratorOracle.java View source code |
public static void main(String[] args) {
final String url = "jdbc:oracle:thin:@[SERVER]:1521/[SID]";
final Properties props = new Properties();
props.setProperty("user", "user");
props.setProperty("password", "pwd");
Connection conn = null;
PreparedStatement stmt = null;
ResultSet res = null;
try {
conn = DriverManager.getConnection(url, props);
conn.setAutoCommit(false);
stmt = conn.prepareStatement("select count(*) c from dba_tables where table_name = 'USR' and owner = 'SCHEMA'");
res = stmt.executeQuery();
res.next();
if (res.getInt(1) != 1) {
System.out.println("Table not found");
stmt = conn.prepareStatement("create table usr(field NUMBER(11,0),v NUMBER(11,0), s VARCHAR2(1024))");
stmt.execute();
stmt = conn.prepareStatement("insert into usr(field,s) select rownum r,DBMS_RANDOM.STRING('U',1024) from dual connect by rownum <= 10000");
stmt.execute();
stmt = conn.prepareStatement("alter table usr add primary key (field)");
stmt.execute();
conn.commit();
System.out.println("Table created");
}
ExecutorService service = Executors.newFixedThreadPool(MAX_SESSIONS);
int sessionCount = 0;
int field = 1;
while (sessionCount < MAX_SESSIONS) {
final int fieldVal = field;
service.submit(new Runnable() {
@Override
public void run() {
Connection c = null;
PreparedStatement s = null;
ResultSet r = null;
try {
c = DriverManager.getConnection(url, props);
c.setAutoCommit(false);
String pid = String.valueOf(getPid(c));
System.out.println("[" + pid + "] Submited root session for " + String.valueOf(fieldVal));
s = c.prepareStatement("/*ROOT " + String.valueOf(fieldVal) + " */ update usr set v = 100500 where field = ?");
s.setInt(1, fieldVal);
s.executeUpdate();
while (true) {
try {
Thread.sleep(600 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
c.close();
} catch (SQLException e) {
e.printStackTrace();
return;
}
}
});
sessionCount++;
if ((MAX_SESSIONS - sessionCount) > MIN_CHAIN_SIZE) {
int chainCount = ThreadLocalRandom.current().nextInt(MIN_CHAIN_SIZE, MAX_CHAIN_SIZE + 1);
if ((MAX_SESSIONS - sessionCount) >= chainCount) {
for (int i = 0; i < chainCount; i++) {
final int level = i;
int levelCount = ThreadLocalRandom.current().nextInt(1, MAX_LEVEL_ITEMS + 1);
for (int j = 0; j < levelCount; j++) {
final int levelNo = j;
service.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Connection c = null;
PreparedStatement s = null;
ResultSet r = null;
try {
c = DriverManager.getConnection(url, props);
c.setAutoCommit(false);
int pid = getPid(c);
String prefix;
if (levelNo > 0) {
int sublock = MAX_SESSIONS + (level * MAX_CHAIN_SIZE);
prefix = String.format("[%d] Sublock %d for %d -> %d (%d) ", pid, sublock, fieldVal, level, levelNo);
s = c.prepareStatement("/*" + prefix + "*/ update usr set v = 100500 where field = ?");
System.out.println("Sublock for " + prefix);
s.setInt(1, sublock);
s.executeUpdate();
}
prefix = String.format("[%d] %d->%d (%d) ", pid, fieldVal, level, levelNo);
s = c.prepareStatement("/*" + prefix + "*/ update usr set v = 100500 where field = ?");
s.setInt(1, fieldVal);
System.out.println("Wait session for " + prefix);
s.executeUpdate();
c.close();
} catch (SQLException e) {
e.printStackTrace();
return;
}
}
});
sessionCount++;
if (sessionCount >= MAX_SESSIONS) {
break;
}
}
if (sessionCount >= MAX_SESSIONS) {
break;
}
}
}
}
field++;
}
System.out.println("Sbmited " + sessionCount);
service.shutdown();
service.awaitTermination(1, TimeUnit.HOURS);
} catch (Exception e) {
e.printStackTrace();
}
}Example 91
| Project: diqube-master File: LogoutCleaner.java View source code |
@Override
public void run() {
long randomWaitDiff = ThreadLocalRandom.current().nextLong((MAX_POLL_SEC / 2) * 1_000L);
while (true) {
try {
// random so not everybody executes simultaneously
Thread.sleep((MAX_POLL_SEC / 2) * 1_000L + randomWaitDiff);
} catch (InterruptedException e) {
return;
}
Map<Long, Set<Ticket>> timeoutedTickets = timeouts.headMap(System.currentTimeMillis() - TicketValidityService.CLEANUP_NO_REMOVE_MOST_RECENT_MS);
if (!timeoutedTickets.isEmpty()) {
logger.info("Found {} tickets that have been logged out but are invalid now anyway. " + "Removing them from the consensus cluster.", timeoutedTickets.size());
try (ClosableProvider<LogoutStateMachine> p = consensusClient.getStateMachineClient(LogoutStateMachine.class)) {
Set<Ticket> allTickets = timeoutedTickets.values().stream().flatMap( s -> s.stream()).collect(Collectors.toSet());
for (Ticket t : allTickets) p.getClient().cleanLogoutTicket(CleanLogoutTicket.local(t));
timeoutedTickets.clear();
} catch (ConsensusClusterUnavailableException e) {
logger.warn("Could not contact consensus cluster to remove old logged out tickets.", e);
} catch (ConsensusStateMachineClientInterruptedException e) {
return;
} catch (RuntimeException e) {
logger.warn("Could not contact consensus cluster to remove old logged out tickets", e);
}
}
}
}Example 92
| Project: drill-master File: UserWorker.java View source code |
/**
* Helper method to generate QueryId
* @return generated QueryId
*/
private static QueryId queryIdGenerator() {
ThreadLocalRandom r = ThreadLocalRandom.current();
// create a new queryid where the first four bytes are a growing time (each new value comes earlier in sequence). Last 12 bytes are random.
final long time = (int) (System.currentTimeMillis() / 1000);
final long p1 = ((Integer.MAX_VALUE - time) << 32) + r.nextInt();
final long p2 = r.nextLong();
final QueryId id = QueryId.newBuilder().setPart1(p1).setPart2(p2).build();
return id;
}Example 93
| Project: elasticsearch-lang-groovy-master File: GroovyScriptMultiThreadedTest.java View source code |
@Override
public void run() {
try {
barrier.await();
long x = ThreadLocalRandom.current().nextInt();
long y = ThreadLocalRandom.current().nextInt();
long addition = x + y;
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("x", x);
vars.put("y", y);
ExecutableScript script = se.executable(compiled, vars);
for (int i = 0; i < 100000; i++) {
long result = ((Number) script.run()).longValue();
assertThat(result, equalTo(addition));
}
} catch (Throwable t) {
failed.set(true);
logger.error("failed", t);
} finally {
latch.countDown();
}
}Example 94
| Project: elasticsearch-lang-mvel-master File: MvelScriptMultiThreadedTest.java View source code |
@Override
public void run() {
try {
barrier.await();
long x = ThreadLocalRandom.current().nextInt();
long y = ThreadLocalRandom.current().nextInt();
long addition = x + y;
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("x", x);
vars.put("y", y);
ExecutableScript script = se.executable(compiled, vars);
for (int i = 0; i < 100000; i++) {
long result = ((Number) script.run()).longValue();
assertThat(result, equalTo(addition));
}
} catch (Throwable t) {
failed.set(true);
logger.error("failed", t);
} finally {
latch.countDown();
}
}Example 95
| Project: hadoop-master File: TestHAAppend.java View source code |
/**
* Test to verify the processing of PendingDataNodeMessageQueue in case of
* append. One block will marked as corrupt if the OP_ADD, OP_UPDATE_BLOCKS
* comes in one edit log segment and OP_CLOSE edit comes in next log segment
* which is loaded during failover. Regression test for HDFS-3605.
*/
@Test
public void testMultipleAppendsDuringCatchupTailing() throws Exception {
Configuration conf = new Configuration();
// Set a length edits tailing period, and explicit rolling, so we can
// control the ingest of edits by the standby for this test.
conf.set(DFSConfigKeys.DFS_HA_TAILEDITS_PERIOD_KEY, "5000");
conf.setInt(DFSConfigKeys.DFS_HA_LOGROLL_PERIOD_KEY, -1);
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).nnTopology(MiniDFSNNTopology.simpleHATopology()).numDataNodes(3).build();
FileSystem fs = null;
try {
cluster.transitionToActive(0);
fs = HATestUtil.configureFailoverFs(cluster, conf);
Path fileToAppend = new Path("/FileToAppend");
Path fileToTruncate = new Path("/FileToTruncate");
final byte[] data = new byte[1 << 16];
ThreadLocalRandom.current().nextBytes(data);
final int[] appendPos = AppendTestUtil.randomFilePartition(data.length, COUNT);
final int[] truncatePos = AppendTestUtil.randomFilePartition(data.length, 1);
// Create file, write some data, and hflush so that the first
// block is in the edit log prior to roll.
FSDataOutputStream out = createAndHflush(fs, fileToAppend, data, appendPos[0]);
FSDataOutputStream out4Truncate = createAndHflush(fs, fileToTruncate, data, data.length);
// Let the StandbyNode catch the creation of the file.
cluster.getNameNode(0).getRpcServer().rollEditLog();
cluster.getNameNode(1).getNamesystem().getEditLogTailer().doTailEdits();
out.close();
out4Truncate.close();
// Append and re-close a few time, so that many block entries are queued.
for (int i = 0; i < COUNT; i++) {
int end = i < COUNT - 1 ? appendPos[i + 1] : data.length;
out = fs.append(fileToAppend);
out.write(data, appendPos[i], end - appendPos[i]);
out.close();
}
boolean isTruncateReady = fs.truncate(fileToTruncate, truncatePos[0]);
// Ensure that blocks have been reported to the SBN ahead of the edits
// arriving.
cluster.triggerBlockReports();
// Failover the current standby to active.
cluster.shutdownNameNode(0);
cluster.transitionToActive(1);
// Check the FSCK doesn't detect any bad blocks on the SBN.
int rc = ToolRunner.run(new DFSck(cluster.getConfiguration(1)), new String[] { "/", "-files", "-blocks" });
assertEquals(0, rc);
assertEquals("CorruptBlocks should be empty.", 0, cluster.getNameNode(1).getNamesystem().getCorruptReplicaBlocks());
AppendTestUtil.checkFullFile(fs, fileToAppend, data.length, data, fileToAppend.toString());
if (!isTruncateReady) {
TestFileTruncate.checkBlockRecovery(fileToTruncate, cluster.getFileSystem(1));
}
AppendTestUtil.checkFullFile(fs, fileToTruncate, truncatePos[0], data, fileToTruncate.toString());
} finally {
if (null != cluster) {
cluster.shutdown();
}
if (null != fs) {
fs.close();
}
}
}Example 96
| Project: HERD-master File: SearchIndexValidationServiceTest.java View source code |
@Test
public void testCreateSearchIndexValidationBusinessObjectDefinitions() {
// Create a search index key.
SearchIndexKey searchIndexKey = new SearchIndexKey(SEARCH_INDEX_NAME);
// Get the search index type value.
String searchIndexType = SearchIndexTypeEntity.SearchIndexTypes.BUS_OBJCT_DFNTN.name();
// Create a search index create request.
SearchIndexValidationCreateRequest searchIndexValidationCreateRequest = new SearchIndexValidationCreateRequest(searchIndexKey);
//Create the search index type entity
SearchIndexTypeEntity searchIndexTypeEntity = new SearchIndexTypeEntity();
searchIndexTypeEntity.setCode(searchIndexType);
//Create a search index entity
SearchIndexEntity searchIndexEntity = new SearchIndexEntity();
searchIndexEntity.setName(SEARCH_INDEX_NAME);
searchIndexEntity.setType(searchIndexTypeEntity);
//validation response
boolean sizeCheck = ThreadLocalRandom.current().nextDouble() < 0.5;
boolean spotCheckPercentage = ThreadLocalRandom.current().nextDouble() < 0.5;
boolean spotCheckMostRecent = ThreadLocalRandom.current().nextDouble() < 0.5;
// Mock some of the external call responses.
@SuppressWarnings("unchecked") Future<Void> mockedFuture = mock(Future.class);
// Mock the external calls.
when(alternateKeyHelper.validateStringParameter("Search index name", SEARCH_INDEX_NAME)).thenReturn(SEARCH_INDEX_NAME);
when(searchIndexDaoHelper.getSearchIndexEntity(searchIndexKey)).thenReturn(searchIndexEntity);
when(businessObjectDefinitionService.indexValidateAllBusinessObjectDefinitions()).thenReturn(new AsyncResult<>(null));
when(businessObjectDefinitionService.indexSizeCheckValidationBusinessObjectDefinitions()).thenReturn(sizeCheck);
when(businessObjectDefinitionService.indexSpotCheckPercentageValidationBusinessObjectDefinitions()).thenReturn(spotCheckPercentage);
when(businessObjectDefinitionService.indexSpotCheckMostRecentValidationBusinessObjectDefinitions()).thenReturn(spotCheckMostRecent);
// Create a search index.
SearchIndexValidation response = searchIndexValidationService.createSearchIndexValidation(searchIndexValidationCreateRequest);
// Verify the external calls.
verify(alternateKeyHelper).validateStringParameter("Search index name", SEARCH_INDEX_NAME);
verify(businessObjectDefinitionService, times(1)).indexValidateAllBusinessObjectDefinitions();
verify(searchIndexDaoHelper).getSearchIndexEntity(searchIndexKey);
verify(businessObjectDefinitionService).indexValidateAllBusinessObjectDefinitions();
verify(businessObjectDefinitionService).indexSizeCheckValidationBusinessObjectDefinitions();
verify(businessObjectDefinitionService).indexSpotCheckPercentageValidationBusinessObjectDefinitions();
verify(businessObjectDefinitionService).indexSpotCheckMostRecentValidationBusinessObjectDefinitions();
verifyNoMoreInteractions(alternateKeyHelper, searchIndexDaoHelper, businessObjectDefinitionService);
// Validate the returned object.
assertEquals(new SearchIndexValidation(searchIndexKey, response.getValidateStartTime(), sizeCheck, spotCheckPercentage, spotCheckMostRecent), response);
}Example 97
| Project: JCTools-master File: MpscOnSpscQueue.java View source code |
@Override
public E poll() {
Queue<E>[] qs = this.queues;
final int start = ThreadLocalRandom.current().nextInt(qs.length);
for (int i = start; i < qs.length; i++) {
E e = qs[i].poll();
if (e != null)
return e;
}
for (int i = 0; i < start; i++) {
E e = qs[i].poll();
if (e != null)
return e;
}
return null;
}Example 98
| Project: jdk7u-jdk-master File: Arrive.java View source code |
void doTest(String[] args) throws Throwable {
final int n = ThreadLocalRandom.current().nextInt(1, 10);
final Phaser startingGate = new Phaser(n);
final Phaser phaser = new Phaser(n);
final List<Thread> threads = new ArrayList<Thread>();
final AtomicInteger count0 = new AtomicInteger(0);
final AtomicInteger count1 = new AtomicInteger(0);
final Runnable task = new Runnable() {
public void run() {
equal(startingGate.getPhase(), 0);
startingGate.arriveAndAwaitAdvance();
equal(startingGate.getPhase(), 1);
int phase = phaser.arrive();
if (phase == 0)
count0.getAndIncrement();
else if (phase == 1)
count1.getAndIncrement();
else
fail();
}
};
for (int i = 0; i < n; i++) threads.add(new Thread(task));
for (Thread thread : threads) thread.start();
for (Thread thread : threads) thread.join();
equal(count0.get(), n);
equal(count1.get(), 0);
equal(phaser.getPhase(), 1);
}Example 99
| Project: jeppetto-master File: BaseNIdGenerator.java View source code |
//-------------------------------------------------------------
// Implementation - IdGenerator
//-------------------------------------------------------------
@Override
public String generateId() {
StringBuilder sb = new StringBuilder();
int bitsLeft = bitsPerId;
while (bitsLeft > 0) {
long random = ThreadLocalRandom.current().nextLong();
if (bitsLeft < BITS_PER_LONG) {
random >>>= (BITS_PER_LONG - bitsLeft);
}
encode(random, sb);
bitsLeft -= BITS_PER_LONG;
}
while (sb.length() < encodedIdLength) {
sb.append(characters[0]);
}
// It's possible we could generate a string larger than we expect. Cut it down if needed.
return sb.length() == encodedIdLength ? sb.toString() : sb.substring(0, encodedIdLength);
}Example 100
| Project: jetbrick-commons-master File: RandomStringUtils.java View source code |
public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars) {
if (count == 0) {
return "";
} else if (count < 0) {
throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
}
if (chars != null && chars.length == 0) {
throw new IllegalArgumentException("The chars array must not be empty");
}
if (start == 0 && end == 0) {
if (chars != null) {
end = chars.length;
} else {
if (!letters && !numbers) {
end = Integer.MAX_VALUE;
} else {
end = 'z' + 1;
start = ' ';
}
}
} else {
if (end <= start) {
throw new IllegalArgumentException("Parameter end (" + end + ") must be greater than start (" + start + ")");
}
}
final char[] buffer = new char[count];
final int gap = end - start;
ThreadLocalRandom random = ThreadLocalRandom.current();
while (count-- != 0) {
char ch;
if (chars == null) {
ch = (char) (random.nextInt(gap) + start);
} else {
ch = chars[random.nextInt(gap) + start];
}
if (letters && Character.isLetter(ch) || numbers && Character.isDigit(ch) || !letters && !numbers) {
if (ch >= 56320 && ch <= 57343) {
if (count == 0) {
count++;
} else {
// low surrogate, insert high surrogate after putting it in
buffer[count] = ch;
count--;
buffer[count] = (char) (55296 + random.nextInt(128));
}
} else if (ch >= 55296 && ch <= 56191) {
if (count == 0) {
count++;
} else {
// high surrogate, insert low surrogate before putting it in
buffer[count] = (char) (56320 + random.nextInt(128));
count--;
buffer[count] = ch;
}
} else if (ch >= 56192 && ch <= 56319) {
// private high surrogate, no effing clue, so skip it
count++;
} else {
buffer[count] = ch;
}
} else {
count++;
}
}
return new String(buffer);
}Example 101
| Project: jlibs-master File: AddAuthentication.java View source code |
@Override
public boolean filter(ClientExchange exchange, FilterType type) throws Exception {
assert type == FilterType.RESPONSE;
Response response = exchange.getResponse();
if (!status.equals(response.status))
return true;
Request request = exchange.getRequest();
if (// we already tried to authenticate && failed
request.getCredentials(proxy) != null)
return true;
Challenge challenge = response.getChallenge(proxy);
if (challenge instanceof BasicChallenge) {
request.setCredentials(basicCredentials, proxy);
exchange.retry();
return true;
}
if (challenge instanceof DigestChallenge) {
DigestChallenge digestChallenge = (DigestChallenge) challenge;
DigestCredentials digestCredentials = new DigestCredentials();
digestCredentials.username = basicCredentials.user;
digestCredentials.realm = digestChallenge.realm;
digestCredentials.nonce = digestChallenge.nonce;
digestCredentials.uri = request.uri;
digestCredentials.algorithm = digestChallenge.algorithm;
digestCredentials.opaque = digestChallenge.opaque;
if (digestChallenge.qops != null && !digestChallenge.qops.isEmpty())
digestCredentials.qop = digestChallenge.qops.contains("auth") ? "auth" : digestChallenge.qops.get(0);
if ("MD5-sess".equals(digestCredentials.algorithm) || digestCredentials.qop != null) {
byte[] bytes = new byte[4];
ThreadLocalRandom.current().nextBytes(bytes);
digestCredentials.cnonce = printHexBinary(bytes).toLowerCase();
}
MessageDigest md5 = MessageDigest.getInstance("MD5");
String a1 = basicCredentials.user + ':' + digestChallenge.realm + ':' + basicCredentials.password;
String ha1 = printHexBinary(md5.digest(a1.getBytes(UTF_8))).toLowerCase();
md5.reset();
if ("MD5-sess".equals(digestCredentials.algorithm)) {
ha1 = printHexBinary(md5.digest((ha1 + ':' + digestCredentials.nonce + ':' + digestCredentials.cnonce).getBytes(UTF_8))).toLowerCase();
md5.reset();
}
md5.update((request.method + ":" + request.uri).getBytes(UTF_8));
if ("auth-init".equals(digestCredentials.qop)) {
// ha2 = md5(method:uri:md5(payload)
if (request.getPayload().getContentLength() == 0)
md5.update((byte) ':');
else {
// not implemented
return true;
}
}
String ha2 = printHexBinary(md5.digest()).toLowerCase();
md5.reset();
String respString = ha1 + ':' + digestChallenge.nonce;
if (digestCredentials.qop != null) {
digestCredentials.nc = String.format("%08x", 1);
respString += ':' + digestCredentials.nc + ':' + digestCredentials.cnonce + ':' + digestCredentials.qop;
}
respString += ':' + ha2;
digestCredentials.response = printHexBinary(md5.digest(respString.getBytes(UTF_8))).toLowerCase();
request.setCredentials(digestCredentials, proxy);
exchange.retry();
return true;
}
// we dont understand the challenge
return true;
}