Skip to content

Commit

Permalink
#62 - refactoring of config options
Browse files Browse the repository at this point in the history
  • Loading branch information
cbellone committed Oct 23, 2015
1 parent d9f52e7 commit c24de36
Show file tree
Hide file tree
Showing 28 changed files with 211 additions and 292 deletions.
3 changes: 2 additions & 1 deletion src/main/java/alfio/config/ConfigurationStatusChecker.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import alfio.manager.system.DataMigrator;
import alfio.manager.user.UserManager;
import alfio.model.system.Configuration;
import alfio.model.system.ConfigurationKeys;
import alfio.model.user.Role;
import alfio.repository.user.AuthorityRepository;
import alfio.repository.user.UserRepository;
Expand Down Expand Up @@ -63,7 +64,7 @@ public ConfigurationStatusChecker(ConfigurationManager configurationManager,

@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
boolean initCompleted = configurationManager.getBooleanConfigValue(Configuration.initCompleted(), false);
boolean initCompleted = configurationManager.getBooleanConfigValue(Configuration.getSystemConfiguration(ConfigurationKeys.INIT_COMPLETED), false);
if (!initCompleted) {
String adminPassword = PasswordGenerator.generateRandomPassword();
userRepository.create(UserManager.ADMIN_USERNAME, passwordEncoder.encode(adminPassword), "The", "Administrator", "admin@localhost", true);
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/alfio/config/MvcConfiguration.java
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static alfio.model.system.ConfigurationKeys.GOOGLE_ANALYTICS_KEY;

@Configuration
@ComponentScan(basePackages = {"alfio.controller", "alfio.config"})
@EnableWebMvc
Expand Down Expand Up @@ -179,7 +181,7 @@ public void postHandle(HttpServletRequest request, HttpServletResponse response,
if(!StringUtils.startsWith(mv.getViewName(), "redirect:")) {
modelMap.putIfAbsent("pageTitle", "empty");
Event event = modelMap.get("event") == null ? null : modelMap.get("event") instanceof Event ? (Event) modelMap.get("event") : ((EventDescriptor) modelMap.get("event")).getEvent();
ConfigurationPathKey googleAnalyticsKey = event != null ? alfio.model.system.Configuration.googleAnalyticsKey(event) : alfio.model.system.Configuration.googleAnalyticsKey();
ConfigurationPathKey googleAnalyticsKey = Optional.ofNullable(event).map(e -> alfio.model.system.Configuration.from(e.getOrganizationId(), e.getId(), GOOGLE_ANALYTICS_KEY)).orElseGet(() -> alfio.model.system.Configuration.getSystemConfiguration(GOOGLE_ANALYTICS_KEY));
modelMap.putIfAbsent("analyticsEnabled", StringUtils.isNotBlank(configurationManager.getStringConfigValue(googleAnalyticsKey, "")));
}
});
Expand Down
10 changes: 8 additions & 2 deletions src/main/java/alfio/controller/DynamicResourcesController.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package alfio.controller;

import alfio.manager.system.ConfigurationManager;
import alfio.model.Event;
import alfio.model.system.Configuration;
import alfio.model.system.Configuration.ConfigurationPathKey;
import alfio.repository.EventRepository;
Expand All @@ -32,6 +33,9 @@
import java.io.IOException;
import java.util.*;

import static alfio.model.system.ConfigurationKeys.GOOGLE_ANALYTICS_ANONYMOUS_MODE;
import static alfio.model.system.ConfigurationKeys.GOOGLE_ANALYTICS_KEY;

@Controller
public class DynamicResourcesController {

Expand All @@ -51,10 +55,12 @@ public DynamicResourcesController(ConfigurationManager configurationManager, Tem
@RequestMapping("/resources/js/google-analytics")
public void getGoogleAnalyticsScript(HttpSession session, HttpServletResponse response, @RequestParam("e") Integer eventId) throws IOException {
response.setContentType("application/javascript");
ConfigurationPathKey pathKey = Optional.ofNullable(eventId).flatMap(id -> Optional.ofNullable(eventRepository.findById(id)).map(Configuration::googleAnalyticsKey)).orElseGet(Configuration::googleAnalyticsKey);
Optional<Event> ev = Optional.ofNullable(eventId).flatMap(id -> Optional.ofNullable(eventRepository.findById(id)));
ConfigurationPathKey pathKey = ev.map(e -> Configuration.from(e.getOrganizationId(), e.getId(), GOOGLE_ANALYTICS_KEY)).orElseGet(() -> Configuration.getSystemConfiguration(GOOGLE_ANALYTICS_KEY));
final Optional<String> id = configurationManager.getStringConfigValue(pathKey);
final String script;
if(id.isPresent() && configurationManager.getBooleanConfigValue(Configuration.googleAnalyticsAnonymousMode(), true)) {
ConfigurationPathKey anonymousPathKey = ev.map(e -> Configuration.from(e.getOrganizationId(), e.getId(), GOOGLE_ANALYTICS_ANONYMOUS_MODE)).orElseGet(() -> Configuration.getSystemConfiguration(GOOGLE_ANALYTICS_ANONYMOUS_MODE));
if(id.isPresent() && configurationManager.getBooleanConfigValue(anonymousPathKey, true)) {
String trackingId = Optional.ofNullable(StringUtils.trimToNull((String)session.getAttribute("GA_TRACKING_ID"))).orElseGet(() -> UUID.randomUUID().toString());
Map<String, Object> model = new HashMap<>();
model.put("clientId", trackingId);
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/alfio/controller/EventController.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import alfio.model.modification.TicketReservationWithOptionalCodeModification;
import alfio.model.modification.support.LocationDescriptor;
import alfio.model.system.Configuration;
import alfio.model.system.ConfigurationKeys;
import alfio.repository.*;
import alfio.repository.user.OrganizationRepository;
import alfio.util.ErrorsCode;
Expand Down Expand Up @@ -195,13 +196,13 @@ public String showEvent(@PathVariable("eventName") String eventName,
List<SaleableTicketCategory> ticketCategories = ticketCategoryRepository.findAllTicketCategories(event.getId()).stream()
.filter((c) -> !c.isAccessRestricted() || (specialCode.isPresent() && specialCode.get().getTicketCategoryId() == c.getId()))
.map((m) -> new SaleableTicketCategory(m, ticketCategoryDescriptionRepository.findByTicketCategoryIdAndLocale(m.getId(), locale.getLanguage()).orElse(""),
now, event, ticketReservationManager.countAvailableTickets(event, m), configurationManager.getIntConfigValue(Configuration.maxAmountOfTicketsByReservation(event.getOrganizationId(), event.getId(), m.getId()), 5), promoCodeDiscount))
now, event, ticketReservationManager.countAvailableTickets(event, m), configurationManager.getIntConfigValue(Configuration.from(event.getOrganizationId(), event.getId(), m.getId(), ConfigurationKeys.MAX_AMOUNT_OF_TICKETS_BY_RESERVATION), 5), promoCodeDiscount))
.collect(Collectors.toList());
//


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

final boolean hasAccessPromotions = ticketCategoryRepository.countAccessRestrictedRepositoryByEventId(event.getId()) > 0 ||
promoCodeRepository.countByEventId(event.getId()) > 0;
Expand Down
11 changes: 7 additions & 4 deletions src/main/java/alfio/controller/ReservationController.java
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@
import java.util.*;
import java.util.stream.Collectors;

import static alfio.model.system.ConfigurationKeys.ALLOW_FREE_TICKETS_CANCELLATION;
import static alfio.model.system.ConfigurationKeys.BANK_ACCOUNT_NR;

@Controller
public class ReservationController {

Expand Down Expand Up @@ -130,7 +133,7 @@ public String showPaymentPage(@PathVariable("eventName") String eventName,
boolean includeStripe = !orderSummary.getFree() && event.getAllowedPaymentProxies().contains(PaymentProxy.STRIPE);
model.addAttribute("includeStripe", includeStripe);
if (includeStripe) {
model.addAttribute("stripe_p_key", stripeManager.getPublicKey());
model.addAttribute("stripe_p_key", stripeManager.getPublicKey(event));
}
Map<String, Object> modelMap = model.asMap();
modelMap.putIfAbsent("paymentForm", new PaymentForm());
Expand Down Expand Up @@ -179,7 +182,7 @@ public String showConfirmationPage(@PathVariable("eventName") String eventName,
tickets.stream().collect(Collectors.groupingBy(Ticket::getCategoryId)).entrySet().stream()
.map((e) -> {
TicketCategory category = eventManager.getTicketCategoryById(e.getKey(), event.get().getId());
return Pair.of(category, TicketDecorator.decorate(e.getValue(), configurationManager.getBooleanConfigValue(Configuration.allowFreeTicketsCancellation(ev, category), false), eventManager.checkTicketCancellationPrerequisites()));
return Pair.of(category, TicketDecorator.decorate(e.getValue(), configurationManager.getBooleanConfigValue(Configuration.from(event.get().getOrganizationId(), event.get().getId(), category.getId(), ALLOW_FREE_TICKETS_CANCELLATION), false), eventManager.checkTicketCancellationPrerequisites()));
})
.collect(Collectors.toList()));
model.addAttribute("ticketsAreAllAssigned", tickets.stream().allMatch(Ticket::getAssigned));
Expand Down Expand Up @@ -276,9 +279,9 @@ public String showWaitingPaymentPage(@PathVariable("eventName") String eventName
model.addAttribute("totalPrice", orderSummary.getTotalPrice());
model.addAttribute("emailAddress", organizationRepository.getById(ev.getOrganizationId()).getEmail());
model.addAttribute("reservation", ticketReservation);
model.addAttribute("paymentReason", ev.getShortName() + " " + ticketReservationManager.getShortReservationID(reservationId));
model.addAttribute("paymentReason", ev.getShortName() + " " + ticketReservationManager.getShortReservationID(ev, reservationId));
model.addAttribute("pageTitle", "reservation-page-waiting.header.title");
model.addAttribute("bankAccount", configurationManager.getStringConfigValue(Configuration.bankAccountNr(ev)).orElse(""));
model.addAttribute("bankAccount", configurationManager.getStringConfigValue(Configuration.from(ev.getOrganizationId(), ev.getId(), BANK_ACCOUNT_NR)).orElse(""));
model.addAttribute("expires", ZonedDateTime.ofInstant(ticketReservation.getValidity().toInstant(), ev.getZoneId()));
model.addAttribute("event", ev);
return "/event/reservation-waiting-for-payment";
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/alfio/controller/TicketController.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@
import java.util.Locale;
import java.util.Optional;

import static alfio.model.system.ConfigurationKeys.ALLOW_FREE_TICKETS_CANCELLATION;

@Controller
public class TicketController {

Expand Down Expand Up @@ -117,7 +119,7 @@ public String showTicketForUpdate(@PathVariable("eventName") String eventName, @
TicketCategory ticketCategory = ticketCategoryRepository.getById(data.getRight().getCategoryId(), event.getId());
Organization organization = organizationRepository.getById(event.getOrganizationId());

boolean enableFreeCancellation = configurationManager.getBooleanConfigValue(Configuration.allowFreeTicketsCancellation(event, ticketCategory), false);
boolean enableFreeCancellation = configurationManager.getBooleanConfigValue(Configuration.from(event.getOrganizationId(), event.getId(), ticketCategory.getId(), ALLOW_FREE_TICKETS_CANCELLATION), false);
Ticket ticket = data.getRight();
model.addAttribute("ticketAndCategory", Pair.of(eventManager.getTicketCategoryById(ticket.getCategoryId(), event.getId()), new TicketDecorator(ticket, enableFreeCancellation, eventManager.checkTicketCancellationPrerequisites().apply(ticket), "ticket/"+ticket.getUuid()+"/view")))//
.addAttribute("reservation", data.getMiddle())//
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import alfio.manager.system.ConfigurationManager;
import alfio.model.modification.support.LocationDescriptor;
import alfio.model.system.Configuration;
import alfio.model.system.ConfigurationKeys;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -65,7 +66,7 @@ public LocationDescriptor geocodeAddress(@RequestParam("location") String addres
}

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

@RequestMapping(value = "/location/map", method = GET)
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/alfio/manager/EventManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import alfio.model.Ticket.TicketStatus;
import alfio.model.modification.*;
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 @@ -560,7 +561,7 @@ public List<PromoCodeDiscountWithFormattedTime> findPromoCodesInEvent(int eventI
}

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

public List<Ticket> findAllConfirmedTickets(String eventName, String username) {
Expand Down
17 changes: 14 additions & 3 deletions src/main/java/alfio/manager/SpecialPriceTokenGenerator.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@
package alfio.manager;

import alfio.manager.system.ConfigurationManager;
import alfio.model.Event;
import alfio.model.SpecialPrice;
import alfio.model.TicketCategory;
import alfio.model.system.Configuration;
import alfio.model.system.ConfigurationKeys;
import alfio.repository.EventRepository;
import alfio.repository.SpecialPriceRepository;
import alfio.repository.TicketCategoryRepository;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.StopWatch;
Expand All @@ -46,13 +50,19 @@ public class SpecialPriceTokenGenerator {
};

private final SpecialPriceRepository specialPriceRepository;
private final TicketCategoryRepository ticketCategoryRepository;
private final EventRepository eventRepository;
private final ConfigurationManager configurationManager;

@Autowired
public SpecialPriceTokenGenerator(ConfigurationManager configurationManager,
SpecialPriceRepository specialPriceRepository) {
SpecialPriceRepository specialPriceRepository,
TicketCategoryRepository ticketCategoryRepository,
EventRepository eventRepository) {
this.specialPriceRepository = specialPriceRepository;
this.configurationManager = configurationManager;
this.ticketCategoryRepository = ticketCategoryRepository;
this.eventRepository = eventRepository;
}

void generatePendingCodes() {
Expand All @@ -67,8 +77,9 @@ void generatePendingCodes() {

private void generateCode(SpecialPrice specialPrice) {

//TODO: get Event from categoryId present in specialPrice
int maxLength = configurationManager.getIntConfigValue(Configuration.specialPriceCodeLength(), 6);
TicketCategory ticketCategory = ticketCategoryRepository.getById(specialPrice.getTicketCategoryId()).orElseThrow(IllegalStateException::new);
Event event = eventRepository.findById(ticketCategory.getEventId());
int maxLength = configurationManager.getIntConfigValue(Configuration.from(event.getOrganizationId(), event.getId(), ticketCategory.getId(), ConfigurationKeys.SPECIAL_PRICE_CODE_LENGTH), 6);

while (true) {
try {
Expand Down
10 changes: 5 additions & 5 deletions src/main/java/alfio/manager/StripeManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,12 @@ public StripeManager(ConfigurationManager configurationManager,
handlers.put(StripeException.class, this::handleGenericException);
}

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

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

/**
Expand Down Expand Up @@ -96,7 +96,7 @@ public Charge chargeCreditCard(String stripeToken, long amountInCent, Event even
initialMetadata.put("billingAddress", billingAddress);
}
chargeParams.put("metadata", initialMetadata);
return Charge.create(chargeParams, RequestOptions.builder().setApiKey(getSecretKey()).build());
return Charge.create(chargeParams, RequestOptions.builder().setApiKey(getSecretKey(event)).build());
}

public String handleException(StripeException exc) {
Expand Down
Loading

0 comments on commit c24de36

Please sign in to comment.