use of org.apache.commons.lang3.tuple.Triple in project alf.io by alfio-event.
the class WaitingQueueManagerIntegrationTest method testAssignTicketToWaitingQueueBoundedCategory.
@Test
public void testAssignTicketToWaitingQueueBoundedCategory() {
LocalDateTime start = LocalDateTime.now().minusMinutes(2);
LocalDateTime end = LocalDateTime.now().plusMinutes(20);
List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null, "default", AVAILABLE_SEATS, new DateTimeModification(start.toLocalDate(), start.toLocalTime()), new DateTimeModification(end.toLocalDate(), end.toLocalTime()), DESCRIPTION, BigDecimal.TEN, false, "", true, null, null, null, null, null));
configurationManager.saveSystemConfiguration(ConfigurationKeys.ENABLE_WAITING_QUEUE, "true");
Event event = initEvent(categories, organizationRepository, userManager, eventManager, eventRepository).getKey();
TicketCategory bounded = ticketCategoryRepository.findByEventId(event.getId()).get(0);
TicketReservationModification tr = new TicketReservationModification();
tr.setAmount(AVAILABLE_SEATS - 1);
tr.setTicketCategoryId(bounded.getId());
TicketReservationModification tr2 = new TicketReservationModification();
tr2.setAmount(1);
tr2.setTicketCategoryId(bounded.getId());
TicketReservationWithOptionalCodeModification multi = new TicketReservationWithOptionalCodeModification(tr, Optional.empty());
TicketReservationWithOptionalCodeModification single = new TicketReservationWithOptionalCodeModification(tr2, Optional.empty());
String reservationId = ticketReservationManager.createTicketReservation(event, Collections.singletonList(multi), Collections.emptyList(), DateUtils.addDays(new Date(), 1), Optional.empty(), Optional.empty(), Locale.ENGLISH, false);
TotalPrice reservationCost = ticketReservationManager.totalReservationCostWithVAT(reservationId);
PaymentResult result = ticketReservationManager.confirm("", null, event, reservationId, "test@test.ch", new CustomerName("Full Name", "Full", "Name", event), Locale.ENGLISH, "", reservationCost, Optional.empty(), Optional.of(PaymentProxy.OFFLINE), false, null, null, null);
assertTrue(result.isSuccessful());
String reservationIdSingle = ticketReservationManager.createTicketReservation(event, Collections.singletonList(single), Collections.emptyList(), DateUtils.addDays(new Date(), 1), Optional.empty(), Optional.empty(), Locale.ENGLISH, false);
TotalPrice reservationCostSingle = ticketReservationManager.totalReservationCostWithVAT(reservationIdSingle);
PaymentResult resultSingle = ticketReservationManager.confirm("", null, event, reservationIdSingle, "test@test.ch", new CustomerName("Full Name", "Full", "Name", event), Locale.ENGLISH, "", reservationCostSingle, Optional.empty(), Optional.of(PaymentProxy.OFFLINE), false, null, null, null);
assertTrue(resultSingle.isSuccessful());
assertEquals(0, eventRepository.findStatisticsFor(event.getId()).getDynamicAllocation());
assertTrue(waitingQueueManager.subscribe(event, customerJohnDoe(event), "john@doe.com", null, Locale.ENGLISH));
ticketReservationManager.deleteOfflinePayment(event, reservationIdSingle, false);
List<Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime>> subscriptions = waitingQueueManager.distributeSeats(event).collect(Collectors.toList());
assertEquals(1, subscriptions.size());
Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime> subscriptionDetail = subscriptions.get(0);
assertEquals("john@doe.com", subscriptionDetail.getLeft().getEmailAddress());
TicketReservationWithOptionalCodeModification reservation = subscriptionDetail.getMiddle();
assertEquals(Integer.valueOf(bounded.getId()), reservation.getTicketCategoryId());
assertEquals(Integer.valueOf(1), reservation.getAmount());
assertTrue(subscriptionDetail.getRight().isAfter(ZonedDateTime.now()));
}
use of org.apache.commons.lang3.tuple.Triple in project alf.io by alfio-event.
the class WaitingQueueManager method distributeAvailableSeats.
private Stream<Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime>> distributeAvailableSeats(Event event, Ticket.TicketStatus status, Supplier<Integer> availableSeatSupplier) {
int availableSeats = availableSeatSupplier.get();
int eventId = event.getId();
log.debug("processing {} subscribers from waiting queue", availableSeats);
List<TicketCategory> unboundedCategories = ticketCategoryRepository.findUnboundedOrderByExpirationDesc(eventId);
Iterator<Ticket> tickets = ticketRepository.selectWaitingTicketsForUpdate(eventId, status.name(), availableSeats).stream().filter(t -> t.getCategoryId() != null || unboundedCategories.size() > 0).iterator();
int expirationTimeout = configurationManager.getIntConfigValue(Configuration.from(event.getOrganizationId(), event.getId(), WAITING_QUEUE_RESERVATION_TIMEOUT), 4);
ZonedDateTime expiration = ZonedDateTime.now(event.getZoneId()).plusHours(expirationTimeout).with(WorkingDaysAdjusters.defaultWorkingDays());
if (!tickets.hasNext()) {
log.warn("Unable to assign tickets, returning an empty stream");
return Stream.empty();
}
return waitingQueueRepository.loadWaiting(eventId, availableSeats).stream().map(wq -> Pair.of(wq, tickets.next())).map(pair -> {
TicketReservationModification ticketReservation = new TicketReservationModification();
ticketReservation.setAmount(1);
Integer categoryId = Optional.ofNullable(pair.getValue().getCategoryId()).orElseGet(() -> findBestCategory(unboundedCategories, pair.getKey()).orElseThrow(RuntimeException::new).getId());
ticketReservation.setTicketCategoryId(categoryId);
return Pair.of(pair.getLeft(), new TicketReservationWithOptionalCodeModification(ticketReservation, Optional.<SpecialPrice>empty()));
}).map(pair -> Triple.of(pair.getKey(), pair.getValue(), expiration));
}
use of org.apache.commons.lang3.tuple.Triple in project alf.io by alfio-event.
the class CustomMessageManager method sendMessages.
public void sendMessages(String eventName, Optional<Integer> categoryId, List<MessageModification> input, String username) {
Event event = eventManager.getSingleEvent(eventName, username);
// dry run for checking the syntax
preview(event, input, username);
Organization organization = eventManager.loadOrganizer(event, username);
AtomicInteger counter = new AtomicInteger();
Map<String, List<MessageModification>> byLanguage = input.stream().collect(Collectors.groupingBy(m -> m.getLocale().getLanguage()));
sendMessagesExecutor.execute(() -> {
categoryId.map(id -> ticketRepository.findConfirmedByCategoryId(event.getId(), id)).orElseGet(() -> ticketRepository.findAllConfirmed(event.getId())).stream().filter(t -> isNotBlank(t.getFullName()) && isNotBlank(t.getEmail())).parallel().map(t -> {
Model model = new ExtendedModelMap();
model.addAttribute("eventName", eventName);
model.addAttribute("fullName", t.getFullName());
model.addAttribute("organizationName", organization.getName());
model.addAttribute("organizationEmail", organization.getEmail());
model.addAttribute("reservationURL", ticketReservationManager.reservationUrl(t.getTicketsReservationId(), event));
model.addAttribute("reservationID", ticketReservationManager.getShortReservationID(event, t.getTicketsReservationId()));
model.addAttribute("ticketURL", ticketReservationManager.ticketUpdateUrl(event, t.getUuid()));
return Triple.of(t, t.getEmail(), model);
}).forEach(triple -> {
Ticket ticket = triple.getLeft();
MessageModification m = Optional.ofNullable(byLanguage.get(ticket.getUserLanguage())).orElseGet(() -> byLanguage.get(byLanguage.keySet().stream().findFirst().orElseThrow(IllegalStateException::new))).get(0);
Model model = triple.getRight();
String subject = renderResource(m.getSubject(), model, m.getLocale(), templateManager);
String text = renderResource(m.getText(), model, m.getLocale(), templateManager);
List<Mailer.Attachment> attachments = new ArrayList<>();
if (m.isAttachTicket()) {
ticketReservationManager.findById(ticket.getTicketsReservationId()).ifPresent(reservation -> {
ticketCategoryRepository.getByIdAndActive(ticket.getCategoryId()).ifPresent(ticketCategory -> {
attachments.add(generateTicketAttachment(ticket, reservation, ticketCategory, organization));
});
});
}
counter.incrementAndGet();
notificationManager.sendSimpleEmail(event, triple.getMiddle(), subject, () -> text, attachments);
});
});
}
use of org.apache.commons.lang3.tuple.Triple in project alf.io by alfio-event.
the class AdminReservationManagerIntegrationTest method performExistingCategoryTest.
private Triple<Event, String, TicketReservation> performExistingCategoryTest(List<TicketCategoryModification> categories, boolean bounded, List<Integer> attendeesNr, boolean addSeatsIfNotAvailable, boolean expectSuccess, int reservedTickets, int expectedEventSeats) {
assertEquals("Test error: categories' size must be equal to attendees' size", categories.size(), attendeesNr.size());
Pair<Event, String> eventWithUsername = initEvent(categories, organizationRepository, userManager, eventManager, eventRepository);
Event event = eventWithUsername.getKey();
String username = eventWithUsername.getValue();
DateTimeModification expiration = DateTimeModification.fromZonedDateTime(ZonedDateTime.now().plusDays(1));
CustomerData customerData = new CustomerData("Integration", "Test", "integration-test@test.ch", "Billing Address", "en");
Iterator<Integer> attendeesIterator = attendeesNr.iterator();
List<TicketCategory> existingCategories = ticketCategoryRepository.findByEventId(event.getId());
List<Attendee> allAttendees = new ArrayList<>();
List<TicketsInfo> ticketsInfoList = existingCategories.stream().map(existingCategory -> {
Category category = new Category(existingCategory.getId(), existingCategory.getName(), existingCategory.getPrice());
List<Attendee> attendees = generateAttendees(attendeesIterator.next());
allAttendees.addAll(attendees);
return new TicketsInfo(category, attendees, addSeatsIfNotAvailable, false);
}).collect(toList());
AdminReservationModification modification = new AdminReservationModification(expiration, customerData, ticketsInfoList, "en", false, null);
if (reservedTickets > 0) {
TicketReservationModification trm = new TicketReservationModification();
trm.setAmount(reservedTickets);
trm.setTicketCategoryId(existingCategories.get(0).getId());
TicketReservationWithOptionalCodeModification r = new TicketReservationWithOptionalCodeModification(trm, Optional.empty());
ticketReservationManager.createTicketReservation(event, Collections.singletonList(r), Collections.emptyList(), DateUtils.addDays(new Date(), 1), Optional.empty(), Optional.empty(), Locale.ENGLISH, false);
}
Result<Pair<TicketReservation, List<Ticket>>> result = adminReservationManager.createReservation(modification, event.getShortName(), username);
if (expectSuccess) {
validateSuccess(bounded, attendeesNr, event, username, existingCategories, result, allAttendees, expectedEventSeats, reservedTickets);
} else {
assertFalse(result.isSuccess());
return null;
}
return Triple.of(eventWithUsername.getLeft(), eventWithUsername.getRight(), result.getData().getKey());
}
use of org.apache.commons.lang3.tuple.Triple in project graal by graphik-team.
the class ChaseWithGRDAndUnfiers method next.
// /////////////////////////////////////////////////////////////////////////
// METHODS
// /////////////////////////////////////////////////////////////////////////
@Override
public void next() throws ChaseException {
Rule rule, unifiedRule;
Substitution unificator;
Queue<Triple<Rule, Substitution, InMemoryAtomSet>> newQueue = new LinkedList<Triple<Rule, Substitution, InMemoryAtomSet>>();
InMemoryAtomSet newAtomSet = new DefaultInMemoryGraphStore();
try {
while (!queue.isEmpty()) {
Triple<Rule, Substitution, InMemoryAtomSet> pair = queue.poll();
if (pair != null) {
unificator = pair.getMiddle();
InMemoryAtomSet part = pair.getRight();
rule = pair.getLeft();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("\nExecute rule: {} with unificator {}", rule, unificator);
}
unifiedRule = DefaultUnifierAlgorithm.getTargetVariablesSubstitution().createImageOf(rule);
unifiedRule = unificator.createImageOf(unifiedRule);
unifiedRule.getBody().removeAll(part);
unificator = targetToSource(unificator);
ConjunctiveQuery query = DefaultConjunctiveQueryFactory.instance().create(unifiedRule.getBody(), new LinkedList<Term>(unifiedRule.getFrontier()));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Rule to execute: {}", unifiedRule.toString());
LOGGER.debug(" -- Query: {}", query.toString());
}
// Get projections
List<Substitution> projections = Iterators.toList(SmartHomomorphism.instance().execute(query, atomSet));
try {
for (Substitution proj : projections) {
InMemoryAtomSet newFacts = proj.createImageOf(unifiedRule.getHead());
ConjunctiveQuery q = new DefaultConjunctiveQuery(newFacts);
if (!SmartHomomorphism.instance().execute(q, newAtomSet).hasNext()) {
// Existential variables instantiation added to proj
CloseableIterator<Atom> it = hc.apply(unifiedRule, proj, atomSet);
if (it.hasNext()) {
LinkedListAtomSet foundPart = new LinkedListAtomSet();
foundPart.addAll(it);
newAtomSet.addAll(foundPart);
// Makes the projection compatible with triggered rules unifiers
Substitution compatibleProj = targetToSource(proj);
for (Pair<Rule, Substitution> p : this.grd.getTriggeredRulesWithUnifiers(rule)) {
Rule triggeredRule = p.getKey();
Substitution u = p.getValue();
if (u != null) {
Substitution comp = unificator.compose(u);
Substitution aggreg = compatibleProj.aggregate(comp);
aggreg = forgetSource(aggreg);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("-- -- Dependency: {}", triggeredRule);
LOGGER.debug("-- -- Substitution:{} ", compatibleProj);
LOGGER.debug("-- -- Unificator: {}", u);
LOGGER.debug("-- -- Aggregation: {}\n", aggreg);
}
if (aggreg != null) {
newQueue.add(new ImmutableTriple<Rule, Substitution, InMemoryAtomSet>(triggeredRule, aggreg, foundPart));
}
}
}
}
}
}
} catch (HomomorphismFactoryException e) {
throw new RuleApplicationException("Error during rule application", e);
} catch (HomomorphismException e) {
throw new RuleApplicationException("Error during rule application", e);
} catch (IteratorException e) {
throw new RuleApplicationException("Error during rule application", e);
}
}
}
queue = newQueue;
atomSet.addAll(newAtomSet);
} catch (Exception e) {
e.printStackTrace();
throw new ChaseException("An error occur pending saturation step.", e);
}
}
Aggregations