use of java.util.function.Predicate in project pravega by pravega.
the class OperationMetadataUpdaterTests method testRollback.
/**
* Tests the ability to rollback update transactions.
*/
@Test
public void testRollback() throws Exception {
// 2 out of 3 UpdateTransactions are failed (to verify multi-failure).
// Commit the rest and verify final metadata is as it should.
final int failEvery = 3;
Predicate<Integer> isIgnored = index -> index % failEvery > 0;
Predicate<Integer> shouldFail = index -> index % failEvery == failEvery - 1;
val referenceMetadata = createBlankMetadata();
val metadata = createBlankMetadata();
val updater = new OperationMetadataUpdater(metadata);
val lastSegmentId = new AtomicLong(-1);
val lastSegmentTxnId = new AtomicLong(-1);
val updateTransactions = new ArrayList<Map.Entry<Long, ContainerMetadata>>();
for (int i = 0; i < TRANSACTION_COUNT; i++) {
// Check to see if this UpdateTransaction is going to end up being rolled back. If so, we should not update
// the reference metadata at all.
UpdateableContainerMetadata txnReferenceMetadata = isIgnored.test(i) ? null : referenceMetadata;
populateUpdateTransaction(updater, txnReferenceMetadata, lastSegmentId, lastSegmentTxnId);
if (shouldFail.test(i)) {
long prevUtId = updateTransactions.get(updateTransactions.size() - 1).getKey();
updater.rollback(prevUtId + 1);
} else if (txnReferenceMetadata != null) {
// Not failing and not ignored: this UpdateTransaction will survive, so record it.
long utId = updater.sealTransaction();
if (updateTransactions.size() > 0) {
long prevUtId = updateTransactions.get(updateTransactions.size() - 1).getKey();
Assert.assertEquals("Unexpected UpdateTransaction.Id.", prevUtId + failEvery - 1, utId);
}
updateTransactions.add(new AbstractMap.SimpleImmutableEntry<>(utId, clone(txnReferenceMetadata)));
}
}
ContainerMetadata previousMetadata = null;
for (val t : updateTransactions) {
val utId = t.getKey();
val expectedMetadata = t.getValue();
// Check to see if it's time to commit.
if (previousMetadata != null) {
// Verify no changes to the metadata prior to commit.
ContainerMetadataUpdateTransactionTests.assertMetadataSame("Before commit " + utId, previousMetadata, metadata);
}
// Commit and verify.
updater.commit(utId);
ContainerMetadataUpdateTransactionTests.assertMetadataSame("After commit " + utId, expectedMetadata, metadata);
previousMetadata = expectedMetadata;
}
}
use of java.util.function.Predicate in project pravega by pravega.
the class BookKeeperLogTests method testRemoveEmptyLedgers.
/**
* Tests the ability of BookKeeperLog to automatically remove empty ledgers during initialization.
*/
@Test
public void testRemoveEmptyLedgers() throws Exception {
final int count = 100;
final int writeEvery = count / 10;
final Predicate<Integer> shouldAppendAnything = i -> i % writeEvery == 0;
val allLedgers = new ArrayList<Map.Entry<Long, LedgerMetadata.Status>>();
final Predicate<Integer> shouldExist = index -> (index >= allLedgers.size() - Ledgers.MIN_FENCE_LEDGER_COUNT) || (allLedgers.get(index).getValue() != LedgerMetadata.Status.Empty);
for (int i = 0; i < count; i++) {
try (BookKeeperLog log = (BookKeeperLog) createDurableDataLog()) {
log.initialize(TIMEOUT);
boolean shouldAppend = shouldAppendAnything.test(i);
val currentMetadata = log.loadMetadata();
val lastLedger = currentMetadata.getLedgers().get(currentMetadata.getLedgers().size() - 1);
allLedgers.add(new AbstractMap.SimpleImmutableEntry<>(lastLedger.getLedgerId(), shouldAppend ? LedgerMetadata.Status.NotEmpty : LedgerMetadata.Status.Empty));
val metadataLedgers = currentMetadata.getLedgers().stream().map(LedgerMetadata::getLedgerId).collect(Collectors.toSet());
// Verify Log Metadata does not contain old empty ledgers.
for (int j = 0; j < allLedgers.size(); j++) {
val e = allLedgers.get(j);
val expectedExist = shouldExist.test(j);
Assert.assertEquals("Unexpected state for metadata. AllLedgerCount=" + allLedgers.size() + ", LedgerIndex=" + j + ", LedgerStatus=" + e.getValue(), expectedExist, metadataLedgers.contains(e.getKey()));
}
// Append some data to this Ledger, if needed.
if (shouldAppend) {
log.append(new ByteArraySegment(getWriteData()), TIMEOUT).get(TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
}
}
}
// Verify that these ledgers have also been deleted from BookKeeper.
for (int i = 0; i < allLedgers.size(); i++) {
val e = allLedgers.get(i);
if (shouldExist.test(i)) {
// This should not throw any exceptions.
Ledgers.openFence(e.getKey(), this.factory.get().getBookKeeperClient(), this.config.get());
} else {
AssertExtensions.assertThrows("Ledger not deleted from BookKeeper.", () -> Ledgers.openFence(e.getKey(), this.factory.get().getBookKeeperClient(), this.config.get()), ex -> true);
}
}
}
use of java.util.function.Predicate in project SpongeCommon by SpongePowered.
the class SelectorResolver method makeFilter.
private Predicate<Entity> makeFilter() {
// for easier reading
final Selector sel = this.selector;
Vector3d position = getPositionOrDefault(this.position, ArgumentTypes.POSITION);
List<Predicate<Entity>> filters = Lists.newArrayList();
addTypeFilters(filters);
addDimensionFilters(position, filters);
addRadiusFilters(position, filters);
addLevelFilters(filters);
addGamemodeFilters(filters);
addNameFilters(filters);
addRotationFilters(filters);
addTeamFilters(filters);
addScoreFilters(filters);
SelectorType selectorType = sel.getType();
Optional<Invertible<EntityType>> type = sel.getArgument(ArgumentTypes.ENTITY_TYPE);
// isn't an ALL_ENTITIES selector or it is a RANDOM selector for only players
boolean isPlayerOnlySelector = selectorType == SelectorTypes.ALL_PLAYERS || selectorType == SelectorTypes.NEAREST_PLAYER || (selectorType == SelectorTypes.RANDOM && type.isPresent() && !type.get().isInverted() && type.get().getValue() != EntityTypes.PLAYER);
if (isPlayerOnlySelector) {
// insert at the start so it applies first
filters.add(0, requireTypePredicate(Entity.class, Player.class));
}
return Functional.predicateAnd(filters);
}
use of java.util.function.Predicate in project alf.io by alfio-event.
the class EventApiController method downloadAllTicketsCSV.
@RequestMapping("/events/{eventName}/export.csv")
public void downloadAllTicketsCSV(@PathVariable("eventName") String eventName, HttpServletRequest request, HttpServletResponse response, Principal principal) throws IOException {
List<String> fields = Arrays.asList(Optional.ofNullable(request.getParameterValues("fields")).orElse(new String[] {}));
Event event = loadEvent(eventName, principal);
Map<Integer, TicketCategory> categoriesMap = eventManager.loadTicketCategories(event).stream().collect(Collectors.toMap(TicketCategory::getId, Function.identity()));
ZoneId eventZoneId = event.getZoneId();
Predicate<String> contains = FIXED_FIELDS::contains;
response.setContentType("text/csv;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + eventName + "-export.csv");
try (ServletOutputStream out = response.getOutputStream();
CSVWriter writer = new CSVWriter(new OutputStreamWriter(out))) {
for (int marker : BOM_MARKERS) {
// UGLY-MODE_ON: specify that the file is written in UTF-8 with BOM, thanks to alexr http://stackoverflow.com/a/4192897
out.write(marker);
}
writer.writeNext(fields.stream().map(f -> {
if (f.startsWith(CUSTOM_FIELDS_PREFIX)) {
return f.substring(CUSTOM_FIELDS_PREFIX.length());
}
return f;
}).toArray(String[]::new));
eventManager.findAllConfirmedTicketsForCSV(eventName, principal.getName()).stream().map(t -> {
List<String> line = new ArrayList<>();
if (fields.contains("ID")) {
line.add(t.getUuid());
}
if (fields.contains("Creation")) {
line.add(t.getCreation().withZoneSameInstant(eventZoneId).toString());
}
if (fields.contains("Category")) {
line.add(categoriesMap.get(t.getCategoryId()).getName());
}
if (fields.contains("Event")) {
line.add(eventName);
}
if (fields.contains("Status")) {
line.add(t.getStatus().toString());
}
if (fields.contains("OriginalPrice")) {
line.add(MonetaryUtil.centsToUnit(t.getSrcPriceCts()).toString());
}
if (fields.contains("PaidPrice")) {
line.add(MonetaryUtil.centsToUnit(t.getFinalPriceCts()).toString());
}
if (fields.contains("Discount")) {
line.add(MonetaryUtil.centsToUnit(t.getDiscountCts()).toString());
}
if (fields.contains("VAT")) {
line.add(MonetaryUtil.centsToUnit(t.getVatCts()).toString());
}
if (fields.contains("ReservationID")) {
line.add(t.getTicketsReservationId());
}
if (fields.contains("Full Name")) {
line.add(t.getFullName());
}
if (fields.contains("First Name")) {
line.add(t.getFirstName());
}
if (fields.contains("Last Name")) {
line.add(t.getLastName());
}
if (fields.contains("E-Mail")) {
line.add(t.getEmail());
}
if (fields.contains("Locked")) {
line.add(String.valueOf(t.getLockedAssignment()));
}
if (fields.contains("Language")) {
line.add(String.valueOf(t.getUserLanguage()));
}
if (fields.contains("Confirmation")) {
line.add(t.getTicketReservation().getConfirmationTimestamp().withZoneSameInstant(eventZoneId).toString());
}
if (fields.contains("Billing Address")) {
line.add(t.getTicketReservation().getBillingAddress());
}
// obviously not optimized
Map<String, String> additionalValues = ticketFieldRepository.findAllValuesForTicketId(t.getId());
fields.stream().filter(contains.negate()).filter(f -> f.startsWith(CUSTOM_FIELDS_PREFIX)).forEachOrdered(field -> {
String customFieldName = field.substring(CUSTOM_FIELDS_PREFIX.length());
line.add(additionalValues.getOrDefault(customFieldName, "").replaceAll("\"", ""));
});
return line.toArray(new String[line.size()]);
}).forEachOrdered(writer::writeNext);
writer.flush();
out.flush();
}
}
use of java.util.function.Predicate in project kie-wb-common by kiegroup.
the class BaseExpressionGrid method executeRenderQueueCommands.
@Override
protected void executeRenderQueueCommands(final boolean isSelectionLayer) {
final List<Pair<Group, GridRenderer.RendererCommand>> gridLineCommands = new ArrayList<>();
final List<Pair<Group, GridRenderer.RendererCommand>> allOtherCommands = new ArrayList<>();
final List<Pair<Group, GridRenderer.RendererCommand>> selectedCellsCommands = new ArrayList<>();
for (Pair<Group, List<GridRenderer.RendererCommand>> p : renderQueue) {
final Group parent = p.getK1();
final List<GridRenderer.RendererCommand> commands = p.getK2();
for (GridRenderer.RendererCommand command : commands) {
if (command instanceof GridRenderer.RenderSelectedCellsCommand) {
selectedCellsCommands.add(new Pair<>(parent, command));
} else if (command instanceof GridRenderer.RenderHeaderGridLinesCommand) {
gridLineCommands.add(new Pair<>(parent, command));
} else if (command instanceof GridRenderer.RenderBodyGridLinesCommand) {
gridLineCommands.add(new Pair<>(parent, command));
} else {
allOtherCommands.add(new Pair<>(parent, command));
}
}
}
final Predicate<Pair<Group, GridRenderer.RendererCommand>> renderHeader = (p) -> {
final GridRenderer.RendererCommand command = p.getK2();
if (isHeaderHidden()) {
return !(command instanceof GridRenderer.RendererHeaderCommand);
}
return true;
};
renderQueue.clear();
allOtherCommands.stream().filter(renderHeader).forEach(p -> addCommandToRenderQueue(p.getK1(), p.getK2()));
gridLineCommands.stream().filter(renderHeader).forEach(p -> addCommandToRenderQueue(p.getK1(), p.getK2()));
selectedCellsCommands.stream().filter(renderHeader).forEach(p -> addCommandToRenderQueue(p.getK1(), p.getK2()));
super.executeRenderQueueCommands(isSelectionLayer);
}
Aggregations