From 1e2d8a4895373c0c56a2e7c3c389924202832860 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Mon, 15 Apr 2024 16:59:39 +0200 Subject: [PATCH 1/6] chore: upgrade to java 17 --- .github/workflows/dockerImage.yml | 2 +- .github/workflows/feature-branch.yml | 2 +- Dockerfile | 2 +- google_checks_light.xml | 1 - pom.xml | 90 ++++++----- .../mailservice/MailServiceApplication.java | 1 - ...DefaultResponseEntityExceptionHandler.java | 11 +- .../ApiResponseEntityExceptionHandler.java | 68 +++----- .../api/TranslationMessageSource.java | 8 +- .../api/cache/CacheEventLogger.java | 15 -- .../controller/CustomSwaggerUIController.java | 18 --- .../api/controller/MailController.java | 25 ++- .../api/controller/TranslationController.java | 4 - .../ExchangeMailServiceException.java | 1 - .../InternalServerErrorException.java | 5 +- .../exception/SmtpMailServiceException.java | 1 - .../TemplateDescriptionServiceException.java | 1 - .../exception/TemplateServiceException.java | 1 - .../cob/mailservice/api/helper/Helper.java | 8 +- .../api/helper/TemplateDataConverter.java | 22 +-- .../api/helper/ThymeleafHelper.java | 7 +- .../api/mailtemplate/SubjectDescription.java | 3 +- .../api/mailtemplate/TemplateDescription.java | 4 +- .../api/mailtemplate/TemplateImage.java | 5 +- .../service/DefaultTranslationsService.java | 79 ++++++---- .../api/service/ExchangeMailService.java | 47 +++--- .../mailservice/api/service/LogService.java | 15 +- .../api/service/MailErrorMessageBuilder.java | 9 +- .../mailservice/api/service/MailService.java | 49 +++--- .../api/service/SmtpMailService.java | 61 ++++---- .../service/TemplateDescriptionService.java | 33 ++-- .../api/service/TemplateService.java | 68 ++++---- .../api/service/TranslationService.java | 42 +++-- .../cob/mailservice/config/AppConfig.java | 5 +- .../CustomSwaggerUIPathWebMvcConfigurer.java | 4 +- .../mailservice/config/SecurityConfig.java | 59 ++++--- .../mailservice/config/SpringFoxConfig.java | 90 ----------- .../mailservice/config/ThymeleafConfig.java | 14 +- ...TranslationManagementServiceApiClient.java | 22 ++- .../filter/StatelessCsrfFilter.java | 30 ++-- src/main/resources/application.properties | 1 + .../cob/mailservice/api/ResourceIT.java | 29 ++-- .../api/TranslationMessageSourceTest.java | 22 +-- .../api/config/MailTestConfiguration.java | 4 +- .../api/controller/MailControllerE2EIT.java | 148 +++++++++--------- .../MailControllerTestExchangeIT.java | 69 ++++---- .../controller/MailControllerTestSmtpIT.java | 38 +++-- .../mailservice/api/helper/HelperTest.java | 21 +-- .../api/helper/TemplateDataConverterTest.java | 12 +- .../service/DefaultTranslationsServiceIT.java | 58 +++---- .../api/service/ExchangeMailServiceTest.java | 14 +- .../api/service/LogServiceTest.java | 59 ------- .../service/MailErrorMessageBuilderTest.java | 10 +- .../api/service/MailServiceTest.java | 117 +++++++------- .../api/service/SmtpMailServiceTest.java | 8 +- .../TemplateServiceIntegrationTest.java | 53 +++---- .../api/service/TemplateServiceTest.java | 54 +++---- .../api/service/TranslationServiceTest.java | 76 +++++---- 58 files changed, 801 insertions(+), 924 deletions(-) delete mode 100644 src/main/java/de/caritas/cob/mailservice/api/cache/CacheEventLogger.java delete mode 100644 src/main/java/de/caritas/cob/mailservice/api/controller/CustomSwaggerUIController.java delete mode 100644 src/main/java/de/caritas/cob/mailservice/config/SpringFoxConfig.java delete mode 100644 src/test/java/de/caritas/cob/mailservice/api/service/LogServiceTest.java diff --git a/.github/workflows/dockerImage.yml b/.github/workflows/dockerImage.yml index a4d8b48..d05d196 100644 --- a/.github/workflows/dockerImage.yml +++ b/.github/workflows/dockerImage.yml @@ -27,7 +27,7 @@ jobs: - name: Setup JVM uses: actions/setup-java@v1 with: - java-version: 11.0.10 + java-version: 17.0.7 java-package: jdk architecture: x64 diff --git a/.github/workflows/feature-branch.yml b/.github/workflows/feature-branch.yml index 5bad8b6..18bda43 100644 --- a/.github/workflows/feature-branch.yml +++ b/.github/workflows/feature-branch.yml @@ -19,7 +19,7 @@ jobs: - name: Setup JVM uses: actions/setup-java@v1 with: - java-version: 11.0.10 + java-version: 17.0.7 java-package: jdk architecture: x64 diff --git a/Dockerfile b/Dockerfile index ddad38e..7c48c7d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM adoptopenjdk/openjdk11 +FROM openjdk:17-oracle VOLUME ["/tmp","/log"] EXPOSE 8080 ARG JAR_FILE diff --git a/google_checks_light.xml b/google_checks_light.xml index 339138d..241ddfa 100644 --- a/google_checks_light.xml +++ b/google_checks_light.xml @@ -306,7 +306,6 @@ --> - diff --git a/pom.xml b/pom.xml index 85552a9..eed0ab9 100644 --- a/pom.xml +++ b/pom.xml @@ -16,20 +16,28 @@ org.springframework.boot spring-boot-starter-parent - 2.7.5 - + 3.0.6 + UTF-8 UTF-8 - 11 + 17 2.17.1 - 6.2.1 + 6.6.0 3.0.0 0.2.3 - 5.7.5 + 6.0.5 + 17 + 17 + 8.0.0.Final + + 3.11 + 1.10.0 + 2.6 + 2.1.1 @@ -47,8 +55,15 @@ spring-boot-starter-cache - org.ehcache + net.sf.ehcache ehcache + 2.10.9.2 + + + com.fasterxml.jackson.core + jackson-databind + + javax.cache @@ -58,7 +73,7 @@ org.hibernate.validator hibernate-validator - 6.1.6.Final + ${hibernate-validator.version} @@ -81,24 +96,21 @@ - io.springfox - springfox-swagger2 - ${springfox-swagger2.version} - - - io.springfox - springfox-bean-validators - ${springfox-swagger2.version} + io.swagger.core.v3 + swagger-annotations + 2.2.15 + + - io.springfox - springfox-swagger-ui - ${springfox-swagger2.version} + org.springdoc + springdoc-openapi-starter-webmvc-ui + 2.4.0 javax.ws.rs javax.ws.rs-api - 2.1.1 + ${javax.ws.rs-api.version} javax.xml.ws @@ -108,7 +120,7 @@ org.springframework.security spring-security-core - ${spring.security} + ${spring-security.version} @@ -129,17 +141,17 @@ org.apache.commons commons-lang3 - 3.11 + ${commons-lang3.version} org.apache.commons commons-text - 1.10.0 + ${commons-text.version} commons-io commons-io - 2.6 + ${commons-io.version} @@ -153,7 +165,6 @@ org.springframework.boot spring-boot-starter-thymeleaf - 2.3.5.RELEASE @@ -167,18 +178,6 @@ spring-security-test test - - powermock-module-junit4 - org.powermock - test - 2.0.2 - - - powermock-api-mockito2 - org.powermock - test - 2.0.2 - @@ -204,6 +203,11 @@ 3.3.0 + + org.apache.httpcomponents.client5 + httpclient5 + + com.github.jknack handlebars @@ -234,8 +238,17 @@ + + + + junit + junit + 4.13.2 + test + + ${project.name} @@ -264,9 +277,10 @@ true / - + javax.mail:mailapi:1.4.3 - + + true ${project.basedir}/api/mailservice.yaml spring diff --git a/src/main/java/de/caritas/cob/mailservice/MailServiceApplication.java b/src/main/java/de/caritas/cob/mailservice/MailServiceApplication.java index f81936b..b5ab1bb 100644 --- a/src/main/java/de/caritas/cob/mailservice/MailServiceApplication.java +++ b/src/main/java/de/caritas/cob/mailservice/MailServiceApplication.java @@ -9,5 +9,4 @@ public class MailServiceApplication { public static void main(String[] args) { SpringApplication.run(MailServiceApplication.class, args); } - } diff --git a/src/main/java/de/caritas/cob/mailservice/api/ApiDefaultResponseEntityExceptionHandler.java b/src/main/java/de/caritas/cob/mailservice/api/ApiDefaultResponseEntityExceptionHandler.java index bd10aa7..59f8e94 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/ApiDefaultResponseEntityExceptionHandler.java +++ b/src/main/java/de/caritas/cob/mailservice/api/ApiDefaultResponseEntityExceptionHandler.java @@ -1,5 +1,6 @@ package de.caritas.cob.mailservice.api; +import lombok.extern.slf4j.Slf4j; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; @@ -7,7 +8,6 @@ import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; -import lombok.extern.slf4j.Slf4j; @Slf4j @ControllerAdvice @@ -18,15 +18,16 @@ public class ApiDefaultResponseEntityExceptionHandler { * "Catch all" respectively fallback for all controller error messages that are not specifically * retained by {@link ApiResponseEntityExceptionHandler}. For the caller side does not need to * know the exact error stack trace, this method catches the trace and logs it. - * + * * @param ex * @param request * @return */ @ExceptionHandler({RuntimeException.class}) - public ResponseEntity handleInternal(final RuntimeException ex, - final WebRequest request) { - log.error("Default: MailService API: 500 Internal Server Error: {}", + public ResponseEntity handleInternal( + final RuntimeException ex, final WebRequest request) { + log.error( + "Default: MailService API: 500 Internal Server Error: {}", org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(ex)); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); diff --git a/src/main/java/de/caritas/cob/mailservice/api/ApiResponseEntityExceptionHandler.java b/src/main/java/de/caritas/cob/mailservice/api/ApiResponseEntityExceptionHandler.java index 2f7ef23..23b17ed 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/ApiResponseEntityExceptionHandler.java +++ b/src/main/java/de/caritas/cob/mailservice/api/ApiResponseEntityExceptionHandler.java @@ -4,103 +4,75 @@ import de.caritas.cob.mailservice.api.service.LogService; import java.net.UnknownHostException; import javax.validation.ConstraintViolationException; +import lombok.NoArgsConstructor; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.HttpMessageNotReadableException; -import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; -import lombok.NoArgsConstructor; -import lombok.extern.slf4j.Slf4j; /** * Customizes API error/exception handling to hide information and/or possible security * vulnerabilities. - * */ @NoArgsConstructor @ControllerAdvice @Order(Ordered.HIGHEST_PRECEDENCE) public class ApiResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { - /** - * - * Handle all common "Bad Request" errors (400) - * - */ + /** Handle all common "Bad Request" errors (400) */ /** * Constraint violations - * + * * @param ex * @param request * @return */ @ExceptionHandler({ConstraintViolationException.class}) - public ResponseEntity handleBadRequest(final RuntimeException ex, - final WebRequest request) { + public ResponseEntity handleBadRequest( + final RuntimeException ex, final WebRequest request) { LogService.logWarn(ex); return handleExceptionInternal(null, null, new HttpHeaders(), HttpStatus.BAD_REQUEST, request); } - /** - * Incoming request body could not be deserialized - */ - @Override - protected ResponseEntity handleHttpMessageNotReadable( - final HttpMessageNotReadableException ex, final HttpHeaders headers, final HttpStatus status, - final WebRequest request) { - LogService.logWarn(status, ex); - - return handleExceptionInternal(null, null, headers, status, request); - } - - /** - * @Valid on object fails validation - */ - @Override - protected ResponseEntity handleMethodArgumentNotValid( - final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status, - final WebRequest request) { - LogService.logWarn(status, ex); - - return handleExceptionInternal(null, null, headers, status, request); - } - /** * {@link RestTemplate} API client errors */ @ExceptionHandler({HttpClientErrorException.class}) - protected ResponseEntity handleHttpClientException(final HttpClientErrorException ex, - final WebRequest request) { - LogService.logWarn(ex.getStatusCode(), ex); + protected ResponseEntity handleHttpClientException( + final HttpClientErrorException ex, final WebRequest request) { + LogService.logWarn((HttpStatus) ex.getStatusCode(), ex); return handleExceptionInternal(null, null, new HttpHeaders(), ex.getStatusCode(), request); } /** * 500 - Internal Server Error - * + * * @param ex * @param request * @return */ - @ExceptionHandler({NullPointerException.class, IllegalArgumentException.class, - IllegalStateException.class, UnknownHostException.class, InternalServerErrorException.class}) - public ResponseEntity handleInternal(final RuntimeException ex, - final WebRequest request) { + @ExceptionHandler({ + NullPointerException.class, + IllegalArgumentException.class, + IllegalStateException.class, + UnknownHostException.class, + InternalServerErrorException.class + }) + public ResponseEntity handleInternal( + final RuntimeException ex, final WebRequest request) { LogService.logError(ex); - return handleExceptionInternal(null, null, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, - request); + return handleExceptionInternal( + null, null, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request); } - } diff --git a/src/main/java/de/caritas/cob/mailservice/api/TranslationMessageSource.java b/src/main/java/de/caritas/cob/mailservice/api/TranslationMessageSource.java index ab60791..b87a768 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/TranslationMessageSource.java +++ b/src/main/java/de/caritas/cob/mailservice/api/TranslationMessageSource.java @@ -21,8 +21,12 @@ public class TranslationMessageSource implements MessageSource { @Override public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) { - log.info("getMessage called with code: {}, args: {}, defaultMessage: {}, locale: {}", code, - args, defaultMessage, locale); + log.info( + "getMessage called with code: {}, args: {}, defaultMessage: {}, locale: {}", + code, + args, + defaultMessage, + locale); Dialect dialect = determineDialect(locale); return translationService.fetchTranslations(locale.getLanguage(), dialect).get(code); } diff --git a/src/main/java/de/caritas/cob/mailservice/api/cache/CacheEventLogger.java b/src/main/java/de/caritas/cob/mailservice/api/cache/CacheEventLogger.java deleted file mode 100644 index 1434ac7..0000000 --- a/src/main/java/de/caritas/cob/mailservice/api/cache/CacheEventLogger.java +++ /dev/null @@ -1,15 +0,0 @@ -package de.caritas.cob.mailservice.api.cache; - -import lombok.extern.slf4j.Slf4j; -import org.ehcache.event.CacheEvent; -import org.ehcache.event.CacheEventListener; - -@Slf4j -public class CacheEventLogger implements CacheEventListener { - - @Override - public void onEvent(CacheEvent cacheEvent) { - log.info( - "caching event: ", cacheEvent.getKey(), cacheEvent.getOldValue(), cacheEvent.getNewValue()); - } -} diff --git a/src/main/java/de/caritas/cob/mailservice/api/controller/CustomSwaggerUIController.java b/src/main/java/de/caritas/cob/mailservice/api/controller/CustomSwaggerUIController.java deleted file mode 100644 index 846f232..0000000 --- a/src/main/java/de/caritas/cob/mailservice/api/controller/CustomSwaggerUIController.java +++ /dev/null @@ -1,18 +0,0 @@ -package de.caritas.cob.mailservice.api.controller; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import springfox.documentation.annotations.ApiIgnore; - -@Controller -@ApiIgnore -public class CustomSwaggerUIController { - @Value("${springfox.docuPath}") - private String docuPath; - - @RequestMapping(value = "${springfox.docuPath}") - public String index() { - return "redirect:" + docuPath + "/swagger-ui.html"; - } -} diff --git a/src/main/java/de/caritas/cob/mailservice/api/controller/MailController.java b/src/main/java/de/caritas/cob/mailservice/api/controller/MailController.java index c4599bb..cb04eca 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/controller/MailController.java +++ b/src/main/java/de/caritas/cob/mailservice/api/controller/MailController.java @@ -16,9 +16,7 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; -/** - * Controller for mail requests. - */ +/** Controller for mail requests. */ @RestController @RequiredArgsConstructor @Api(tags = "mails-controller") @@ -26,26 +24,25 @@ public class MailController implements MailsApi { private final @NonNull MailService mailService; - /** - * Entry point for mail sending. - */ + /** Entry point for mail sending. */ @Override public ResponseEntity sendMails(@Valid @RequestBody MailsDTO mails) { var defaultLanguage = new MailDTO().getLanguage(); - mails.getMails().forEach(mail -> { - if (isNull(mail.getLanguage())) { - mail.setLanguage(defaultLanguage); - } - }); + mails + .getMails() + .forEach( + mail -> { + if (isNull(mail.getLanguage())) { + mail.setLanguage(defaultLanguage); + } + }); this.mailService.sendHtmlMails(mails); return new ResponseEntity<>(HttpStatus.OK); } - /** - * Entry point for error mail sending. - */ + /** Entry point for error mail sending. */ @Override public ResponseEntity sendErrorMail(@Valid ErrorMailDTO errorMailDTO) { this.mailService.sendErrorMailDto(errorMailDTO); diff --git a/src/main/java/de/caritas/cob/mailservice/api/controller/TranslationController.java b/src/main/java/de/caritas/cob/mailservice/api/controller/TranslationController.java index a7649e4..6c71b0f 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/controller/TranslationController.java +++ b/src/main/java/de/caritas/cob/mailservice/api/controller/TranslationController.java @@ -6,13 +6,10 @@ import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; - @RestController @RequiredArgsConstructor public class TranslationController { @@ -35,5 +32,4 @@ public String evictTranslationCache() { translationService.evictCache(); return "Cache evicted"; } - } diff --git a/src/main/java/de/caritas/cob/mailservice/api/exception/ExchangeMailServiceException.java b/src/main/java/de/caritas/cob/mailservice/api/exception/ExchangeMailServiceException.java index 0f4068a..4a875d0 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/exception/ExchangeMailServiceException.java +++ b/src/main/java/de/caritas/cob/mailservice/api/exception/ExchangeMailServiceException.java @@ -29,5 +29,4 @@ public ExchangeMailServiceException(String message, Exception ex) { public ExchangeMailServiceException(String message) { super(message); } - } diff --git a/src/main/java/de/caritas/cob/mailservice/api/exception/InternalServerErrorException.java b/src/main/java/de/caritas/cob/mailservice/api/exception/InternalServerErrorException.java index 3f0bd9d..6201e9d 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/exception/InternalServerErrorException.java +++ b/src/main/java/de/caritas/cob/mailservice/api/exception/InternalServerErrorException.java @@ -1,8 +1,6 @@ package de.caritas.cob.mailservice.api.exception; -/** - * Server error exception to return status code 500. - */ +/** Server error exception to return status code 500. */ public class InternalServerErrorException extends RuntimeException { /** @@ -23,5 +21,4 @@ public InternalServerErrorException(String message) { public InternalServerErrorException(String message, Exception e) { super(message, e); } - } diff --git a/src/main/java/de/caritas/cob/mailservice/api/exception/SmtpMailServiceException.java b/src/main/java/de/caritas/cob/mailservice/api/exception/SmtpMailServiceException.java index c247605..5dff7cd 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/exception/SmtpMailServiceException.java +++ b/src/main/java/de/caritas/cob/mailservice/api/exception/SmtpMailServiceException.java @@ -29,5 +29,4 @@ public SmtpMailServiceException(String message, Exception ex) { public SmtpMailServiceException(String message) { super(message); } - } diff --git a/src/main/java/de/caritas/cob/mailservice/api/exception/TemplateDescriptionServiceException.java b/src/main/java/de/caritas/cob/mailservice/api/exception/TemplateDescriptionServiceException.java index a261e1b..f708e7b 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/exception/TemplateDescriptionServiceException.java +++ b/src/main/java/de/caritas/cob/mailservice/api/exception/TemplateDescriptionServiceException.java @@ -11,5 +11,4 @@ public class TemplateDescriptionServiceException extends Exception { public TemplateDescriptionServiceException(String message, Exception ex) { super(message, ex); } - } diff --git a/src/main/java/de/caritas/cob/mailservice/api/exception/TemplateServiceException.java b/src/main/java/de/caritas/cob/mailservice/api/exception/TemplateServiceException.java index 03f028b..8926489 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/exception/TemplateServiceException.java +++ b/src/main/java/de/caritas/cob/mailservice/api/exception/TemplateServiceException.java @@ -10,5 +10,4 @@ public class TemplateServiceException extends Exception { public TemplateServiceException(String message) { super(message); } - } diff --git a/src/main/java/de/caritas/cob/mailservice/api/helper/Helper.java b/src/main/java/de/caritas/cob/mailservice/api/helper/Helper.java index c78b130..55e58d0 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/helper/Helper.java +++ b/src/main/java/de/caritas/cob/mailservice/api/helper/Helper.java @@ -8,17 +8,13 @@ import org.jsoup.safety.Whitelist; import org.springframework.stereotype.Component; -/** - * Helper class - * - */ +/** Helper class */ @Component public class Helper { /** - * * Remove HTML code from a text (XSS-Protection) - * + * * @param text * @return the given text without html */ diff --git a/src/main/java/de/caritas/cob/mailservice/api/helper/TemplateDataConverter.java b/src/main/java/de/caritas/cob/mailservice/api/helper/TemplateDataConverter.java index cb7c971..afe03fc 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/helper/TemplateDataConverter.java +++ b/src/main/java/de/caritas/cob/mailservice/api/helper/TemplateDataConverter.java @@ -1,16 +1,14 @@ package de.caritas.cob.mailservice.api.helper; +import de.caritas.cob.mailservice.api.model.TemplateDataDTO; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.springframework.stereotype.Component; -import de.caritas.cob.mailservice.api.model.TemplateDataDTO; import org.springframework.util.CollectionUtils; -/** - * Converter for TemplateDataDTO - */ +/** Converter for TemplateDataDTO */ @Component public class TemplateDataConverter { @@ -22,7 +20,7 @@ public TemplateDataConverter(Helper helper) { /** * Converts a {@link TemplateDataDTO} list to a map - * + * * @param templateDataDTOList The list with objects of {@link TemplateDataDTO} * @return the map */ @@ -32,13 +30,15 @@ public Map convertFromTemplateDataDTOList( Map templateData = new HashMap<>(); if (!CollectionUtils.isEmpty(templateDataDTOList)) { - templateData = templateDataDTOList.stream() - .collect(Collectors.toMap(TemplateDataDTO::getKey, TemplateDataDTO::getValue)); + templateData = + templateDataDTOList.stream() + .collect(Collectors.toMap(TemplateDataDTO::getKey, TemplateDataDTO::getValue)); } - return templateData.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, - e -> helper.unescapeHtml(helper.removeHTMLFromText(String.valueOf(e.getValue()))))); - + return templateData.entrySet().stream() + .collect( + Collectors.toMap( + Map.Entry::getKey, + e -> helper.unescapeHtml(helper.removeHTMLFromText(String.valueOf(e.getValue()))))); } - } diff --git a/src/main/java/de/caritas/cob/mailservice/api/helper/ThymeleafHelper.java b/src/main/java/de/caritas/cob/mailservice/api/helper/ThymeleafHelper.java index c44258f..7e4f55e 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/helper/ThymeleafHelper.java +++ b/src/main/java/de/caritas/cob/mailservice/api/helper/ThymeleafHelper.java @@ -16,8 +16,7 @@ public class ThymeleafHelper { private static final String INFORMAL_GERMAN_LANGUAGE_TAG = "de-DE-u-va-posix"; - @Autowired - private TemplateEngine tempTemplateEngine; + @Autowired private TemplateEngine tempTemplateEngine; private static TemplateEngine templateEngine; @@ -26,7 +25,8 @@ void init() { templateEngine = tempTemplateEngine; } - public static Optional getProcessedHtml(Map data, LanguageCode languageCode, String templateName, Dialect dialect) { + public static Optional getProcessedHtml( + Map data, LanguageCode languageCode, String templateName, Dialect dialect) { Context context = new Context(); Locale locale = Locale.forLanguageTag(getLanguageTag(languageCode, dialect)); @@ -36,7 +36,6 @@ public static Optional getProcessedHtml(Map data, Langua return Optional.of(templateEngine.process(templateName, context)); } return Optional.empty(); - } private static String getLanguageTag(LanguageCode languageCode, Dialect dialect) { diff --git a/src/main/java/de/caritas/cob/mailservice/api/mailtemplate/SubjectDescription.java b/src/main/java/de/caritas/cob/mailservice/api/mailtemplate/SubjectDescription.java index c3a8f8d..7e43652 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/mailtemplate/SubjectDescription.java +++ b/src/main/java/de/caritas/cob/mailservice/api/mailtemplate/SubjectDescription.java @@ -13,6 +13,5 @@ @Builder public class SubjectDescription { - String key; - + String key; } diff --git a/src/main/java/de/caritas/cob/mailservice/api/mailtemplate/TemplateDescription.java b/src/main/java/de/caritas/cob/mailservice/api/mailtemplate/TemplateDescription.java index 4d23da4..e430b17 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/mailtemplate/TemplateDescription.java +++ b/src/main/java/de/caritas/cob/mailservice/api/mailtemplate/TemplateDescription.java @@ -9,9 +9,7 @@ import lombok.NoArgsConstructor; import lombok.Setter; -/** - * Representation for mail a mail template - */ +/** Representation for mail a mail template */ @AllArgsConstructor @NoArgsConstructor @Getter diff --git a/src/main/java/de/caritas/cob/mailservice/api/mailtemplate/TemplateImage.java b/src/main/java/de/caritas/cob/mailservice/api/mailtemplate/TemplateImage.java index 6fc87e7..9931c0f 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/mailtemplate/TemplateImage.java +++ b/src/main/java/de/caritas/cob/mailservice/api/mailtemplate/TemplateImage.java @@ -5,9 +5,7 @@ import lombok.NoArgsConstructor; import lombok.Setter; -/** - * Representation for an image in a mail template - */ +/** Representation for an image in a mail template */ @AllArgsConstructor @NoArgsConstructor @Getter @@ -16,5 +14,4 @@ public class TemplateImage { private String filename; private String filetype; - } diff --git a/src/main/java/de/caritas/cob/mailservice/api/service/DefaultTranslationsService.java b/src/main/java/de/caritas/cob/mailservice/api/service/DefaultTranslationsService.java index 4765b95..f06fa45 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/service/DefaultTranslationsService.java +++ b/src/main/java/de/caritas/cob/mailservice/api/service/DefaultTranslationsService.java @@ -1,20 +1,18 @@ package de.caritas.cob.mailservice.api.service; +import de.caritas.cob.mailservice.api.model.Dialect; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.List; - +import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; -import de.caritas.cob.mailservice.api.model.Dialect; -import lombok.extern.slf4j.Slf4j; - @Slf4j @Service public class DefaultTranslationsService { @@ -25,50 +23,69 @@ public class DefaultTranslationsService { @Value("${template.use.custom.resources.path}") private boolean useCustomResourcesPath; - public String fetchDefaultTranslations(String translationComponentName, String languageCode, - Dialect dialect) { - InputStream inputStream = useCustomResourcesPath ? tryFetchExternalTranslationWithFallbackToEmptyDialect(translationComponentName, languageCode, dialect) : - tryFetchDefaultTranslationWithFallbackToEmptyDialect(translationComponentName, languageCode, dialect); + public String fetchDefaultTranslations( + String translationComponentName, String languageCode, Dialect dialect) { + InputStream inputStream = + useCustomResourcesPath + ? tryFetchExternalTranslationWithFallbackToEmptyDialect( + translationComponentName, languageCode, dialect) + : tryFetchDefaultTranslationWithFallbackToEmptyDialect( + translationComponentName, languageCode, dialect); if (inputStream == null) { return "{}"; } try { - final List fileLines = IOUtils - .readLines(inputStream, StandardCharsets.UTF_8.displayName()); + final List fileLines = + IOUtils.readLines(inputStream, StandardCharsets.UTF_8.displayName()); return String.join("", fileLines); } catch (IOException ex) { - throw new IllegalStateException(String.format( - "Json file with translations could not be loaded, translation component name: %s", - translationComponentName), ex); + throw new IllegalStateException( + String.format( + "Json file with translations could not be loaded, translation component name: %s", + translationComponentName), + ex); } } - private InputStream tryFetchExternalTranslationWithFallbackToEmptyDialect(String translationComponentName, String languageCode, - Dialect dialect) { - InputStream inputStream = buildStreamForExternalPath(translationComponentName, languageCode, dialect); - return inputStream != null ? inputStream : buildStreamForExternalPath(translationComponentName, languageCode, null); + private InputStream tryFetchExternalTranslationWithFallbackToEmptyDialect( + String translationComponentName, String languageCode, Dialect dialect) { + InputStream inputStream = + buildStreamForExternalPath(translationComponentName, languageCode, dialect); + return inputStream != null + ? inputStream + : buildStreamForExternalPath(translationComponentName, languageCode, null); } - private FileInputStream buildStreamForExternalPath(String translationComponentName, String languageCode, Dialect dialect) { + private FileInputStream buildStreamForExternalPath( + String translationComponentName, String languageCode, Dialect dialect) { try { - String filename = String.format("%s/%s.%s%s.json", customTranslationsPath, translationComponentName.toLowerCase(), languageCode, getDialectSuffix(dialect)); + String filename = + String.format( + "%s/%s.%s%s.json", + customTranslationsPath, + translationComponentName.toLowerCase(), + languageCode, + getDialectSuffix(dialect)); return new FileInputStream(filename); } catch (FileNotFoundException e) { - log.warn("Default translations for component {}, language {} not found in external path {}", translationComponentName, - languageCode, customTranslationsPath); + log.warn( + "Default translations for component {}, language {} not found in external path {}", + translationComponentName, + languageCode, + customTranslationsPath); return null; } } - private InputStream tryFetchDefaultTranslationWithFallbackToEmptyDialect(String translationComponentName, String languageCode, - Dialect dialect) { - InputStream inputStream = getInputStream(translationComponentName, languageCode, - dialect); + private InputStream tryFetchDefaultTranslationWithFallbackToEmptyDialect( + String translationComponentName, String languageCode, Dialect dialect) { + InputStream inputStream = getInputStream(translationComponentName, languageCode, dialect); if (inputStream == null) { log.warn( "Default translations for component {}, language {}, dialect {} not found in resources. Will try to fallback to default translations for empty dialect.", translationComponentName, - languageCode, dialect); + languageCode, + dialect); inputStream = getInputStream(translationComponentName, languageCode, null); if (inputStream == null) { @@ -82,11 +99,11 @@ private InputStream tryFetchDefaultTranslationWithFallbackToEmptyDialect(String return inputStream; } - private InputStream getInputStream(String translationComponentName, String languageCode, - Dialect dialect) { - String translationFilename = getTranslationFilename( - translationComponentName + "." + languageCode - + getDialectSuffix(dialect)); + private InputStream getInputStream( + String translationComponentName, String languageCode, Dialect dialect) { + String translationFilename = + getTranslationFilename( + translationComponentName + "." + languageCode + getDialectSuffix(dialect)); return TranslationService.class.getResourceAsStream(translationFilename); } diff --git a/src/main/java/de/caritas/cob/mailservice/api/service/ExchangeMailService.java b/src/main/java/de/caritas/cob/mailservice/api/service/ExchangeMailService.java index 30862dc..bdd9e32 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/service/ExchangeMailService.java +++ b/src/main/java/de/caritas/cob/mailservice/api/service/ExchangeMailService.java @@ -20,16 +20,13 @@ import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; -/** - * Service for sending mails via exchange - */ +/** Service for sending mails via exchange */ @Service public class ExchangeMailService { private static final String TEMPLATE_IMAGE_DIR = "/templates/images/"; private static final String CUSTOM_TEMPLATE_IMAGE_DIR = "images/"; - @Value("${mail.sender}") private String mailSender; @@ -57,12 +54,13 @@ public class ExchangeMailService { /** * Preparing and sending an html mail via Exchange. * - * @param recipient The mail address of the recipient - * @param subject The subject of the mail + * @param recipient The mail address of the recipient + * @param subject The subject of the mail * @param htmlTemplate The name of the html template */ - public void prepareAndSendHtmlMail(String recipient, String subject, String htmlTemplate, - List templateImages) throws ExchangeMailServiceException { + public void prepareAndSendHtmlMail( + String recipient, String subject, String htmlTemplate, List templateImages) + throws ExchangeMailServiceException { this.prepareAndSendMail(recipient, subject, htmlTemplate, templateImages, BodyType.HTML); } @@ -70,16 +68,21 @@ public void prepareAndSendHtmlMail(String recipient, String subject, String html * Preparing and sending an text mail via Exchange. * * @param recipients The mail address of the recipients - * @param subject The subject of the mail - * @param body The text to send + * @param subject The subject of the mail + * @param body The text to send */ public void prepareAndSendTextMail(String recipients, String subject, String body) throws ExchangeMailServiceException { this.prepareAndSendMail(recipients, subject, body, null, BodyType.Text); } - private void prepareAndSendMail(String recipients, String subject, String bodyText, - List templateImages, BodyType bodyType) throws ExchangeMailServiceException { + private void prepareAndSendMail( + String recipients, + String subject, + String bodyText, + List templateImages, + BodyType bodyType) + throws ExchangeMailServiceException { if (isNull(mailSender)) { throw new ExchangeMailServiceException("No sender mail address set"); @@ -116,8 +119,9 @@ private void setupExchangeService(ExchangeService exchangeService) } } - private EmailMessage buildEmailMessage(String subject, String bodyText, BodyType bodyType, - ExchangeService exchangeService) throws ExchangeMailServiceException { + private EmailMessage buildEmailMessage( + String subject, String bodyText, BodyType bodyType, ExchangeService exchangeService) + throws ExchangeMailServiceException { try { var msg = new EmailMessage(exchangeService); msg.setSubject(subject); @@ -140,16 +144,20 @@ private void addEmailAttachmentsIfNecessary(List templateImages, for (TemplateImage templateImage : templateImages) { try { var inputStream = - useCustomResourcesPath ? buildStreamForExternalPath(templateImage.getFilename()) + useCustomResourcesPath + ? buildStreamForExternalPath(templateImage.getFilename()) : getClass() .getResourceAsStream(TEMPLATE_IMAGE_DIR + templateImage.getFilename()); msg.getAttachments().addFileAttachment(templateImage.getFilename(), inputStream); msg.getAttachments().getItems().get(attachmentIndex).setIsInline(true); - msg.getAttachments().getItems().get(attachmentIndex) + msg.getAttachments() + .getItems() + .get(attachmentIndex) .setContentId(templateImage.getFilename()); - msg.getAttachments().getItems().get(attachmentIndex) - .setName(templateImage.getFilename()); - msg.getAttachments().getItems().get(attachmentIndex) + msg.getAttachments().getItems().get(attachmentIndex).setName(templateImage.getFilename()); + msg.getAttachments() + .getItems() + .get(attachmentIndex) .setContentType(templateImage.getFiletype()); attachmentIndex++; } catch (Exception e) { @@ -180,5 +188,4 @@ private void setMailRecipients(String recipients, EmailMessage msg) throw new ExchangeMailServiceException("Could not set recipient", e); } } - } diff --git a/src/main/java/de/caritas/cob/mailservice/api/service/LogService.java b/src/main/java/de/caritas/cob/mailservice/api/service/LogService.java index 2c033c2..3fa690f 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/service/LogService.java +++ b/src/main/java/de/caritas/cob/mailservice/api/service/LogService.java @@ -4,15 +4,12 @@ import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; -/** - * Service for logging. - */ +/** Service for logging. */ public class LogService { private static final Logger LOGGER = LoggerFactory.getLogger(LogService.class); - private LogService() { - } + private LogService() {} /** * Logs a an error with exception. @@ -69,7 +66,9 @@ public static void logWarn(String message) { * @param exception the exception to be logged */ public static void logWarn(HttpStatus status, Exception exception) { - LOGGER.warn("MailService API: {}: {}", status.getReasonPhrase(), + LOGGER.warn( + "MailService API: {}: {}", + status.getReasonPhrase(), org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(exception)); } @@ -79,8 +78,8 @@ public static void logWarn(HttpStatus status, Exception exception) { * @param exception the exception */ public static void logWarn(Exception exception) { - LOGGER.warn("MailService API: {}: ", + LOGGER.warn( + "MailService API: {}: ", org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(exception)); } - } diff --git a/src/main/java/de/caritas/cob/mailservice/api/service/MailErrorMessageBuilder.java b/src/main/java/de/caritas/cob/mailservice/api/service/MailErrorMessageBuilder.java index 60d0c35..91c978b 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/service/MailErrorMessageBuilder.java +++ b/src/main/java/de/caritas/cob/mailservice/api/service/MailErrorMessageBuilder.java @@ -20,16 +20,13 @@ public class MailErrorMessageBuilder { * @return the generated error message without email addresses */ public String buildEmailErrorMessage(MailDTO mail, Exception ex) { - String errorMessage = String.format("Mail request for template %s could not be executed.", - mail.getTemplate()); + String errorMessage = + String.format("Mail request for template %s could not be executed.", mail.getTemplate()); - return "Error message:" - + errorMessage + "\n" - + replaceMailAddresses(getStackTrace(ex)); + return "Error message:" + errorMessage + "\n" + replaceMailAddresses(getStackTrace(ex)); } private String replaceMailAddresses(String stacktrace) { return stacktrace.replaceAll(SIMPLE_EMAIL_PATTERN, ""); } - } diff --git a/src/main/java/de/caritas/cob/mailservice/api/service/MailService.java b/src/main/java/de/caritas/cob/mailservice/api/service/MailService.java index 60e9bc2..2485a8b 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/service/MailService.java +++ b/src/main/java/de/caritas/cob/mailservice/api/service/MailService.java @@ -53,10 +53,11 @@ public void sendHtmlMails(MailsDTO mailsDTO) { private Consumer renderAndSendHtmlMail() { return mailDTO -> { try { - templateDescriptionService.getTemplateDescription(mailDTO.getTemplate()).ifPresentOrElse( - desc -> loadRequiredMailDataAndSendMail(mailDTO, desc), - () -> logAndSendErrorMessage(mailDTO) - ); + templateDescriptionService + .getTemplateDescription(mailDTO.getTemplate()) + .ifPresentOrElse( + desc -> loadRequiredMailDataAndSendMail(mailDTO, desc), + () -> logAndSendErrorMessage(mailDTO)); } catch (TemplateDescriptionServiceException ex) { handleMailSendFailure(mailDTO, ex); } @@ -64,8 +65,8 @@ private Consumer renderAndSendHtmlMail() { } private void logAndSendErrorMessage(MailDTO mail) { - String errorMessage = String - .format("Template description %s could not be found.", mail.getTemplate()); + String errorMessage = + String.format("Template description %s could not be found.", mail.getTemplate()); LogService.logError(errorMessage); sendErrorMail(errorMessage); } @@ -87,15 +88,15 @@ private void renderAndSend(MailDTO mail, TemplateDescription desc, Map loadUnescapedMailDataAndSendMail(mailDTO, - templateDescription)); + templateDescriptionService + .getTemplateDescription(mailDTO.getTemplate()) + .ifPresent( + templateDescription -> + loadUnescapedMailDataAndSendMail(mailDTO, templateDescription)); } catch (TemplateDescriptionServiceException e) { handleMailSendFailure(mailDTO, e); } } private void loadUnescapedMailDataAndSendMail(MailDTO mail, TemplateDescription desc) { - Map templateData = mail.getTemplateData() - .stream() - .collect(Collectors.toMap(TemplateDataDTO::getKey, TemplateDataDTO::getValue)); + Map templateData = + mail.getTemplateData().stream() + .collect(Collectors.toMap(TemplateDataDTO::getKey, TemplateDataDTO::getValue)); renderAndSend(mail, desc, templateData); } diff --git a/src/main/java/de/caritas/cob/mailservice/api/service/SmtpMailService.java b/src/main/java/de/caritas/cob/mailservice/api/service/SmtpMailService.java index f5ab0ec..04ab90e 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/service/SmtpMailService.java +++ b/src/main/java/de/caritas/cob/mailservice/api/service/SmtpMailService.java @@ -20,9 +20,7 @@ import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; -/** - * Service for sending mails via smtp - */ +/** Service for sending mails via smtp */ @Service public class SmtpMailService { @@ -43,9 +41,7 @@ public class SmtpMailService { @Value("${template.use.custom.resources.path}") private boolean useCustomResourcesPath; - /** - * Standard constructor for mail service - */ + /** Standard constructor for mail service */ @Autowired public SmtpMailService(JavaMailSender javaMailSender) { this.javaMailSender = javaMailSender; @@ -54,31 +50,31 @@ public SmtpMailService(JavaMailSender javaMailSender) { /** * Preparing and sending an html mail via smtp. * - * @param recipient The mail address of the recipient - * @param subject The subject of the mail + * @param recipient The mail address of the recipient + * @param subject The subject of the mail * @param htmlTemplate The name of the html template */ - public void prepareAndSendHtmlMail(String recipient, String subject, String htmlTemplate, - List templateImages) throws SmtpMailServiceException { + public void prepareAndSendHtmlMail( + String recipient, String subject, String htmlTemplate, List templateImages) + throws SmtpMailServiceException { if (isNull(mailSender)) { throw new SmtpMailServiceException("No sender mail address set"); } try { - javaMailSender - .send(buildHtmlMessagePreparator(recipient, subject, htmlTemplate, templateImages)); + javaMailSender.send( + buildHtmlMessagePreparator(recipient, subject, htmlTemplate, templateImages)); } catch (MailException ex) { throw new SmtpMailServiceException("Mail could not be send", ex); } - } - private MimeMessagePreparator buildHtmlMessagePreparator(String recipient, String subject, - String htmlTemplate, List templateImages) { + private MimeMessagePreparator buildHtmlMessagePreparator( + String recipient, String subject, String htmlTemplate, List templateImages) { return mimeMessage -> { - var messageHelper = new MimeMessageHelper(mimeMessage, - (!CollectionUtils.isEmpty(templateImages)), "UTF-8"); + var messageHelper = + new MimeMessageHelper(mimeMessage, (!CollectionUtils.isEmpty(templateImages)), "UTF-8"); messageHelper.setFrom(this.mailSender); messageHelper.setTo(getRecipients(recipient)); messageHelper.setSubject(subject); @@ -88,17 +84,19 @@ private MimeMessagePreparator buildHtmlMessagePreparator(String recipient, Strin for (TemplateImage templateImage : templateImages) { InputStreamSource inputStreamSource; if (useCustomResourcesPath) { - inputStreamSource = new ByteArrayResource( - IOUtils.toByteArray(new FileInputStream( - customResourcePath + CUSTOM_TEMPLATE_IMAGE_DIR + templateImage - .getFilename()))); + inputStreamSource = + new ByteArrayResource( + IOUtils.toByteArray( + new FileInputStream( + customResourcePath + + CUSTOM_TEMPLATE_IMAGE_DIR + + templateImage.getFilename()))); } else { - inputStreamSource = new ClassPathResource( - TEMPLATE_IMAGE_DIR + templateImage - .getFilename()); + inputStreamSource = + new ClassPathResource(TEMPLATE_IMAGE_DIR + templateImage.getFilename()); } - messageHelper.addInline(templateImage.getFilename(), inputStreamSource, - templateImage.getFiletype()); + messageHelper.addInline( + templateImage.getFilename(), inputStreamSource, templateImage.getFiletype()); } } }; @@ -108,8 +106,8 @@ private MimeMessagePreparator buildHtmlMessagePreparator(String recipient, Strin * Preparing and sending an simple text mail. * * @param recipient The mail address of the recipient - * @param subject The subject of the mail - * @param body The body of the mail + * @param subject The subject of the mail + * @param body The body of the mail */ public void prepareAndSendTextMail(String recipient, String subject, String body) throws SmtpMailServiceException { @@ -125,10 +123,9 @@ public void prepareAndSendTextMail(String recipient, String subject, String body } } - private MimeMessagePreparator buildTextMessagePreparator(String recipient, String subject, - String body) { + private MimeMessagePreparator buildTextMessagePreparator( + String recipient, String subject, String body) { return mimeMessage -> { - var messageHelper = new MimeMessageHelper(mimeMessage); messageHelper.setFrom(this.mailSender); messageHelper.setTo(getRecipients(recipient)); @@ -139,7 +136,7 @@ private MimeMessagePreparator buildTextMessagePreparator(String recipient, Strin private String[] getRecipients(String recipient) { if (isNotBlank(fixMailRecipient)) { - return new String[] { fixMailRecipient }; + return new String[] {fixMailRecipient}; } else { return recipient.split(","); } diff --git a/src/main/java/de/caritas/cob/mailservice/api/service/TemplateDescriptionService.java b/src/main/java/de/caritas/cob/mailservice/api/service/TemplateDescriptionService.java index ae2efde..d6ed20a 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/service/TemplateDescriptionService.java +++ b/src/main/java/de/caritas/cob/mailservice/api/service/TemplateDescriptionService.java @@ -12,9 +12,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; -/** - * Service for mail templates - */ +/** Service for mail templates */ @Service public class TemplateDescriptionService { @@ -37,7 +35,6 @@ public Optional getTemplateDescription(String templateName) throws TemplateDescriptionServiceException { return Optional.of(loadTemplateDescription(templateName)); - } /** @@ -53,9 +50,11 @@ private TemplateDescription loadTemplateDescription(String templateName) try { return mapper.readValue(templateDescriptionJson, TemplateDescription.class); } catch (Exception ex) { - throw new TemplateDescriptionServiceException(String.format( - "Json file with template description could not be parsed, template name: %s", - templateName), ex); + throw new TemplateDescriptionServiceException( + String.format( + "Json file with template description could not be parsed, template name: %s", + templateName), + ex); } } @@ -68,16 +67,21 @@ private TemplateDescription loadTemplateDescription(String templateName) private String loadTemplateDescriptionFile(String templateName) throws TemplateDescriptionServiceException { try { - var inputStream = useCustomResourcesPath ? buildStreamForExternalPath(templateName) - : TemplateDescriptionService.class.getResourceAsStream(getTemplateFilename(templateName)); + var inputStream = + useCustomResourcesPath + ? buildStreamForExternalPath(templateName) + : TemplateDescriptionService.class.getResourceAsStream( + getTemplateFilename(templateName)); assert inputStream != null; - final List fileLines = IOUtils - .readLines(inputStream, StandardCharsets.UTF_8.displayName()); + final List fileLines = + IOUtils.readLines(inputStream, StandardCharsets.UTF_8.displayName()); return String.join("", fileLines); } catch (Exception ex) { - throw new TemplateDescriptionServiceException(String.format( - "Json file with template description could not be loaded, template name: %s", - templateName), ex); + throw new TemplateDescriptionServiceException( + String.format( + "Json file with template description could not be loaded, template name: %s", + templateName), + ex); } } @@ -96,5 +100,4 @@ private FileInputStream buildStreamForExternalPath(String templateName) private String getTemplateFilename(String templateName) { return TEMPLATE_DIR + templateName.toLowerCase() + TEMPLATE_EXTENSION; } - } diff --git a/src/main/java/de/caritas/cob/mailservice/api/service/TemplateService.java b/src/main/java/de/caritas/cob/mailservice/api/service/TemplateService.java index 1ec094d..f1d1477 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/service/TemplateService.java +++ b/src/main/java/de/caritas/cob/mailservice/api/service/TemplateService.java @@ -20,9 +20,7 @@ import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; -/** - * Service for template processing - **/ +/** Service for template processing */ @Service @RequiredArgsConstructor @Slf4j @@ -34,61 +32,71 @@ public class TemplateService { @Value("${app.dataprivacy.url}") private String dataPrivacyUrl; - @NonNull - private final TranslationService translationService; + @NonNull private final TranslationService translationService; /** * Get the processed html template with replaced placeholders * - * @param desc the template description - * @param data the template data + * @param desc the template description + * @param data the template data * @return if success, an optional with the html template, otherwise an empty optional */ - public Optional render(TemplateDescription desc, MailDTO mail, Map data) throws TemplateServiceException { + public Optional render(TemplateDescription desc, MailDTO mail, Map data) + throws TemplateServiceException { data.put("urlimpressum", imprintUrl); data.put("urldatenschutz", dataPrivacyUrl); - data.putAll(getTranslationMapAndDefaultToGermanIfNotFound(mail.getLanguage(), mail.getDialect())); + data.putAll( + getTranslationMapAndDefaultToGermanIfNotFound(mail.getLanguage(), mail.getDialect())); List missingFieldList = getMissingTemplateFields(desc, data); if (!CollectionUtils.isEmpty(missingFieldList)) { - throw new TemplateServiceException(String.format( - "Mail request for template %s could not be executed due to missing fields for template processing. Missing fields: %s", - mail.getTemplate(), String.join(",", missingFieldList))); + throw new TemplateServiceException( + String.format( + "Mail request for template %s could not be executed due to missing fields for template processing. Missing fields: %s", + mail.getTemplate(), String.join(",", missingFieldList))); } var templateFilename = desc.getTemplateFilenameOrFallback(mail.getLanguage()); - return translationsArePresentAndNotEmpty(mail) ? getProcessedHtml(data, mail.getLanguage(), templateFilename, mail.getDialect()) : - getProcessedHtml(data, LanguageCode.DE, templateFilename, mail.getDialect()); + return translationsArePresentAndNotEmpty(mail) + ? getProcessedHtml(data, mail.getLanguage(), templateFilename, mail.getDialect()) + : getProcessedHtml(data, LanguageCode.DE, templateFilename, mail.getDialect()); } private boolean translationsArePresentAndNotEmpty(MailDTO mailDTO) { - var translations = translationService.tryFetchTranslations( - mailDTO.getLanguage().getValue(), mailDTO.getDialect()); + var translations = + translationService.tryFetchTranslations( + mailDTO.getLanguage().getValue(), mailDTO.getDialect()); return translations.isPresent() && !translations.get().isEmpty(); } - private Map getTranslationMapAndDefaultToGermanIfNotFound(LanguageCode language, Dialect dialect) { - return translationService.tryFetchTranslations(language.getValue(), dialect).orElse( - translationService.tryFetchTranslations(LanguageCode.DE.getValue(), dialect) - .orElse(new HashMap<>())); + private Map getTranslationMapAndDefaultToGermanIfNotFound( + LanguageCode language, Dialect dialect) { + return translationService + .tryFetchTranslations(language.getValue(), dialect) + .orElse( + translationService + .tryFetchTranslations(LanguageCode.DE.getValue(), dialect) + .orElse(new HashMap<>())); } /** * Get the processed subject with replaced placeholders * * @param templateDescription the mail template - * @param templateData the template data + * @param templateData the template data * @return the subject with replaced placeholders */ - public String getRenderedSubject(TemplateDescription templateDescription, - Map templateData, MailDTO mailDTO) { + public String getRenderedSubject( + TemplateDescription templateDescription, Map templateData, MailDTO mailDTO) { StringSubstitutor stringSubstitutor = new StringSubstitutor(templateData, "${", "}"); var subjectKey = templateDescription.getSubject().getKey(); if (subjectKey == null) { - log.warn("Subject key is null for template {}", templateDescription.getHtmlTemplateFilename().get(LanguageCode.DE)); + log.warn( + "Subject key is null for template {}", + templateDescription.getHtmlTemplateFilename().get(LanguageCode.DE)); return tryRenderDefaultSubject(stringSubstitutor); } return getRenderedSubjectForSubjectKeyNotNull(mailDTO, stringSubstitutor, subjectKey); @@ -98,10 +106,10 @@ private String tryRenderDefaultSubject(StringSubstitutor stringSubstitutor) { return stringSubstitutor.replace("${subject}"); } - private String getRenderedSubjectForSubjectKeyNotNull(MailDTO mailDTO, StringSubstitutor stringSubstitutor, - String subjectKey) { - var translationKeys = getTranslationMapAndDefaultToGermanIfNotFound(mailDTO.getLanguage(), - mailDTO.getDialect()); + private String getRenderedSubjectForSubjectKeyNotNull( + MailDTO mailDTO, StringSubstitutor stringSubstitutor, String subjectKey) { + var translationKeys = + getTranslationMapAndDefaultToGermanIfNotFound(mailDTO.getLanguage(), mailDTO.getDialect()); String subject = translationKeys.get(subjectKey); if (subject != null) { return stringSubstitutor.replace(subject); @@ -118,8 +126,8 @@ private String getRenderedSubjectForSubjectKeyNotNull(MailDTO mailDTO, StringSub * @param templateData The template data * @return a list with the missing fields */ - private List getMissingTemplateFields(TemplateDescription mailTemplate, - Map templateData) { + private List getMissingTemplateFields( + TemplateDescription mailTemplate, Map templateData) { if (templateData == null) { templateData = new HashMap<>(); } diff --git a/src/main/java/de/caritas/cob/mailservice/api/service/TranslationService.java b/src/main/java/de/caritas/cob/mailservice/api/service/TranslationService.java index a7b6c28..5ad15ee 100644 --- a/src/main/java/de/caritas/cob/mailservice/api/service/TranslationService.java +++ b/src/main/java/de/caritas/cob/mailservice/api/service/TranslationService.java @@ -35,12 +35,14 @@ public class TranslationService { @Value("${translation.management.system.enabled}") private boolean translationManagementSystemEnabled; - private final @NonNull TranslationManagementServiceApiClient translationManagementServiceApiClient; + private final @NonNull TranslationManagementServiceApiClient + translationManagementServiceApiClient; private final @NonNull DefaultTranslationsService defaultTranslationsService; public TranslationService( - TranslationManagementServiceApiClient translationManagementServiceApiClient, DefaultTranslationsService defaultTranslationsService) { + TranslationManagementServiceApiClient translationManagementServiceApiClient, + DefaultTranslationsService defaultTranslationsService) { this.translationManagementServiceApiClient = translationManagementServiceApiClient; this.defaultTranslationsService = defaultTranslationsService; } @@ -51,9 +53,11 @@ public Map fetchTranslations(String languageCode, Dialect dialec return fetchTranslationAsMap(languageCode, dialect); } catch (JsonProcessingException ex) { - throw new TranslationServiceException(String.format( - "Json file with translations could not be parsed, translation component name: %s", - component), ex); + throw new TranslationServiceException( + String.format( + "Json file with translations could not be parsed, translation component name: %s", + component), + ex); } } @@ -76,8 +80,8 @@ public Optional> tryFetchTranslations(String languageCode, D var result = fetchTranslationAsMap(languageCode, dialect); return result.isEmpty() ? Optional.empty() : Optional.of(result); } catch (JsonProcessingException e) { - log.warn("Error while processing json file with translations. Returning empty translations", - e); + log.warn( + "Error while processing json file with translations. Returning empty translations", e); return Optional.empty(); } } @@ -86,34 +90,38 @@ private String fetchTranslationsAsString(String languageCode, Dialect dialect) { return fetchDefaultTranslationsFromTranslationsManagementSystem(languageCode, dialect); } - private String fetchDefaultTranslationsFromTranslationsManagementSystem(String languageCode, Dialect dialect) { + private String fetchDefaultTranslationsFromTranslationsManagementSystem( + String languageCode, Dialect dialect) { try { - log.info("Fetching translations. Translation management system enabled value: {}", + log.info( + "Fetching translations. Translation management system enabled value: {}", translationManagementSystemEnabled); - return translationManagementSystemEnabled ? translationManagementServiceApiClient.tryFetchTranslationsFromTranslationManagementService( - project, component, - languageCode, dialect) : defaultTranslationsService.fetchDefaultTranslations(component, languageCode, - dialect); + return translationManagementSystemEnabled + ? translationManagementServiceApiClient + .tryFetchTranslationsFromTranslationManagementService( + project, component, + languageCode, dialect) + : defaultTranslationsService.fetchDefaultTranslations(component, languageCode, dialect); } catch (HttpClientErrorException e) { if (HttpStatus.NOT_FOUND.equals(e.getStatusCode())) { log.warn( "Translations for component {}, language {} not found in weblate, returning default translations", component, languageCode); - return defaultTranslationsService.fetchDefaultTranslations(component, languageCode, - dialect); + return defaultTranslationsService.fetchDefaultTranslations( + component, languageCode, dialect); } else { log.error("Error while fetching translations from translation management service", e); throw e; } } catch (ResourceAccessException ex) { - log.error("ResourceAccessException error while fetching translations from translation management service. Will fallback to resolve default translations."); + log.error( + "ResourceAccessException error while fetching translations from translation management service. Will fallback to resolve default translations."); log.debug("Exception details: ", ex); return defaultTranslationsService.fetchDefaultTranslations(component, languageCode, dialect); } } - private class TranslationServiceException extends RuntimeException { public TranslationServiceException(String format, JsonProcessingException ex) { diff --git a/src/main/java/de/caritas/cob/mailservice/config/AppConfig.java b/src/main/java/de/caritas/cob/mailservice/config/AppConfig.java index 804227a..2024189 100644 --- a/src/main/java/de/caritas/cob/mailservice/config/AppConfig.java +++ b/src/main/java/de/caritas/cob/mailservice/config/AppConfig.java @@ -9,9 +9,7 @@ import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.client.RestTemplate; -/** - * Contains some general spring boot application configurations - */ +/** Contains some general spring boot application configurations */ @Configuration @ComponentScan(basePackages = {"de.caritas.cob.mailservice"}) @EnableCaching @@ -34,5 +32,4 @@ public LocalValidatorFactoryBean validator(MessageSource messageSource) { public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } - } diff --git a/src/main/java/de/caritas/cob/mailservice/config/CustomSwaggerUIPathWebMvcConfigurer.java b/src/main/java/de/caritas/cob/mailservice/config/CustomSwaggerUIPathWebMvcConfigurer.java index 4f1fff9..1e5d707 100644 --- a/src/main/java/de/caritas/cob/mailservice/config/CustomSwaggerUIPathWebMvcConfigurer.java +++ b/src/main/java/de/caritas/cob/mailservice/config/CustomSwaggerUIPathWebMvcConfigurer.java @@ -13,8 +13,8 @@ public class CustomSwaggerUIPathWebMvcConfigurer implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler(docuPath + "/**") + registry + .addResourceHandler(docuPath + "/**") .addResourceLocations("classpath:/META-INF/resources/"); } - } diff --git a/src/main/java/de/caritas/cob/mailservice/config/SecurityConfig.java b/src/main/java/de/caritas/cob/mailservice/config/SecurityConfig.java index 66a36fa..4fd787b 100644 --- a/src/main/java/de/caritas/cob/mailservice/config/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/mailservice/config/SecurityConfig.java @@ -1,22 +1,36 @@ package de.caritas.cob.mailservice.config; +import de.caritas.cob.mailservice.filter.StatelessCsrfFilter; +import java.util.List; import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy; import org.springframework.security.web.csrf.CsrfFilter; -import de.caritas.cob.mailservice.filter.StatelessCsrfFilter; -/** - * Provides the Security configuration. - * - */ +/** Provides the Security configuration. */ @Configuration @EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { +public class SecurityConfig { + + public static final List WHITE_LIST = + List.of( + "/mails/docs", + "/mails/docs/**", + "/v2/api-docs", + "/configuration/ui", + "/swagger-resources/**", + "/configuration/security", + "/swagger-ui.html", + "/webjars/**", + "/actuator/health", + "/actuator/health/**", + "/translations", + "/translations/**"); @Value("${csrf.cookie.property}") private String csrfCookieProperty; @@ -24,19 +38,24 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Value("${csrf.header.property}") private String csrfHeaderProperty; - /** - * Configure spring security filter chain - * - */ - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable() - .addFilterBefore(new StatelessCsrfFilter(csrfCookieProperty, csrfHeaderProperty), - CsrfFilter.class) - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) - .sessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy()).and() + @Bean + public SecurityFilterChain configure(HttpSecurity http) throws Exception { + + var httpSecurity = + http.csrf() + .disable() + .addFilterBefore( + new StatelessCsrfFilter(csrfCookieProperty, csrfHeaderProperty), CsrfFilter.class); + + httpSecurity + .sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .sessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy()) + .and() .authorizeRequests() - .anyRequest().permitAll(); - } + .anyRequest() + .permitAll(); + return httpSecurity.build(); + } } diff --git a/src/main/java/de/caritas/cob/mailservice/config/SpringFoxConfig.java b/src/main/java/de/caritas/cob/mailservice/config/SpringFoxConfig.java deleted file mode 100644 index a0b395f..0000000 --- a/src/main/java/de/caritas/cob/mailservice/config/SpringFoxConfig.java +++ /dev/null @@ -1,90 +0,0 @@ -package de.caritas.cob.mailservice.config; - -import java.time.LocalTime; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.service.Contact; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; - -/** - * Provides the SpringFox (API documentation generation) configuration. - * - */ -@Configuration -@Import(BeanValidatorPluginsConfiguration.class) -public class SpringFoxConfig { - - @Value("${springfox.docuTitle}") - private String docuTitle; - @Value("${springfox.docuDescription}") - private String docuDescription; - @Value("${springfox.docuVersion}") - private String docuVersion; - @Value("${springfox.docuTermsUrl}") - private String docuTermsUrl; - @Value("${springfox.docuContactName}") - private String docuContactName; - @Value("${springfox.docuContactUrl}") - private String docuContactUrl; - @Value("${springfox.docuContactEmail}") - private String docuContactEmail; - @Value("${springfox.docuLicense}") - private String docuLicense; - @Value("${springfox.docuLicenseUrl}") - private String docuLicenseUrl; - - // White list for path patterns that should be white listed so that swagger UI can be accessed - // without authorization - public static final String[] WHITE_LIST = - new String[] {"/mails/docs", "/mails/docs/**", "/v2/api-docs", "/configuration/ui", - "/swagger-resources/**", "/configuration/security", "/swagger-ui.html", "/webjars/**", "/actuator/health", "/actuator/health/**", "/translations", "/translations/**"}; - - @Bean - public Docket apiDocket() { - return new Docket(DocumentationType.SWAGGER_2).select() - .apis(RequestHandlerSelectors.basePackage("de.caritas.cob.mailservice.api")).build() - .consumes(getContentTypes()).produces(getContentTypes()).apiInfo(getApiInfo()) - .useDefaultResponseMessages(false).protocols(protocols()) - .directModelSubstitute(LocalTime.class, String.class); - } - - /** - * Returns the API protocols (for documentation) - * - * @return - */ - private Set protocols() { - Set protocols = new HashSet<>(); - protocols.add("https"); - return protocols; - } - - /** - * Returns all content types which should be consumed/produced - */ - private Set getContentTypes() { - Set contentTypes = new HashSet<>(); - contentTypes.add("application/json"); - return contentTypes; - } - - /** - * Returns the API information (defined in application.properties) - * - * @return - */ - private ApiInfo getApiInfo() { - return new ApiInfo(docuTitle, docuDescription, docuVersion, docuTermsUrl, - new Contact(docuContactName, docuContactUrl, docuContactEmail), docuLicense, docuLicenseUrl, - Collections.emptyList()); - } -} diff --git a/src/main/java/de/caritas/cob/mailservice/config/ThymeleafConfig.java b/src/main/java/de/caritas/cob/mailservice/config/ThymeleafConfig.java index 0be7804..79e7422 100644 --- a/src/main/java/de/caritas/cob/mailservice/config/ThymeleafConfig.java +++ b/src/main/java/de/caritas/cob/mailservice/config/ThymeleafConfig.java @@ -21,12 +21,12 @@ public class ThymeleafConfig { @Value("${template.use.custom.resources.path}") private boolean useCustomResourcesPath; - /** - * Based on the {@link ThymeleafConfig#useCustomResourcesPath} value this method creates the right template resolver. - * useCustomResourcesPath == true -> {@link ThymeleafConfig#htmlFileTemplateResolver()} - * useCustomResourcesPath == true -> {@link ThymeleafConfig#htmlClassLoaderTemplateResolver()} - * + * Based on the {@link ThymeleafConfig#useCustomResourcesPath} value this method creates the right + * template resolver. useCustomResourcesPath == true -> {@link + * ThymeleafConfig#htmlFileTemplateResolver()} useCustomResourcesPath == true -> {@link + * ThymeleafConfig#htmlClassLoaderTemplateResolver()} + * * @return ClassLoaderTemplateResolver. */ @Bean @@ -45,7 +45,8 @@ private ITemplateResolver htmlFileTemplateResolver() { } private ITemplateResolver htmlClassLoaderTemplateResolver() { - ClassLoaderTemplateResolver emailClassLoaderTemplateResolver = new ClassLoaderTemplateResolver(); + ClassLoaderTemplateResolver emailClassLoaderTemplateResolver = + new ClassLoaderTemplateResolver(); emailClassLoaderTemplateResolver.setOrder(2); emailClassLoaderTemplateResolver.setPrefix("/templates/"); emailClassLoaderTemplateResolver.setSuffix(".html"); @@ -58,5 +59,4 @@ private ITemplateResolver htmlClassLoaderTemplateResolver() { public MessageSource messageSource(TranslationService translationService) { return new TranslationMessageSource(translationService); } - } diff --git a/src/main/java/de/caritas/cob/mailservice/config/apiclient/TranslationManagementServiceApiClient.java b/src/main/java/de/caritas/cob/mailservice/config/apiclient/TranslationManagementServiceApiClient.java index 8ec5776..f70a543 100644 --- a/src/main/java/de/caritas/cob/mailservice/config/apiclient/TranslationManagementServiceApiClient.java +++ b/src/main/java/de/caritas/cob/mailservice/config/apiclient/TranslationManagementServiceApiClient.java @@ -24,18 +24,26 @@ public class TranslationManagementServiceApiClient { @Value("${weblate.api.key}") private String apiKey; - private final @NonNull RestTemplate restTemplate; + private final @NonNull RestTemplate restTemplate; - public String tryFetchTranslationsFromTranslationManagementService(String project, - String component, String languageCode, Dialect dialect) { + public String tryFetchTranslationsFromTranslationManagementService( + String project, String component, String languageCode, Dialect dialect) { HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Token " + apiKey); - String url = apiUrl + "translations/" + project + "/" + component + "/" + languageCode + getTranslationManagementServiceDialectSuffix(dialect) - + "/file.json"; + String url = + apiUrl + + "translations/" + + project + + "/" + + component + + "/" + + languageCode + + getTranslationManagementServiceDialectSuffix(dialect) + + "/file.json"; log.info("Calling url to fetch translations: {}", url); - ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, - new HttpEntity<>(headers), String.class); + ResponseEntity response = + restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headers), String.class); return response.getBody(); } diff --git a/src/main/java/de/caritas/cob/mailservice/filter/StatelessCsrfFilter.java b/src/main/java/de/caritas/cob/mailservice/filter/StatelessCsrfFilter.java index 9d08900..4af6f92 100644 --- a/src/main/java/de/caritas/cob/mailservice/filter/StatelessCsrfFilter.java +++ b/src/main/java/de/caritas/cob/mailservice/filter/StatelessCsrfFilter.java @@ -1,24 +1,20 @@ package de.caritas.cob.mailservice.filter; +import de.caritas.cob.mailservice.config.SecurityConfig; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; -import java.util.Arrays; import java.util.regex.Pattern; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.access.AccessDeniedHandlerImpl; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.web.filter.OncePerRequestFilter; -import de.caritas.cob.mailservice.config.SpringFoxConfig; -/** - * This custom filter checks CSRF cookie and header token for equality - * - */ +/** This custom filter checks CSRF cookie and header token for equality */ public class StatelessCsrfFilter extends OncePerRequestFilter { private final RequestMatcher requireCsrfProtectionMatcher = new DefaultRequiresCsrfMatcher(); @@ -32,8 +28,9 @@ public StatelessCsrfFilter(String cookieProperty, String headerProperty) { } @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, - FilterChain filterChain) throws ServletException, IOException { + protected void doFilterInternal( + HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { if (requireCsrfProtectionMatcher.matches(request)) { final String csrfTokenValue = request.getHeader(csrfHeaderProperty); @@ -49,8 +46,8 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse } if (csrfTokenValue == null || !csrfTokenValue.equals(csrfCookieValue)) { - accessDeniedHandler.handle(request, response, - new AccessDeniedException("Missing or non-matching CSRF-token")); + accessDeniedHandler.handle( + request, response, new AccessDeniedException("Missing or non-matching CSRF-token")); return; } } @@ -64,7 +61,8 @@ public static final class DefaultRequiresCsrfMatcher implements RequestMatcher { public boolean matches(HttpServletRequest request) { // Allow specific whitelist items to disable CSRF protection for Swagger UI documentation - if (Arrays.stream(SpringFoxConfig.WHITE_LIST).parallel() + if (SecurityConfig.WHITE_LIST.stream() + .parallel() .anyMatch(request.getRequestURI().toLowerCase()::contains)) { return false; } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index c77c27a..755df8f 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -77,3 +77,4 @@ management.health.probes.enabled=true spring.cache.jcache.config=classpath:ehcache.xml logging.level.net.sf.ehcache=info +springdoc.api-docs.enabled=false \ No newline at end of file diff --git a/src/test/java/de/caritas/cob/mailservice/api/ResourceIT.java b/src/test/java/de/caritas/cob/mailservice/api/ResourceIT.java index 5ec8db4..68e1423 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/ResourceIT.java +++ b/src/test/java/de/caritas/cob/mailservice/api/ResourceIT.java @@ -21,15 +21,13 @@ @ActiveProfiles("testing") class ResourceIT { - private static final String TEMPLATES_DIR = ResourcePatternResolver.CLASSPATH_URL_PREFIX - + "templates/"; + private static final String TEMPLATES_DIR = + ResourcePatternResolver.CLASSPATH_URL_PREFIX + "templates/"; private static final String DESC_FILE_PATTERN = "*.json"; - @Autowired - private ObjectMapper objectMapper; + @Autowired private ObjectMapper objectMapper; - @Autowired - private ResourcePatternResolver resourceResolver; + @Autowired private ResourcePatternResolver resourceResolver; @Test void descriptionShouldDefineDefaultLanguageAndExistingTemplate() throws IOException { @@ -61,11 +59,12 @@ void descriptionShouldDeclareExistingTemplates() throws IOException { var templates = desc.getHtmlTemplateFilename(); assertTrue(templates.size() > 0); - templates.forEach((languageCode, templateFilename) -> { - var templatePath = TEMPLATES_DIR + templateFilename; - var templateResource = resourceResolver.getResource(templatePath); - assertTrue(templateResource.exists()); - }); + templates.forEach( + (languageCode, templateFilename) -> { + var templatePath = TEMPLATES_DIR + templateFilename; + var templateResource = resourceResolver.getResource(templatePath); + assertTrue(templateResource.exists()); + }); } } @@ -110,9 +109,11 @@ void descriptionShouldHaveSubjectKey() throws IOException { var json = Files.readString(jsonFile.getFile().toPath()); var desc = objectMapper.readValue(json, TemplateDescription.class); var subjectKey = desc.getSubject(); - assertNotNull(subjectKey, String.format( - "Json file with resource description does not contain subject key: %s", - jsonFile.getFilename())); + assertNotNull( + subjectKey, + String.format( + "Json file with resource description does not contain subject key: %s", + jsonFile.getFilename())); } } } diff --git a/src/test/java/de/caritas/cob/mailservice/api/TranslationMessageSourceTest.java b/src/test/java/de/caritas/cob/mailservice/api/TranslationMessageSourceTest.java index 9f862c3..1b62ad8 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/TranslationMessageSourceTest.java +++ b/src/test/java/de/caritas/cob/mailservice/api/TranslationMessageSourceTest.java @@ -17,11 +17,9 @@ class TranslationMessageSourceTest { private static final String INFORMAL_GERMAL_LANGUAGE_TAG = "de-DE-u-va-posix"; - @InjectMocks - private TranslationMessageSource translationMessageSource; + @InjectMocks private TranslationMessageSource translationMessageSource; - @Mock - private TranslationService translationService; + @Mock private TranslationService translationService; @Test void getMessage_Should_CallFetchTranslations_With_FormalDialect_For_DefaultLocale() { @@ -29,22 +27,24 @@ void getMessage_Should_CallFetchTranslations_With_FormalDialect_For_DefaultLocal Locale locale = Locale.getDefault(); // when - translationMessageSource.getMessage("translation_key", new Object[]{}, "Message", locale); + translationMessageSource.getMessage("translation_key", new Object[] {}, "Message", locale); // then - verify(translationService, Mockito.times(1)).fetchTranslations(locale.getLanguage(), Dialect.FORMAL); + verify(translationService, Mockito.times(1)) + .fetchTranslations(locale.getLanguage(), Dialect.FORMAL); } @Test - void getMessage_Should_CallFetchTranslations_With_InformalDialect_For_ForLocaleForInformalGerman() { + void + getMessage_Should_CallFetchTranslations_With_InformalDialect_For_ForLocaleForInformalGerman() { // given Locale locale = Locale.forLanguageTag(INFORMAL_GERMAL_LANGUAGE_TAG); // when - translationMessageSource.getMessage("translation_key", new Object[]{}, "Message", locale); + translationMessageSource.getMessage("translation_key", new Object[] {}, "Message", locale); // then - verify(translationService, Mockito.times(1)).fetchTranslations(locale.getLanguage(), Dialect.INFORMAL); + verify(translationService, Mockito.times(1)) + .fetchTranslations(locale.getLanguage(), Dialect.INFORMAL); } - -} \ No newline at end of file +} diff --git a/src/test/java/de/caritas/cob/mailservice/api/config/MailTestConfiguration.java b/src/test/java/de/caritas/cob/mailservice/api/config/MailTestConfiguration.java index 5a5156a..401142b 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/config/MailTestConfiguration.java +++ b/src/test/java/de/caritas/cob/mailservice/api/config/MailTestConfiguration.java @@ -10,8 +10,8 @@ public class MailTestConfiguration { @Bean("emailsender") // need to define it for spring-actuator - public JavaMailSender getJavaMailSender(@Value("${spring.mail.host}") String host, - @Value("${spring.mail.port}") int port) { + public JavaMailSender getJavaMailSender( + @Value("${spring.mail.host}") String host, @Value("${spring.mail.port}") int port) { final JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); javaMailSender.setHost(host); javaMailSender.setPort(port); diff --git a/src/test/java/de/caritas/cob/mailservice/api/controller/MailControllerE2EIT.java b/src/test/java/de/caritas/cob/mailservice/api/controller/MailControllerE2EIT.java index c94b66c..e7be338 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/controller/MailControllerE2EIT.java +++ b/src/test/java/de/caritas/cob/mailservice/api/controller/MailControllerE2EIT.java @@ -15,9 +15,9 @@ import de.caritas.cob.mailservice.api.model.MailsDTO; import de.caritas.cob.mailservice.api.model.TemplateDataDTO; import de.caritas.cob.mailservice.config.apiclient.TranslationManagementServiceApiClient; +import jakarta.servlet.http.Cookie; import java.util.List; import java.util.Map; -import javax.servlet.http.Cookie; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -46,43 +46,42 @@ class MailControllerE2EIT { private static final String CSRF_VALUE = "test"; private static final Cookie CSRF_COOKIE = new Cookie("csrfCookie", CSRF_VALUE); - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; - @Autowired - private ObjectMapper objectMapper; + @Autowired private ObjectMapper objectMapper; @MockBean @Qualifier("emailsender") private JavaMailSender javaMailSender; - @MockBean - private TranslationManagementServiceApiClient translationManagementServiceApiClient; + @MockBean private TranslationManagementServiceApiClient translationManagementServiceApiClient; - @Captor - private ArgumentCaptor mimeMessagePrepCaptor; + @Captor private ArgumentCaptor mimeMessagePrepCaptor; private MailsDTO mailsDTO; private Map>> mailsDTOMap; @BeforeEach void setUp() { - Mockito.doThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)).when(translationManagementServiceApiClient).tryFetchTranslationsFromTranslationManagementService( - anyString(), anyString(), anyString(), any(Dialect.class)); + Mockito.doThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)) + .when(translationManagementServiceApiClient) + .tryFetchTranslationsFromTranslationManagementService( + anyString(), anyString(), anyString(), any(Dialect.class)); } @Test void sendMailsShouldRespondWithOkWhenEmailListIsEmpty() throws Exception { givenAnEmptyEmailList(); - mockMvc.perform( - post("/mails/send") - .cookie(CSRF_COOKIE) - .header(CSRF_HEADER, CSRF_VALUE) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(mailsDTO)) - .accept(MediaType.APPLICATION_JSON) - ).andExpect(status().isOk()); + mockMvc + .perform( + post("/mails/send") + .cookie(CSRF_COOKIE) + .header(CSRF_HEADER, CSRF_VALUE) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(mailsDTO)) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); } @Test @@ -90,14 +89,15 @@ void sendMailsShouldSendEmailAndRenderDataWithDefaultLanguageWhenLanguageNotGive throws Exception { givenAnEmailListWithoutLanguage(); - mockMvc.perform( - post("/mails/send") - .cookie(CSRF_COOKIE) - .header(CSRF_HEADER, CSRF_VALUE) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(mailsDTOMap)) - .accept(MediaType.APPLICATION_JSON) - ).andExpect(status().isOk()); + mockMvc + .perform( + post("/mails/send") + .cookie(CSRF_COOKIE) + .header(CSRF_HEADER, CSRF_VALUE) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(mailsDTOMap)) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); verify(javaMailSender).send(mimeMessagePrepCaptor.capture()); @@ -119,14 +119,15 @@ void sendMailsShouldSendEmailAndRenderDataWithDefaultLanguageWhenLanguageIsNull( throws Exception { givenAnEmailList(null); - mockMvc.perform( - post("/mails/send") - .cookie(CSRF_COOKIE) - .header(CSRF_HEADER, CSRF_VALUE) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(mailsDTO)) - .accept(MediaType.APPLICATION_JSON) - ).andExpect(status().isOk()); + mockMvc + .perform( + post("/mails/send") + .cookie(CSRF_COOKIE) + .header(CSRF_HEADER, CSRF_VALUE) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(mailsDTO)) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); verify(javaMailSender).send(mimeMessagePrepCaptor.capture()); @@ -148,14 +149,15 @@ void sendMailsShouldSendEmailAndRenderDataWithDefaultLanguageWhenLanguageDoesNot throws Exception { givenAnEmailList(LanguageCode.IO); - mockMvc.perform( - post("/mails/send") - .cookie(CSRF_COOKIE) - .header(CSRF_HEADER, CSRF_VALUE) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(mailsDTO)) - .accept(MediaType.APPLICATION_JSON) - ).andExpect(status().isOk()); + mockMvc + .perform( + post("/mails/send") + .cookie(CSRF_COOKIE) + .header(CSRF_HEADER, CSRF_VALUE) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(mailsDTO)) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); verify(javaMailSender).send(mimeMessagePrepCaptor.capture()); @@ -176,14 +178,15 @@ void sendMailsShouldSendEmailAndRenderDataWithDefaultLanguageWhenLanguageDoesNot void sendMailsShouldSendEmailAndRenderDataWhenLanguageIsDefaultLanguage() throws Exception { givenAnEmailList(LanguageCode.DE); - mockMvc.perform( - post("/mails/send") - .cookie(CSRF_COOKIE) - .header(CSRF_HEADER, CSRF_VALUE) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(mailsDTO)) - .accept(MediaType.APPLICATION_JSON) - ).andExpect(status().isOk()); + mockMvc + .perform( + post("/mails/send") + .cookie(CSRF_COOKIE) + .header(CSRF_HEADER, CSRF_VALUE) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(mailsDTO)) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); verify(javaMailSender).send(mimeMessagePrepCaptor.capture()); @@ -204,14 +207,15 @@ void sendMailsShouldSendEmailAndRenderDataWhenLanguageIsDefaultLanguage() throws void sendMailsShouldSendEmailAndRenderDataWithSetLanguage() throws Exception { givenAnEmailList(LanguageCode.EN); - mockMvc.perform( - post("/mails/send") - .cookie(CSRF_COOKIE) - .header(CSRF_HEADER, CSRF_VALUE) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(mailsDTO)) - .accept(MediaType.APPLICATION_JSON) - ).andExpect(status().isOk()); + mockMvc + .perform( + post("/mails/send") + .cookie(CSRF_COOKIE) + .header(CSRF_HEADER, CSRF_VALUE) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(mailsDTO)) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); verify(javaMailSender).send(mimeMessagePrepCaptor.capture()); @@ -238,15 +242,13 @@ private void givenAnEmailList(LanguageCode languageCode) { email.setTemplate("reassign-confirmation-notification"); email.setDialect(Dialect.FORMAL); - var nameRecipient = new TemplateDataDTO() - .key("name_recipient") - .value(RandomStringUtils.randomAlphanumeric(16)); - var nameFromConsultant = new TemplateDataDTO() - .key("name_from_consultant") - .value(RandomStringUtils.randomAlphanumeric(16)); - var url = new TemplateDataDTO() - .key("url") - .value(RandomStringUtils.randomAlphanumeric(16)); + var nameRecipient = + new TemplateDataDTO().key("name_recipient").value(RandomStringUtils.randomAlphanumeric(16)); + var nameFromConsultant = + new TemplateDataDTO() + .key("name_from_consultant") + .value(RandomStringUtils.randomAlphanumeric(16)); + var url = new TemplateDataDTO().key("url").value(RandomStringUtils.randomAlphanumeric(16)); email.setTemplateData(List.of(nameRecipient, nameFromConsultant, url)); email.setLanguage(languageCode); @@ -287,12 +289,14 @@ private void assertTextIsGerman(MimeMessagePreparator prep, MailDTO mailDTO) throws NoSuchFieldException, IllegalAccessException { var text = getArg(prep, 5); var data = mailDTO.getTemplateData(); - var salutation = "Liebe(r) " + valueOf("name_recipient", data) + ","; + var salutation = + "Liebe(r) " + valueOf("name_recipient", data) + ","; assertTrue(text.contains(salutation)); - var message = "" - + valueOf("name_from_consultant", data) - + " hat Ihnen eine(n) Ratsuchende(n) übergeben."; + var message = + "" + + valueOf("name_from_consultant", data) + + " hat Ihnen eine(n) Ratsuchende(n) übergeben."; assertTrue(text.contains(message)); var anchorStart = ""; diff --git a/src/test/java/de/caritas/cob/mailservice/api/controller/MailControllerTestExchangeIT.java b/src/test/java/de/caritas/cob/mailservice/api/controller/MailControllerTestExchangeIT.java index 9d1297f..be65c88 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/controller/MailControllerTestExchangeIT.java +++ b/src/test/java/de/caritas/cob/mailservice/api/controller/MailControllerTestExchangeIT.java @@ -28,62 +28,77 @@ public class MailControllerTestExchangeIT { private final String PATH_SEND_ERROR_MAIL = "/mails/error/send"; private final String TEMPLATE = "test"; private final String VALID_REQUEST_BODY = - "{\"mails\":[{" + "\"template\":\"" + TEMPLATE + "\",\"email\":\"dah@o4b.de\"," - + "\"templateData\":[" + "{\"key\":\"name\"," + "\"value\":\"Max Mustermann\"}," - + "{\"key\":\"text\"," + "\"value\":\"hello, world!\"}" + "]}]}"; + "{\"mails\":[{" + + "\"template\":\"" + + TEMPLATE + + "\",\"email\":\"dah@o4b.de\"," + + "\"templateData\":[" + + "{\"key\":\"name\"," + + "\"value\":\"Max Mustermann\"}," + + "{\"key\":\"text\"," + + "\"value\":\"hello, world!\"}" + + "]}]}"; private final String VALID_ERROR_REQUEST_BODY = - "{" + "\"template\":\"" + TEMPLATE + "\",\"email\":\"dah@o4b.de\"," - + "\"templateData\":[" + "{\"key\":\"name\"," + "\"value\":\"Max Mustermann\"}," - + "{\"key\":\"text\"," + "\"value\":\"hello, world!\"}" + "]}"; + "{" + + "\"template\":\"" + + TEMPLATE + + "\",\"email\":\"dah@o4b.de\"," + + "\"templateData\":[" + + "{\"key\":\"name\"," + + "\"value\":\"Max Mustermann\"}," + + "{\"key\":\"text\"," + + "\"value\":\"hello, world!\"}" + + "]}"; - @Autowired - private MockMvc mvc; + @Autowired private MockMvc mvc; - @MockBean - MailService mailService; + @MockBean MailService mailService; @Test public void sendMail_Should_ReturnOk_WhenTemplateDescriptionIsNotFound() throws Exception { - mvc.perform(post(PATH_SEND_MAIL).content(VALID_REQUEST_BODY) - .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) + mvc.perform( + post(PATH_SEND_MAIL) + .content(VALID_REQUEST_BODY) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); - } @Test public void sendMail_Should_SendHtmlMail_And_ReturnOk_WhenExchange() throws Exception { - mvc.perform(post(PATH_SEND_MAIL).content(VALID_REQUEST_BODY) - .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) + mvc.perform( + post(PATH_SEND_MAIL) + .content(VALID_REQUEST_BODY) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); verify(mailService, times(1)).sendHtmlMails(Mockito.any()); - } @Test public void sendErrorMail_Should_ReturnOk_WhenTemplateDescriptionIsNotFound() throws Exception { - mvc.perform(post(PATH_SEND_ERROR_MAIL) - .content(VALID_ERROR_REQUEST_BODY) - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) + mvc.perform( + post(PATH_SEND_ERROR_MAIL) + .content(VALID_ERROR_REQUEST_BODY) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); - } @Test public void sendErrorMail_Should_SendHtmlMail_And_ReturnOk_WhenExchange() throws Exception { - mvc.perform(post(PATH_SEND_ERROR_MAIL) - .content(VALID_ERROR_REQUEST_BODY) - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) + mvc.perform( + post(PATH_SEND_ERROR_MAIL) + .content(VALID_ERROR_REQUEST_BODY) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); verify(mailService, times(1)).sendErrorMailDto(Mockito.any()); - } - } diff --git a/src/test/java/de/caritas/cob/mailservice/api/controller/MailControllerTestSmtpIT.java b/src/test/java/de/caritas/cob/mailservice/api/controller/MailControllerTestSmtpIT.java index 2fb4c4f..facb056 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/controller/MailControllerTestSmtpIT.java +++ b/src/test/java/de/caritas/cob/mailservice/api/controller/MailControllerTestSmtpIT.java @@ -27,36 +27,42 @@ public class MailControllerTestSmtpIT { private final String PATH_SEND_MAIL = "/mails/send"; private final String TEMPLATE = "test"; private final String VALID_REQUEST_BODY = - "{\"mails\":[{" + "\"template\":\"" + TEMPLATE + "\",\"email\":\"dah@o4b.de\"," - + "\"templateData\":[" + "{\"key\":\"name\"," + "\"value\":\"Max Mustermann\"}," - + "{\"key\":\"text\"," + "\"value\":\"hello, world!\"}" + "]}]}"; + "{\"mails\":[{" + + "\"template\":\"" + + TEMPLATE + + "\",\"email\":\"dah@o4b.de\"," + + "\"templateData\":[" + + "{\"key\":\"name\"," + + "\"value\":\"Max Mustermann\"}," + + "{\"key\":\"text\"," + + "\"value\":\"hello, world!\"}" + + "]}]}"; - @Autowired - private MockMvc mvc; + @Autowired private MockMvc mvc; - @MockBean - MailService mailService; + @MockBean MailService mailService; @Test public void sendMail_Should_ReturnOk_WhenTemplateDescriptionIsNotFound() throws Exception { - mvc.perform(post(PATH_SEND_MAIL).content(VALID_REQUEST_BODY) - .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) + mvc.perform( + post(PATH_SEND_MAIL) + .content(VALID_REQUEST_BODY) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); - } @Test public void sendMail_Should_SendHtmlMail_And_ReturnOk_WhenExchange() throws Exception { - mvc.perform(post(PATH_SEND_MAIL).content(VALID_REQUEST_BODY) - .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) + mvc.perform( + post(PATH_SEND_MAIL) + .content(VALID_REQUEST_BODY) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); verify(mailService, times(1)).sendHtmlMails(Mockito.any()); - } - - - } diff --git a/src/test/java/de/caritas/cob/mailservice/api/helper/HelperTest.java b/src/test/java/de/caritas/cob/mailservice/api/helper/HelperTest.java index ec89a78..de285ca 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/helper/HelperTest.java +++ b/src/test/java/de/caritas/cob/mailservice/api/helper/HelperTest.java @@ -13,14 +13,14 @@ public class HelperTest { private Helper helper; - private final static String TEXT = "Lorem Ipsum"; - private final static String TEXT_WITH_NEWLINE = "Lorem Ipsum\nLorem Ipsum"; - private final static String TEXT_WITH_NEWLINE_AND_HTML_AND_JS = + private static final String TEXT = "Lorem Ipsum"; + private static final String TEXT_WITH_NEWLINE = "Lorem Ipsum\nLorem Ipsum"; + private static final String TEXT_WITH_NEWLINE_AND_HTML_AND_JS = "Lorem Ipsum\nLorem Ipsum"; - private final static String TEXT_WITH_HTML = "Lorem Ipsum"; - private final static String TEXT_WITH_JS = "Lorem Ipsum"; - private final static String TEXT_WITH_HTML_ENTITY = "Hallo &"; - private final static String TEXT_WITH_UNESCAPED_HTML_ENTITY = "Hallo &"; + private static final String TEXT_WITH_HTML = "Lorem Ipsum"; + private static final String TEXT_WITH_JS = "Lorem Ipsum"; + private static final String TEXT_WITH_HTML_ENTITY = "Hallo &"; + private static final String TEXT_WITH_UNESCAPED_HTML_ENTITY = "Hallo &"; @Before public void setup() { @@ -43,7 +43,8 @@ public void removeHTMLFromText_ShouldNot_RemoveNewlinesFromText() { } @Test - public void removeHTMLFromText_Should_RemoveHtmlAndJavascriptFromText_And_ShouldNot_RemoveNewlines() { + public void + removeHTMLFromText_Should_RemoveHtmlAndJavascriptFromText_And_ShouldNot_RemoveNewlines() { assertEquals(TEXT_WITH_NEWLINE, helper.removeHTMLFromText(TEXT_WITH_NEWLINE_AND_HTML_AND_JS)); } @@ -53,8 +54,8 @@ public void unescapeHtml_Should_ConvertHtmlEntity() { } @Test(expected = InternalServerErrorException.class) - public void removeHTMLFromText_Should_ThrowInternalServerErrorException_When_removeTextFromNull() { + public void + removeHTMLFromText_Should_ThrowInternalServerErrorException_When_removeTextFromNull() { helper.removeHTMLFromText(null); } - } diff --git a/src/test/java/de/caritas/cob/mailservice/api/helper/TemplateDataConverterTest.java b/src/test/java/de/caritas/cob/mailservice/api/helper/TemplateDataConverterTest.java index 4937d3d..59c7553 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/helper/TemplateDataConverterTest.java +++ b/src/test/java/de/caritas/cob/mailservice/api/helper/TemplateDataConverterTest.java @@ -2,6 +2,8 @@ import static org.junit.Assert.assertThat; import static org.mockito.Mockito.when; + +import de.caritas.cob.mailservice.api.model.TemplateDataDTO; import java.util.Arrays; import java.util.List; import java.util.Map; @@ -12,21 +14,20 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import de.caritas.cob.mailservice.api.model.TemplateDataDTO; @RunWith(MockitoJUnitRunner.class) public class TemplateDataConverterTest { private TemplateDataConverter templateDataConverter; - @Mock - private Helper helper; + @Mock private Helper helper; private final String KEY1 = "key1"; private final String VALUE1 = "value1"; private final String KEY2 = "key2"; private final String VALUE2 = "value2"; private final List TEMPLATE_DTO_LIST = - Arrays.asList(new TemplateDataDTO().key(KEY1).value(VALUE1), + Arrays.asList( + new TemplateDataDTO().key(KEY1).value(VALUE1), new TemplateDataDTO().key(KEY2).value(VALUE2)); @Before @@ -47,8 +48,5 @@ public void convertFromTemplateDataDTOList_Should() { assertThat(result, IsMapContaining.hasEntry(KEY1, VALUE1)); assertThat(result, IsMapContaining.hasEntry(KEY2, VALUE2)); - - } - } diff --git a/src/test/java/de/caritas/cob/mailservice/api/service/DefaultTranslationsServiceIT.java b/src/test/java/de/caritas/cob/mailservice/api/service/DefaultTranslationsServiceIT.java index 5611ec4..32fa92b 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/service/DefaultTranslationsServiceIT.java +++ b/src/test/java/de/caritas/cob/mailservice/api/service/DefaultTranslationsServiceIT.java @@ -3,7 +3,6 @@ import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import de.caritas.cob.mailservice.api.model.Dialect; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,8 +15,7 @@ @ActiveProfiles("testing") class DefaultTranslationsServiceIT { - @Autowired - private DefaultTranslationsService defaultTranslationsService; + @Autowired private DefaultTranslationsService defaultTranslationsService; public final String USE_CUSTOM_RESOURCES_PATH_FIELD_NAME = "useCustomResourcesPath"; public final String CUSTOM_TRANSLATIONS_PATH_FIELD_NAME = "customTranslationsPath"; @@ -25,19 +23,23 @@ class DefaultTranslationsServiceIT { @BeforeEach public void setUp() { defaultTranslationsService = new DefaultTranslationsService(); - ReflectionTestUtils.setField(defaultTranslationsService, CUSTOM_TRANSLATIONS_PATH_FIELD_NAME, System.getProperty("user.dir") + "/src/main/resources/i18n"); + ReflectionTestUtils.setField( + defaultTranslationsService, + CUSTOM_TRANSLATIONS_PATH_FIELD_NAME, + System.getProperty("user.dir") + "/src/main/resources/i18n"); } @AfterEach public void clean() { - ReflectionTestUtils.setField(defaultTranslationsService, USE_CUSTOM_RESOURCES_PATH_FIELD_NAME, false); + ReflectionTestUtils.setField( + defaultTranslationsService, USE_CUSTOM_RESOURCES_PATH_FIELD_NAME, false); } @Test void fetchDefaultTranslations_Should_FetchTranlsationsForInformalGerman() { - String translations = defaultTranslationsService.fetchDefaultTranslations("mailing", "de", - Dialect.INFORMAL); + String translations = + defaultTranslationsService.fetchDefaultTranslations("mailing", "de", Dialect.INFORMAL); assertThat(translations).isNotNull(); assertThat(translations).contains("hat Dir {0} als neuen Ratsuchenden zugewiesen."); @@ -46,8 +48,8 @@ void fetchDefaultTranslations_Should_FetchTranlsationsForInformalGerman() { @Test void fetchDefaultTranslations_Should_FetchTranlsationsForFormalIfDialectNullGerman() { - String translations = defaultTranslationsService.fetchDefaultTranslations("mailing", "de", - null); + String translations = + defaultTranslationsService.fetchDefaultTranslations("mailing", "de", null); assertThat(translations).isNotNull(); assertThat(translations).contains("hat Ihnen {0} als neuen Ratsuchenden zugewiesen."); @@ -56,50 +58,52 @@ void fetchDefaultTranslations_Should_FetchTranlsationsForFormalIfDialectNullGerm @Test void fetchDefaultTranslations_Should_FetchTranlsationsForEnglish() { - String translations = defaultTranslationsService.fetchDefaultTranslations("mailing", "en", - null); + String translations = + defaultTranslationsService.fetchDefaultTranslations("mailing", "en", null); assertThat(translations).isNotNull(); assertThat(translations).contains("has assigned you {0} new advice seeker."); } @Test - void fetchDefaultTranslations_Should_fetchExternalTranslationsForFormalIfDialectNullGerman_When_useCustomResourcesPath_is_true() { + void + fetchDefaultTranslations_Should_fetchExternalTranslationsForFormalIfDialectNullGerman_When_useCustomResourcesPath_is_true() { - ReflectionTestUtils.setField(defaultTranslationsService, USE_CUSTOM_RESOURCES_PATH_FIELD_NAME, true); + ReflectionTestUtils.setField( + defaultTranslationsService, USE_CUSTOM_RESOURCES_PATH_FIELD_NAME, true); - String translations = defaultTranslationsService.fetchDefaultTranslations("mailing", "de", - null); + String translations = + defaultTranslationsService.fetchDefaultTranslations("mailing", "de", null); assertThat(translations).isNotNull(); assertThat(translations).contains("Sie haben eine neue Nachricht in Ihren Beratungen"); - } @Test - void fetchDefaultTranslations_Should_fetchExternalTranslationsForEnglish_When_useCustomResourcesPath_is_true() { + void + fetchDefaultTranslations_Should_fetchExternalTranslationsForEnglish_When_useCustomResourcesPath_is_true() { - ReflectionTestUtils.setField(defaultTranslationsService, USE_CUSTOM_RESOURCES_PATH_FIELD_NAME, true); + ReflectionTestUtils.setField( + defaultTranslationsService, USE_CUSTOM_RESOURCES_PATH_FIELD_NAME, true); - String translations = defaultTranslationsService.fetchDefaultTranslations("mailing", "en", - null); + String translations = + defaultTranslationsService.fetchDefaultTranslations("mailing", "en", null); assertThat(translations).isNotNull(); assertThat(translations).contains("You have a new message in your counselings"); - } @Test - void fetchDefaultTranslations_Should_fetchExternalTranslationsForInformalGerman_When_useCustomResourcesPath_is_true() { + void + fetchDefaultTranslations_Should_fetchExternalTranslationsForInformalGerman_When_useCustomResourcesPath_is_true() { - ReflectionTestUtils.setField(defaultTranslationsService, USE_CUSTOM_RESOURCES_PATH_FIELD_NAME, true); + ReflectionTestUtils.setField( + defaultTranslationsService, USE_CUSTOM_RESOURCES_PATH_FIELD_NAME, true); - String translations = defaultTranslationsService.fetchDefaultTranslations("mailing", "de", - Dialect.INFORMAL); + String translations = + defaultTranslationsService.fetchDefaultTranslations("mailing", "de", Dialect.INFORMAL); assertThat(translations).isNotNull(); assertThat(translations).contains("Du hast eine neue Nachricht in Deinen Beratungen"); - } - } diff --git a/src/test/java/de/caritas/cob/mailservice/api/service/ExchangeMailServiceTest.java b/src/test/java/de/caritas/cob/mailservice/api/service/ExchangeMailServiceTest.java index fb7802c..f2c006a 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/service/ExchangeMailServiceTest.java +++ b/src/test/java/de/caritas/cob/mailservice/api/service/ExchangeMailServiceTest.java @@ -35,7 +35,8 @@ public class ExchangeMailServiceTest { public void setup() throws Exception { this.mailService = new ExchangeMailService(); ReflectionTestUtils.setField(mailService, EXCHANGE_USER_FIELD_NAME, EXCHANGE_USER_VALUE); - ReflectionTestUtils.setField(mailService, EXCHANGE_PASSWORD_FIELD_NAME, EXCHANGE_PASSWORD_VALUE); + ReflectionTestUtils.setField( + mailService, EXCHANGE_PASSWORD_FIELD_NAME, EXCHANGE_PASSWORD_VALUE); ReflectionTestUtils.setField(mailService, EXCHANGE_URL_FIELD_NAME, EXCHANGE_URL_VALUE); ReflectionTestUtils.setField(mailService, EXCHANGE_VERSION_FIELD_NAME, EXCHANGE_VERSION_VALUE); } @@ -80,17 +81,18 @@ public void prepareAndSendTextMail_Should_ThrowServiceException_When_MailCouldNo } @Test(expected = ExchangeMailServiceException.class) - public void prepareAndSendTextMail_Should_ThrowExchangeMailServiceException_When_MailUrlIsInvalid() - throws NoSuchFieldException, ExchangeMailServiceException { + public void + prepareAndSendTextMail_Should_ThrowExchangeMailServiceException_When_MailUrlIsInvalid() + throws NoSuchFieldException, ExchangeMailServiceException { ReflectionTestUtils.setField(mailService, EXCHANGE_URL_FIELD_NAME, "Invalid"); mailService.prepareAndSendTextMail(RECIPIENT, SUBJECT, BODY); } @Test(expected = ExchangeMailServiceException.class) - public void prepareAndSendTextMail_Should_ThrowExchangeMailServiceException_When_ParametersAreNull() - throws ExchangeMailServiceException, NoSuchFieldException { + public void + prepareAndSendTextMail_Should_ThrowExchangeMailServiceException_When_ParametersAreNull() + throws ExchangeMailServiceException, NoSuchFieldException { ReflectionTestUtils.setField(mailService, "mailSender", SENDER); mailService.prepareAndSendTextMail(null, null, null); } - } diff --git a/src/test/java/de/caritas/cob/mailservice/api/service/LogServiceTest.java b/src/test/java/de/caritas/cob/mailservice/api/service/LogServiceTest.java deleted file mode 100644 index 4e31608..0000000 --- a/src/test/java/de/caritas/cob/mailservice/api/service/LogServiceTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package de.caritas.cob.mailservice.api.service; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.verify; -import static org.powermock.reflect.Whitebox.setInternalState; - -import java.io.PrintWriter; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.slf4j.Logger; - -@RunWith(MockitoJUnitRunner.class) -public class LogServiceTest { - - private final String ERROR_MESSAGE = "error message"; - - @Mock - private Logger logger; - - @Before - public void setup() { - setInternalState(LogService.class, "LOGGER", logger); - } - - @Test - public void logError_Should_LogExceptionStackTrace() { - Exception exception = Mockito.mock(Exception.class); - LogService.logError(ERROR_MESSAGE, exception); - verify(logger, atLeastOnce()).error(anyString(), eq(ERROR_MESSAGE)); - verify(exception, atLeastOnce()).printStackTrace(any(PrintWriter.class)); - } - - @Test - public void logError_Should_LogErrorMessage() { - LogService.logError(ERROR_MESSAGE); - verify(logger, atLeastOnce()).error(anyString(), eq(ERROR_MESSAGE)); - } - - @Test - public void logDebug_Should_LogDebugMessage() { - LogService.logDebug(ERROR_MESSAGE); - verify(logger, atLeastOnce()).debug(eq(ERROR_MESSAGE)); - } - - @Test - public void logWarn_Should_LogWarnMessage() { - LogService.logWarn(ERROR_MESSAGE); - verify(logger, atLeastOnce()).warn(eq(ERROR_MESSAGE)); - } - - -} diff --git a/src/test/java/de/caritas/cob/mailservice/api/service/MailErrorMessageBuilderTest.java b/src/test/java/de/caritas/cob/mailservice/api/service/MailErrorMessageBuilderTest.java index dee6810..fe6b659 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/service/MailErrorMessageBuilderTest.java +++ b/src/test/java/de/caritas/cob/mailservice/api/service/MailErrorMessageBuilderTest.java @@ -13,7 +13,8 @@ public class MailErrorMessageBuilderTest { private final MailDTO mailDTO = new MailDTO().template("template"); @Test - public void buildEmailErrorMessage_Should_returnErrorMessageWithoutEmail_When_emailIsContainedInStacktrace() { + public void + buildEmailErrorMessage_Should_returnErrorMessageWithoutEmail_When_emailIsContainedInStacktrace() { Exception exception = new RuntimeException("test@test.de"); String errorMessage = this.mailErrorMessageBuilder.buildEmailErrorMessage(mailDTO, exception); @@ -22,7 +23,8 @@ public void buildEmailErrorMessage_Should_returnErrorMessageWithoutEmail_When_em } @Test - public void buildEmailErrorMessage_Should_returnErrorMessageWithoutOnlyEmail_When_emailIsContainedInStacktrace() { + public void + buildEmailErrorMessage_Should_returnErrorMessageWithoutOnlyEmail_When_emailIsContainedInStacktrace() { Exception exception = new RuntimeException("address is test@test.de for given user"); String errorMessage = this.mailErrorMessageBuilder.buildEmailErrorMessage(mailDTO, exception); @@ -32,12 +34,12 @@ public void buildEmailErrorMessage_Should_returnErrorMessageWithoutOnlyEmail_Whe } @Test - public void buildEmailErrorMessage_Should_returnErrorMessageWithCustomReason_When_noEmailIsContainedInReason() { + public void + buildEmailErrorMessage_Should_returnErrorMessageWithCustomReason_When_noEmailIsContainedInReason() { Exception exception = new RuntimeException("My custom reason"); String errorMessage = this.mailErrorMessageBuilder.buildEmailErrorMessage(mailDTO, exception); assertThat(errorMessage, containsString("My custom reason")); } - } diff --git a/src/test/java/de/caritas/cob/mailservice/api/service/MailServiceTest.java b/src/test/java/de/caritas/cob/mailservice/api/service/MailServiceTest.java index 97a0aec..5cd4712 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/service/MailServiceTest.java +++ b/src/test/java/de/caritas/cob/mailservice/api/service/MailServiceTest.java @@ -20,7 +20,6 @@ import de.caritas.cob.mailservice.api.helper.TemplateDataConverter; import de.caritas.cob.mailservice.api.mailtemplate.TemplateDescription; import de.caritas.cob.mailservice.api.model.ErrorMailDTO; -import de.caritas.cob.mailservice.api.model.LanguageCode; import de.caritas.cob.mailservice.api.model.MailDTO; import de.caritas.cob.mailservice.api.model.MailsDTO; import de.caritas.cob.mailservice.api.model.TemplateDataDTO; @@ -44,23 +43,17 @@ public class MailServiceTest { private final String ERROR_RECIPIENTS = "name@domain.de"; private final String FIELD_NAME_USE_SMTP = "useSmtp"; - @InjectMocks - private MailService mailService; + @InjectMocks private MailService mailService; - @Mock - private SmtpMailService smtpMailService; + @Mock private SmtpMailService smtpMailService; - @Mock - private ExchangeMailService exchangeMailService; + @Mock private ExchangeMailService exchangeMailService; - @Mock - private TemplateDescriptionService templateDescriptionService; + @Mock private TemplateDescriptionService templateDescriptionService; - @Mock - private TemplateService templateService; + @Mock private TemplateService templateService; - @Mock - private TemplateDataConverter templateDataConverter; + @Mock private TemplateDataConverter templateDataConverter; @Test public void sendErrorMail_Should_SendErrorMail_When_ErrorRecipientIsSetAndUsingExchange() @@ -69,8 +62,8 @@ public void sendErrorMail_Should_SendErrorMail_When_ErrorRecipientIsSetAndUsingE ReflectionTestUtils.setField(mailService, FIELD_NAME_USE_SMTP, false); mailService.sendErrorMail(ERROR_MESSAGE); - verify(exchangeMailService, atLeastOnce()).prepareAndSendTextMail(eq(ERROR_RECIPIENTS), - Mockito.anyString(), Mockito.anyString()); + verify(exchangeMailService, atLeastOnce()) + .prepareAndSendTextMail(eq(ERROR_RECIPIENTS), Mockito.anyString(), Mockito.anyString()); } @Test @@ -80,8 +73,8 @@ public void sendErrorMail_Should_SendErrorMail_When_ErrorRecipientIsSetAndUsingS ReflectionTestUtils.setField(mailService, FIELD_NAME_USE_SMTP, true); mailService.sendErrorMail(ERROR_MESSAGE); - verify(smtpMailService, atLeastOnce()).prepareAndSendTextMail(eq(ERROR_RECIPIENTS), - Mockito.anyString(), Mockito.anyString()); + verify(smtpMailService, atLeastOnce()) + .prepareAndSendTextMail(eq(ERROR_RECIPIENTS), Mockito.anyString(), Mockito.anyString()); } @Test @@ -95,40 +88,42 @@ public void sendErrorMail_ShouldNot_SendErrorMail_When_ErrorRecipientIsNotSet() @Test public void sendHtmlMails_Should_sendHtmlMails_When_MailHasAddressAndUsingExchange() - throws SecurityException, ExchangeMailServiceException, TemplateDescriptionServiceException, TemplateServiceException { + throws SecurityException, ExchangeMailServiceException, TemplateDescriptionServiceException, + TemplateServiceException { ReflectionTestUtils.setField(mailService, "errorRecipients", ERROR_RECIPIENTS); ReflectionTestUtils.setField(mailService, FIELD_NAME_USE_SMTP, false); when(templateDescriptionService.getTemplateDescription(any())) .thenReturn(Optional.of(new TemplateDescription())); - when(templateService.render(any(), any(), any())) - .thenReturn(Optional.of("success")); + when(templateService.render(any(), any(), any())).thenReturn(Optional.of("success")); MailsDTO mailsDTO = new MailsDTO().mails(singletonList(createMailDTO())); mailService.sendHtmlMails(mailsDTO); - verify(exchangeMailService, atLeastOnce()).prepareAndSendHtmlMail(eq(EMAIL), - any(), eq("success"), any()); + verify(exchangeMailService, atLeastOnce()) + .prepareAndSendHtmlMail(eq(EMAIL), any(), eq("success"), any()); } private MailDTO createMailDTO() { - return new MailDTO().template("template").email(EMAIL).templateData( - singletonList(new TemplateDataDTO().key("key").value("value"))); + return new MailDTO() + .template("template") + .email(EMAIL) + .templateData(singletonList(new TemplateDataDTO().key("key").value("value"))); } @Test public void sendHtmlMails_Should_sendHtmlMails_When_UsingSmtp() - throws SecurityException, SmtpMailServiceException, TemplateDescriptionServiceException, TemplateServiceException { + throws SecurityException, SmtpMailServiceException, TemplateDescriptionServiceException, + TemplateServiceException { ReflectionTestUtils.setField(mailService, FIELD_NAME_USE_SMTP, true); when(templateDescriptionService.getTemplateDescription(any())) .thenReturn(Optional.of(new TemplateDescription())); - when(templateService.render(any(), any(), any())) - .thenReturn(Optional.of("success")); + when(templateService.render(any(), any(), any())).thenReturn(Optional.of("success")); MailsDTO mailsDTO = new MailsDTO().mails(singletonList(createMailDTO())); mailService.sendHtmlMails(mailsDTO); - verify(smtpMailService, atLeastOnce()).prepareAndSendHtmlMail(eq(EMAIL), - any(), eq("success"), any()); + verify(smtpMailService, atLeastOnce()) + .prepareAndSendHtmlMail(eq(EMAIL), any(), eq("success"), any()); } @Test @@ -143,19 +138,19 @@ public void sendHtmlMails_ShouldNot_sendHtmlMails_When_NoMailServiceIsSet() @Test public void sendHtmlMails_Should_sendSeveralHtmlMails_When_MoreThanOneMailIsInMailsDTO() - throws SecurityException, SmtpMailServiceException, TemplateDescriptionServiceException, TemplateServiceException { + throws SecurityException, SmtpMailServiceException, TemplateDescriptionServiceException, + TemplateServiceException { ReflectionTestUtils.setField(mailService, FIELD_NAME_USE_SMTP, true); when(templateDescriptionService.getTemplateDescription(any())) .thenReturn(Optional.of(new TemplateDescription())); - when(templateService.render(any(), any(), any())) - .thenReturn(Optional.of("success")); + when(templateService.render(any(), any(), any())).thenReturn(Optional.of("success")); - MailsDTO mailsDTO = new MailsDTO() - .mails(asList(createMailDTO(), createMailDTO(), createMailDTO())); + MailsDTO mailsDTO = + new MailsDTO().mails(asList(createMailDTO(), createMailDTO(), createMailDTO())); mailService.sendHtmlMails(mailsDTO); - verify(smtpMailService, times(3)).prepareAndSendHtmlMail(eq(EMAIL), - any(), eq("success"), any()); + verify(smtpMailService, times(3)) + .prepareAndSendHtmlMail(eq(EMAIL), any(), eq("success"), any()); } @Test @@ -168,21 +163,21 @@ public void sendHtmlMails_Should_sendErrorMail_When_TemplateDescriptionServiceEx MailsDTO mailsDTO = new MailsDTO().mails(singletonList(createMailDTO())); mailService.sendHtmlMails(mailsDTO); - verify(smtpMailService, atLeastOnce()).prepareAndSendTextMail(eq(ERROR_RECIPIENTS), - Mockito.anyString(), Mockito.anyString()); + verify(smtpMailService, atLeastOnce()) + .prepareAndSendTextMail(eq(ERROR_RECIPIENTS), Mockito.anyString(), Mockito.anyString()); } @Test(expected = InternalServerErrorException.class) - public void sendHtmlMail_Should_ThrowInternalServerErrorExceptionAndLogExceptionStackTrace_When_AnErrorOccursDuringSendingMails() - throws ExchangeMailServiceException, TemplateDescriptionServiceException, TemplateServiceException { + public void + sendHtmlMail_Should_ThrowInternalServerErrorExceptionAndLogExceptionStackTrace_When_AnErrorOccursDuringSendingMails() + throws ExchangeMailServiceException, TemplateDescriptionServiceException, + TemplateServiceException { ReflectionTestUtils.setField(mailService, FIELD_NAME_USE_SMTP, false); when(templateDescriptionService.getTemplateDescription(any())) .thenReturn(Optional.of(new TemplateDescription())); - when(templateService.render(any(), any(), any())) - .thenReturn(Optional.of("success")); + when(templateService.render(any(), any(), any())).thenReturn(Optional.of("success")); ExchangeMailServiceException exception = mock(ExchangeMailServiceException.class); - doThrow(exception).when(exchangeMailService) - .prepareAndSendHtmlMail(any(), any(), any(), any()); + doThrow(exception).when(exchangeMailService).prepareAndSendHtmlMail(any(), any(), any(), any()); MailsDTO mailsDTO = new MailsDTO().mails(singletonList(createMailDTO())); mailService.sendHtmlMails(mailsDTO); @@ -197,38 +192,34 @@ public void sendErrotMailDto_Should_sendUnescapedHtmlErrorMail() throws Exceptio TemplateDescription templateDescription = new TemplateDescription(); when(templateDescriptionService.getTemplateDescription(any())) .thenReturn(Optional.of(templateDescription)); - when(templateService.render(any(), any(), any())) - .thenReturn(Optional.of("success")); - ErrorMailDTO errorMailDTO = new ErrorMailDTO() - .template("free-text") - .templateData(singletonList( - new TemplateDataDTO().key("text").value("

test

") - )); + when(templateService.render(any(), any(), any())).thenReturn(Optional.of("success")); + ErrorMailDTO errorMailDTO = + new ErrorMailDTO() + .template("free-text") + .templateData(singletonList(new TemplateDataDTO().key("text").value("

test

"))); this.mailService.sendErrorMailDto(errorMailDTO); Map expectedData = new HashMap<>(); expectedData.put("text", "

test

"); verify(this.exchangeMailService, times(1)).prepareAndSendHtmlMail(any(), any(), any(), any()); - verify(this.templateService, times(1)).getRenderedSubject(eq(templateDescription), - eq(expectedData), any(MailDTO.class)); + verify(this.templateService, times(1)) + .getRenderedSubject(eq(templateDescription), eq(expectedData), any(MailDTO.class)); } @Test(expected = InternalServerErrorException.class) - public void sendErrotMailDto_Should_ThrowInternalServerErrorExceptionAndLogExceptionStackTrace_When_AnErrorOccursDuringSendingMails() - throws Exception { + public void + sendErrotMailDto_Should_ThrowInternalServerErrorExceptionAndLogExceptionStackTrace_When_AnErrorOccursDuringSendingMails() + throws Exception { ReflectionTestUtils.setField(mailService, FIELD_NAME_USE_SMTP, false); when(templateDescriptionService.getTemplateDescription(any())) .thenReturn(Optional.of(new TemplateDescription())); - when(templateService.render(any(), any(), any())) - .thenThrow(new TemplateServiceException("")); - ErrorMailDTO errorMailDTO = new ErrorMailDTO() - .template("free-text") - .templateData(singletonList( - new TemplateDataDTO().key("text").value("

test

") - )); + when(templateService.render(any(), any(), any())).thenThrow(new TemplateServiceException("")); + ErrorMailDTO errorMailDTO = + new ErrorMailDTO() + .template("free-text") + .templateData(singletonList(new TemplateDataDTO().key("text").value("

test

"))); mailService.sendErrorMailDto(errorMailDTO); } - } diff --git a/src/test/java/de/caritas/cob/mailservice/api/service/SmtpMailServiceTest.java b/src/test/java/de/caritas/cob/mailservice/api/service/SmtpMailServiceTest.java index d0b8856..a9c5ee9 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/service/SmtpMailServiceTest.java +++ b/src/test/java/de/caritas/cob/mailservice/api/service/SmtpMailServiceTest.java @@ -26,8 +26,7 @@ public class SmtpMailServiceTest { public final String TEMPLATE = "test"; public final String BODY = "test"; - @Mock - private JavaMailSender javaMailSender; + @Mock private JavaMailSender javaMailSender; private SmtpMailService mailService; @@ -45,7 +44,6 @@ public void prepareAndSendHtmlMail_Should_ThrowServiceException_WhenSenderMailAd } catch (SmtpMailServiceException serviceException) { assertTrue("Excepted ServiceException thrown", true); } - } @Test @@ -64,7 +62,6 @@ public void prepareAndSendHtmlMail_Should_ThrowServiceException_WhenMailCouldNot } catch (SmtpMailServiceException serviceException) { assertTrue("Excepted ServiceException thrown", true); } - } @Test @@ -76,7 +73,6 @@ public void prepareAndSendTextMail_Should_ThrowServiceException_WhenSenderMailAd } catch (SmtpMailServiceException serviceException) { assertTrue("Excepted ServiceException thrown", true); } - } @Test @@ -95,7 +91,5 @@ public void prepareAndSendTextMail_Should_ThrowServiceException_WhenMailCouldNot } catch (SmtpMailServiceException serviceException) { assertTrue("Excepted ServiceException thrown", true); } - } - } diff --git a/src/test/java/de/caritas/cob/mailservice/api/service/TemplateServiceIntegrationTest.java b/src/test/java/de/caritas/cob/mailservice/api/service/TemplateServiceIntegrationTest.java index be7dc0f..8dca9f1 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/service/TemplateServiceIntegrationTest.java +++ b/src/test/java/de/caritas/cob/mailservice/api/service/TemplateServiceIntegrationTest.java @@ -1,7 +1,5 @@ package de.caritas.cob.mailservice.api.service; - - import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import com.google.common.collect.Lists; @@ -25,26 +23,26 @@ @ActiveProfiles("testing") class TemplateServiceIntegrationTest { - @Autowired - private TemplateService templateService; + @Autowired private TemplateService templateService; - @Autowired - private TranslationService translationService; + @Autowired private TranslationService translationService; @Test void getProcessedHtmlTemplate_Should_RenderTemplateData_With_InformalDialect() throws TemplateServiceException { - Optional renderedHtml = templateService.render( - new TemplateDescription(Map.of(LanguageCode.DE, "message-notification-consultant.html"), - new SubjectDescription("translationKey"), - Lists.newArrayList(), - null), - new MailDTO() - .template("message-notification-consultant") - .language(LanguageCode.DE) - .dialect(Dialect.INFORMAL), - new HashMap<>()); + Optional renderedHtml = + templateService.render( + new TemplateDescription( + Map.of(LanguageCode.DE, "message-notification-consultant.html"), + new SubjectDescription("translationKey"), + Lists.newArrayList(), + null), + new MailDTO() + .template("message-notification-consultant") + .language(LanguageCode.DE) + .dialect(Dialect.INFORMAL), + new HashMap<>()); assertThat(renderedHtml).isPresent(); assertThat(renderedHtml.get()).contains("Du hast eine neue Nachricht in Deinen Beratungen"); } @@ -53,18 +51,19 @@ void getProcessedHtmlTemplate_Should_RenderTemplateData_With_InformalDialect() void getProcessedHtmlTemplate_Should_RenderTemplateData_With_FormalDialect() throws TemplateServiceException { - Optional renderedHtml = templateService.render( - new TemplateDescription(Map.of(LanguageCode.DE, "message-notification-consultant.html"), - new SubjectDescription("translationKey"), - Lists.newArrayList(), - null), - new MailDTO() - .template("message-notification-consultant") - .language(LanguageCode.DE) - .dialect(Dialect.FORMAL), - new HashMap<>()); + Optional renderedHtml = + templateService.render( + new TemplateDescription( + Map.of(LanguageCode.DE, "message-notification-consultant.html"), + new SubjectDescription("translationKey"), + Lists.newArrayList(), + null), + new MailDTO() + .template("message-notification-consultant") + .language(LanguageCode.DE) + .dialect(Dialect.FORMAL), + new HashMap<>()); assertThat(renderedHtml).isPresent(); assertThat(renderedHtml.get()).contains("Sie haben eine neue Nachricht in Ihren Beratungen"); } - } diff --git a/src/test/java/de/caritas/cob/mailservice/api/service/TemplateServiceTest.java b/src/test/java/de/caritas/cob/mailservice/api/service/TemplateServiceTest.java index 8e43a74..fa2d4b9 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/service/TemplateServiceTest.java +++ b/src/test/java/de/caritas/cob/mailservice/api/service/TemplateServiceTest.java @@ -35,19 +35,22 @@ public class TemplateServiceTest { "Test ${" + PLACEHOLDER1 + "} Test ${" + PLACEHOLDER2 + "}"; private final String SUBJECT_WITH_REPLACED_PLACEHOLDERS = "Test " + PLACEHOLDER1_VALUE + " Test " + PLACEHOLDER2_VALUE; - private final TemplateDescription TEMPLATE_DESCRIPTION = new TemplateDescription( - Map.of(LanguageCode.DE, "test.html"), - new SubjectDescription("translationKey"), - FIELDS, - null - ); + private final TemplateDescription TEMPLATE_DESCRIPTION = + new TemplateDescription( + Map.of(LanguageCode.DE, "test.html"), + new SubjectDescription("translationKey"), + FIELDS, + null); + @SuppressWarnings("serial") - private final Map TEMPLATE_DATA = new HashMap() { - { - put(PLACEHOLDER1, PLACEHOLDER1_VALUE); - put(PLACEHOLDER2, PLACEHOLDER2_VALUE); - } - }; + private final Map TEMPLATE_DATA = + new HashMap() { + { + put(PLACEHOLDER1, PLACEHOLDER1_VALUE); + put(PLACEHOLDER2, PLACEHOLDER2_VALUE); + } + }; + @SuppressWarnings("serial") private final Map TEMPLATE_DATA_WITH_MISSING_FIELD = new HashMap<>() { @@ -58,8 +61,7 @@ public class TemplateServiceTest { private TemplateService templateService; - @Mock - private TranslationService translationService; + @Mock private TranslationService translationService; @Before public void setup() { @@ -72,30 +74,28 @@ public void getProcessedSubject_Should_ReturnSubjectWithReplacedPlaceholders() { when(translationService.tryFetchTranslations(LanguageCode.DE.getValue(), Dialect.INFORMAL)) .thenReturn(Optional.of(Map.of("translationKey", SUBJECT_WITH_PLACEHOLDERS))); - var result = templateService.getRenderedSubject( - TEMPLATE_DESCRIPTION, TEMPLATE_DATA, new MailDTO() - .template(TEMPLATE_NAME) - .language(LanguageCode.DE) - .dialect(Dialect.INFORMAL) - ); + var result = + templateService.getRenderedSubject( + TEMPLATE_DESCRIPTION, + TEMPLATE_DATA, + new MailDTO() + .template(TEMPLATE_NAME) + .language(LanguageCode.DE) + .dialect(Dialect.INFORMAL)); assertEquals(SUBJECT_WITH_REPLACED_PLACEHOLDERS, result); - } @Test public void getProcessedHtmlTemplate_Should_ThrowServiceException_WhenTemplateDataIsMissing() { try { - templateService.render(TEMPLATE_DESCRIPTION, new MailDTO() - .template(TEMPLATE_NAME) - .language(LanguageCode.DE) - .dialect(Dialect.INFORMAL), + templateService.render( + TEMPLATE_DESCRIPTION, + new MailDTO().template(TEMPLATE_NAME).language(LanguageCode.DE).dialect(Dialect.INFORMAL), TEMPLATE_DATA_WITH_MISSING_FIELD); fail("Expected exception: ServiceException"); } catch (TemplateServiceException serviceException) { assertTrue("Excepted ServiceException thrown", true); } - } - } diff --git a/src/test/java/de/caritas/cob/mailservice/api/service/TranslationServiceTest.java b/src/test/java/de/caritas/cob/mailservice/api/service/TranslationServiceTest.java index eea8d00..013075f 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/service/TranslationServiceTest.java +++ b/src/test/java/de/caritas/cob/mailservice/api/service/TranslationServiceTest.java @@ -1,5 +1,13 @@ package de.caritas.cob.mailservice.api.service; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import de.caritas.cob.mailservice.api.model.Dialect; +import de.caritas.cob.mailservice.config.apiclient.TranslationManagementServiceApiClient; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -9,41 +17,38 @@ import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.client.HttpClientErrorException; -import de.caritas.cob.mailservice.api.model.Dialect; -import de.caritas.cob.mailservice.config.apiclient.TranslationManagementServiceApiClient; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - @ExtendWith(MockitoExtension.class) class TranslationServiceTest { private TranslationService translationService; - @Mock - private TranslationManagementServiceApiClient translationManagementServiceApiClient; + @Mock private TranslationManagementServiceApiClient translationManagementServiceApiClient; - @Mock - private DefaultTranslationsService defaultTranslationsService; + @Mock private DefaultTranslationsService defaultTranslationsService; - public final String TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_NAME = "translationManagementSystemEnabled"; + public final String TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_NAME = + "translationManagementSystemEnabled"; @BeforeEach public void setUp() { - translationService = new TranslationService(translationManagementServiceApiClient, defaultTranslationsService); + translationService = + new TranslationService(translationManagementServiceApiClient, defaultTranslationsService); } @Test - void fetchTranslations_Should_call_translationManagementServiceApiClient_When_translationManagementSystemEnabled_is_true() { + void + fetchTranslations_Should_call_translationManagementServiceApiClient_When_translationManagementSystemEnabled_is_true() { // Given final boolean TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_VALUE = true; - ReflectionTestUtils.setField(translationService, TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_NAME, TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_VALUE); - when(translationManagementServiceApiClient.tryFetchTranslationsFromTranslationManagementService(any(), any(), any(), any())).thenReturn("{\"mail.label.header\": \"Beratung\"}"); + ReflectionTestUtils.setField( + translationService, + TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_NAME, + TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_VALUE); + when(translationManagementServiceApiClient.tryFetchTranslationsFromTranslationManagementService( + any(), any(), any(), any())) + .thenReturn("{\"mail.label.header\": \"Beratung\"}"); // When @@ -51,20 +56,27 @@ void fetchTranslations_Should_call_translationManagementServiceApiClient_When_tr // Then - verify(translationManagementServiceApiClient).tryFetchTranslationsFromTranslationManagementService(any(), any(), any(), any()); + verify(translationManagementServiceApiClient) + .tryFetchTranslationsFromTranslationManagementService(any(), any(), any(), any()); verifyNoInteractions(defaultTranslationsService); - } @Test - void fetchTranslations_Should_call_fetchDefaultTranslations_When_translationManagementSystemEnabled_is_true_but_translationManagementServiceApiClient_Throws_HttpClientErrorException() { + void + fetchTranslations_Should_call_fetchDefaultTranslations_When_translationManagementSystemEnabled_is_true_but_translationManagementServiceApiClient_Throws_HttpClientErrorException() { // Given final boolean TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_VALUE = true; - ReflectionTestUtils.setField(translationService, TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_NAME, TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_VALUE); - when(translationManagementServiceApiClient.tryFetchTranslationsFromTranslationManagementService(any(), any(), any(), any())).thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)); - when(defaultTranslationsService.fetchDefaultTranslations(any(), any(), any())).thenReturn("{\"mail.label.header\": \"Beratung\"}"); + ReflectionTestUtils.setField( + translationService, + TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_NAME, + TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_VALUE); + when(translationManagementServiceApiClient.tryFetchTranslationsFromTranslationManagementService( + any(), any(), any(), any())) + .thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)); + when(defaultTranslationsService.fetchDefaultTranslations(any(), any(), any())) + .thenReturn("{\"mail.label.header\": \"Beratung\"}"); // When @@ -72,20 +84,25 @@ void fetchTranslations_Should_call_fetchDefaultTranslations_When_translationMana // Then - verify(translationManagementServiceApiClient).tryFetchTranslationsFromTranslationManagementService(any(), any(), any(), any()); + verify(translationManagementServiceApiClient) + .tryFetchTranslationsFromTranslationManagementService(any(), any(), any(), any()); verify(defaultTranslationsService).fetchDefaultTranslations(any(), any(), any()); verifyNoMoreInteractions(translationManagementServiceApiClient); - } @Test - void fetchTranslations_Should_call_fetchDefaultTranslations_When_translationManagementSystemEnabled_is_false() { + void + fetchTranslations_Should_call_fetchDefaultTranslations_When_translationManagementSystemEnabled_is_false() { // Given final boolean TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_VALUE = false; - ReflectionTestUtils.setField(translationService, TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_NAME, TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_VALUE); - when(defaultTranslationsService.fetchDefaultTranslations(any(), any(), any())).thenReturn("{\"mail.label.header\": \"Beratung\"}"); + ReflectionTestUtils.setField( + translationService, + TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_NAME, + TRANSLATION_MANAGEMENT_SYSTEM_ENABLED_FIELD_VALUE); + when(defaultTranslationsService.fetchDefaultTranslations(any(), any(), any())) + .thenReturn("{\"mail.label.header\": \"Beratung\"}"); // When @@ -95,6 +112,5 @@ void fetchTranslations_Should_call_fetchDefaultTranslations_When_translationMana verifyNoInteractions(translationManagementServiceApiClient); verify(defaultTranslationsService).fetchDefaultTranslations(any(), any(), any()); - } } From 3b2fb4fc8fea566489804f4bdc8fdf6691abc960 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Mon, 15 Apr 2024 17:00:55 +0200 Subject: [PATCH 2/6] chore: build only ghcr image --- .github/workflows/dockerImage.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dockerImage.yml b/.github/workflows/dockerImage.yml index d05d196..f69763f 100644 --- a/.github/workflows/dockerImage.yml +++ b/.github/workflows/dockerImage.yml @@ -63,7 +63,7 @@ jobs: push_to_registry: strategy: matrix: - registry: ["docker.pkg.github.com", "ghcr.io"] + registry: ["ghcr.io"] needs: [test] name: Push Docker image to GitHub Packages runs-on: ubuntu-latest From b881b992b2a473b3ff3bb1b648f8fea538852e95 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Tue, 16 Apr 2024 09:08:27 +0200 Subject: [PATCH 3/6] fix: LineInputStream dependency issue --- pom.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pom.xml b/pom.xml index eed0ab9..5c9ca94 100644 --- a/pom.xml +++ b/pom.xml @@ -87,6 +87,10 @@ javax.mail mailapi + + com.sun.mail + mailapi + From 7925f2e1aeba75a66ddca0dcdb001005f8461222 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Wed, 17 Apr 2024 09:51:49 +0200 Subject: [PATCH 4/6] feat: attempt to fix sonar --- .../java/de/caritas/cob/mailservice/config/SecurityConfig.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/de/caritas/cob/mailservice/config/SecurityConfig.java b/src/main/java/de/caritas/cob/mailservice/config/SecurityConfig.java index 4fd787b..b386e41 100644 --- a/src/main/java/de/caritas/cob/mailservice/config/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/mailservice/config/SecurityConfig.java @@ -42,8 +42,7 @@ public class SecurityConfig { public SecurityFilterChain configure(HttpSecurity http) throws Exception { var httpSecurity = - http.csrf() - .disable() + http .addFilterBefore( new StatelessCsrfFilter(csrfCookieProperty, csrfHeaderProperty), CsrfFilter.class); From 7a9db361f8792e012c27c0f3036da9c52d4897e0 Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Wed, 17 Apr 2024 09:53:18 +0200 Subject: [PATCH 5/6] feat: revert due to failing tests --- .../java/de/caritas/cob/mailservice/config/SecurityConfig.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/de/caritas/cob/mailservice/config/SecurityConfig.java b/src/main/java/de/caritas/cob/mailservice/config/SecurityConfig.java index b386e41..4fd787b 100644 --- a/src/main/java/de/caritas/cob/mailservice/config/SecurityConfig.java +++ b/src/main/java/de/caritas/cob/mailservice/config/SecurityConfig.java @@ -42,7 +42,8 @@ public class SecurityConfig { public SecurityFilterChain configure(HttpSecurity http) throws Exception { var httpSecurity = - http + http.csrf() + .disable() .addFilterBefore( new StatelessCsrfFilter(csrfCookieProperty, csrfHeaderProperty), CsrfFilter.class); From 6d5b84dd54a0ecc477e4dd22bbeffca7e87bd21e Mon Sep 17 00:00:00 2001 From: tkuzynow Date: Wed, 17 Apr 2024 10:01:13 +0200 Subject: [PATCH 6/6] feat: add unit test to cover that CRSF filter is working --- .../api/controller/MailControllerE2EIT.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/test/java/de/caritas/cob/mailservice/api/controller/MailControllerE2EIT.java b/src/test/java/de/caritas/cob/mailservice/api/controller/MailControllerE2EIT.java index e7be338..096f096 100644 --- a/src/test/java/de/caritas/cob/mailservice/api/controller/MailControllerE2EIT.java +++ b/src/test/java/de/caritas/cob/mailservice/api/controller/MailControllerE2EIT.java @@ -84,6 +84,20 @@ void sendMailsShouldRespondWithOkWhenEmailListIsEmpty() throws Exception { .andExpect(status().isOk()); } + @Test + void sendMailsShouldRespondWithAccessDeniedWhenCrsfTokenIsNotGiven() throws Exception { + givenAnEmptyEmailList(); + + mockMvc + .perform( + post("/mails/send") + .cookie(CSRF_COOKIE) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(mailsDTO)) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isForbidden()); + } + @Test void sendMailsShouldSendEmailAndRenderDataWithDefaultLanguageWhenLanguageNotGiven() throws Exception {