use of java.util.Collections in project pravega by pravega.
the class ThrottlerTests method testUninterruptibleDelay.
/**
* Tests the case when an interruption is called on an uninterruptible throttling source.
*
* @throws Exception
*/
@Test
public void testUninterruptibleDelay() throws Exception {
// Supply monotonically decreasing delays.
val suppliedDelays = Arrays.asList(2000);
val delays = Collections.<Integer>synchronizedList(new ArrayList<>());
val calculator = new TestCalculatorThrottler(ThrottlerCalculator.ThrottlerName.Batching);
val nextDelay = suppliedDelays.iterator();
Consumer<Integer> recordDelay = delayMillis -> {
delays.add(delayMillis);
// 0 means we're done (no more throttling).
calculator.setDelayMillis(nextDelay.hasNext() ? nextDelay.next() : 0);
};
@Cleanup TestThrottler t = new TestThrottler(this.containerId, wrap(calculator), executorService(), metrics, recordDelay);
// Set a non-maximum delay and ask to throttle, then verify we throttled the correct amount.
calculator.setDelayMillis(nextDelay.next());
val t1 = t.throttle();
Assert.assertFalse("Not expected throttle future to be completed yet.", t1.isDone());
t.notifyThrottleSourceChanged();
TestUtils.await(t1::isDone, 5, TIMEOUT_MILLIS);
Assert.assertEquals("Last reported delay is equal to last supplied delay.", (int) suppliedDelays.get(0), (int) getThrottlerMetric(calculator.getName()));
}
use of java.util.Collections in project pravega by pravega.
the class ThrottlerTests method testInterruptedDelay.
/**
* Tests the case when {@link Throttler#throttle()} returns a delay that can be interrupted using {@link Throttler#notifyThrottleSourceChanged()}}.
*/
private void testInterruptedDelay(ThrottlerCalculator.ThrottlerName throttlerName) throws Exception {
val suppliedDelays = Arrays.asList(5000, 2500, 5000);
val delays = Collections.<Integer>synchronizedList(new ArrayList<>());
val calculator = new TestCalculatorThrottler(throttlerName);
val nextDelay = suppliedDelays.iterator();
Consumer<Integer> recordDelay = delayMillis -> {
delays.add(delayMillis);
// 0 means we're done (no more throttling).
calculator.setDelayMillis(nextDelay.hasNext() ? nextDelay.next() : 0);
};
@Cleanup TestThrottler t = new TestThrottler(this.containerId, wrap(calculator), executorService(), metrics, recordDelay);
// Set a non-maximum delay and ask to throttle, then verify we throttled the correct amount.
calculator.setDelayMillis(nextDelay.next());
val t1 = t.throttle();
Assert.assertFalse("Not expected throttle future to be completed yet.", t1.isDone());
// currently running throttle cycle and request the next throttling value.
for (int i = 1; i < suppliedDelays.size(); i++) {
// Interrupt the current throttle cycle.
t.notifyThrottleSourceChanged();
Assert.assertFalse("Not expected throttle future to be completed yet.", t1.isDone());
// Wait for the new cycle to begin (we use the recordDelay consumer above to figure this out).
int expectedDelayCount = i + 1;
TestUtils.await(() -> delays.size() == expectedDelayCount, 5, TIMEOUT_MILLIS);
}
// When we are done, complete the last throttle cycle and check final results.
t.completeDelayFuture();
TestUtils.await(t1::isDone, 5, TIMEOUT_MILLIS);
Assert.assertEquals("Unexpected number of delays recorded.", suppliedDelays.size(), delays.size());
Assert.assertEquals("Unexpected first delay value.", suppliedDelays.get(0), delays.get(0));
// runs and different environments. We can only check that they decrease in value (by design).
for (int i = 1; i < delays.size(); i++) {
AssertExtensions.assertLessThanOrEqual("Expected delays to be decreasing.", delays.get(i - 1), delays.get(i));
}
}
use of java.util.Collections in project alf.io by alfio-event.
the class EventApiV1Controller method insertEvent.
private Optional<Event> insertEvent(EventCreationRequest request, Principal user, String imageRef) {
Organization organization = userManager.findUserOrganizations(user.getName()).get(0);
EventModification em = request.toEventModification(organization, eventNameManager::generateShortName, imageRef);
eventManager.createEvent(em, user.getName());
Optional<Event> event = eventManager.getOptionalByName(em.getShortName(), user.getName());
event.ifPresent(e -> {
Optional.ofNullable(request.getTickets().getPromoCodes()).ifPresent(promoCodes -> promoCodes.forEach(// TODO add ref to categories
pc -> eventManager.addPromoCode(pc.getName(), e.getId(), organization.getId(), ZonedDateTime.of(pc.getValidFrom(), e.getZoneId()), ZonedDateTime.of(pc.getValidTo(), e.getZoneId()), pc.getDiscount(), pc.getDiscountType(), Collections.emptyList(), null, null, null, PromoCodeDiscount.CodeType.DISCOUNT, null)));
// link categories to groups, if any
request.getTickets().getCategories().stream().filter(cr -> cr.getGroupLink() != null && cr.getGroupLink().getGroupId() != null).map(cr -> Pair.of(cr, groupManager.findById(cr.getGroupLink().getGroupId(), organization.getId()))).forEach(link -> {
if (link.getRight().isPresent()) {
Group group = link.getRight().get();
EventCreationRequest.CategoryRequest categoryRequest = link.getLeft();
findCategoryByName(e, categoryRequest.getName()).ifPresent(category -> {
EventCreationRequest.GroupLinkRequest groupLinkRequest = categoryRequest.getGroupLink();
LinkedGroupModification modification = new LinkedGroupModification(null, group.getId(), e.getId(), category.getId(), groupLinkRequest.getType(), groupLinkRequest.getMatchType(), groupLinkRequest.getMaxAllocation());
groupManager.createLink(group.getId(), e.getId(), modification);
});
}
});
if (!CollectionUtils.isEmpty(request.getExtensionSettings())) {
request.getExtensionSettings().stream().collect(Collectors.groupingBy(EventCreationRequest.ExtensionSetting::getExtensionId)).forEach((id, settings) -> {
List<ExtensionSupport.ExtensionMetadataIdAndName> metadata = extensionService.getSingle(organization, e, id).map(es -> extensionRepository.findAllParametersForExtension(es.getId())).orElseGet(Collections::emptyList);
List<ExtensionMetadataValue> values = settings.stream().map(es -> Pair.of(es, metadata.stream().filter(mm -> mm.getName().equals(es.getKey())).findFirst())).filter(pair -> {
if (pair.getRight().isEmpty()) {
log.warn("ignoring non-existent extension setting key {}", pair.getLeft().getKey());
}
return pair.getRight().isPresent();
}).map(pair -> new ExtensionMetadataValue(pair.getRight().get().getId(), pair.getLeft().getValue())).collect(Collectors.toList());
extensionService.bulkUpdateEventSettings(organization, e, values);
});
}
});
return event;
}
use of java.util.Collections in project elasticsearch by elastic.
the class TermsQueryBuilder method convert.
/**
* Convert the list in a way that optimizes storage in the case that all
* elements are either integers or {@link String}s/{@link BytesRef}s. This
* is useful to help garbage collections for use-cases that involve sending
* very large terms queries to Elasticsearch. If the list does not only
* contain integers or {@link String}s, then a list is returned where all
* {@link String}s have been replaced with {@link BytesRef}s.
*/
static List<?> convert(List<?> list) {
if (list.isEmpty()) {
return Collections.emptyList();
}
final boolean allNumbers = list.stream().allMatch(o -> o != null && INTEGER_TYPES.contains(o.getClass()));
if (allNumbers) {
final long[] elements = list.stream().mapToLong(o -> ((Number) o).longValue()).toArray();
return new AbstractList<Object>() {
@Override
public Object get(int index) {
return elements[index];
}
@Override
public int size() {
return elements.length;
}
};
}
final boolean allStrings = list.stream().allMatch(o -> o != null && STRING_TYPES.contains(o.getClass()));
if (allStrings) {
final BytesRefBuilder builder = new BytesRefBuilder();
try (BytesStreamOutput bytesOut = new BytesStreamOutput()) {
final int[] endOffsets = new int[list.size()];
int i = 0;
for (Object o : list) {
BytesRef b;
if (o instanceof BytesRef) {
b = (BytesRef) o;
} else {
builder.copyChars(o.toString());
b = builder.get();
}
bytesOut.writeBytes(b.bytes, b.offset, b.length);
if (i == 0) {
endOffsets[0] = b.length;
} else {
endOffsets[i] = Math.addExact(endOffsets[i - 1], b.length);
}
++i;
}
final BytesReference bytes = bytesOut.bytes();
return new AbstractList<Object>() {
public Object get(int i) {
final int startOffset = i == 0 ? 0 : endOffsets[i - 1];
final int endOffset = endOffsets[i];
return bytes.slice(startOffset, endOffset - startOffset).toBytesRef();
}
public int size() {
return endOffsets.length;
}
};
}
}
return list.stream().map(o -> o instanceof String ? new BytesRef(o.toString()) : o).collect(Collectors.toList());
}
use of java.util.Collections in project torodb by torodb.
the class RecoveryService method cloneDatabases.
private void cloneDatabases(@Nonnull MongoClient remoteClient) throws CloningException, MongoException, UserException {
enableDataImportMode();
try {
Stream<String> dbNames;
try (MongoConnection remoteConnection = remoteClient.openConnection()) {
RemoteCommandResponse<ListDatabasesReply> remoteResponse = remoteConnection.execute(ListDatabasesCommand.INSTANCE, "admin", true, Empty.getInstance());
if (!remoteResponse.isOk()) {
throw remoteResponse.asMongoException();
}
dbNames = remoteResponse.getCommandReply().get().getDatabases().stream().map(db -> db.getName());
}
dbNames.filter(this::isReplicable).forEach(databaseName -> {
MyWritePermissionSupplier writePermissionSupplier = new MyWritePermissionSupplier(databaseName);
CloneOptions options = new CloneOptions(true, true, true, false, databaseName, Collections.<String>emptySet(), writePermissionSupplier, (colName) -> replFilters.getCollectionPredicate().test(databaseName, colName), (collection, indexName, unique, keys) -> replFilters.getIndexPredicate().test(databaseName, collection, indexName, unique, keys));
try {
cloner.cloneDatabase(databaseName, remoteClient, server, options);
} catch (MongoException ex) {
throw new CloningException(ex);
}
});
} finally {
disableDataImportMode();
}
}
Aggregations