Skip to content

Commit

Permalink
Refactor configuration get value (#665)
Browse files Browse the repository at this point in the history
* refactor: configuration manager: bulk get

* initial work for a better api, fix test

* configuration manager: get values: refactor/cleanup + optimize mailjet mailer

* configuration manager: get values new api: refactor: mailgun mailer

* configuration manager: get values new api: refactor: smtp mailer + mark deprecated a configuration manager method

* configuration manager: get values new api: refactor: passkit manager

* configuration manager: get values: refactor/cleanup in LocationApiController, remove deprecated method

* configuration manager: cleanup new api

* config manager: cleanup api

* configuration manager: additional cleanup/refactoring: try to move as much as possible to new api

* configuration manager: move more use to new api, add note in test

* fix tests/cleanup/clarify

* fix TicketReservationManagerTest.lockFailed test

* mark @deprecated some additional methods

* configuration manager: move use to new api

* configuration manager: refactor: better naming

* configuration manager: refactor: better constructor for MaybeConfiguration, fix parameters

* refactor: switch from configurationManager.getRequiredValue to configurationManager.for

* refactor: switch from configurationManager.getRequiredValue to configurationManager.for

* refactor: switch from configurationManager.getRequiredValue to configurationManager.for

* refactor: switch from configurationManager.getRequiredValue/getStringConfigValue to configurationManager.for

* refactor: switch from configurationManager.getRequiredValue/getStringConfigValue to configurationManager.for

* refactor: switch from configurationManager.getBooleanConfigValue to configurationManager.for

* cleanup: remove MustacheCustomTagInterceptor, remove unused mustache custom tags

* cleanup: remove i18n tag use in index.ms for admin

* refactor: switch from configurationManager.getStringConfigValue to configurationManager.getFor

* refactor: switch from configurationManager.getStringConfigValue to configurationManager.getFor

* configuration manager: getFor: handle case of EventAndOrganizationId as null -> we fetch only at system level
  • Loading branch information
syjer authored and cbellone committed Jun 18, 2019
1 parent 172d72b commit 8c5164c
Show file tree
Hide file tree
Showing 60 changed files with 700 additions and 631 deletions.
3 changes: 1 addition & 2 deletions src/main/java/alfio/config/ConfigurationStatusChecker.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import alfio.manager.system.ConfigurationManager;
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.model.user.User;
Expand Down Expand Up @@ -65,7 +64,7 @@ public ConfigurationStatusChecker(ConfigurationManager configurationManager,

@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
boolean initCompleted = configurationManager.getBooleanConfigValue(Configuration.getSystemConfiguration(ConfigurationKeys.INIT_COMPLETED), false);
boolean initCompleted = configurationManager.getFor(ConfigurationKeys.INIT_COMPLETED).getValueAsBooleanOrDefault(false);
if (!initCompleted) {
String adminPassword = PasswordGenerator.generateRandomPassword();
userRepository.create(UserManager.ADMIN_USERNAME, passwordEncoder.encode(adminPassword), "The", "Administrator", "admin@localhost", true, User.Type.INTERNAL, null, null);
Expand Down
6 changes: 6 additions & 0 deletions src/main/java/alfio/config/DataSourceConfiguration.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import alfio.repository.system.AdminJobQueueRepository;
import alfio.repository.user.OrganizationRepository;
import alfio.util.CustomResourceBundleMessageSource;
import alfio.util.Json;
import alfio.util.TemplateManager;
import ch.digitalfondue.npjt.EnableNpjt;
import ch.digitalfondue.npjt.mapper.ColumnMapperFactory;
Expand Down Expand Up @@ -171,6 +172,11 @@ public MessageSource messageSource() {
return source;
}

@Bean
public Json getJson() {
return new Json();
}

@Bean
public TemplateManager getTemplateManager(UploadedResourceManager uploadedResourceManager, ConfigurationManager configurationManager) {
return new TemplateManager(getTemplateLoader(), messageSource(), uploadedResourceManager, configurationManager);
Expand Down
15 changes: 4 additions & 11 deletions src/main/java/alfio/config/MvcConfiguration.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

import alfio.manager.system.ConfigurationManager;
import alfio.model.system.ConfigurationKeys;
import alfio.util.MustacheCustomTagInterceptor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
Expand Down Expand Up @@ -99,7 +98,6 @@ public void addResourceHandlers(ResourceHandlerRegistry registry) {
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getLocaleChangeInterceptor());
registry.addInterceptor(getTemplateMessagesInterceptor());
registry.addInterceptor(new MustacheCustomTagInterceptor(configurationManager));
registry.addInterceptor(getCSPInterceptor());
}

Expand All @@ -118,14 +116,12 @@ public void postHandle(HttpServletRequest request, HttpServletResponse response,

//
String reportUri = "";
boolean enabledReport = Boolean.parseBoolean(configurationCache.get(ConfigurationKeys.SECURITY_CSP_REPORT_ENABLED, (k) ->
configurationManager.getStringConfigValue(
alfio.model.system.Configuration.getSystemConfiguration(k), "false")
boolean enabledReport = Boolean.parseBoolean(configurationCache.get(ConfigurationKeys.SECURITY_CSP_REPORT_ENABLED,
(k) -> configurationManager.getFor(k).getValueOrDefault("false")
));
if (enabledReport) {
reportUri = " report-uri " + configurationCache.get(ConfigurationKeys.SECURITY_CSP_REPORT_URI, (k) ->
configurationManager.getStringConfigValue(
alfio.model.system.Configuration.getSystemConfiguration(k), "/report-csp-violation")
reportUri = " report-uri " + configurationCache.get(ConfigurationKeys.SECURITY_CSP_REPORT_URI,
(k) -> configurationManager.getFor(k).getValueOrDefault("/report-csp-violation")
);
}
//
Expand Down Expand Up @@ -232,7 +228,4 @@ public ObjectMapper objectMapper() {
public CommonsMultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}



}
2 changes: 1 addition & 1 deletion src/main/java/alfio/config/WebSecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,7 @@ private static class RecaptchaLoginFilter extends GenericFilterBean {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
boolean captchaEnabled = configurationManager.getBooleanConfigValue(getSystemConfiguration(ENABLE_CAPTCHA_FOR_LOGIN), true);
boolean captchaEnabled = configurationManager.getFor(ENABLE_CAPTCHA_FOR_LOGIN).getValueAsBooleanOrDefault(true);
if(captchaEnabled && requestMatcher.matches(req) && !recaptchaService.checkRecaptcha(null, req)) {
res.sendRedirect(recaptchaFailureUrl);
return;
Expand Down
5 changes: 2 additions & 3 deletions src/main/java/alfio/controller/LoginController.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import alfio.config.Initializer;
import alfio.config.WebSecurityConfig;
import alfio.manager.system.ConfigurationManager;
import alfio.model.system.Configuration;
import alfio.model.system.ConfigurationKeys;
import lombok.AllArgsConstructor;
import org.springframework.core.env.Environment;
Expand Down Expand Up @@ -62,8 +61,8 @@ public String getLoginPage(@RequestParam(value="failed", required = false) Strin
model.addAttribute(WebSecurityConfig.CSRF_PARAM_NAME, request.getAttribute(CsrfToken.class.getName()));
//

configurationManager.getStringConfigValue(Configuration.getSystemConfiguration(ConfigurationKeys.RECAPTCHA_API_KEY))
.filter(key -> configurationManager.getBooleanConfigValue(Configuration.getSystemConfiguration(ENABLE_CAPTCHA_FOR_LOGIN), true))
configurationManager.getFor(ConfigurationKeys.RECAPTCHA_API_KEY).getValue()
.filter(key -> configurationManager.getFor(ENABLE_CAPTCHA_FOR_LOGIN).getValueAsBooleanOrDefault(true))
.ifPresent(key -> {
model.addAttribute("hasRecaptchaApiKey", true);
model.addAttribute("recaptchaApiKey", key);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import alfio.model.Event;
import alfio.model.WaitingQueueSubscription;
import alfio.model.modification.ConfigurationModification;
import alfio.model.system.Configuration;
import alfio.model.system.ConfigurationKeys;
import alfio.util.EventUtil;
import alfio.util.ExportUtils;
Expand Down Expand Up @@ -73,7 +72,7 @@ private Map<String, Boolean> loadStatus(Event event) {
.map(tc -> new SaleableTicketCategory(tc, now, event, ticketReservationManager.countAvailableTickets(event, tc), tc.getMaxTickets(), null))
.collect(Collectors.toList());
boolean active = EventUtil.checkWaitingQueuePreconditions(event, stcList, configurationManager, eventStatisticsManager.noSeatsAvailable());
boolean paused = active && configurationManager.getBooleanConfigValue(Configuration.from(event, STOP_WAITING_QUEUE_SUBSCRIPTIONS), false);
boolean paused = active && configurationManager.getFor(event, STOP_WAITING_QUEUE_SUBSCRIPTIONS).getValueAsBooleanOrDefault(false);
Map<String, Boolean> result = new HashMap<>();
result.put("active", active);
result.put("paused", paused);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import alfio.manager.system.ConfigurationManager;
import alfio.model.EventAndOrganizationId;
import alfio.model.FullTicketInfo;
import alfio.model.system.Configuration;
import alfio.model.system.ConfigurationKeys;
import alfio.util.Json;
import com.fasterxml.jackson.annotation.JsonCreator;
Expand Down Expand Up @@ -237,7 +236,7 @@ private ResponseEntity<LabelLayout> parseLabelLayout(EventAndOrganizationId even
}

private Optional<LabelLayout> loadLabelLayout(EventAndOrganizationId event) {
return configurationManager.getStringConfigValue(Configuration.from(event, ConfigurationKeys.LABEL_LAYOUT))
return configurationManager.getFor(event, ConfigurationKeys.LABEL_LAYOUT).getValue()
.flatMap(str -> optionally(() -> Json.fromJson(str, LabelLayout.class)));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,13 +137,13 @@ public boolean deleteKey(@PathVariable("key") String key) {

@RequestMapping(value = "/eu-countries", method = GET)
public List<Pair<String, String>> loadEUCountries() {
return TicketHelper.getLocalizedEUCountriesForVat(Locale.ENGLISH, configurationManager.getRequiredValue(getSystemConfiguration(ConfigurationKeys.EU_COUNTRIES_LIST)));
return TicketHelper.getLocalizedEUCountriesForVat(Locale.ENGLISH, configurationManager.getFor(ConfigurationKeys.EU_COUNTRIES_LIST).getRequiredValue());
}

@RequestMapping(value = "/platform-mode/status/{organizationId}", method = GET)
public Map<String, Boolean> loadPlatformModeStatus(@PathVariable("organizationId") int organizationId) {
Map<String, Boolean> result = new HashMap<>();
boolean platformModeEnabled = configurationManager.getBooleanConfigValue(getSystemConfiguration(PLATFORM_MODE_ENABLED), false);
boolean platformModeEnabled = configurationManager.getFor(PLATFORM_MODE_ENABLED).getValueAsBooleanOrDefault(false);
boolean stripeConnected = platformModeEnabled && StringUtils.isNotBlank(configurationManager.getStringConfigValue(from(organizationId, STRIPE_CONNECTED_ID), null));
result.put("enabled", platformModeEnabled);
result.put("stripeConnected", stripeConnected);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

import alfio.manager.system.ConfigurationManager;
import alfio.model.modification.support.LocationDescriptor;
import alfio.model.system.Configuration;
import alfio.model.system.ConfigurationKeys;
import com.moodysalem.TimezoneMapper;
import lombok.AllArgsConstructor;
Expand All @@ -29,7 +28,8 @@

import java.time.ZoneId;
import java.util.*;
import java.util.function.Function;

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

@RestController
@RequestMapping("/admin/api")
Expand Down Expand Up @@ -72,12 +72,11 @@ public String getMapImage(
}

private Map<ConfigurationKeys, Optional<String>> getGeoConf() {
Function<ConfigurationKeys, Configuration.ConfigurationPathKey> pathKeyBuilder = Configuration::getSystemConfiguration;
return configurationManager.getStringConfigValueFrom(
pathKeyBuilder.apply(ConfigurationKeys.MAPS_PROVIDER),
pathKeyBuilder.apply(ConfigurationKeys.MAPS_CLIENT_API_KEY),
pathKeyBuilder.apply(ConfigurationKeys.MAPS_HERE_APP_ID),
pathKeyBuilder.apply(ConfigurationKeys.MAPS_HERE_APP_CODE));
var keys = Set.of(MAPS_PROVIDER, MAPS_CLIENT_API_KEY, MAPS_HERE_APP_ID, MAPS_HERE_APP_CODE);
var conf = configurationManager.getFor(keys);
var res = new EnumMap<ConfigurationKeys, Optional<String>>(ConfigurationKeys.class);
conf.forEach((k,v) -> res.put(k, v.getValue()));
return res;
}

@RequestMapping("/location/map-provider-client-api-key")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ public void getAllApiKeys(@PathVariable("organizationId") int organizationId, Ht
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=apiKeys.zip");

String baseUrl = configurationManager.getStringConfigValue(Configuration.getSystemConfiguration(ConfigurationKeys.BASE_URL)).orElseThrow(IllegalStateException::new);
String baseUrl = configurationManager.getFor(ConfigurationKeys.BASE_URL).getRequiredValue();
try(OutputStream os = response.getOutputStream(); ZipOutputStream zipOS = new ZipOutputStream(os)) {
for (User user : userManager.findAllApiKeysFor(organizationId)) {
Pair<String, byte[]> result = generateApiKeyQRCode(user, baseUrl);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import alfio.controller.api.support.CurrencyDescriptor;
import alfio.controller.api.support.TicketHelper;
import alfio.manager.EventNameManager;
import alfio.util.MustacheCustomTagInterceptor;
import alfio.util.MustacheCustomTag;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.text.StringEscapeUtils;
Expand Down Expand Up @@ -83,7 +83,7 @@ public boolean validateShortName(@RequestParam("shortName") String shortName, Ht

@RequestMapping(value = "/render-commonmark")
public String renderCommonmark(@RequestParam("text") String input) {
return MustacheCustomTagInterceptor.renderToCommonmark(StringEscapeUtils.escapeHtml4(input));
return MustacheCustomTag.renderToCommonmark(StringEscapeUtils.escapeHtml4(input));
}

@RequestMapping(value = "/alfio/info", method = GET)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
package alfio.controller.api.support;

import alfio.manager.system.ConfigurationManager;
import alfio.model.system.Configuration;
import alfio.model.system.ConfigurationKeys;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.RequestMapping;
Expand All @@ -27,8 +25,12 @@

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Set;
import java.util.stream.Collectors;

import static alfio.model.system.ConfigurationKeys.SECURITY_CSP_REPORT_ENABLED;
import static alfio.model.system.ConfigurationKeys.SECURITY_CSP_REPORT_URI;


@RestController
@Log4j2
Expand All @@ -41,12 +43,11 @@ public class CspReportApiController {
@RequestMapping(value = "/report-csp-violation", method = RequestMethod.POST)
public boolean logCspViolation(HttpServletRequest request) throws IOException {

var conf = configurationManager.getFor(Set.of(SECURITY_CSP_REPORT_ENABLED, SECURITY_CSP_REPORT_URI));

boolean enabledReport = configurationManager.getBooleanConfigValue(
Configuration.getSystemConfiguration(ConfigurationKeys.SECURITY_CSP_REPORT_ENABLED), false);
boolean enabledReport = conf.get(SECURITY_CSP_REPORT_ENABLED).getValueAsBooleanOrDefault(false);

String uri = configurationManager.getStringConfigValue(
Configuration.getSystemConfiguration(ConfigurationKeys.SECURITY_CSP_REPORT_URI), "/report-csp-violation");
String uri = conf.get(SECURITY_CSP_REPORT_URI).getValueOrDefault("/report-csp-violation");

if (enabledReport && "/report-csp-violation".equals(uri)) {
String report = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public List<LocalizedCountry> getCountriesForVat(@PathVariable("lang") String la
@GetMapping("/public/i18n/eu-countries-vat/{lang}")
public List<LocalizedCountry> getEuCountriesForVat(@PathVariable("lang") String lang) {
var countries = TicketHelper.getLocalizedEUCountriesForVat(Locale.forLanguageTag(lang),
configurationManager.getRequiredValue(getSystemConfiguration(ConfigurationKeys.EU_COUNTRIES_LIST)));
configurationManager.getFor(ConfigurationKeys.EU_COUNTRIES_LIST).getRequiredValue());
return fromPair(countries);
}

Expand Down
Loading

0 comments on commit 8c5164c

Please sign in to comment.