Skip to content

Commit

Permalink
#56 align all the configuration manager call to the same configuratio…
Browse files Browse the repository at this point in the history
…n path
  • Loading branch information
syjer committed Jul 13, 2015
1 parent 368924c commit d72a5d9
Show file tree
Hide file tree
Showing 25 changed files with 322 additions and 149 deletions.
2 changes: 1 addition & 1 deletion src/main/java/alfio/config/ConfigurationStatusChecker.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public ConfigurationStatusChecker(ConfigurationManager configurationManager,

@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
boolean initCompleted = configurationManager.getBooleanConfigValue(Configuration.system(), INIT_COMPLETED, false);
boolean initCompleted = configurationManager.getBooleanConfigValue(Configuration.initCompleted(), false);
if (!initCompleted) {
String adminPassword = PasswordGenerator.generateRandomPassword();
userRepository.create(UserManager.ADMIN_USERNAME, passwordEncoder.encode(adminPassword), "The", "Administrator", "admin@localhost", true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public DynamicResourcesController(ConfigurationManager configurationManager) {
@RequestMapping("/resources/js/google-analytics")
public void getGoogleAnalyticsScript(HttpServletResponse response) throws IOException {
response.setContentType("application/javascript");
final Optional<String> id = configurationManager.getStringConfigValue(Configuration.system(), ConfigurationKeys.GOOGLE_ANALYTICS_KEY);
final Optional<String> id = configurationManager.getStringConfigValue(Configuration.googleAnalyticsKey());
response.getWriter().write(id.map(x -> String.format(GOOGLE_ANALYTICS_SCRIPT, x)).orElse(EMPTY));
}
}
4 changes: 2 additions & 2 deletions src/main/java/alfio/controller/EventController.java
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ public String showEvent(@PathVariable("eventName") String eventName,
.flatMap((code) -> optionally(() -> promoCodeRepository.findPromoCodeInEvent(event.getId(), code)));

final ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
final int maxTickets = configurationManager.getIntConfigValue(Configuration.event(event), MAX_AMOUNT_OF_TICKETS_BY_RESERVATION, 5);
final int maxTickets = configurationManager.getIntConfigValue(Configuration.maxAmountOfTicketsByReservation(event), 5);
//hide access restricted ticket categories
List<SaleableTicketCategory> ticketCategories = ticketCategoryRepository.findAllTicketCategories(event.getId()).stream()
.filter((c) -> !c.isAccessRestricted() || (specialCode.isPresent() && specialCode.get().getTicketCategoryId() == c.getId()))
Expand All @@ -189,7 +189,7 @@ public String showEvent(@PathVariable("eventName") String eventName,


LocationDescriptor ld = LocationDescriptor.fromGeoData(event.getLatLong(), TimeZone.getTimeZone(event.getTimeZone()),
configurationManager.getStringConfigValue(Configuration.event(event), MAPS_CLIENT_API_KEY));
configurationManager.getStringConfigValue(Configuration.mapsClientApiKey()));

final boolean hasAccessPromotions = ticketCategoryRepository.countAccessRestrictedRepositoryByEventId(event.getId()) > 0 ||
promoCodeRepository.countByEventId(event.getId()) > 0;
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/alfio/controller/ReservationController.java
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ public String showConfirmationPage(@PathVariable("eventName") String eventName,

Event ev = event.get();

boolean enableFreeCancellation = configurationManager.getBooleanConfigValue(Configuration.event(ev), ConfigurationKeys.ALLOW_FREE_TICKETS_CANCELLATION, false);
boolean enableFreeCancellation = configurationManager.getBooleanConfigValue(Configuration.allowFreeTicketsCancellation(ev), false);
model.addAttribute(
"ticketsByCategory",
tickets.stream().collect(Collectors.groupingBy(Ticket::getCategoryId)).entrySet().stream()
Expand Down Expand Up @@ -272,7 +272,7 @@ public String showWaitingPaymentPage(@PathVariable("eventName") String eventName
model.addAttribute("reservation", ticketReservation);
model.addAttribute("paymentReason", ev.getShortName() + " " + ticketReservationManager.getShortReservationID(reservationId));
model.addAttribute("pageTitle", "reservation-page-waiting.header.title");
model.addAttribute("bankAccount", configurationManager.getStringConfigValue(Configuration.event(ev), ConfigurationKeys.BANK_ACCOUNT_NR).orElse(""));
model.addAttribute("bankAccount", configurationManager.getStringConfigValue(Configuration.bankAccountNr(ev)).orElse(""));
model.addAttribute("expires", ZonedDateTime.ofInstant(ticketReservation.getValidity().toInstant(), ev.getZoneId()));
model.addAttribute("event", ev);
return "/event/reservation-waiting-for-payment";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import java.util.Optional;
import java.util.TimeZone;

import static alfio.model.system.ConfigurationKeys.MAPS_CLIENT_API_KEY;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
Expand Down Expand Up @@ -66,7 +65,7 @@ public LocationDescriptor geocodeAddress(@RequestParam("location") String addres
}

private Optional<String> getMapsClientApiKey() {
return configurationManager.getStringConfigValue(Configuration.system(), MAPS_CLIENT_API_KEY);
return configurationManager.getStringConfigValue(Configuration.mapsClientApiKey());
}

@RequestMapping(value = "/location/map", method = GET)
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/alfio/manager/EventManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,7 @@ public List<PromoCodeDiscountWithFormattedTime> findPromoCodesInEvent(int eventI
}

public String getEventUrl(Event event) {
return StringUtils.removeEnd(configurationManager.getRequiredValue(Configuration.event(event), ConfigurationKeys.BASE_URL), "/") + "/event/" + event.getShortName() + "/";
return StringUtils.removeEnd(configurationManager.getRequiredValue(Configuration.baseUrl(event)), "/") + "/event/" + event.getShortName() + "/";
}

public List<Ticket> findAllConfirmedTickets(String eventName, String username) {
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/alfio/manager/NotificationManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public void sendSimpleEmail(Event event, String recipient, String subject, Strin
}

void sendWaitingMessages() {
Set<EmailMessage> toBeSent = messages.poll(configurationManager.getIntConfigValue(Configuration.system(), ConfigurationKeys.MAX_EMAIL_PER_CYCLE, 10));
Set<EmailMessage> toBeSent = messages.poll(configurationManager.getIntConfigValue(Configuration.maxEmailPerCycle(), 10));
toBeSent.forEach(m -> {
try {
processMessage(m);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ void generatePendingCodes() {
private void generateCode(SpecialPrice specialPrice) {

//TODO: get Event from categoryId present in specialPrice
int maxLength = configurationManager.getIntConfigValue(Configuration.system(), ConfigurationKeys.SPECIAL_PRICE_CODE_LENGTH, 6);
int maxLength = configurationManager.getIntConfigValue(Configuration.specialPriceCodeLength(), 6);

while (true) {
try {
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/alfio/manager/StripeManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,11 @@ public StripeManager(ConfigurationManager configurationManager,
}

private String getSecretKey(Event event) {
return configurationManager.getRequiredValue(Configuration.event(event), STRIPE_SECRET_KEY);
return configurationManager.getRequiredValue(Configuration.stripeSecretKey(event));
}

public String getPublicKey(Event event) {
return configurationManager.getRequiredValue(Configuration.event(event), STRIPE_PUBLIC_KEY);
return configurationManager.getRequiredValue(Configuration.stripePublicKey(event));
}

/**
Expand Down
32 changes: 18 additions & 14 deletions src/main/java/alfio/manager/TicketReservationManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import alfio.model.modification.TicketReservationWithOptionalCodeModification;
import alfio.model.modification.TicketWithStatistic;
import alfio.model.system.Configuration;
import alfio.model.system.ConfigurationKeys;
import alfio.model.transaction.PaymentProxy;
import alfio.model.user.Organization;
import alfio.repository.*;
Expand Down Expand Up @@ -383,7 +382,7 @@ public static int getOfflinePaymentWaitingPeriod(Event event, ConfigurationManag
ZonedDateTime eventBegin = event.getBegin();
int daysToBegin = Period.between(now.toLocalDate(), eventBegin.toLocalDate()).getDays();
Validate.isTrue(daysToBegin >= 0, "Cannot confirm an offline reservation after event start");
int waitingPeriod = configurationManager.getIntConfigValue(Configuration.event(event), OFFLINE_PAYMENT_DAYS, 5);
int waitingPeriod = configurationManager.getIntConfigValue(Configuration.offlinePaymentDays(event), 5);
return Math.min(daysToBegin, waitingPeriod);
}

Expand Down Expand Up @@ -607,18 +606,18 @@ public String reservationUrl(String reservationId) {
}

public String reservationUrl(String reservationId, Event event) {
return StringUtils.removeEnd(configurationManager.getRequiredValue(Configuration.event(event), ConfigurationKeys.BASE_URL), "/")
return StringUtils.removeEnd(configurationManager.getRequiredValue(Configuration.baseUrl(event)), "/")
+ "/event/" + event.getShortName() + "/reservation/" + reservationId;
}

public String ticketUrl(String reservationId, Event event, String ticketId) {
return StringUtils.removeEnd(configurationManager.getRequiredValue(Configuration.event(event), ConfigurationKeys.BASE_URL), "/")
return StringUtils.removeEnd(configurationManager.getRequiredValue(Configuration.baseUrl(event)), "/")
+ "/event/" + event.getShortName() + "/reservation/" + reservationId+ "/" + ticketId;
}


public int maxAmountOfTickets(Event event) {
return configurationManager.getIntConfigValue(Configuration.event(event), ConfigurationKeys.MAX_AMOUNT_OF_TICKETS_BY_RESERVATION, 5);
return configurationManager.getIntConfigValue(Configuration.maxAmountOfTicketsByReservation(event), 5);
}

public Optional<TicketReservation> findById(String reservationId) {
Expand Down Expand Up @@ -692,7 +691,7 @@ public List<Ticket> findTicketsInReservation(String reservationId) {
}

public Optional<String> getVAT() {
return configurationManager.getStringConfigValue(Configuration.system(), ConfigurationKeys.VAT_NR);
return configurationManager.getStringConfigValue(Configuration.vatNr());
}

public void updateTicketOwner(Ticket ticket,
Expand Down Expand Up @@ -786,7 +785,7 @@ public List<Pair<TicketReservation, OrderSummary>> fetchWaitingForPayment(List<S
}

void sendReminderForOfflinePayments() {
Date expiration = truncate(addHours(new Date(), configurationManager.getIntConfigValue(Configuration.system(), OFFLINE_REMINDER_HOURS, 24)), Calendar.DATE);
Date expiration = truncate(addHours(new Date(), configurationManager.getIntConfigValue(Configuration.offlineReminderHours(), 24)), Calendar.DATE);
ticketReservationRepository.findAllOfflinePaymentReservationForNotification(expiration).stream()
.map(reservation -> {
Optional<Ticket> ticket = ticketRepository.findTicketsInReservation(reservation.getId()).stream().findFirst();
Expand All @@ -808,9 +807,9 @@ void sendReminderForOfflinePayments() {
}

void sendReminderForTicketAssignment() {
int daysBeforeStart = configurationManager.getIntConfigValue(Configuration.system(), ASSIGNMENT_REMINDER_START, 10);
eventRepository.findAll().stream()
.filter(e -> {
int daysBeforeStart = configurationManager.getIntConfigValue(Configuration.assignmentReminderStart(e), 10);
int days = Period.between(ZonedDateTime.now(e.getZoneId()).toLocalDate(), e.getBegin().toLocalDate()).getDays();
return days > 0 && days <= daysBeforeStart;
})
Expand All @@ -824,7 +823,7 @@ private void sendAssignmentReminder(Pair<Event, List<String>> p) {
requiresNewTransactionTemplate.execute(status -> {
Event event = p.getLeft();
ZoneId eventZoneId = event.getZoneId();
int quietPeriod = configurationManager.getIntConfigValue(Configuration.event(event), ConfigurationKeys.ASSIGNMENT_REMINDER_INTERVAL, 3);
int quietPeriod = configurationManager.getIntConfigValue(Configuration.assignmentReminderInterval(event), 3);
p.getRight().stream()
.map(id -> findByIdForNotification(id, eventZoneId, quietPeriod))
.filter(Optional::isPresent)
Expand Down Expand Up @@ -853,7 +852,7 @@ public TicketReservation findByPartialID(String reservationId) {
}

public String getShortReservationID(String reservationId) {
return StringUtils.substring(reservationId, 0, configurationManager.getIntConfigValue(Configuration.system(), PARTIAL_RESERVATION_ID_LENGTH, 8)).toUpperCase();
return StringUtils.substring(reservationId, 0, configurationManager.getIntConfigValue(Configuration.partialReservationIdLength(), 8)).toUpperCase();
}

public int countAvailableTickets(Event event, TicketCategory category) {
Expand All @@ -879,16 +878,21 @@ public void releaseTicket(Event event, TicketReservation ticketReservation, Tick
model.put("ticket", ticket);
model.put("organization", organization);
Locale locale = Locale.forLanguageTag(Optional.ofNullable(ticket.getUserLanguage()).orElse("en"));
notificationManager.sendSimpleEmail(event, ticket.getEmail(), messageSource.getMessage("email-ticket-released.subject", new Object[]{event.getShortName()}, locale), () -> templateManager.renderClassPathResource("/alfio/templates/ticket-has-been-cancelled-txt.ms", model, locale, TemplateOutput.TEXT));
String adminTemplate = messageSource.getMessage("email-ticket-released.admin.text", new Object[] {ticket.getId(), ticket.getUuid(), ticket.getFullName(), ticket.getEmail(), category.getDescription(), category.getId()}, Locale.ENGLISH);
notificationManager.sendSimpleEmail(event, organization.getEmail(), messageSource.getMessage("email-ticket-released.admin.subject", new Object[]{ticket.getId(), event.getShortName()}, locale), () -> templateManager.renderString(adminTemplate, model, Locale.ENGLISH, TemplateOutput.TEXT));
notificationManager.sendSimpleEmail(event, ticket.getEmail(), messageSource.getMessage("email-ticket-released.subject",
new Object[]{event.getShortName()}, locale),
() -> templateManager.renderClassPathResource("/alfio/templates/ticket-has-been-cancelled-txt.ms", model, locale, TemplateOutput.TEXT));
String adminTemplate = messageSource.getMessage("email-ticket-released.admin.text",
new Object[] {ticket.getId(), ticket.getUuid(), ticket.getFullName(), ticket.getEmail(), category.getDescription(), category.getId()}, Locale.ENGLISH);
notificationManager.sendSimpleEmail(event, organization.getEmail(), messageSource.getMessage("email-ticket-released.admin.subject",
new Object[]{ticket.getId(), event.getShortName()}, locale),
() -> templateManager.renderString(adminTemplate, model, Locale.ENGLISH, TemplateOutput.TEXT));
if(ticketRepository.countTicketsInReservation(ticketReservation.getId()) == 0) {
deleteReservations(singletonList(ticketReservation.getId()));
}
}

public int getReservationTimeout(Event event) {
return configurationManager.getIntConfigValue(Configuration.event(event), RESERVATION_TIMEOUT, 25);
return configurationManager.getIntConfigValue(Configuration.reservationTimeout(event), 25);
}

public void validateAndConfirmOfflinePayment(String reservationId, Event event, BigDecimal paidAmount) {
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/alfio/manager/WaitingQueueManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ Stream<Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModific
ticketRepository.revertToFree(eventId);
} else if (waitingPeople > 0 && waitingTickets > 0) {
return distributeAvailableSeats(event, waitingPeople, waitingTickets);
} else if(configurationManager.getBooleanConfigValue(Configuration.event(event), ConfigurationKeys.ENABLE_PRE_REGISTRATION, false)) {
} else if(configurationManager.getBooleanConfigValue(Configuration.enablePreRegistration(event), false)) {
return handlePreReservation(event, waitingPeople, waitingTickets);
}
return Stream.empty();
Expand Down Expand Up @@ -159,7 +159,7 @@ private Stream<Triple<WaitingQueueSubscription, TicketReservationWithOptionalCod
log.debug("processing {} subscribers from waiting queue", availableSeats);
Iterator<Ticket> tickets = ticketRepository.selectWaitingTicketsForUpdate(eventId, status.name(), availableSeats).iterator();
Optional<TicketCategory> unboundedCategory = ticketCategoryRepository.findUnboundedOrderByExpirationDesc(eventId).stream().findFirst();
int expirationTimeout = configurationManager.getIntConfigValue(Configuration.event(event), ConfigurationKeys.WAITING_QUEUE_RESERVATION_TIMEOUT, 4);
int expirationTimeout = configurationManager.getIntConfigValue(Configuration.waitingQueueReservationTimeout(event), 4);
ZonedDateTime expiration = ZonedDateTime.now(event.getZoneId()).plusHours(expirationTimeout).with(WorkingDaysAdjusters.defaultWorkingDays());

if(!tickets.hasNext()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,8 @@ public void handleWaitingTickets() {
}

private boolean isWaitingListFormEnabled(Event event) {
Configuration.ConfigurationPath conf = Configuration.event(event);
return configurationManager.getBooleanConfigValue(conf, ConfigurationKeys.ENABLE_WAITING_QUEUE, false)
|| configurationManager.getBooleanConfigValue(conf, ConfigurationKeys.ENABLE_PRE_REGISTRATION, false);
return configurationManager.getBooleanConfigValue(Configuration.enableWaitingQueue(event), false)
|| configurationManager.getBooleanConfigValue(Configuration.enablePreRegistration(event), false);
}

void distributeAvailableSeats(Event event) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public Pair<String, String> geocode(String address) {
private GeoApiContext getApiContext() {
GeoApiContext ctx = CTX.get();
if(ctx == null) {
ctx = new GeoApiContext().setApiKey(configurationManager.getRequiredValue(Configuration.system(), ConfigurationKeys.MAPS_SERVER_API_KEY));
ctx = new GeoApiContext().setApiKey(configurationManager.getRequiredValue(Configuration.mapsServerApiKey()));
CTX.compareAndSet(null, ctx);
}
return CTX.get();
Expand Down
22 changes: 11 additions & 11 deletions src/main/java/alfio/manager/system/ConfigurationManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -82,34 +82,34 @@ private static <T> T from(ConfigurationPath c) {
return (T) c;
}

public int getIntConfigValue(ConfigurationPath path, ConfigurationKeys key, int defaultValue) {
public int getIntConfigValue(ConfigurationPathKey pathKey, int defaultValue) {
try {
return Optional.ofNullable(findByConfigurationPathAndKey(path, key))
return Optional.ofNullable(findByConfigurationPathAndKey(pathKey.getPath(), pathKey.getKey()))
.map(Configuration::getValue)
.map(Integer::parseInt).orElse(defaultValue);
} catch (NumberFormatException | EmptyResultDataAccessException e) {
return defaultValue;
}
}

public boolean getBooleanConfigValue(ConfigurationPath path, ConfigurationKeys key, boolean defaultValue) {
return getStringConfigValue(path, key)
public boolean getBooleanConfigValue(ConfigurationPathKey pathKey, boolean defaultValue) {
return getStringConfigValue(pathKey)
.map(Boolean::parseBoolean)
.orElse(defaultValue);
}


public String getStringConfigValue(ConfigurationPath path, ConfigurationKeys key, String defaultValue) {
return getStringConfigValue(path, key).orElse(defaultValue);
public String getStringConfigValue(ConfigurationPathKey pathKey, String defaultValue) {
return getStringConfigValue(pathKey).orElse(defaultValue);
}

public Optional<String> getStringConfigValue(ConfigurationPath path, ConfigurationKeys key) {
return optionally(() -> findByConfigurationPathAndKey(path, key)).map(Configuration::getValue);
public Optional<String> getStringConfigValue(ConfigurationPathKey pathKey) {
return optionally(() -> findByConfigurationPathAndKey(pathKey.getPath(), pathKey.getKey())).map(Configuration::getValue);
}

public String getRequiredValue(ConfigurationPath path, ConfigurationKeys key) {
return getStringConfigValue(path, key)
.orElseThrow(() -> new IllegalArgumentException("Mandatory configuration key " + key + " not present"));
public String getRequiredValue(ConfigurationPathKey pathKey) {
return getStringConfigValue(pathKey)
.orElseThrow(() -> new IllegalArgumentException("Mandatory configuration key " + pathKey.getKey() + " not present"));
}

// begin SYSTEM related configuration methods
Expand Down
Loading

0 comments on commit d72a5d9

Please sign in to comment.