diff --git a/src/main/java/org/hostsharing/hsadminng/ApplicationWebXml.java b/src/main/java/org/hostsharing/hsadminng/ApplicationWebXml.java index b33bf680..d6b76fff 100644 --- a/src/main/java/org/hostsharing/hsadminng/ApplicationWebXml.java +++ b/src/main/java/org/hostsharing/hsadminng/ApplicationWebXml.java @@ -1,6 +1,8 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng; import org.hostsharing.hsadminng.config.DefaultProfileUtil; + import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; diff --git a/src/main/java/org/hostsharing/hsadminng/HsadminNgApp.java b/src/main/java/org/hostsharing/hsadminng/HsadminNgApp.java index a0ecca17..d96b3bd5 100644 --- a/src/main/java/org/hostsharing/hsadminng/HsadminNgApp.java +++ b/src/main/java/org/hostsharing/hsadminng/HsadminNgApp.java @@ -1,11 +1,14 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng; -import io.github.jhipster.config.JHipsterConstants; -import org.apache.commons.lang3.StringUtils; import org.hostsharing.hsadminng.config.ApplicationProperties; import org.hostsharing.hsadminng.config.DefaultProfileUtil; import org.hostsharing.hsadminng.security.SecurityUtils; import org.hostsharing.hsadminng.service.accessfilter.Role; + +import io.github.jhipster.config.JHipsterConstants; + +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; @@ -14,14 +17,15 @@ import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.core.env.Environment; -import javax.annotation.PostConstruct; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Collection; +import javax.annotation.PostConstruct; + @SpringBootApplication -@EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class}) +@EnableConfigurationProperties({ LiquibaseProperties.class, ApplicationProperties.class }) public class HsadminNgApp { private static final Logger log = LoggerFactory.getLogger(HsadminNgApp.class); @@ -37,19 +41,24 @@ public class HsadminNgApp { *

* Spring profiles can be configured with a program argument --spring.profiles.active=your-active-profile *

- * You can find more information on how profiles work with JHipster on https://www.jhipster.tech/profiles/. + * You can find more information on how profiles work with JHipster on + * https://www.jhipster.tech/profiles/. */ @PostConstruct public void initApplication() { Collection activeProfiles = Arrays.asList(env.getActiveProfiles()); - if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { - log.error("You have misconfigured your application! It should not run " + - "with both the 'dev' and 'prod' profiles at the same time."); + if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) + && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { + log.error( + "You have misconfigured your application! It should not run " + + "with both the 'dev' and 'prod' profiles at the same time."); } - if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) { - log.error("You have misconfigured your application! It should not " + - "run with both the 'dev' and 'cloud' profiles at the same time."); + if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) + && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) { + log.error( + "You have misconfigured your application! It should not " + + "run with both the 'dev' and 'cloud' profiles at the same time."); } // TODO: remove this hack once proper user roles are implemented @@ -89,19 +98,20 @@ public class HsadminNgApp { } catch (UnknownHostException e) { log.warn("The host name could not be determined, using `localhost` as fallback"); } - log.info("\n----------------------------------------------------------\n\t" + - "Application '{}' is running! Access URLs:\n\t" + - "Local: \t\t{}://localhost:{}{}\n\t" + - "External: \t{}://{}:{}{}\n\t" + - "Profile(s): \t{}\n----------------------------------------------------------", - env.getProperty("spring.application.name"), - protocol, - serverPort, - contextPath, - protocol, - hostAddress, - serverPort, - contextPath, - env.getActiveProfiles()); + log.info( + "\n----------------------------------------------------------\n\t" + + "Application '{}' is running! Access URLs:\n\t" + + "Local: \t\t{}://localhost:{}{}\n\t" + + "External: \t{}://{}:{}{}\n\t" + + "Profile(s): \t{}\n----------------------------------------------------------", + env.getProperty("spring.application.name"), + protocol, + serverPort, + contextPath, + protocol, + hostAddress, + serverPort, + contextPath, + env.getActiveProfiles()); } } diff --git a/src/main/java/org/hostsharing/hsadminng/aop/logging/LoggingAspect.java b/src/main/java/org/hostsharing/hsadminng/aop/logging/LoggingAspect.java index 9e8b7452..f6574ef4 100644 --- a/src/main/java/org/hostsharing/hsadminng/aop/logging/LoggingAspect.java +++ b/src/main/java/org/hostsharing/hsadminng/aop/logging/LoggingAspect.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.aop.logging; import io.github.jhipster.config.JHipsterConstants; @@ -34,8 +35,8 @@ public class LoggingAspect { * Pointcut that matches all repositories, services and Web REST endpoints. */ @Pointcut("within(@org.springframework.stereotype.Repository *)" + - " || within(@org.springframework.stereotype.Service *)" + - " || within(@org.springframework.web.bind.annotation.RestController *)") + " || within(@org.springframework.stereotype.Service *)" + + " || within(@org.springframework.web.bind.annotation.RestController *)") public void springBeanPointcut() { // Method is empty as this is just a Pointcut, the implementations are in the advices. } @@ -43,9 +44,9 @@ public class LoggingAspect { /** * Pointcut that matches all Spring beans in the application's main packages. */ - @Pointcut("within(org.hostsharing.hsadminng.repository..*)"+ - " || within(org.hostsharing.hsadminng.service..*)"+ - " || within(org.hostsharing.hsadminng.web.rest..*)") + @Pointcut("within(org.hostsharing.hsadminng.repository..*)" + + " || within(org.hostsharing.hsadminng.service..*)" + + " || within(org.hostsharing.hsadminng.web.rest..*)") public void applicationPackagePointcut() { // Method is empty as this is just a Pointcut, the implementations are in the advices. } @@ -59,12 +60,20 @@ public class LoggingAspect { @AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { - log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(), - joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e); + log.error( + "Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", + joinPoint.getSignature().getDeclaringTypeName(), + joinPoint.getSignature().getName(), + e.getCause() != null ? e.getCause() : "NULL", + e.getMessage(), + e); } else { - log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), - joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL"); + log.error( + "Exception in {}.{}() with cause = {}", + joinPoint.getSignature().getDeclaringTypeName(), + joinPoint.getSignature().getName(), + e.getCause() != null ? e.getCause() : "NULL"); } } @@ -78,19 +87,28 @@ public class LoggingAspect { @Around("applicationPackagePointcut() && springBeanPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { if (log.isDebugEnabled()) { - log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(), - joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); + log.debug( + "Enter: {}.{}() with argument[s] = {}", + joinPoint.getSignature().getDeclaringTypeName(), + joinPoint.getSignature().getName(), + Arrays.toString(joinPoint.getArgs())); } try { Object result = joinPoint.proceed(); if (log.isDebugEnabled()) { - log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(), - joinPoint.getSignature().getName(), result); + log.debug( + "Exit: {}.{}() with result = {}", + joinPoint.getSignature().getDeclaringTypeName(), + joinPoint.getSignature().getName(), + result); } return result; } catch (IllegalArgumentException e) { - log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()), - joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()); + log.error( + "Illegal argument: {} in {}.{}()", + Arrays.toString(joinPoint.getArgs()), + joinPoint.getSignature().getDeclaringTypeName(), + joinPoint.getSignature().getName()); throw e; } diff --git a/src/main/java/org/hostsharing/hsadminng/config/ApplicationProperties.java b/src/main/java/org/hostsharing/hsadminng/config/ApplicationProperties.java index e34fdaa6..19bc4cdb 100644 --- a/src/main/java/org/hostsharing/hsadminng/config/ApplicationProperties.java +++ b/src/main/java/org/hostsharing/hsadminng/config/ApplicationProperties.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; import org.springframework.boot.context.properties.ConfigurationProperties; diff --git a/src/main/java/org/hostsharing/hsadminng/config/AsyncConfiguration.java b/src/main/java/org/hostsharing/hsadminng/config/AsyncConfiguration.java index f4d89ec1..c87c3b44 100644 --- a/src/main/java/org/hostsharing/hsadminng/config/AsyncConfiguration.java +++ b/src/main/java/org/hostsharing/hsadminng/config/AsyncConfiguration.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; import io.github.jhipster.async.ExceptionHandlingAsyncTaskExecutor; @@ -10,8 +11,8 @@ import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.*; -import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.annotation.SchedulingConfigurer; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import java.util.concurrent.Executor; @@ -46,7 +47,7 @@ public class AsyncConfiguration implements AsyncConfigurer, SchedulingConfigurer public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new SimpleAsyncUncaughtExceptionHandler(); } - + @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(scheduledTaskExecutor()); diff --git a/src/main/java/org/hostsharing/hsadminng/config/CacheConfiguration.java b/src/main/java/org/hostsharing/hsadminng/config/CacheConfiguration.java index f0697857..73cf132f 100644 --- a/src/main/java/org/hostsharing/hsadminng/config/CacheConfiguration.java +++ b/src/main/java/org/hostsharing/hsadminng/config/CacheConfiguration.java @@ -1,16 +1,16 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; -import java.time.Duration; - -import org.ehcache.config.builders.*; -import org.ehcache.jsr107.Eh107Configuration; - import io.github.jhipster.config.JHipsterProperties; +import org.ehcache.config.builders.*; +import org.ehcache.jsr107.Eh107Configuration; import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.*; +import java.time.Duration; + @Configuration @EnableCaching public class CacheConfiguration { @@ -18,14 +18,16 @@ public class CacheConfiguration { private final javax.cache.configuration.Configuration jcacheConfiguration; public CacheConfiguration(JHipsterProperties jHipsterProperties) { - JHipsterProperties.Cache.Ehcache ehcache = - jHipsterProperties.getCache().getEhcache(); + JHipsterProperties.Cache.Ehcache ehcache = jHipsterProperties.getCache().getEhcache(); jcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration( - CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class, - ResourcePoolsBuilder.heap(ehcache.getMaxEntries())) - .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(ehcache.getTimeToLiveSeconds()))) - .build()); + CacheConfigurationBuilder.newCacheConfigurationBuilder( + Object.class, + Object.class, + ResourcePoolsBuilder.heap(ehcache.getMaxEntries())) + .withExpiry( + ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(ehcache.getTimeToLiveSeconds()))) + .build()); } @Bean diff --git a/src/main/java/org/hostsharing/hsadminng/config/CloudDatabaseConfiguration.java b/src/main/java/org/hostsharing/hsadminng/config/CloudDatabaseConfiguration.java index 4422aba3..f28cc4b4 100644 --- a/src/main/java/org/hostsharing/hsadminng/config/CloudDatabaseConfiguration.java +++ b/src/main/java/org/hostsharing/hsadminng/config/CloudDatabaseConfiguration.java @@ -1,22 +1,22 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; import io.github.jhipster.config.JHipsterConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.config.java.AbstractCloudConfig; import org.springframework.context.annotation.*; import javax.sql.DataSource; -import org.springframework.boot.context.properties.ConfigurationProperties; - @Configuration @Profile(JHipsterConstants.SPRING_PROFILE_CLOUD) public class CloudDatabaseConfiguration extends AbstractCloudConfig { private final Logger log = LoggerFactory.getLogger(CloudDatabaseConfiguration.class); - + private static final String CLOUD_CONFIGURATION_HIKARI_PREFIX = "spring.datasource.hikari"; @Bean diff --git a/src/main/java/org/hostsharing/hsadminng/config/Constants.java b/src/main/java/org/hostsharing/hsadminng/config/Constants.java index 5cfeea37..82186df3 100644 --- a/src/main/java/org/hostsharing/hsadminng/config/Constants.java +++ b/src/main/java/org/hostsharing/hsadminng/config/Constants.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; /** @@ -11,7 +12,7 @@ public final class Constants { public static final String SYSTEM_ACCOUNT = "system"; public static final String ANONYMOUS_USER = "anonymoususer"; public static final String DEFAULT_LANGUAGE = "de"; - + private Constants() { } } diff --git a/src/main/java/org/hostsharing/hsadminng/config/DatabaseConfiguration.java b/src/main/java/org/hostsharing/hsadminng/config/DatabaseConfiguration.java index 519bf7c1..e9a2b893 100644 --- a/src/main/java/org/hostsharing/hsadminng/config/DatabaseConfiguration.java +++ b/src/main/java/org/hostsharing/hsadminng/config/DatabaseConfiguration.java @@ -1,13 +1,14 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.h2.H2ConfigurationHelper; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; - import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @@ -42,7 +43,7 @@ public class DatabaseConfiguration { log.debug("H2 database is available on port {}", port); return H2ConfigurationHelper.createServer(port); } - + private String getValidPortForH2() { int port = Integer.parseInt(env.getProperty("server.port")); if (port < 10000) { diff --git a/src/main/java/org/hostsharing/hsadminng/config/DateTimeFormatConfiguration.java b/src/main/java/org/hostsharing/hsadminng/config/DateTimeFormatConfiguration.java index a4afa568..fb50c23d 100644 --- a/src/main/java/org/hostsharing/hsadminng/config/DateTimeFormatConfiguration.java +++ b/src/main/java/org/hostsharing/hsadminng/config/DateTimeFormatConfiguration.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; import org.springframework.context.annotation.Configuration; diff --git a/src/main/java/org/hostsharing/hsadminng/config/DefaultProfileUtil.java b/src/main/java/org/hostsharing/hsadminng/config/DefaultProfileUtil.java index fda28af8..234b69cb 100644 --- a/src/main/java/org/hostsharing/hsadminng/config/DefaultProfileUtil.java +++ b/src/main/java/org/hostsharing/hsadminng/config/DefaultProfileUtil.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; import io.github.jhipster.config.JHipsterConstants; @@ -27,10 +28,10 @@ public final class DefaultProfileUtil { public static void addDefaultProfile(SpringApplication app) { Map defProperties = new HashMap<>(); /* - * The default profile to use when no other profiles are defined - * This cannot be set in the application.yml file. - * See https://github.com/spring-projects/spring-boot/issues/1219 - */ + * The default profile to use when no other profiles are defined + * This cannot be set in the application.yml file. + * See https://github.com/spring-projects/spring-boot/issues/1219 + */ defProperties.put(SPRING_PROFILE_DEFAULT, JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); app.setDefaultProperties(defProperties); } diff --git a/src/main/java/org/hostsharing/hsadminng/config/JacksonConfiguration.java b/src/main/java/org/hostsharing/hsadminng/config/JacksonConfiguration.java index 16a4bcda..0105111b 100644 --- a/src/main/java/org/hostsharing/hsadminng/config/JacksonConfiguration.java +++ b/src/main/java/org/hostsharing/hsadminng/config/JacksonConfiguration.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module; @@ -15,6 +16,7 @@ public class JacksonConfiguration { /** * Support for Java date and time API. + * * @return the corresponding Jackson module. */ @Bean @@ -27,7 +29,6 @@ public class JacksonConfiguration { return new Jdk8Module(); } - /* * Support for Hibernate types in Jackson. */ diff --git a/src/main/java/org/hostsharing/hsadminng/config/LiquibaseConfiguration.java b/src/main/java/org/hostsharing/hsadminng/config/LiquibaseConfiguration.java index 18a7df43..196d907e 100644 --- a/src/main/java/org/hostsharing/hsadminng/config/LiquibaseConfiguration.java +++ b/src/main/java/org/hostsharing/hsadminng/config/LiquibaseConfiguration.java @@ -1,6 +1,9 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; -import javax.sql.DataSource; +import io.github.jhipster.config.JHipsterConstants; +import io.github.jhipster.config.liquibase.AsyncSpringLiquibase; +import liquibase.integration.spring.SpringLiquibase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -11,9 +14,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.task.TaskExecutor; -import io.github.jhipster.config.JHipsterConstants; -import io.github.jhipster.config.liquibase.AsyncSpringLiquibase; -import liquibase.integration.spring.SpringLiquibase; +import javax.sql.DataSource; @Configuration public class LiquibaseConfiguration { @@ -22,14 +23,15 @@ public class LiquibaseConfiguration { private final Environment env; - public LiquibaseConfiguration(Environment env) { this.env = env; } @Bean - public SpringLiquibase liquibase(@Qualifier("taskExecutor") TaskExecutor taskExecutor, - DataSource dataSource, LiquibaseProperties liquibaseProperties) { + public SpringLiquibase liquibase( + @Qualifier("taskExecutor") TaskExecutor taskExecutor, + DataSource dataSource, + LiquibaseProperties liquibaseProperties) { // Use liquibase.integration.spring.SpringLiquibase if you don't want Liquibase to start asynchronously SpringLiquibase liquibase = new AsyncSpringLiquibase(taskExecutor, env); diff --git a/src/main/java/org/hostsharing/hsadminng/config/LocaleConfiguration.java b/src/main/java/org/hostsharing/hsadminng/config/LocaleConfiguration.java index ab3962ba..99386585 100644 --- a/src/main/java/org/hostsharing/hsadminng/config/LocaleConfiguration.java +++ b/src/main/java/org/hostsharing/hsadminng/config/LocaleConfiguration.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; import io.github.jhipster.config.locale.AngularCookieLocaleResolver; diff --git a/src/main/java/org/hostsharing/hsadminng/config/LoggingAspectConfiguration.java b/src/main/java/org/hostsharing/hsadminng/config/LoggingAspectConfiguration.java index e27a5a65..149ea1fa 100644 --- a/src/main/java/org/hostsharing/hsadminng/config/LoggingAspectConfiguration.java +++ b/src/main/java/org/hostsharing/hsadminng/config/LoggingAspectConfiguration.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; import org.hostsharing.hsadminng.aop.logging.LoggingAspect; diff --git a/src/main/java/org/hostsharing/hsadminng/config/LoggingConfiguration.java b/src/main/java/org/hostsharing/hsadminng/config/LoggingConfiguration.java index 57e2f46c..83ecbb1a 100644 --- a/src/main/java/org/hostsharing/hsadminng/config/LoggingConfiguration.java +++ b/src/main/java/org/hostsharing/hsadminng/config/LoggingConfiguration.java @@ -1,10 +1,6 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; -import java.net.InetSocketAddress; -import java.util.Iterator; - -import io.github.jhipster.config.JHipsterProperties; - import ch.qos.logback.classic.AsyncAppender; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; @@ -15,14 +11,19 @@ import ch.qos.logback.core.Appender; import ch.qos.logback.core.filter.EvaluatorFilter; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.spi.FilterReply; +import io.github.jhipster.config.JHipsterProperties; import net.logstash.logback.appender.LogstashTcpSocketAppender; import net.logstash.logback.encoder.LogstashEncoder; import net.logstash.logback.stacktrace.ShortenedThrowableConverter; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; +import java.net.InetSocketAddress; +import java.util.Iterator; + @Configuration public class LoggingConfiguration { @@ -40,8 +41,10 @@ public class LoggingConfiguration { private final JHipsterProperties jHipsterProperties; - public LoggingConfiguration(@Value("${spring.application.name}") String appName, @Value("${server.port}") String serverPort, - JHipsterProperties jHipsterProperties) { + public LoggingConfiguration( + @Value("${spring.application.name}") String appName, + @Value("${server.port}") String serverPort, + JHipsterProperties jHipsterProperties) { this.appName = appName; this.serverPort = serverPort; this.jHipsterProperties = jHipsterProperties; @@ -71,7 +74,10 @@ public class LoggingConfiguration { // More documentation is available at: https://github.com/logstash/logstash-logback-encoder LogstashEncoder logstashEncoder = new LogstashEncoder(); // Set the Logstash appender config from JHipster properties - logstashAppender.addDestinations(new InetSocketAddress(jHipsterProperties.getLogging().getLogstash().getHost(), jHipsterProperties.getLogging().getLogstash().getPort())); + logstashAppender.addDestinations( + new InetSocketAddress( + jHipsterProperties.getLogging().getLogstash().getHost(), + jHipsterProperties.getLogging().getLogstash().getPort())); ShortenedThrowableConverter throwableConverter = new ShortenedThrowableConverter(); throwableConverter.setRootCauseFirst(true); diff --git a/src/main/java/org/hostsharing/hsadminng/config/SecurityConfiguration.java b/src/main/java/org/hostsharing/hsadminng/config/SecurityConfiguration.java index 17ec6616..db8a5482 100644 --- a/src/main/java/org/hostsharing/hsadminng/config/SecurityConfiguration.java +++ b/src/main/java/org/hostsharing/hsadminng/config/SecurityConfiguration.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; import org.hostsharing.hsadminng.security.*; @@ -41,7 +42,12 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { private final SecurityProblemSupport problemSupport; - public SecurityConfiguration(AuthenticationManagerBuilder authenticationManagerBuilder, UserDetailsService userDetailsService, TokenProvider tokenProvider, CorsFilter corsFilter, SecurityProblemSupport problemSupport) { + public SecurityConfiguration( + AuthenticationManagerBuilder authenticationManagerBuilder, + UserDetailsService userDetailsService, + TokenProvider tokenProvider, + CorsFilter corsFilter, + SecurityProblemSupport problemSupport) { this.authenticationManagerBuilder = authenticationManagerBuilder; this.userDetailsService = userDetailsService; this.tokenProvider = tokenProvider; @@ -53,8 +59,8 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { public void init() { try { authenticationManagerBuilder - .userDetailsService(userDetailsService) - .passwordEncoder(passwordEncoder()); + .userDetailsService(userDetailsService) + .passwordEncoder(passwordEncoder()); } catch (Exception e) { throw new BeanInitializationException("Security configuration failed", e); } @@ -74,17 +80,18 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Override public void configure(WebSecurity web) throws Exception { web.ignoring() - .antMatchers(HttpMethod.OPTIONS, "/**") - .antMatchers("/app/**/*.{js,html}") - .antMatchers("/i18n/**") - .antMatchers("/content/**") - .antMatchers("/h2-console/**") - .antMatchers("/swagger-ui/index.html") - .antMatchers("/test/**"); + .antMatchers(HttpMethod.OPTIONS, "/**") + .antMatchers("/app/**/*.{js,html}") + .antMatchers("/i18n/**") + .antMatchers("/content/**") + .antMatchers("/h2-console/**") + .antMatchers("/swagger-ui/index.html") + .antMatchers("/test/**"); } @Override public void configure(HttpSecurity http) throws Exception { + // @formatter:off http .csrf() .disable() @@ -112,7 +119,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN) .and() .apply(securityConfigurerAdapter()); - + // @formatter:on } private JWTConfigurer securityConfigurerAdapter() { diff --git a/src/main/java/org/hostsharing/hsadminng/config/WebConfigurer.java b/src/main/java/org/hostsharing/hsadminng/config/WebConfigurer.java index 0eea3091..e0265aff 100644 --- a/src/main/java/org/hostsharing/hsadminng/config/WebConfigurer.java +++ b/src/main/java/org/hostsharing/hsadminng/config/WebConfigurer.java @@ -1,13 +1,16 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; +import static java.net.URLDecoder.decode; + import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.JHipsterProperties; import io.github.jhipster.config.h2.H2ConfigurationHelper; import io.github.jhipster.web.filter.CachingHttpHeadersFilter; import io.undertow.UndertowOptions; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; import org.springframework.boot.web.server.*; import org.springframework.boot.web.servlet.ServletContextInitializer; @@ -20,14 +23,13 @@ import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; -import javax.servlet.*; import java.io.File; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.*; -import static java.net.URLDecoder.decode; +import javax.servlet.*; /** * Configuration of web application with Servlet 3.0 APIs. @@ -78,11 +80,10 @@ public class WebConfigurer implements ServletContextInitializer, WebServerFactor * for more information. */ if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && - server instanceof UndertowServletWebServerFactory) { + server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) - .addBuilderCustomizers(builder -> - builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); + .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } @@ -133,11 +134,12 @@ public class WebConfigurer implements ServletContextInitializer, WebServerFactor /** * Initializes the caching HTTP Headers Filter. */ - private void initCachingHttpHeadersFilter(ServletContext servletContext, - EnumSet disps) { + private void initCachingHttpHeadersFilter( + ServletContext servletContext, + EnumSet disps) { log.debug("Registering Caching HTTP Headers Filter"); - FilterRegistration.Dynamic cachingHttpHeadersFilter = - servletContext.addFilter("cachingHttpHeadersFilter", + FilterRegistration.Dynamic cachingHttpHeadersFilter = servletContext.addFilter( + "cachingHttpHeadersFilter", new CachingHttpHeadersFilter(jHipsterProperties)); cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/i18n/*"); diff --git a/src/main/java/org/hostsharing/hsadminng/config/audit/AuditEventConverter.java b/src/main/java/org/hostsharing/hsadminng/config/audit/AuditEventConverter.java index e54a06b1..9a591c96 100644 --- a/src/main/java/org/hostsharing/hsadminng/config/audit/AuditEventConverter.java +++ b/src/main/java/org/hostsharing/hsadminng/config/audit/AuditEventConverter.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config.audit; import org.hostsharing.hsadminng.domain.PersistentAuditEvent; @@ -38,8 +39,11 @@ public class AuditEventConverter { if (persistentAuditEvent == null) { return null; } - return new AuditEvent(persistentAuditEvent.getAuditEventDate(), persistentAuditEvent.getPrincipal(), - persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData())); + return new AuditEvent( + persistentAuditEvent.getAuditEventDate(), + persistentAuditEvent.getPrincipal(), + persistentAuditEvent.getAuditEventType(), + convertDataToObjects(persistentAuditEvent.getData())); } /** diff --git a/src/main/java/org/hostsharing/hsadminng/domain/AbstractAuditingEntity.java b/src/main/java/org/hostsharing/hsadminng/domain/AbstractAuditingEntity.java index 40805725..d1f27399 100644 --- a/src/main/java/org/hostsharing/hsadminng/domain/AbstractAuditingEntity.java +++ b/src/main/java/org/hostsharing/hsadminng/domain/AbstractAuditingEntity.java @@ -1,6 +1,8 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.domain; import com.fasterxml.jackson.annotation.JsonIgnore; + import org.hibernate.envers.Audited; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; @@ -10,6 +12,7 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener; import java.io.Serializable; import java.time.Instant; + import javax.persistence.Column; import javax.persistence.EntityListeners; import javax.persistence.MappedSuperclass; diff --git a/src/main/java/org/hostsharing/hsadminng/domain/Asset.java b/src/main/java/org/hostsharing/hsadminng/domain/Asset.java index ef7fa87e..f0d1cfd1 100644 --- a/src/main/java/org/hostsharing/hsadminng/domain/Asset.java +++ b/src/main/java/org/hostsharing/hsadminng/domain/Asset.java @@ -1,17 +1,19 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.domain; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.hostsharing.hsadminng.domain.enumeration.AssetAction; -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import java.io.Serializable; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Objects; +import javax.persistence.*; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + /** * A Asset. */ @@ -170,12 +172,12 @@ public class Asset implements Serializable { @Override public String toString() { return "Asset{" + - "id=" + getId() + - ", documentDate='" + getDocumentDate() + "'" + - ", valueDate='" + getValueDate() + "'" + - ", action='" + getAction() + "'" + - ", amount=" + getAmount() + - ", remark='" + getRemark() + "'" + - "}"; + "id=" + getId() + + ", documentDate='" + getDocumentDate() + "'" + + ", valueDate='" + getValueDate() + "'" + + ", action='" + getAction() + "'" + + ", amount=" + getAmount() + + ", remark='" + getRemark() + "'" + + "}"; } } diff --git a/src/main/java/org/hostsharing/hsadminng/domain/Authority.java b/src/main/java/org/hostsharing/hsadminng/domain/Authority.java index cac1692b..422347c7 100644 --- a/src/main/java/org/hostsharing/hsadminng/domain/Authority.java +++ b/src/main/java/org/hostsharing/hsadminng/domain/Authority.java @@ -1,12 +1,14 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.domain; +import java.io.Serializable; + +import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; -import javax.persistence.Column; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; -import java.io.Serializable; /** * An authority (a security role) used by Spring Security. @@ -53,7 +55,7 @@ public class Authority implements Serializable { @Override public String toString() { return "Authority{" + - "name='" + name + '\'' + - "}"; + "name='" + name + '\'' + + "}"; } } diff --git a/src/main/java/org/hostsharing/hsadminng/domain/Customer.java b/src/main/java/org/hostsharing/hsadminng/domain/Customer.java index b1745ea5..55276b75 100644 --- a/src/main/java/org/hostsharing/hsadminng/domain/Customer.java +++ b/src/main/java/org/hostsharing/hsadminng/domain/Customer.java @@ -1,17 +1,18 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.domain; - import org.hostsharing.hsadminng.domain.enumeration.CustomerKind; import org.hostsharing.hsadminng.domain.enumeration.VatRegion; -import javax.persistence.*; -import javax.validation.constraints.*; import java.io.Serializable; import java.time.LocalDate; import java.util.HashSet; import java.util.Objects; import java.util.Set; +import javax.persistence.*; +import javax.validation.constraints.*; + /** * A Customer. */ @@ -20,7 +21,7 @@ import java.util.Set; public class Customer implements Serializable { private static final long serialVersionUID = 1L; - + @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") @SequenceGenerator(name = "sequenceGenerator") @@ -384,22 +385,22 @@ public class Customer implements Serializable { @Override public String toString() { return "Customer{" + - "id=" + getId() + - ", reference=" + getReference() + - ", prefix='" + getPrefix() + "'" + - ", name='" + getName() + "'" + - ", kind='" + getKind() + "'" + - ", birthDate='" + getBirthDate() + "'" + - ", birthPlace='" + getBirthPlace() + "'" + - ", registrationCourt='" + getRegistrationCourt() + "'" + - ", registrationNumber='" + getRegistrationNumber() + "'" + - ", vatRegion='" + getVatRegion() + "'" + - ", vatNumber='" + getVatNumber() + "'" + - ", contractualSalutation='" + getContractualSalutation() + "'" + - ", contractualAddress='" + getContractualAddress() + "'" + - ", billingSalutation='" + getBillingSalutation() + "'" + - ", billingAddress='" + getBillingAddress() + "'" + - ", remark='" + getRemark() + "'" + - "}"; + "id=" + getId() + + ", reference=" + getReference() + + ", prefix='" + getPrefix() + "'" + + ", name='" + getName() + "'" + + ", kind='" + getKind() + "'" + + ", birthDate='" + getBirthDate() + "'" + + ", birthPlace='" + getBirthPlace() + "'" + + ", registrationCourt='" + getRegistrationCourt() + "'" + + ", registrationNumber='" + getRegistrationNumber() + "'" + + ", vatRegion='" + getVatRegion() + "'" + + ", vatNumber='" + getVatNumber() + "'" + + ", contractualSalutation='" + getContractualSalutation() + "'" + + ", contractualAddress='" + getContractualAddress() + "'" + + ", billingSalutation='" + getBillingSalutation() + "'" + + ", billingAddress='" + getBillingAddress() + "'" + + ", remark='" + getRemark() + "'" + + "}"; } } diff --git a/src/main/java/org/hostsharing/hsadminng/domain/Membership.java b/src/main/java/org/hostsharing/hsadminng/domain/Membership.java index 0e6f4b0e..f940ab32 100644 --- a/src/main/java/org/hostsharing/hsadminng/domain/Membership.java +++ b/src/main/java/org/hostsharing/hsadminng/domain/Membership.java @@ -1,17 +1,18 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.domain; - import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; import java.io.Serializable; import java.time.LocalDate; import java.util.HashSet; import java.util.Objects; import java.util.Set; +import javax.persistence.*; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + /** * A Membership. */ @@ -225,12 +226,12 @@ public class Membership implements Serializable { @Override public String toString() { return "Membership{" + - "id=" + getId() + - ", admissionDocumentDate='" + getAdmissionDocumentDate() + "'" + - ", cancellationDocumentDate='" + getCancellationDocumentDate() + "'" + - ", memberFromDate='" + getMemberFromDate() + "'" + - ", memberUntilDate='" + getMemberUntilDate() + "'" + - ", remark='" + getRemark() + "'" + - "}"; + "id=" + getId() + + ", admissionDocumentDate='" + getAdmissionDocumentDate() + "'" + + ", cancellationDocumentDate='" + getCancellationDocumentDate() + "'" + + ", memberFromDate='" + getMemberFromDate() + "'" + + ", memberUntilDate='" + getMemberUntilDate() + "'" + + ", remark='" + getRemark() + "'" + + "}"; } } diff --git a/src/main/java/org/hostsharing/hsadminng/domain/PersistentAuditEvent.java b/src/main/java/org/hostsharing/hsadminng/domain/PersistentAuditEvent.java index 3288e892..d59463c2 100644 --- a/src/main/java/org/hostsharing/hsadminng/domain/PersistentAuditEvent.java +++ b/src/main/java/org/hostsharing/hsadminng/domain/PersistentAuditEvent.java @@ -1,12 +1,14 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.domain; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.io.Serializable; import java.time.Instant; import java.util.HashMap; -import java.util.Objects; import java.util.Map; +import java.util.Objects; + +import javax.persistence.*; +import javax.validation.constraints.NotNull; /** * Persist AuditEvent managed by the Spring Boot actuator. @@ -38,7 +40,7 @@ public class PersistentAuditEvent implements Serializable { @ElementCollection @MapKeyColumn(name = "name") @Column(name = "value") - @CollectionTable(name = "jhi_persistent_audit_evt_data", joinColumns=@JoinColumn(name="event_id")) + @CollectionTable(name = "jhi_persistent_audit_evt_data", joinColumns = @JoinColumn(name = "event_id")) private Map data = new HashMap<>(); public Long getId() { @@ -91,7 +93,8 @@ public class PersistentAuditEvent implements Serializable { } PersistentAuditEvent persistentAuditEvent = (PersistentAuditEvent) o; - return !(persistentAuditEvent.getId() == null || getId() == null) && Objects.equals(getId(), persistentAuditEvent.getId()); + return !(persistentAuditEvent.getId() == null || getId() == null) + && Objects.equals(getId(), persistentAuditEvent.getId()); } @Override @@ -102,9 +105,9 @@ public class PersistentAuditEvent implements Serializable { @Override public String toString() { return "PersistentAuditEvent{" + - "principal='" + principal + '\'' + - ", auditEventDate=" + auditEventDate + - ", auditEventType='" + auditEventType + '\'' + - '}'; + "principal='" + principal + '\'' + + ", auditEventDate=" + auditEventDate + + ", auditEventType='" + auditEventType + '\'' + + '}'; } } diff --git a/src/main/java/org/hostsharing/hsadminng/domain/SepaMandate.java b/src/main/java/org/hostsharing/hsadminng/domain/SepaMandate.java index bff9b4bf..bc0ef38c 100644 --- a/src/main/java/org/hostsharing/hsadminng/domain/SepaMandate.java +++ b/src/main/java/org/hostsharing/hsadminng/domain/SepaMandate.java @@ -1,14 +1,15 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.domain; - import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import java.io.Serializable; +import java.time.LocalDate; +import java.util.Objects; + import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; -import java.io.Serializable; -import java.time.LocalDate; -import java.util.Objects; /** * A SepaMandate. @@ -18,7 +19,7 @@ import java.util.Objects; public class SepaMandate implements Serializable { private static final long serialVersionUID = 1L; - + @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") @SequenceGenerator(name = "sequenceGenerator") @@ -232,16 +233,16 @@ public class SepaMandate implements Serializable { @Override public String toString() { return "SepaMandate{" + - "id=" + getId() + - ", reference='" + getReference() + "'" + - ", iban='" + getIban() + "'" + - ", bic='" + getBic() + "'" + - ", grantingDocumentDate='" + getGrantingDocumentDate() + "'" + - ", revokationDocumentDate='" + getRevokationDocumentDate() + "'" + - ", validFromDate='" + getValidFromDate() + "'" + - ", validUntilDate='" + getValidUntilDate() + "'" + - ", lastUsedDate='" + getLastUsedDate() + "'" + - ", remark='" + getRemark() + "'" + - "}"; + "id=" + getId() + + ", reference='" + getReference() + "'" + + ", iban='" + getIban() + "'" + + ", bic='" + getBic() + "'" + + ", grantingDocumentDate='" + getGrantingDocumentDate() + "'" + + ", revokationDocumentDate='" + getRevokationDocumentDate() + "'" + + ", validFromDate='" + getValidFromDate() + "'" + + ", validUntilDate='" + getValidUntilDate() + "'" + + ", lastUsedDate='" + getLastUsedDate() + "'" + + ", remark='" + getRemark() + "'" + + "}"; } } diff --git a/src/main/java/org/hostsharing/hsadminng/domain/Share.java b/src/main/java/org/hostsharing/hsadminng/domain/Share.java index 4c3c8ab1..b8032f4d 100644 --- a/src/main/java/org/hostsharing/hsadminng/domain/Share.java +++ b/src/main/java/org/hostsharing/hsadminng/domain/Share.java @@ -1,15 +1,17 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.domain; +import org.hostsharing.hsadminng.domain.enumeration.ShareAction; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.hostsharing.hsadminng.domain.enumeration.ShareAction; + +import java.io.Serializable; +import java.time.LocalDate; +import java.util.Objects; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; -import java.io.Serializable; -import java.time.LocalDate; -import java.util.Objects; /** * A Share. @@ -169,12 +171,12 @@ public class Share implements Serializable { @Override public String toString() { return "Share{" + - "id=" + getId() + - ", documentDate='" + getDocumentDate() + "'" + - ", valueDate='" + getValueDate() + "'" + - ", action='" + getAction() + "'" + - ", quantity=" + getQuantity() + - ", remark='" + getRemark() + "'" + - "}"; + "id=" + getId() + + ", documentDate='" + getDocumentDate() + "'" + + ", valueDate='" + getValueDate() + "'" + + ", action='" + getAction() + "'" + + ", quantity=" + getQuantity() + + ", remark='" + getRemark() + "'" + + "}"; } } diff --git a/src/main/java/org/hostsharing/hsadminng/domain/User.java b/src/main/java/org/hostsharing/hsadminng/domain/User.java index d8708e45..1f7ffebf 100644 --- a/src/main/java/org/hostsharing/hsadminng/domain/User.java +++ b/src/main/java/org/hostsharing/hsadminng/domain/User.java @@ -1,22 +1,25 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.domain; import org.hostsharing.hsadminng.config.Constants; import com.fasterxml.jackson.annotation.JsonIgnore; + import org.apache.commons.lang3.StringUtils; import org.hibernate.annotations.BatchSize; -import javax.validation.constraints.Email; -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Size; import java.io.Serializable; +import java.time.Instant; import java.util.HashSet; import java.util.Locale; import java.util.Objects; import java.util.Set; -import java.time.Instant; + +import javax.persistence.*; +import javax.validation.constraints.Email; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; /** * A user. @@ -86,9 +89,9 @@ public class User extends AbstractAuditingEntity implements Serializable { @JsonIgnore @ManyToMany @JoinTable( - name = "jhi_user_authority", - joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")}, - inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")}) + name = "jhi_user_authority", + joinColumns = { @JoinColumn(name = "user_id", referencedColumnName = "id") }, + inverseJoinColumns = { @JoinColumn(name = "authority_name", referencedColumnName = "name") }) @BatchSize(size = 20) private Set authorities = new HashSet<>(); @@ -219,14 +222,14 @@ public class User extends AbstractAuditingEntity implements Serializable { @Override public String toString() { return "User{" + - "login='" + login + '\'' + - ", firstName='" + firstName + '\'' + - ", lastName='" + lastName + '\'' + - ", email='" + email + '\'' + - ", imageUrl='" + imageUrl + '\'' + - ", activated='" + activated + '\'' + - ", langKey='" + langKey + '\'' + - ", activationKey='" + activationKey + '\'' + - "}"; + "login='" + login + '\'' + + ", firstName='" + firstName + '\'' + + ", lastName='" + lastName + '\'' + + ", email='" + email + '\'' + + ", imageUrl='" + imageUrl + '\'' + + ", activated='" + activated + '\'' + + ", langKey='" + langKey + '\'' + + ", activationKey='" + activationKey + '\'' + + "}"; } } diff --git a/src/main/java/org/hostsharing/hsadminng/domain/enumeration/AssetAction.java b/src/main/java/org/hostsharing/hsadminng/domain/enumeration/AssetAction.java index a42d7a04..c60ee96a 100644 --- a/src/main/java/org/hostsharing/hsadminng/domain/enumeration/AssetAction.java +++ b/src/main/java/org/hostsharing/hsadminng/domain/enumeration/AssetAction.java @@ -1,8 +1,14 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.domain.enumeration; /** * The AssetAction enumeration. */ public enum AssetAction { - PAYMENT, HANDOVER, ADOPTION, LOSS, CLEARING, PAYBACK + PAYMENT, + HANDOVER, + ADOPTION, + LOSS, + CLEARING, + PAYBACK } diff --git a/src/main/java/org/hostsharing/hsadminng/domain/enumeration/CustomerKind.java b/src/main/java/org/hostsharing/hsadminng/domain/enumeration/CustomerKind.java index 46092119..7e301271 100644 --- a/src/main/java/org/hostsharing/hsadminng/domain/enumeration/CustomerKind.java +++ b/src/main/java/org/hostsharing/hsadminng/domain/enumeration/CustomerKind.java @@ -1,8 +1,10 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.domain.enumeration; /** * The CustomerKind enumeration. */ public enum CustomerKind { - NATURAL, LEGAL + NATURAL, + LEGAL } diff --git a/src/main/java/org/hostsharing/hsadminng/domain/enumeration/ShareAction.java b/src/main/java/org/hostsharing/hsadminng/domain/enumeration/ShareAction.java index 032d8638..c8ce2108 100644 --- a/src/main/java/org/hostsharing/hsadminng/domain/enumeration/ShareAction.java +++ b/src/main/java/org/hostsharing/hsadminng/domain/enumeration/ShareAction.java @@ -1,8 +1,10 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.domain.enumeration; /** * The ShareAction enumeration. */ public enum ShareAction { - SUBSCRIPTION, CANCELLATION + SUBSCRIPTION, + CANCELLATION } diff --git a/src/main/java/org/hostsharing/hsadminng/domain/enumeration/VatRegion.java b/src/main/java/org/hostsharing/hsadminng/domain/enumeration/VatRegion.java index 22bf49ac..067cd04e 100644 --- a/src/main/java/org/hostsharing/hsadminng/domain/enumeration/VatRegion.java +++ b/src/main/java/org/hostsharing/hsadminng/domain/enumeration/VatRegion.java @@ -1,8 +1,11 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.domain.enumeration; /** * The VatRegion enumeration. */ public enum VatRegion { - DOMESTIC, EU, OTHER + DOMESTIC, + EU, + OTHER } diff --git a/src/main/java/org/hostsharing/hsadminng/repository/AssetRepository.java b/src/main/java/org/hostsharing/hsadminng/repository/AssetRepository.java index 31c5a947..cb8f92c8 100644 --- a/src/main/java/org/hostsharing/hsadminng/repository/AssetRepository.java +++ b/src/main/java/org/hostsharing/hsadminng/repository/AssetRepository.java @@ -1,12 +1,13 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.repository; import org.hostsharing.hsadminng.domain.Asset; + import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; - /** - * Spring Data repository for the Asset entity. + * Spring Data repository for the Asset entity. */ @SuppressWarnings("unused") @Repository diff --git a/src/main/java/org/hostsharing/hsadminng/repository/AuthorityRepository.java b/src/main/java/org/hostsharing/hsadminng/repository/AuthorityRepository.java index 66ea1920..2d7a8c20 100644 --- a/src/main/java/org/hostsharing/hsadminng/repository/AuthorityRepository.java +++ b/src/main/java/org/hostsharing/hsadminng/repository/AuthorityRepository.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.repository; import org.hostsharing.hsadminng.domain.Authority; diff --git a/src/main/java/org/hostsharing/hsadminng/repository/CustomAuditEventRepository.java b/src/main/java/org/hostsharing/hsadminng/repository/CustomAuditEventRepository.java index 90fe3ade..54eb2165 100644 --- a/src/main/java/org/hostsharing/hsadminng/repository/CustomAuditEventRepository.java +++ b/src/main/java/org/hostsharing/hsadminng/repository/CustomAuditEventRepository.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.repository; import org.hostsharing.hsadminng.config.Constants; @@ -34,7 +35,8 @@ public class CustomAuditEventRepository implements AuditEventRepository { private final Logger log = LoggerFactory.getLogger(getClass()); - public CustomAuditEventRepository(PersistenceAuditEventRepository persistenceAuditEventRepository, + public CustomAuditEventRepository( + PersistenceAuditEventRepository persistenceAuditEventRepository, AuditEventConverter auditEventConverter) { this.persistenceAuditEventRepository = persistenceAuditEventRepository; @@ -43,8 +45,8 @@ public class CustomAuditEventRepository implements AuditEventRepository { @Override public List find(String principal, Instant after, String type) { - Iterable persistentAuditEvents = - persistenceAuditEventRepository.findByPrincipalAndAuditEventDateAfterAndAuditEventType(principal, after, type); + Iterable persistentAuditEvents = persistenceAuditEventRepository + .findByPrincipalAndAuditEventDateAfterAndAuditEventType(principal, after, type); return auditEventConverter.convertToAuditEvent(persistentAuditEvents); } @@ -52,7 +54,7 @@ public class CustomAuditEventRepository implements AuditEventRepository { @Transactional(propagation = Propagation.REQUIRES_NEW) public void add(AuditEvent event) { if (!AUTHORIZATION_FAILURE.equals(event.getType()) && - !Constants.ANONYMOUS_USER.equals(event.getPrincipal())) { + !Constants.ANONYMOUS_USER.equals(event.getPrincipal())) { PersistentAuditEvent persistentAuditEvent = new PersistentAuditEvent(); persistentAuditEvent.setPrincipal(event.getPrincipal()); @@ -77,8 +79,11 @@ public class CustomAuditEventRepository implements AuditEventRepository { int length = value.length(); if (length > EVENT_DATA_COLUMN_MAX_LENGTH) { value = value.substring(0, EVENT_DATA_COLUMN_MAX_LENGTH); - log.warn("Event data for {} too long ({}) has been truncated to {}. Consider increasing column width.", - entry.getKey(), length, EVENT_DATA_COLUMN_MAX_LENGTH); + log.warn( + "Event data for {} too long ({}) has been truncated to {}. Consider increasing column width.", + entry.getKey(), + length, + EVENT_DATA_COLUMN_MAX_LENGTH); } } results.put(entry.getKey(), value); diff --git a/src/main/java/org/hostsharing/hsadminng/repository/CustomerRepository.java b/src/main/java/org/hostsharing/hsadminng/repository/CustomerRepository.java index 11367351..9c434cb2 100644 --- a/src/main/java/org/hostsharing/hsadminng/repository/CustomerRepository.java +++ b/src/main/java/org/hostsharing/hsadminng/repository/CustomerRepository.java @@ -1,12 +1,13 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.repository; import org.hostsharing.hsadminng.domain.Customer; + import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; - /** - * Spring Data repository for the Customer entity. + * Spring Data repository for the Customer entity. */ @SuppressWarnings("unused") @Repository diff --git a/src/main/java/org/hostsharing/hsadminng/repository/MembershipRepository.java b/src/main/java/org/hostsharing/hsadminng/repository/MembershipRepository.java index 95810440..291deca7 100644 --- a/src/main/java/org/hostsharing/hsadminng/repository/MembershipRepository.java +++ b/src/main/java/org/hostsharing/hsadminng/repository/MembershipRepository.java @@ -1,21 +1,22 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.repository; import org.hostsharing.hsadminng.domain.Membership; + import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; - /** - * Spring Data repository for the Membership entity. + * Spring Data repository for the Membership entity. */ @SuppressWarnings("unused") @Repository public interface MembershipRepository extends JpaRepository, JpaSpecificationExecutor { @Query("SELECT CASE WHEN COUNT(m)> 0 THEN TRUE ELSE FALSE END " + - " FROM Membership m WHERE m.customer.id=:customerId AND m.memberUntilDate IS NULL") + " FROM Membership m WHERE m.customer.id=:customerId AND m.memberUntilDate IS NULL") boolean hasUncancelledMembershipForCustomer(@Param("customerId") final long customerId); } diff --git a/src/main/java/org/hostsharing/hsadminng/repository/PersistenceAuditEventRepository.java b/src/main/java/org/hostsharing/hsadminng/repository/PersistenceAuditEventRepository.java index 39b6946b..18e367cc 100644 --- a/src/main/java/org/hostsharing/hsadminng/repository/PersistenceAuditEventRepository.java +++ b/src/main/java/org/hostsharing/hsadminng/repository/PersistenceAuditEventRepository.java @@ -1,6 +1,8 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.repository; import org.hostsharing.hsadminng.domain.PersistentAuditEvent; + import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; @@ -19,7 +21,10 @@ public interface PersistenceAuditEventRepository extends JpaRepository findByPrincipalAndAuditEventDateAfter(String principal, Instant after); - List findByPrincipalAndAuditEventDateAfterAndAuditEventType(String principal, Instant after, String type); + List findByPrincipalAndAuditEventDateAfterAndAuditEventType( + String principal, + Instant after, + String type); Page findAllByAuditEventDateBetween(Instant fromDate, Instant toDate, Pageable pageable); } diff --git a/src/main/java/org/hostsharing/hsadminng/repository/SepaMandateRepository.java b/src/main/java/org/hostsharing/hsadminng/repository/SepaMandateRepository.java index 323a7783..d1ad0459 100644 --- a/src/main/java/org/hostsharing/hsadminng/repository/SepaMandateRepository.java +++ b/src/main/java/org/hostsharing/hsadminng/repository/SepaMandateRepository.java @@ -1,12 +1,13 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.repository; import org.hostsharing.hsadminng.domain.SepaMandate; + import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; - /** - * Spring Data repository for the SepaMandate entity. + * Spring Data repository for the SepaMandate entity. */ @SuppressWarnings("unused") @Repository diff --git a/src/main/java/org/hostsharing/hsadminng/repository/ShareRepository.java b/src/main/java/org/hostsharing/hsadminng/repository/ShareRepository.java index 660f4d9b..12cd086e 100644 --- a/src/main/java/org/hostsharing/hsadminng/repository/ShareRepository.java +++ b/src/main/java/org/hostsharing/hsadminng/repository/ShareRepository.java @@ -1,12 +1,13 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.repository; import org.hostsharing.hsadminng.domain.Share; + import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; - /** - * Spring Data repository for the Share entity. + * Spring Data repository for the Share entity. */ @SuppressWarnings("unused") @Repository diff --git a/src/main/java/org/hostsharing/hsadminng/repository/UserRepository.java b/src/main/java/org/hostsharing/hsadminng/repository/UserRepository.java index d835bbf4..f91ff561 100644 --- a/src/main/java/org/hostsharing/hsadminng/repository/UserRepository.java +++ b/src/main/java/org/hostsharing/hsadminng/repository/UserRepository.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.repository; import org.hostsharing.hsadminng.domain.User; @@ -8,9 +9,10 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; + +import java.time.Instant; import java.util.List; import java.util.Optional; -import java.time.Instant; /** * Spring Data JPA repository for the User entity. diff --git a/src/main/java/org/hostsharing/hsadminng/security/AuthoritiesConstants.java b/src/main/java/org/hostsharing/hsadminng/security/AuthoritiesConstants.java index bb1fd344..6df501ec 100644 --- a/src/main/java/org/hostsharing/hsadminng/security/AuthoritiesConstants.java +++ b/src/main/java/org/hostsharing/hsadminng/security/AuthoritiesConstants.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.security; /** diff --git a/src/main/java/org/hostsharing/hsadminng/security/DomainUserDetailsService.java b/src/main/java/org/hostsharing/hsadminng/security/DomainUserDetailsService.java index 7b20fe3d..570f0449 100644 --- a/src/main/java/org/hostsharing/hsadminng/security/DomainUserDetailsService.java +++ b/src/main/java/org/hostsharing/hsadminng/security/DomainUserDetailsService.java @@ -1,7 +1,9 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.security; import org.hostsharing.hsadminng.domain.User; import org.hostsharing.hsadminng.repository.UserRepository; + import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,14 +39,15 @@ public class DomainUserDetailsService implements UserDetailsService { if (new EmailValidator().isValid(login, null)) { return userRepository.findOneWithAuthoritiesByEmail(login) - .map(user -> createSpringSecurityUser(login, user)) - .orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database")); + .map(user -> createSpringSecurityUser(login, user)) + .orElseThrow( + () -> new UsernameNotFoundException("User with email " + login + " was not found in the database")); } String lowercaseLogin = login.toLowerCase(Locale.ENGLISH); return userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin) - .map(user -> createSpringSecurityUser(lowercaseLogin, user)) - .orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database")); + .map(user -> createSpringSecurityUser(lowercaseLogin, user)) + .orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database")); } @@ -52,11 +55,13 @@ public class DomainUserDetailsService implements UserDetailsService { if (!user.getActivated()) { throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated"); } - List grantedAuthorities = user.getAuthorities().stream() - .map(authority -> new SimpleGrantedAuthority(authority.getName())) - .collect(Collectors.toList()); - return new org.springframework.security.core.userdetails.User(user.getLogin(), - user.getPassword(), - grantedAuthorities); + List grantedAuthorities = user.getAuthorities() + .stream() + .map(authority -> new SimpleGrantedAuthority(authority.getName())) + .collect(Collectors.toList()); + return new org.springframework.security.core.userdetails.User( + user.getLogin(), + user.getPassword(), + grantedAuthorities); } } diff --git a/src/main/java/org/hostsharing/hsadminng/security/SecurityUtils.java b/src/main/java/org/hostsharing/hsadminng/security/SecurityUtils.java index 93a40dd8..0145b2f6 100644 --- a/src/main/java/org/hostsharing/hsadminng/security/SecurityUtils.java +++ b/src/main/java/org/hostsharing/hsadminng/security/SecurityUtils.java @@ -1,6 +1,8 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.security; import org.hostsharing.hsadminng.service.accessfilter.Role; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.context.SecurityContext; @@ -31,15 +33,15 @@ public final class SecurityUtils { public static Optional getCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) - .map(authentication -> { - if (authentication.getPrincipal() instanceof UserDetails) { - UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); - return springSecurityUser.getUsername(); - } else if (authentication.getPrincipal() instanceof String) { - return (String) authentication.getPrincipal(); - } - return null; - }); + .map(authentication -> { + if (authentication.getPrincipal() instanceof UserDetails) { + UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); + return springSecurityUser.getUsername(); + } else if (authentication.getPrincipal() instanceof String) { + return (String) authentication.getPrincipal(); + } + return null; + }); } /** @@ -50,8 +52,8 @@ public final class SecurityUtils { public static Optional getCurrentUserJWT() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) - .filter(authentication -> authentication.getCredentials() instanceof String) - .map(authentication -> (String) authentication.getCredentials()); + .filter(authentication -> authentication.getCredentials() instanceof String) + .map(authentication -> (String) authentication.getCredentials()); } /** @@ -62,9 +64,13 @@ public final class SecurityUtils { public static boolean isAuthenticated() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) - .map(authentication -> authentication.getAuthorities().stream() - .noneMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS))) - .orElse(false); + .map( + authentication -> authentication.getAuthorities() + .stream() + .noneMatch( + grantedAuthority -> grantedAuthority.getAuthority() + .equals(AuthoritiesConstants.ANONYMOUS))) + .orElse(false); } /** @@ -78,24 +84,27 @@ public final class SecurityUtils { public static boolean isCurrentUserInRole(String authority) { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) - .map(authentication -> authentication.getAuthorities().stream() - .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority))) - .orElse(false); + .map( + authentication -> authentication.getAuthorities() + .stream() + .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority))) + .orElse(false); } public static Role getLoginUserRoleFor(final Class onDtoClass, final Long onId) { - final Role highestRole = userRoleAssignments.stream(). - map(ura -> - matches(onDtoClass, onId, ura) - ? ura.role - : Role.ANYBODY). - reduce(Role.ANYBODY, (r1, r2) -> r1.covers(r2) ? r1 : r2); + final Role highestRole = userRoleAssignments.stream() + .map( + ura -> matches(onDtoClass, onId, ura) + ? ura.role + : Role.ANYBODY) + .reduce(Role.ANYBODY, (r1, r2) -> r1.covers(r2) ? r1 : r2); log.debug("getLoginUserRoleFor({}, {}) returned {}", onDtoClass, onId, highestRole); return highestRole; } private static boolean matches(Class onDtoClass, Long onId, UserRoleAssignment ura) { - final boolean matches = (ura.onClass == null || onDtoClass == ura.onClass) && (ura.onId == null || ura.onId.equals(onId)); + final boolean matches = (ura.onClass == null || onDtoClass == ura.onClass) + && (ura.onId == null || ura.onId.equals(onId)); return matches; } @@ -111,6 +120,7 @@ public final class SecurityUtils { } private static class UserRoleAssignment { + final Class onClass; final Long onId; final Role role; diff --git a/src/main/java/org/hostsharing/hsadminng/security/SpringSecurityAuditorAware.java b/src/main/java/org/hostsharing/hsadminng/security/SpringSecurityAuditorAware.java index 8813f4b8..f187f01e 100644 --- a/src/main/java/org/hostsharing/hsadminng/security/SpringSecurityAuditorAware.java +++ b/src/main/java/org/hostsharing/hsadminng/security/SpringSecurityAuditorAware.java @@ -1,12 +1,13 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.security; import org.hostsharing.hsadminng.config.Constants; -import java.util.Optional; - import org.springframework.data.domain.AuditorAware; import org.springframework.stereotype.Component; +import java.util.Optional; + /** * Implementation of AuditorAware based on Spring Security. */ diff --git a/src/main/java/org/hostsharing/hsadminng/security/UserNotActivatedException.java b/src/main/java/org/hostsharing/hsadminng/security/UserNotActivatedException.java index e919e858..0a94d4e3 100644 --- a/src/main/java/org/hostsharing/hsadminng/security/UserNotActivatedException.java +++ b/src/main/java/org/hostsharing/hsadminng/security/UserNotActivatedException.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.security; import org.springframework.security.core.AuthenticationException; diff --git a/src/main/java/org/hostsharing/hsadminng/security/jwt/JWTConfigurer.java b/src/main/java/org/hostsharing/hsadminng/security/jwt/JWTConfigurer.java index 166bbfbf..5e4af8c8 100644 --- a/src/main/java/org/hostsharing/hsadminng/security/jwt/JWTConfigurer.java +++ b/src/main/java/org/hostsharing/hsadminng/security/jwt/JWTConfigurer.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.security.jwt; import org.springframework.security.config.annotation.SecurityConfigurerAdapter; diff --git a/src/main/java/org/hostsharing/hsadminng/security/jwt/JWTFilter.java b/src/main/java/org/hostsharing/hsadminng/security/jwt/JWTFilter.java index 97ea2851..1eed81b8 100644 --- a/src/main/java/org/hostsharing/hsadminng/security/jwt/JWTFilter.java +++ b/src/main/java/org/hostsharing/hsadminng/security/jwt/JWTFilter.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.security.jwt; import org.springframework.security.core.Authentication; @@ -5,12 +6,13 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.util.StringUtils; import org.springframework.web.filter.GenericFilterBean; +import java.io.IOException; + import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; -import java.io.IOException; /** * Filters incoming requests and installs a Spring Security principal if a header corresponding to a valid user is @@ -28,7 +30,7 @@ public class JWTFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) - throws IOException, ServletException { + throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String jwt = resolveToken(httpServletRequest); if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) { @@ -38,7 +40,7 @@ public class JWTFilter extends GenericFilterBean { filterChain.doFilter(servletRequest, servletResponse); } - private String resolveToken(HttpServletRequest request){ + private String resolveToken(HttpServletRequest request) { String bearerToken = request.getHeader(AUTHORIZATION_HEADER); if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { return bearerToken.substring(7); diff --git a/src/main/java/org/hostsharing/hsadminng/security/jwt/TokenProvider.java b/src/main/java/org/hostsharing/hsadminng/security/jwt/TokenProvider.java index 71969a7d..ff315141 100644 --- a/src/main/java/org/hostsharing/hsadminng/security/jwt/TokenProvider.java +++ b/src/main/java/org/hostsharing/hsadminng/security/jwt/TokenProvider.java @@ -1,10 +1,10 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.security.jwt; -import java.nio.charset.StandardCharsets; -import java.security.Key; -import java.util.*; -import java.util.stream.Collectors; -import javax.annotation.PostConstruct; +import io.github.jhipster.config.JHipsterProperties; +import io.jsonwebtoken.*; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -16,10 +16,12 @@ import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; -import io.github.jhipster.config.JHipsterProperties; -import io.jsonwebtoken.*; -import io.jsonwebtoken.io.Decoders; -import io.jsonwebtoken.security.Keys; +import java.nio.charset.StandardCharsets; +import java.security.Key; +import java.util.*; +import java.util.stream.Collectors; + +import javax.annotation.PostConstruct; @Component public class TokenProvider { @@ -45,25 +47,28 @@ public class TokenProvider { byte[] keyBytes; String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret(); if (!StringUtils.isEmpty(secret)) { - log.warn("Warning: the JWT key used is not Base64-encoded. " + - "We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security."); + log.warn( + "Warning: the JWT key used is not Base64-encoded. " + + "We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security."); keyBytes = secret.getBytes(StandardCharsets.UTF_8); } else { log.debug("Using a Base64-encoded JWT secret key"); keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret()); } this.key = Keys.hmacShaKeyFor(keyBytes); - this.tokenValidityInMilliseconds = - 1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds(); - this.tokenValidityInMillisecondsForRememberMe = - 1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt() + this.tokenValidityInMilliseconds = 1000 + * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds(); + this.tokenValidityInMillisecondsForRememberMe = 1000 * jHipsterProperties.getSecurity() + .getAuthentication() + .getJwt() .getTokenValidityInSecondsForRememberMe(); } public String createToken(Authentication authentication, boolean rememberMe) { - String authorities = authentication.getAuthorities().stream() - .map(GrantedAuthority::getAuthority) - .collect(Collectors.joining(",")); + String authorities = authentication.getAuthorities() + .stream() + .map(GrantedAuthority::getAuthority) + .collect(Collectors.joining(",")); long now = (new Date()).getTime(); Date validity; @@ -74,21 +79,20 @@ public class TokenProvider { } return Jwts.builder() - .setSubject(authentication.getName()) - .claim(AUTHORITIES_KEY, authorities) - .signWith(key, SignatureAlgorithm.HS512) - .setExpiration(validity) - .compact(); + .setSubject(authentication.getName()) + .claim(AUTHORITIES_KEY, authorities) + .signWith(key, SignatureAlgorithm.HS512) + .setExpiration(validity) + .compact(); } public Authentication getAuthentication(String token) { Claims claims = Jwts.parser() - .setSigningKey(key) - .parseClaimsJws(token) - .getBody(); + .setSigningKey(key) + .parseClaimsJws(token) + .getBody(); - Collection authorities = - Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(",")) + Collection authorities = Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(",")) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); diff --git a/src/main/java/org/hostsharing/hsadminng/service/AssetQueryService.java b/src/main/java/org/hostsharing/hsadminng/service/AssetQueryService.java index 82137a84..3e869f24 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/AssetQueryService.java +++ b/src/main/java/org/hostsharing/hsadminng/service/AssetQueryService.java @@ -1,8 +1,14 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; -import java.util.List; +import org.hostsharing.hsadminng.domain.*; +import org.hostsharing.hsadminng.domain.Asset; +import org.hostsharing.hsadminng.repository.AssetRepository; +import org.hostsharing.hsadminng.service.dto.AssetCriteria; +import org.hostsharing.hsadminng.service.dto.AssetDTO; +import org.hostsharing.hsadminng.service.mapper.AssetMapper; -import javax.persistence.criteria.JoinType; +import io.github.jhipster.service.QueryService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -12,14 +18,9 @@ import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import io.github.jhipster.service.QueryService; +import java.util.List; -import org.hostsharing.hsadminng.domain.Asset; -import org.hostsharing.hsadminng.domain.*; // for static metamodels -import org.hostsharing.hsadminng.repository.AssetRepository; -import org.hostsharing.hsadminng.service.dto.AssetCriteria; -import org.hostsharing.hsadminng.service.dto.AssetDTO; -import org.hostsharing.hsadminng.service.mapper.AssetMapper; +import javax.persistence.criteria.JoinType; /** * Service for executing complex queries for Asset entities in the database. @@ -44,6 +45,7 @@ public class AssetQueryService extends QueryService { /** * Return a {@link List} of {@link AssetDTO} which matches the criteria from the database + * * @param criteria The object which holds all the filters, which the entities should match. * @return the matching entities. */ @@ -56,6 +58,7 @@ public class AssetQueryService extends QueryService { /** * Return a {@link Page} of {@link AssetDTO} which matches the criteria from the database + * * @param criteria The object which holds all the filters, which the entities should match. * @param page The page, which should be returned. * @return the matching entities. @@ -65,11 +68,12 @@ public class AssetQueryService extends QueryService { log.debug("find by criteria : {}, page: {}", criteria, page); final Specification specification = createSpecification(criteria); return assetRepository.findAll(specification, page) - .map(assetMapper::toDto); + .map(assetMapper::toDto); } /** * Return the number of matching entities in the database + * * @param criteria The object which holds all the filters, which the entities should match. * @return the number of matching entities. */ @@ -105,8 +109,10 @@ public class AssetQueryService extends QueryService { specification = specification.and(buildStringSpecification(criteria.getRemark(), Asset_.remark)); } if (criteria.getMembershipId() != null) { - specification = specification.and(buildSpecification(criteria.getMembershipId(), - root -> root.join(Asset_.membership, JoinType.LEFT).get(Membership_.id))); + specification = specification.and( + buildSpecification( + criteria.getMembershipId(), + root -> root.join(Asset_.membership, JoinType.LEFT).get(Membership_.id))); } } return specification; diff --git a/src/main/java/org/hostsharing/hsadminng/service/AssetService.java b/src/main/java/org/hostsharing/hsadminng/service/AssetService.java index dd60f120..f7b71120 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/AssetService.java +++ b/src/main/java/org/hostsharing/hsadminng/service/AssetService.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; import org.hostsharing.hsadminng.domain.Asset; @@ -5,6 +6,7 @@ import org.hostsharing.hsadminng.repository.AssetRepository; import org.hostsharing.hsadminng.service.dto.AssetDTO; import org.hostsharing.hsadminng.service.mapper.AssetMapper; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; @@ -12,9 +14,10 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.EntityManager; import java.util.Optional; +import javax.persistence.EntityManager; + /** * Service Implementation for managing Asset. */ @@ -31,7 +34,11 @@ public class AssetService implements IdToDtoResolver { private final AssetMapper assetMapper; private final AssetValidator assetValidator; - public AssetService(final EntityManager em, final AssetRepository assetRepository, final AssetMapper assetMapper, final AssetValidator assetValidator) { + public AssetService( + final EntityManager em, + final AssetRepository assetRepository, + final AssetMapper assetMapper, + final AssetValidator assetValidator) { this.em = em; this.assetRepository = assetRepository; this.assetMapper = assetMapper; @@ -64,10 +71,9 @@ public class AssetService implements IdToDtoResolver { public Page findAll(Pageable pageable) { log.debug("Request to get all Assets"); return assetRepository.findAll(pageable) - .map(assetMapper::toDto); + .map(assetMapper::toDto); } - /** * Get one asset by id. * @@ -78,7 +84,7 @@ public class AssetService implements IdToDtoResolver { public Optional findOne(Long id) { log.debug("Request to get Asset : {}", id); return assetRepository.findById(id) - .map(assetMapper::toDto); + .map(assetMapper::toDto); } /** diff --git a/src/main/java/org/hostsharing/hsadminng/service/AssetValidator.java b/src/main/java/org/hostsharing/hsadminng/service/AssetValidator.java index 01da9875..1d0f9620 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/AssetValidator.java +++ b/src/main/java/org/hostsharing/hsadminng/service/AssetValidator.java @@ -1,42 +1,69 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; import org.hostsharing.hsadminng.domain.Asset; import org.hostsharing.hsadminng.domain.enumeration.AssetAction; import org.hostsharing.hsadminng.service.dto.AssetDTO; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + import org.springframework.stereotype.Service; import java.math.BigDecimal; @Service public class AssetValidator { + public void validate(final AssetDTO assetDTO) { if (assetDTO.getId() != null) { - throw new BadRequestAlertException("Asset transactions are immutable", Asset.ENTITY_NAME, "assetTransactionImmutable"); + throw new BadRequestAlertException( + "Asset transactions are immutable", + Asset.ENTITY_NAME, + "assetTransactionImmutable"); } if (assetDTO.getDocumentDate().isAfter(assetDTO.getValueDate())) { - throw new BadRequestAlertException("Document date may not be after value date", Asset.ENTITY_NAME, "documentDateMayNotBeAfterValueDate"); + throw new BadRequestAlertException( + "Document date may not be after value date", + Asset.ENTITY_NAME, + "documentDateMayNotBeAfterValueDate"); } if ((assetDTO.getAction() == AssetAction.PAYMENT) && (assetDTO.getAmount().compareTo(BigDecimal.valueOf(0)) <= 0)) { - throw new BadRequestAlertException("Asset payments require a positive amount", Asset.ENTITY_NAME, "assetPaymentsPositiveAmount"); + throw new BadRequestAlertException( + "Asset payments require a positive amount", + Asset.ENTITY_NAME, + "assetPaymentsPositiveAmount"); } if ((assetDTO.getAction() == AssetAction.ADOPTION) && (assetDTO.getAmount().compareTo(BigDecimal.valueOf(0)) <= 0)) { - throw new BadRequestAlertException("Asset adoptions require a positive amount", Asset.ENTITY_NAME, "assetAdoptionsPositiveAmount"); + throw new BadRequestAlertException( + "Asset adoptions require a positive amount", + Asset.ENTITY_NAME, + "assetAdoptionsPositiveAmount"); } if ((assetDTO.getAction() == AssetAction.PAYBACK) && (assetDTO.getAmount().compareTo(BigDecimal.valueOf(0)) >= 0)) { - throw new BadRequestAlertException("Asset paybacks require a negative amount", Asset.ENTITY_NAME, "assetPaybacksNegativeAmount"); + throw new BadRequestAlertException( + "Asset paybacks require a negative amount", + Asset.ENTITY_NAME, + "assetPaybacksNegativeAmount"); } if ((assetDTO.getAction() == AssetAction.HANDOVER) && (assetDTO.getAmount().compareTo(BigDecimal.valueOf(0)) >= 0)) { - throw new BadRequestAlertException("Asset handovers require a negative amount", Asset.ENTITY_NAME, "assetHandoversNegativeAmount"); + throw new BadRequestAlertException( + "Asset handovers require a negative amount", + Asset.ENTITY_NAME, + "assetHandoversNegativeAmount"); } if ((assetDTO.getAction() == AssetAction.LOSS) && (assetDTO.getAmount().compareTo(BigDecimal.valueOf(0)) >= 0)) { - throw new BadRequestAlertException("Asset losses require a negative amount", Asset.ENTITY_NAME, "assetLossesNegativeAmount"); + throw new BadRequestAlertException( + "Asset losses require a negative amount", + Asset.ENTITY_NAME, + "assetLossesNegativeAmount"); } if ((assetDTO.getAction() == AssetAction.CLEARING) && (assetDTO.getAmount().compareTo(BigDecimal.valueOf(0)) >= 0)) { - throw new BadRequestAlertException("Asset clearings require a negative amount", Asset.ENTITY_NAME, "assetClearingsNegativeAmount"); + throw new BadRequestAlertException( + "Asset clearings require a negative amount", + Asset.ENTITY_NAME, + "assetClearingsNegativeAmount"); } } diff --git a/src/main/java/org/hostsharing/hsadminng/service/AuditEventService.java b/src/main/java/org/hostsharing/hsadminng/service/AuditEventService.java index bf19c3c1..b41fb9c2 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/AuditEventService.java +++ b/src/main/java/org/hostsharing/hsadminng/service/AuditEventService.java @@ -1,7 +1,9 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; import org.hostsharing.hsadminng.config.audit.AuditEventConverter; import org.hostsharing.hsadminng.repository.PersistenceAuditEventRepository; + import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -25,8 +27,8 @@ public class AuditEventService { private final AuditEventConverter auditEventConverter; public AuditEventService( - PersistenceAuditEventRepository persistenceAuditEventRepository, - AuditEventConverter auditEventConverter) { + PersistenceAuditEventRepository persistenceAuditEventRepository, + AuditEventConverter auditEventConverter) { this.persistenceAuditEventRepository = persistenceAuditEventRepository; this.auditEventConverter = auditEventConverter; @@ -34,18 +36,18 @@ public class AuditEventService { public Page findAll(Pageable pageable) { return persistenceAuditEventRepository.findAll(pageable) - .map(auditEventConverter::convertToAuditEvent); + .map(auditEventConverter::convertToAuditEvent); } public Page findByDates(Instant fromDate, Instant toDate, Pageable pageable) { return persistenceAuditEventRepository.findAllByAuditEventDateBetween(fromDate, toDate, pageable) - .map(auditEventConverter::convertToAuditEvent); + .map(auditEventConverter::convertToAuditEvent); } public Optional find(Long id) { return Optional.ofNullable(persistenceAuditEventRepository.findById(id)) - .filter(Optional::isPresent) - .map(Optional::get) - .map(auditEventConverter::convertToAuditEvent); + .filter(Optional::isPresent) + .map(Optional::get) + .map(auditEventConverter::convertToAuditEvent); } } diff --git a/src/main/java/org/hostsharing/hsadminng/service/CustomerQueryService.java b/src/main/java/org/hostsharing/hsadminng/service/CustomerQueryService.java index 718575f0..b3352819 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/CustomerQueryService.java +++ b/src/main/java/org/hostsharing/hsadminng/service/CustomerQueryService.java @@ -1,6 +1,6 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; -import io.github.jhipster.service.QueryService; import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.domain.Customer_; import org.hostsharing.hsadminng.domain.Membership_; @@ -9,6 +9,9 @@ import org.hostsharing.hsadminng.repository.CustomerRepository; import org.hostsharing.hsadminng.service.dto.CustomerCriteria; import org.hostsharing.hsadminng.service.dto.CustomerDTO; import org.hostsharing.hsadminng.service.mapper.CustomerMapper; + +import io.github.jhipster.service.QueryService; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; @@ -17,9 +20,10 @@ import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.criteria.JoinType; import java.util.List; +import javax.persistence.criteria.JoinType; + /** * Service for executing complex queries for Customer entities in the database. * The main input is a {@link CustomerCriteria} which gets converted to {@link Specification}, @@ -43,6 +47,7 @@ public class CustomerQueryService extends QueryService { /** * Return a {@link List} of {@link CustomerDTO} which matches the criteria from the database + * * @param criteria The object which holds all the filters, which the entities should match. * @return the matching entities. */ @@ -55,6 +60,7 @@ public class CustomerQueryService extends QueryService { /** * Return a {@link Page} of {@link CustomerDTO} which matches the criteria from the database + * * @param criteria The object which holds all the filters, which the entities should match. * @param page The page, which should be returned. * @return the matching entities. @@ -64,11 +70,12 @@ public class CustomerQueryService extends QueryService { log.debug("find by criteria : {}, page: {}", criteria, page); final Specification specification = createSpecification(criteria); return customerRepository.findAll(specification, page) - .map(customerMapper::toDto); + .map(customerMapper::toDto); } /** * Return the number of matching entities in the database + * * @param criteria The object which holds all the filters, which the entities should match. * @return the number of matching entities. */ @@ -107,10 +114,12 @@ public class CustomerQueryService extends QueryService { specification = specification.and(buildStringSpecification(criteria.getBirthPlace(), Customer_.birthPlace)); } if (criteria.getRegistrationCourt() != null) { - specification = specification.and(buildStringSpecification(criteria.getRegistrationCourt(), Customer_.registrationCourt)); + specification = specification + .and(buildStringSpecification(criteria.getRegistrationCourt(), Customer_.registrationCourt)); } if (criteria.getRegistrationNumber() != null) { - specification = specification.and(buildStringSpecification(criteria.getRegistrationNumber(), Customer_.registrationNumber)); + specification = specification + .and(buildStringSpecification(criteria.getRegistrationNumber(), Customer_.registrationNumber)); } if (criteria.getVatRegion() != null) { specification = specification.and(buildSpecification(criteria.getVatRegion(), Customer_.vatRegion)); @@ -119,27 +128,35 @@ public class CustomerQueryService extends QueryService { specification = specification.and(buildStringSpecification(criteria.getVatNumber(), Customer_.vatNumber)); } if (criteria.getContractualSalutation() != null) { - specification = specification.and(buildStringSpecification(criteria.getContractualSalutation(), Customer_.contractualSalutation)); + specification = specification + .and(buildStringSpecification(criteria.getContractualSalutation(), Customer_.contractualSalutation)); } if (criteria.getContractualAddress() != null) { - specification = specification.and(buildStringSpecification(criteria.getContractualAddress(), Customer_.contractualAddress)); + specification = specification + .and(buildStringSpecification(criteria.getContractualAddress(), Customer_.contractualAddress)); } if (criteria.getBillingSalutation() != null) { - specification = specification.and(buildStringSpecification(criteria.getBillingSalutation(), Customer_.billingSalutation)); + specification = specification + .and(buildStringSpecification(criteria.getBillingSalutation(), Customer_.billingSalutation)); } if (criteria.getBillingAddress() != null) { - specification = specification.and(buildStringSpecification(criteria.getBillingAddress(), Customer_.billingAddress)); + specification = specification + .and(buildStringSpecification(criteria.getBillingAddress(), Customer_.billingAddress)); } if (criteria.getRemark() != null) { specification = specification.and(buildStringSpecification(criteria.getRemark(), Customer_.remark)); } if (criteria.getMembershipId() != null) { - specification = specification.and(buildSpecification(criteria.getMembershipId(), - root -> root.join(Customer_.memberships, JoinType.LEFT).get(Membership_.id))); + specification = specification.and( + buildSpecification( + criteria.getMembershipId(), + root -> root.join(Customer_.memberships, JoinType.LEFT).get(Membership_.id))); } if (criteria.getSepamandateId() != null) { - specification = specification.and(buildSpecification(criteria.getSepamandateId(), - root -> root.join(Customer_.sepamandates, JoinType.LEFT).get(SepaMandate_.id))); + specification = specification.and( + buildSpecification( + criteria.getSepamandateId(), + root -> root.join(Customer_.sepamandates, JoinType.LEFT).get(SepaMandate_.id))); } } return specification; diff --git a/src/main/java/org/hostsharing/hsadminng/service/CustomerService.java b/src/main/java/org/hostsharing/hsadminng/service/CustomerService.java index 06d8d978..48ffbc79 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/CustomerService.java +++ b/src/main/java/org/hostsharing/hsadminng/service/CustomerService.java @@ -1,9 +1,11 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.repository.CustomerRepository; import org.hostsharing.hsadminng.service.dto.CustomerDTO; import org.hostsharing.hsadminng.service.mapper.CustomerMapper; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; @@ -54,10 +56,9 @@ public class CustomerService implements IdToDtoResolver { public Page findAll(Pageable pageable) { log.debug("Request to get all Customers"); return customerRepository.findAll(pageable) - .map(customerMapper::toDto); + .map(customerMapper::toDto); } - /** * Get one customer by id. * @@ -68,7 +69,7 @@ public class CustomerService implements IdToDtoResolver { public Optional findOne(Long id) { log.debug("Request to get Customer : {}", id); return customerRepository.findById(id) - .map(customerMapper::toDto); + .map(customerMapper::toDto); } /** diff --git a/src/main/java/org/hostsharing/hsadminng/service/IdToDtoResolver.java b/src/main/java/org/hostsharing/hsadminng/service/IdToDtoResolver.java index 32851fb6..3b19c2ef 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/IdToDtoResolver.java +++ b/src/main/java/org/hostsharing/hsadminng/service/IdToDtoResolver.java @@ -1,7 +1,9 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; import java.util.Optional; public interface IdToDtoResolver { + Optional findOne(Long id); } diff --git a/src/main/java/org/hostsharing/hsadminng/service/MailService.java b/src/main/java/org/hostsharing/hsadminng/service/MailService.java index b1e5688c..14575309 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/MailService.java +++ b/src/main/java/org/hostsharing/hsadminng/service/MailService.java @@ -1,13 +1,10 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; import org.hostsharing.hsadminng.domain.User; import io.github.jhipster.config.JHipsterProperties; -import java.nio.charset.StandardCharsets; -import java.util.Locale; -import javax.mail.internet.MimeMessage; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; @@ -18,6 +15,11 @@ import org.springframework.stereotype.Service; import org.thymeleaf.context.Context; import org.thymeleaf.spring5.SpringTemplateEngine; +import java.nio.charset.StandardCharsets; +import java.util.Locale; + +import javax.mail.internet.MimeMessage; + /** * Service for sending emails. *

@@ -40,8 +42,11 @@ public class MailService { private final SpringTemplateEngine templateEngine; - public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender, - MessageSource messageSource, SpringTemplateEngine templateEngine) { + public MailService( + JHipsterProperties jHipsterProperties, + JavaMailSender javaMailSender, + MessageSource messageSource, + SpringTemplateEngine templateEngine) { this.jHipsterProperties = jHipsterProperties; this.javaMailSender = javaMailSender; @@ -51,8 +56,13 @@ public class MailService { @Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { - log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", - isMultipart, isHtml, to, subject, content); + log.debug( + "Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", + isMultipart, + isHtml, + to, + subject, + content); // Prepare message using a Spring helper MimeMessage mimeMessage = javaMailSender.createMimeMessage(); diff --git a/src/main/java/org/hostsharing/hsadminng/service/MembershipQueryService.java b/src/main/java/org/hostsharing/hsadminng/service/MembershipQueryService.java index adb07608..0c42ffd2 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/MembershipQueryService.java +++ b/src/main/java/org/hostsharing/hsadminng/service/MembershipQueryService.java @@ -1,11 +1,14 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; -import io.github.jhipster.service.QueryService; import org.hostsharing.hsadminng.domain.*; import org.hostsharing.hsadminng.repository.MembershipRepository; import org.hostsharing.hsadminng.service.dto.MembershipCriteria; import org.hostsharing.hsadminng.service.dto.MembershipDTO; import org.hostsharing.hsadminng.service.mapper.MembershipMapper; + +import io.github.jhipster.service.QueryService; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; @@ -14,9 +17,10 @@ import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.criteria.JoinType; import java.util.List; +import javax.persistence.criteria.JoinType; + /** * Service for executing complex queries for Membership entities in the database. * The main input is a {@link MembershipCriteria} which gets converted to {@link Specification}, @@ -40,6 +44,7 @@ public class MembershipQueryService extends QueryService { /** * Return a {@link List} of {@link MembershipDTO} which matches the criteria from the database + * * @param criteria The object which holds all the filters, which the entities should match. * @return the matching entities. */ @@ -52,6 +57,7 @@ public class MembershipQueryService extends QueryService { /** * Return a {@link Page} of {@link MembershipDTO} which matches the criteria from the database + * * @param criteria The object which holds all the filters, which the entities should match. * @param page The page, which should be returned. * @return the matching entities. @@ -61,11 +67,12 @@ public class MembershipQueryService extends QueryService { log.debug("find by criteria : {}, page: {}", criteria, page); final Specification specification = createSpecification(criteria); return membershipRepository.findAll(specification, page) - .map(membershipMapper::toDto); + .map(membershipMapper::toDto); } /** * Return the number of matching entities in the database + * * @param criteria The object which holds all the filters, which the entities should match. * @return the number of matching entities. */ @@ -86,31 +93,41 @@ public class MembershipQueryService extends QueryService { specification = specification.and(buildSpecification(criteria.getId(), Membership_.id)); } if (criteria.getAdmissionDocumentDate() != null) { - specification = specification.and(buildRangeSpecification(criteria.getAdmissionDocumentDate(), Membership_.admissionDocumentDate)); + specification = specification + .and(buildRangeSpecification(criteria.getAdmissionDocumentDate(), Membership_.admissionDocumentDate)); } if (criteria.getCancellationDocumentDate() != null) { - specification = specification.and(buildRangeSpecification(criteria.getCancellationDocumentDate(), Membership_.cancellationDocumentDate)); + specification = specification.and( + buildRangeSpecification(criteria.getCancellationDocumentDate(), Membership_.cancellationDocumentDate)); } if (criteria.getMemberFromDate() != null) { - specification = specification.and(buildRangeSpecification(criteria.getMemberFromDate(), Membership_.memberFromDate)); + specification = specification + .and(buildRangeSpecification(criteria.getMemberFromDate(), Membership_.memberFromDate)); } if (criteria.getMemberUntilDate() != null) { - specification = specification.and(buildRangeSpecification(criteria.getMemberUntilDate(), Membership_.memberUntilDate)); + specification = specification + .and(buildRangeSpecification(criteria.getMemberUntilDate(), Membership_.memberUntilDate)); } if (criteria.getRemark() != null) { specification = specification.and(buildStringSpecification(criteria.getRemark(), Membership_.remark)); } if (criteria.getShareId() != null) { - specification = specification.and(buildSpecification(criteria.getShareId(), - root -> root.join(Membership_.shares, JoinType.LEFT).get(Share_.id))); + specification = specification.and( + buildSpecification( + criteria.getShareId(), + root -> root.join(Membership_.shares, JoinType.LEFT).get(Share_.id))); } if (criteria.getAssetId() != null) { - specification = specification.and(buildSpecification(criteria.getAssetId(), - root -> root.join(Membership_.assets, JoinType.LEFT).get(Asset_.id))); + specification = specification.and( + buildSpecification( + criteria.getAssetId(), + root -> root.join(Membership_.assets, JoinType.LEFT).get(Asset_.id))); } if (criteria.getCustomerId() != null) { - specification = specification.and(buildSpecification(criteria.getCustomerId(), - root -> root.join(Membership_.customer, JoinType.LEFT).get(Customer_.id))); + specification = specification.and( + buildSpecification( + criteria.getCustomerId(), + root -> root.join(Membership_.customer, JoinType.LEFT).get(Customer_.id))); } } return specification; diff --git a/src/main/java/org/hostsharing/hsadminng/service/MembershipService.java b/src/main/java/org/hostsharing/hsadminng/service/MembershipService.java index 82e365d2..53f7a923 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/MembershipService.java +++ b/src/main/java/org/hostsharing/hsadminng/service/MembershipService.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; import org.hostsharing.hsadminng.domain.Membership; @@ -5,6 +6,7 @@ import org.hostsharing.hsadminng.repository.MembershipRepository; import org.hostsharing.hsadminng.service.dto.MembershipDTO; import org.hostsharing.hsadminng.service.mapper.MembershipMapper; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; @@ -12,9 +14,10 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.EntityManager; import java.util.Optional; +import javax.persistence.EntityManager; + /** * Service Implementation for managing Membership. */ @@ -32,10 +35,11 @@ public class MembershipService implements IdToDtoResolver { private final MembershipMapper membershipMapper; - public MembershipService(final EntityManager em, - final MembershipValidator membershipValidator, - final MembershipRepository membershipRepository, - final MembershipMapper membershipMapper) { + public MembershipService( + final EntityManager em, + final MembershipValidator membershipValidator, + final MembershipRepository membershipRepository, + final MembershipMapper membershipMapper) { this.em = em; this.membershipValidator = membershipValidator; this.membershipRepository = membershipRepository; @@ -70,10 +74,9 @@ public class MembershipService implements IdToDtoResolver { public Page findAll(Pageable pageable) { log.debug("Request to get all Memberships"); return membershipRepository.findAll(pageable) - .map(membershipMapper::toDto); + .map(membershipMapper::toDto); } - /** * Get one membership by id. * @@ -85,7 +88,7 @@ public class MembershipService implements IdToDtoResolver { public Optional findOne(Long id) { log.debug("Request to get Membership : {}", id); return membershipRepository.findById(id) - .map(membershipMapper::toDto); + .map(membershipMapper::toDto); } /** diff --git a/src/main/java/org/hostsharing/hsadminng/service/MembershipValidator.java b/src/main/java/org/hostsharing/hsadminng/service/MembershipValidator.java index f14e7dad..9d8a33ad 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/MembershipValidator.java +++ b/src/main/java/org/hostsharing/hsadminng/service/MembershipValidator.java @@ -1,9 +1,11 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; import org.hostsharing.hsadminng.domain.Membership; import org.hostsharing.hsadminng.repository.MembershipRepository; import org.hostsharing.hsadminng.service.dto.MembershipDTO; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -14,14 +16,18 @@ public class MembershipValidator { private MembershipRepository membershipRepository; public void validate(final MembershipDTO membershipDTO) { - if (membershipDTO.getMemberUntilDate() != null && !membershipDTO.getMemberUntilDate().isAfter(membershipDTO.getMemberFromDate())) { + if (membershipDTO.getMemberUntilDate() != null + && !membershipDTO.getMemberUntilDate().isAfter(membershipDTO.getMemberFromDate())) { throw new BadRequestAlertException("Invalid untilDate", Membership.ENTITY_NAME, "untilDateMustBeAfterSinceDate"); } // It's known that this validation can cause a race condition if two memberships of the same customer are saved at // same time (overlapping transactions). This is ignored in this case because it's too unlikely to be worth the effort. if (membershipRepository.hasUncancelledMembershipForCustomer(membershipDTO.getCustomerId())) { - throw new BadRequestAlertException("Another uncancelled membership exists", Membership.ENTITY_NAME, "anotherUncancelledMembershipExists"); + throw new BadRequestAlertException( + "Another uncancelled membership exists", + Membership.ENTITY_NAME, + "anotherUncancelledMembershipExists"); } } } diff --git a/src/main/java/org/hostsharing/hsadminng/service/SepaMandateQueryService.java b/src/main/java/org/hostsharing/hsadminng/service/SepaMandateQueryService.java index 3789d8d1..ba0e34b6 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/SepaMandateQueryService.java +++ b/src/main/java/org/hostsharing/hsadminng/service/SepaMandateQueryService.java @@ -1,6 +1,6 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; -import io.github.jhipster.service.QueryService; import org.hostsharing.hsadminng.domain.Customer_; import org.hostsharing.hsadminng.domain.SepaMandate; import org.hostsharing.hsadminng.domain.SepaMandate_; @@ -8,6 +8,9 @@ import org.hostsharing.hsadminng.repository.SepaMandateRepository; import org.hostsharing.hsadminng.service.dto.SepaMandateCriteria; import org.hostsharing.hsadminng.service.dto.SepaMandateDTO; import org.hostsharing.hsadminng.service.mapper.SepaMandateMapper; + +import io.github.jhipster.service.QueryService; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; @@ -16,9 +19,10 @@ import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.criteria.JoinType; import java.util.List; +import javax.persistence.criteria.JoinType; + /** * Service for executing complex queries for SepaMandate entities in the database. * The main input is a {@link SepaMandateCriteria} which gets converted to {@link Specification}, @@ -42,6 +46,7 @@ public class SepaMandateQueryService extends QueryService { /** * Return a {@link List} of {@link SepaMandateDTO} which matches the criteria from the database + * * @param criteria The object which holds all the filters, which the entities should match. * @return the matching entities. */ @@ -54,6 +59,7 @@ public class SepaMandateQueryService extends QueryService { /** * Return a {@link Page} of {@link SepaMandateDTO} which matches the criteria from the database + * * @param criteria The object which holds all the filters, which the entities should match. * @param page The page, which should be returned. * @return the matching entities. @@ -63,11 +69,12 @@ public class SepaMandateQueryService extends QueryService { log.debug("find by criteria : {}, page: {}", criteria, page); final Specification specification = createSpecification(criteria); return sepaMandateRepository.findAll(specification, page) - .map(sepaMandateMapper::toDto); + .map(sepaMandateMapper::toDto); } /** * Return the number of matching entities in the database + * * @param criteria The object which holds all the filters, which the entities should match. * @return the number of matching entities. */ @@ -97,26 +104,33 @@ public class SepaMandateQueryService extends QueryService { specification = specification.and(buildStringSpecification(criteria.getBic(), SepaMandate_.bic)); } if (criteria.getGrantingDocumentDate() != null) { - specification = specification.and(buildRangeSpecification(criteria.getGrantingDocumentDate(), SepaMandate_.grantingDocumentDate)); + specification = specification + .and(buildRangeSpecification(criteria.getGrantingDocumentDate(), SepaMandate_.grantingDocumentDate)); } if (criteria.getRevokationDocumentDate() != null) { - specification = specification.and(buildRangeSpecification(criteria.getRevokationDocumentDate(), SepaMandate_.revokationDocumentDate)); + specification = specification.and( + buildRangeSpecification(criteria.getRevokationDocumentDate(), SepaMandate_.revokationDocumentDate)); } if (criteria.getValidFromDate() != null) { - specification = specification.and(buildRangeSpecification(criteria.getValidFromDate(), SepaMandate_.validFromDate)); + specification = specification + .and(buildRangeSpecification(criteria.getValidFromDate(), SepaMandate_.validFromDate)); } if (criteria.getValidUntilDate() != null) { - specification = specification.and(buildRangeSpecification(criteria.getValidUntilDate(), SepaMandate_.validUntilDate)); + specification = specification + .and(buildRangeSpecification(criteria.getValidUntilDate(), SepaMandate_.validUntilDate)); } if (criteria.getLastUsedDate() != null) { - specification = specification.and(buildRangeSpecification(criteria.getLastUsedDate(), SepaMandate_.lastUsedDate)); + specification = specification + .and(buildRangeSpecification(criteria.getLastUsedDate(), SepaMandate_.lastUsedDate)); } if (criteria.getRemark() != null) { specification = specification.and(buildStringSpecification(criteria.getRemark(), SepaMandate_.remark)); } if (criteria.getCustomerId() != null) { - specification = specification.and(buildSpecification(criteria.getCustomerId(), - root -> root.join(SepaMandate_.customer, JoinType.LEFT).get(Customer_.id))); + specification = specification.and( + buildSpecification( + criteria.getCustomerId(), + root -> root.join(SepaMandate_.customer, JoinType.LEFT).get(Customer_.id))); } } return specification; diff --git a/src/main/java/org/hostsharing/hsadminng/service/SepaMandateService.java b/src/main/java/org/hostsharing/hsadminng/service/SepaMandateService.java index 0f0f33ae..41900658 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/SepaMandateService.java +++ b/src/main/java/org/hostsharing/hsadminng/service/SepaMandateService.java @@ -1,9 +1,11 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; import org.hostsharing.hsadminng.domain.SepaMandate; import org.hostsharing.hsadminng.repository.SepaMandateRepository; import org.hostsharing.hsadminng.service.dto.SepaMandateDTO; import org.hostsharing.hsadminng.service.mapper.SepaMandateMapper; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; @@ -11,9 +13,10 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.EntityManager; import java.util.Optional; +import javax.persistence.EntityManager; + /** * Service Implementation for managing SepaMandate. */ @@ -29,7 +32,10 @@ public class SepaMandateService implements IdToDtoResolver { private final SepaMandateMapper sepaMandateMapper; - public SepaMandateService(final EntityManager em, final SepaMandateRepository sepaMandateRepository, final SepaMandateMapper sepaMandateMapper) { + public SepaMandateService( + final EntityManager em, + final SepaMandateRepository sepaMandateRepository, + final SepaMandateMapper sepaMandateMapper) { this.em = em; this.sepaMandateRepository = sepaMandateRepository; this.sepaMandateMapper = sepaMandateMapper; @@ -60,10 +66,9 @@ public class SepaMandateService implements IdToDtoResolver { public Page findAll(Pageable pageable) { log.debug("Request to get all SepaMandates"); return sepaMandateRepository.findAll(pageable) - .map(sepaMandateMapper::toDto); + .map(sepaMandateMapper::toDto); } - /** * Get one sepaMandate by id. * @@ -74,7 +79,7 @@ public class SepaMandateService implements IdToDtoResolver { public Optional findOne(Long id) { log.debug("Request to get SepaMandate : {}", id); return sepaMandateRepository.findById(id) - .map(sepaMandateMapper::toDto); + .map(sepaMandateMapper::toDto); } /** diff --git a/src/main/java/org/hostsharing/hsadminng/service/ShareQueryService.java b/src/main/java/org/hostsharing/hsadminng/service/ShareQueryService.java index 7dcfb36c..55f851e4 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/ShareQueryService.java +++ b/src/main/java/org/hostsharing/hsadminng/service/ShareQueryService.java @@ -1,8 +1,14 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; -import java.util.List; +import org.hostsharing.hsadminng.domain.*; +import org.hostsharing.hsadminng.domain.Share; +import org.hostsharing.hsadminng.repository.ShareRepository; +import org.hostsharing.hsadminng.service.dto.ShareCriteria; +import org.hostsharing.hsadminng.service.dto.ShareDTO; +import org.hostsharing.hsadminng.service.mapper.ShareMapper; -import javax.persistence.criteria.JoinType; +import io.github.jhipster.service.QueryService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -12,14 +18,9 @@ import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import io.github.jhipster.service.QueryService; +import java.util.List; -import org.hostsharing.hsadminng.domain.Share; -import org.hostsharing.hsadminng.domain.*; // for static metamodels -import org.hostsharing.hsadminng.repository.ShareRepository; -import org.hostsharing.hsadminng.service.dto.ShareCriteria; -import org.hostsharing.hsadminng.service.dto.ShareDTO; -import org.hostsharing.hsadminng.service.mapper.ShareMapper; +import javax.persistence.criteria.JoinType; /** * Service for executing complex queries for Share entities in the database. @@ -44,6 +45,7 @@ public class ShareQueryService extends QueryService { /** * Return a {@link List} of {@link ShareDTO} which matches the criteria from the database + * * @param criteria The object which holds all the filters, which the entities should match. * @return the matching entities. */ @@ -56,6 +58,7 @@ public class ShareQueryService extends QueryService { /** * Return a {@link Page} of {@link ShareDTO} which matches the criteria from the database + * * @param criteria The object which holds all the filters, which the entities should match. * @param page The page, which should be returned. * @return the matching entities. @@ -65,11 +68,12 @@ public class ShareQueryService extends QueryService { log.debug("find by criteria : {}, page: {}", criteria, page); final Specification specification = createSpecification(criteria); return shareRepository.findAll(specification, page) - .map(shareMapper::toDto); + .map(shareMapper::toDto); } /** * Return the number of matching entities in the database + * * @param criteria The object which holds all the filters, which the entities should match. * @return the number of matching entities. */ @@ -105,8 +109,10 @@ public class ShareQueryService extends QueryService { specification = specification.and(buildStringSpecification(criteria.getRemark(), Share_.remark)); } if (criteria.getMembershipId() != null) { - specification = specification.and(buildSpecification(criteria.getMembershipId(), - root -> root.join(Share_.membership, JoinType.LEFT).get(Membership_.id))); + specification = specification.and( + buildSpecification( + criteria.getMembershipId(), + root -> root.join(Share_.membership, JoinType.LEFT).get(Membership_.id))); } } return specification; diff --git a/src/main/java/org/hostsharing/hsadminng/service/ShareService.java b/src/main/java/org/hostsharing/hsadminng/service/ShareService.java index 4fbc8bec..d7aa137d 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/ShareService.java +++ b/src/main/java/org/hostsharing/hsadminng/service/ShareService.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; import org.hostsharing.hsadminng.domain.Share; @@ -5,6 +6,7 @@ import org.hostsharing.hsadminng.repository.ShareRepository; import org.hostsharing.hsadminng.service.dto.ShareDTO; import org.hostsharing.hsadminng.service.mapper.ShareMapper; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; @@ -12,9 +14,10 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.EntityManager; import java.util.Optional; +import javax.persistence.EntityManager; + /** * Service Implementation for managing Share. */ @@ -32,7 +35,11 @@ public class ShareService implements IdToDtoResolver { private final ShareValidator shareValidator; - public ShareService(final EntityManager em, final ShareRepository shareRepository, final ShareMapper shareMapper, final ShareValidator shareValidator) { + public ShareService( + final EntityManager em, + final ShareRepository shareRepository, + final ShareMapper shareMapper, + final ShareValidator shareValidator) { this.em = em; this.shareRepository = shareRepository; this.shareMapper = shareMapper; @@ -67,10 +74,9 @@ public class ShareService implements IdToDtoResolver { public Page findAll(Pageable pageable) { log.debug("Request to get all Shares"); return shareRepository.findAll(pageable) - .map(shareMapper::toDto); + .map(shareMapper::toDto); } - /** * Get one share by id. * @@ -81,7 +87,7 @@ public class ShareService implements IdToDtoResolver { public Optional findOne(Long id) { log.debug("Request to get Share : {}", id); return shareRepository.findById(id) - .map(shareMapper::toDto); + .map(shareMapper::toDto); } /** diff --git a/src/main/java/org/hostsharing/hsadminng/service/ShareValidator.java b/src/main/java/org/hostsharing/hsadminng/service/ShareValidator.java index 44479a86..022ba196 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/ShareValidator.java +++ b/src/main/java/org/hostsharing/hsadminng/service/ShareValidator.java @@ -1,9 +1,11 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; import org.hostsharing.hsadminng.domain.Share; import org.hostsharing.hsadminng.domain.enumeration.ShareAction; import org.hostsharing.hsadminng.service.dto.ShareDTO; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + import org.springframework.stereotype.Service; @Service @@ -11,19 +13,31 @@ public class ShareValidator { public void validate(final ShareDTO shareDTO) { if (shareDTO.getId() != null) { - throw new BadRequestAlertException("Share transactions are immutable", Share.ENTITY_NAME, "shareTransactionImmutable"); + throw new BadRequestAlertException( + "Share transactions are immutable", + Share.ENTITY_NAME, + "shareTransactionImmutable"); } if (shareDTO.getDocumentDate().isAfter(shareDTO.getValueDate())) { - throw new BadRequestAlertException("Document date may not be after value date", Share.ENTITY_NAME, "documentDateMayNotBeAfterValueDate"); + throw new BadRequestAlertException( + "Document date may not be after value date", + Share.ENTITY_NAME, + "documentDateMayNotBeAfterValueDate"); } if ((shareDTO.getAction() == ShareAction.SUBSCRIPTION) && (shareDTO.getQuantity() <= 0)) { - throw new BadRequestAlertException("Share subscriptions require a positive quantity", Share.ENTITY_NAME, "shareSubscriptionPositiveQuantity"); + throw new BadRequestAlertException( + "Share subscriptions require a positive quantity", + Share.ENTITY_NAME, + "shareSubscriptionPositiveQuantity"); } if ((shareDTO.getAction() == ShareAction.CANCELLATION) && (shareDTO.getQuantity() >= 0)) { - throw new BadRequestAlertException("Share cancellations require a negative quantity", Share.ENTITY_NAME, "shareCancellationNegativeQuantity"); + throw new BadRequestAlertException( + "Share cancellations require a negative quantity", + Share.ENTITY_NAME, + "shareCancellationNegativeQuantity"); } } diff --git a/src/main/java/org/hostsharing/hsadminng/service/UserService.java b/src/main/java/org/hostsharing/hsadminng/service/UserService.java index 6fb76dc5..aab6278a 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/UserService.java +++ b/src/main/java/org/hostsharing/hsadminng/service/UserService.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; import org.hostsharing.hsadminng.config.Constants; @@ -43,7 +44,11 @@ public class UserService { private final CacheManager cacheManager; - public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, AuthorityRepository authorityRepository, CacheManager cacheManager) { + public UserService( + UserRepository userRepository, + PasswordEncoder passwordEncoder, + AuthorityRepository authorityRepository, + CacheManager cacheManager) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; this.authorityRepository = authorityRepository; @@ -53,38 +58,38 @@ public class UserService { public Optional activateRegistration(String key) { log.debug("Activating user for activation key {}", key); return userRepository.findOneByActivationKey(key) - .map(user -> { - // activate given user for the registration key. - user.setActivated(true); - user.setActivationKey(null); - this.clearUserCaches(user); - log.debug("Activated user: {}", user); - return user; - }); + .map(user -> { + // activate given user for the registration key. + user.setActivated(true); + user.setActivationKey(null); + this.clearUserCaches(user); + log.debug("Activated user: {}", user); + return user; + }); } public Optional completePasswordReset(String newPassword, String key) { log.debug("Reset user password for reset key {}", key); return userRepository.findOneByResetKey(key) - .filter(user -> user.getResetDate().isAfter(Instant.now().minusSeconds(86400))) - .map(user -> { - user.setPassword(passwordEncoder.encode(newPassword)); - user.setResetKey(null); - user.setResetDate(null); - this.clearUserCaches(user); - return user; - }); + .filter(user -> user.getResetDate().isAfter(Instant.now().minusSeconds(86400))) + .map(user -> { + user.setPassword(passwordEncoder.encode(newPassword)); + user.setResetKey(null); + user.setResetDate(null); + this.clearUserCaches(user); + return user; + }); } public Optional requestPasswordReset(String mail) { return userRepository.findOneByEmailIgnoreCase(mail) - .filter(User::getActivated) - .map(user -> { - user.setResetKey(RandomUtil.generateResetKey()); - user.setResetDate(Instant.now()); - this.clearUserCaches(user); - return user; - }); + .filter(User::getActivated) + .map(user -> { + user.setResetKey(RandomUtil.generateResetKey()); + user.setResetDate(Instant.now()); + this.clearUserCaches(user); + return user; + }); } public User registerUser(UserDTO userDTO, String password) { @@ -123,9 +128,9 @@ public class UserService { return newUser; } - private boolean removeNonActivatedUser(User existingUser){ + private boolean removeNonActivatedUser(User existingUser) { if (existingUser.getActivated()) { - return false; + return false; } userRepository.delete(existingUser); userRepository.flush(); @@ -151,11 +156,12 @@ public class UserService { user.setResetDate(Instant.now()); user.setActivated(true); if (userDTO.getAuthorities() != null) { - Set authorities = userDTO.getAuthorities().stream() - .map(authorityRepository::findById) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(Collectors.toSet()); + Set authorities = userDTO.getAuthorities() + .stream() + .map(authorityRepository::findById) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toSet()); user.setAuthorities(authorities); } userRepository.save(user); @@ -175,16 +181,16 @@ public class UserService { */ public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) { SecurityUtils.getCurrentUserLogin() - .flatMap(userRepository::findOneByLogin) - .ifPresent(user -> { - user.setFirstName(firstName); - user.setLastName(lastName); - user.setEmail(email.toLowerCase()); - user.setLangKey(langKey); - user.setImageUrl(imageUrl); - this.clearUserCaches(user); - log.debug("Changed Information for User: {}", user); - }); + .flatMap(userRepository::findOneByLogin) + .ifPresent(user -> { + user.setFirstName(firstName); + user.setLastName(lastName); + user.setEmail(email.toLowerCase()); + user.setLangKey(langKey); + user.setImageUrl(imageUrl); + this.clearUserCaches(user); + log.debug("Changed Information for User: {}", user); + }); } /** @@ -194,31 +200,33 @@ public class UserService { * @return updated user */ public Optional updateUser(UserDTO userDTO) { - return Optional.of(userRepository - .findById(userDTO.getId())) - .filter(Optional::isPresent) - .map(Optional::get) - .map(user -> { - this.clearUserCaches(user); - user.setLogin(userDTO.getLogin().toLowerCase()); - user.setFirstName(userDTO.getFirstName()); - user.setLastName(userDTO.getLastName()); - user.setEmail(userDTO.getEmail().toLowerCase()); - user.setImageUrl(userDTO.getImageUrl()); - user.setActivated(userDTO.isActivated()); - user.setLangKey(userDTO.getLangKey()); - Set managedAuthorities = user.getAuthorities(); - managedAuthorities.clear(); - userDTO.getAuthorities().stream() - .map(authorityRepository::findById) - .filter(Optional::isPresent) - .map(Optional::get) - .forEach(managedAuthorities::add); - this.clearUserCaches(user); - log.debug("Changed Information for User: {}", user); - return user; - }) - .map(UserDTO::new); + return Optional.of( + userRepository + .findById(userDTO.getId())) + .filter(Optional::isPresent) + .map(Optional::get) + .map(user -> { + this.clearUserCaches(user); + user.setLogin(userDTO.getLogin().toLowerCase()); + user.setFirstName(userDTO.getFirstName()); + user.setLastName(userDTO.getLastName()); + user.setEmail(userDTO.getEmail().toLowerCase()); + user.setImageUrl(userDTO.getImageUrl()); + user.setActivated(userDTO.isActivated()); + user.setLangKey(userDTO.getLangKey()); + Set managedAuthorities = user.getAuthorities(); + managedAuthorities.clear(); + userDTO.getAuthorities() + .stream() + .map(authorityRepository::findById) + .filter(Optional::isPresent) + .map(Optional::get) + .forEach(managedAuthorities::add); + this.clearUserCaches(user); + log.debug("Changed Information for User: {}", user); + return user; + }) + .map(UserDTO::new); } public void deleteUser(String login) { @@ -231,17 +239,17 @@ public class UserService { public void changePassword(String currentClearTextPassword, String newPassword) { SecurityUtils.getCurrentUserLogin() - .flatMap(userRepository::findOneByLogin) - .ifPresent(user -> { - String currentEncryptedPassword = user.getPassword(); - if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) { - throw new InvalidPasswordException(); - } - String encryptedPassword = passwordEncoder.encode(newPassword); - user.setPassword(encryptedPassword); - this.clearUserCaches(user); - log.debug("Changed password for User: {}", user); - }); + .flatMap(userRepository::findOneByLogin) + .ifPresent(user -> { + String currentEncryptedPassword = user.getPassword(); + if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) { + throw new InvalidPasswordException(); + } + String encryptedPassword = passwordEncoder.encode(newPassword); + user.setPassword(encryptedPassword); + this.clearUserCaches(user); + log.debug("Changed password for User: {}", user); + }); } @Transactional(readOnly = true) @@ -272,12 +280,12 @@ public class UserService { @Scheduled(cron = "0 0 1 * * ?") public void removeNotActivatedUsers() { userRepository - .findAllByActivatedIsFalseAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS)) - .forEach(user -> { - log.debug("Deleting not activated user {}", user.getLogin()); - userRepository.delete(user); - this.clearUserCaches(user); - }); + .findAllByActivatedIsFalseAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS)) + .forEach(user -> { + log.debug("Deleting not activated user {}", user.getLogin()); + userRepository.delete(user); + this.clearUserCaches(user); + }); } /** diff --git a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/AccessFor.java b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/AccessFor.java index 852f6138..5e76c893 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/AccessFor.java +++ b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/AccessFor.java @@ -1,16 +1,16 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.accessfilter; - import java.lang.annotation.*; @Documented -@Target({ElementType.FIELD, ElementType.TYPE_USE}) +@Target({ ElementType.FIELD, ElementType.TYPE_USE }) @Retention(RetentionPolicy.RUNTIME) public @interface AccessFor { + Role[] init() default Role.NOBODY; Role[] update() default Role.NOBODY; Role[] read() default Role.NOBODY; } - diff --git a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/AccessMappings.java b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/AccessMappings.java index d28d91b3..e3b9252e 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/AccessMappings.java +++ b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/AccessMappings.java @@ -1,9 +1,11 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.accessfilter; import java.io.Serializable; /** - * A marker interface for DTO classes which can be used by {@link JsonSerializerWithAccessFilter} and {@link JsonDeserializerWithAccessFilter}. + * A marker interface for DTO classes which can be used by {@link JsonSerializerWithAccessFilter} and + * {@link JsonDeserializerWithAccessFilter}. */ public interface AccessMappings extends Serializable { } diff --git a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JSonAccessFilter.java b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JSonAccessFilter.java index 273b64cc..e1aed4bf 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JSonAccessFilter.java +++ b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JSonAccessFilter.java @@ -1,19 +1,22 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.accessfilter; +import static com.google.common.base.Verify.verify; + import org.hostsharing.hsadminng.security.SecurityUtils; import org.hostsharing.hsadminng.service.IdToDtoResolver; import org.hostsharing.hsadminng.service.dto.MembershipDTO; import org.hostsharing.hsadminng.service.util.ReflectionUtil; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.ApplicationContext; import java.lang.annotation.Annotation; import java.lang.reflect.Field; -import static com.google.common.base.Verify.verify; - abstract class JSonAccessFilter { + private final ApplicationContext ctx; final T dto; final Field selfIdField; @@ -67,7 +70,7 @@ abstract class JSonAccessFilter { final Class parentDtoLoader = parentIdAnnot.resolver(); final Class rawType = IdToDtoResolver.class; - final Class parentDtoClass = ReflectionUtil.determineGenericInterfaceParameter(parentDtoLoader, rawType, 0); + final Class parentDtoClass = ReflectionUtil. determineGenericInterfaceParameter(parentDtoLoader, rawType, 0); final Long parentId = ReflectionUtil.getValue(dto, parentIdField); final Role roleOnParent = SecurityUtils.getLoginUserRoleFor(parentDtoClass, parentId); @@ -77,23 +80,37 @@ abstract class JSonAccessFilter { @SuppressWarnings("unchecked") protected Object loadDto(final Class resolverClass, final Long id) { - verify(id != null, "id must not be null for " + resolverClass.getSimpleName()); + verify(id != null, "id must not be null for " + resolverClass.getSimpleName()); final AutowireCapableBeanFactory beanFactory = ctx.getAutowireCapableBeanFactory(); - verify(beanFactory != null, "no bean factory found, probably missing mock configuration for ApplicationContext, e.g. given(...)"); + verify( + beanFactory != null, + "no bean factory found, probably missing mock configuration for ApplicationContext, e.g. given(...)"); final IdToDtoResolver resolverBean = beanFactory.createBean(resolverClass); - verify(resolverBean != null, "no " + resolverClass.getSimpleName() + " bean created, probably missing mock configuration for AutowireCapableBeanFactory, e.g. given(...)"); + verify( + resolverBean != null, + "no " + resolverClass.getSimpleName() + + " bean created, probably missing mock configuration for AutowireCapableBeanFactory, e.g. given(...)"); - return resolverBean.findOne(id).orElseThrow(() -> new BadRequestAlertException("Can't resolve entity ID " + id + " via " + resolverClass, resolverClass.getSimpleName(), "isNotFound")); + return resolverBean.findOne(id) + .orElseThrow( + () -> new BadRequestAlertException( + "Can't resolve entity ID " + id + " via " + resolverClass, + resolverClass.getSimpleName(), + "isNotFound")); } - private static Field determineFieldWithAnnotation(final Class dtoClass, final Class idAnnotationClass) { + private static Field determineFieldWithAnnotation( + final Class dtoClass, + final Class idAnnotationClass) { Field parentIdField = null; for (Field field : dtoClass.getDeclaredFields()) { if (field.isAnnotationPresent(idAnnotationClass)) { if (parentIdField != null) { - throw new AssertionError("multiple @" + idAnnotationClass.getSimpleName() + " detected in " + field.getDeclaringClass().getSimpleName()); + throw new AssertionError( + "multiple @" + idAnnotationClass.getSimpleName() + " detected in " + + field.getDeclaringClass().getSimpleName()); } parentIdField = field; } diff --git a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JSonDeserializationWithAccessFilter.java b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JSonDeserializationWithAccessFilter.java index 0756b69a..c594ebc8 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JSonDeserializationWithAccessFilter.java +++ b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JSonDeserializationWithAccessFilter.java @@ -1,13 +1,18 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.accessfilter; +import static org.hostsharing.hsadminng.service.util.ReflectionUtil.unchecked; + +import org.hostsharing.hsadminng.service.util.ReflectionUtil; +import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.TreeNode; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.node.*; + import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.ObjectUtils; -import org.hostsharing.hsadminng.service.util.ReflectionUtil; -import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; import org.springframework.context.ApplicationContext; import java.lang.reflect.Field; @@ -16,9 +21,8 @@ import java.time.LocalDate; import java.util.HashSet; import java.util.Set; -import static org.hostsharing.hsadminng.service.util.ReflectionUtil.unchecked; - -/** Actual implementation of JSON deserialization, where {link JSonDeserializerWithAccessFilter} +/** + * Actual implementation of JSON deserialization, where {link JSonDeserializerWithAccessFilter} * is a stateless bean, {@link JSonDeserializationWithAccessFilter} exists only during the actual * deserialization and contains a deserialization state. * @@ -29,7 +33,11 @@ public class JSonDeserializationWithAccessFilter extends JSonAccessFilter private final TreeNode treeNode; private final Set updatingFields = new HashSet<>(); - public JSonDeserializationWithAccessFilter(final ApplicationContext ctx, final JsonParser jsonParser, final DeserializationContext deserializationContext, Class dtoClass) { + public JSonDeserializationWithAccessFilter( + final ApplicationContext ctx, + final JsonParser jsonParser, + final DeserializationContext deserializationContext, + Class dtoClass) { super(ctx, unchecked(dtoClass::newInstance)); this.treeNode = unchecked(() -> jsonParser.getCodec().readTree(jsonParser)); } @@ -68,9 +76,9 @@ public class JSonDeserializationWithAccessFilter extends JSonAccessFilter return; } for (Field field : currentDto.getClass().getDeclaredFields()) { - if (field.isAnnotationPresent(AccessFor.class) ) { + if (field.isAnnotationPresent(AccessFor.class)) { boolean updatingField = updatingFields.contains(field); - if (updatingField && !isActuallyUpdated(field, dto, currentDto) ) { + if (updatingField && !isActuallyUpdated(field, dto, currentDto)) { updatingFields.remove(field); updatingField = false; } @@ -106,9 +114,13 @@ public class JSonDeserializationWithAccessFilter extends JSonAccessFilter return ((DoubleNode) fieldNode).asDouble(); } if (fieldNode instanceof ArrayNode && LocalDate.class.isAssignableFrom(fieldClass)) { - return LocalDate.of(((ArrayNode) fieldNode).get(0).asInt(), ((ArrayNode) fieldNode).get(1).asInt(), ((ArrayNode) fieldNode).get(2).asInt()); + return LocalDate.of( + ((ArrayNode) fieldNode).get(0).asInt(), + ((ArrayNode) fieldNode).get(1).asInt(), + ((ArrayNode) fieldNode).get(2).asInt()); } - throw new NotImplementedException("JSon node type not implemented: " + fieldNode.getClass() + " -> " + fieldName + ": " + fieldClass); + throw new NotImplementedException( + "JSon node type not implemented: " + fieldNode.getClass() + " -> " + fieldName + ": " + fieldClass); } private void writeValueToDto(final T dto, final Field field, final Object value) { @@ -135,23 +147,35 @@ public class JSonDeserializationWithAccessFilter extends JSonAccessFilter } private void checkAccessToWrittenFields(final T currentDto) { - updatingFields.forEach(field -> { - // TODO this ugly code needs cleanup - if (!field.equals(selfIdField)) { - final Role role = getLoginUserRole(); - if (isInitAccess()) { - if (!role.isAllowedToInit(field)) { - if (!field.equals(parentIdField)) { - throw new BadRequestAlertException("Initialization of field " + toDisplay(field) + " prohibited for current user role " + role, toDisplay(field), "initializationProhibited"); - } else { - throw new BadRequestAlertException("Referencing field " + toDisplay(field) + " prohibited for current user role " + role, toDisplay(field), "referencingProhibited"); + updatingFields.forEach( + field -> { + // TODO this ugly code needs cleanup + if (!field.equals(selfIdField)) { + final Role role = getLoginUserRole(); + if (isInitAccess()) { + if (!role.isAllowedToInit(field)) { + if (!field.equals(parentIdField)) { + throw new BadRequestAlertException( + "Initialization of field " + toDisplay(field) + " prohibited for current user role " + + role, + toDisplay(field), + "initializationProhibited"); + } else { + throw new BadRequestAlertException( + "Referencing field " + toDisplay(field) + " prohibited for current user role " + + role, + toDisplay(field), + "referencingProhibited"); + } + } + } else if (!Role.toBeIgnoredForUpdates(field) && !getLoginUserRole().isAllowedToUpdate(field)) { + throw new BadRequestAlertException( + "Update of field " + toDisplay(field) + " prohibited for current user role " + role, + toDisplay(field), + "updateProhibited"); } } - } else if ( !Role.toBeIgnoredForUpdates(field) && !getLoginUserRole().isAllowedToUpdate(field)) { - throw new BadRequestAlertException("Update of field " + toDisplay(field) + " prohibited for current user role " + role, toDisplay(field), "updateProhibited"); - } - } - }); + }); } private boolean isInitAccess() { @@ -159,6 +183,6 @@ public class JSonDeserializationWithAccessFilter extends JSonAccessFilter } private boolean isActuallyUpdated(final Field field, final T dto, T currentDto) { - return 0 != ObjectUtils.compare(ReflectionUtil.getValue(dto, field), ReflectionUtil.getValue(currentDto, field)); + return 0 != ObjectUtils.compare(ReflectionUtil.getValue(dto, field), ReflectionUtil.getValue(currentDto, field)); } } diff --git a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JSonSerializationWithAccessFilter.java b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JSonSerializationWithAccessFilter.java index d3ac6a10..0b61e0c1 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JSonSerializationWithAccessFilter.java +++ b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JSonSerializationWithAccessFilter.java @@ -1,10 +1,12 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.accessfilter; +import org.hostsharing.hsadminng.service.util.ReflectionUtil; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; + import org.apache.commons.lang3.NotImplementedException; -import org.hostsharing.hsadminng.service.util.ReflectionUtil; import org.springframework.context.ApplicationContext; import java.io.IOException; @@ -12,20 +14,23 @@ import java.lang.reflect.Field; import java.math.BigDecimal; import java.time.LocalDate; -/** Actual implementation of JSON serialization, where {link JsonSerializerWithAccessFilter} +/** + * Actual implementation of JSON serialization, where {link JsonSerializerWithAccessFilter} * is a stateless bean, {@link JSonSerializationWithAccessFilter} exists only during the actual * serialization and contains a serialization state. * * @param DTO class to serialize */ public class JSonSerializationWithAccessFilter extends JSonAccessFilter { + private final JsonGenerator jsonGenerator; private final SerializerProvider serializerProvider; - public JSonSerializationWithAccessFilter(final ApplicationContext ctx, - final JsonGenerator jsonGenerator, - final SerializerProvider serializerProvider, - final T dto) { + public JSonSerializationWithAccessFilter( + final ApplicationContext ctx, + final JsonGenerator jsonGenerator, + final SerializerProvider serializerProvider, + final T dto) { super(ctx, dto); this.jsonGenerator = jsonGenerator; this.serializerProvider = serializerProvider; @@ -45,10 +50,10 @@ public class JSonSerializationWithAccessFilter extends JSonAccessFilter { if (getLoginUserRole().isAllowedToRead(field)) { final String fieldName = field.getName(); // TODO: maybe replace by serializerProvider.defaultSerialize...()? - // But that makes it difficult for parallel structure with the deserializer (clumsy API). - // Alternatively extract the supported types to subclasses of some abstract class and - // here as well as in the deserializer just access the matching implementation through a map. - // Or even completely switch from Jackson to GSON? + // But that makes it difficult for parallel structure with the deserializer (clumsy API). + // Alternatively extract the supported types to subclasses of some abstract class and + // here as well as in the deserializer just access the matching implementation through a map. + // Or even completely switch from Jackson to GSON? final Object fieldValue = ReflectionUtil.getValue(dto, field); if (fieldValue == null) { jsonGenerator.writeNullField(fieldName); diff --git a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JsonDeserializerWithAccessFilter.java b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JsonDeserializerWithAccessFilter.java index 1b926283..19e8255a 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JsonDeserializerWithAccessFilter.java +++ b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JsonDeserializerWithAccessFilter.java @@ -1,9 +1,12 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.accessfilter; +import org.hostsharing.hsadminng.service.util.ReflectionUtil; + import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; -import org.hostsharing.hsadminng.service.util.ReflectionUtil; + import org.springframework.context.ApplicationContext; public abstract class JsonDeserializerWithAccessFilter extends JsonDeserializer { @@ -15,10 +18,12 @@ public abstract class JsonDeserializerWithAccessFilter } @Override - public T deserialize(final JsonParser jsonParser, - final DeserializationContext deserializationContext) { + public T deserialize( + final JsonParser jsonParser, + final DeserializationContext deserializationContext) { - final Class dtoClass = ReflectionUtil.determineGenericClassParameter(this.getClass(), JsonDeserializerWithAccessFilter.class, 0); + final Class dtoClass = ReflectionUtil + .determineGenericClassParameter(this.getClass(), JsonDeserializerWithAccessFilter.class, 0); return new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, deserializationContext, dtoClass).deserialize(); } } diff --git a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JsonSerializerWithAccessFilter.java b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JsonSerializerWithAccessFilter.java index 57a11878..86972af9 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JsonSerializerWithAccessFilter.java +++ b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/JsonSerializerWithAccessFilter.java @@ -1,13 +1,16 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.accessfilter; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; + import org.springframework.context.ApplicationContext; import java.io.IOException; -/** A base class for a Spring bean for JSON serialization with field-based access filters. +/** + * A base class for a Spring bean for JSON serialization with field-based access filters. * Where {@link JSonSerializationWithAccessFilter} is the actual stateful implementation and * it's instances only exist during the process of serialization, this class is a stateless just * used for service and context injection. @@ -23,8 +26,10 @@ public abstract class JsonSerializerWithAccessFilter e } @Override - public void serialize(final T dto, final JsonGenerator jsonGenerator, - final SerializerProvider serializerProvider) throws IOException { + public void serialize( + final T dto, + final JsonGenerator jsonGenerator, + final SerializerProvider serializerProvider) throws IOException { new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, serializerProvider, dto).serialize(); } diff --git a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/ParentId.java b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/ParentId.java index e392374e..9dd46a0a 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/ParentId.java +++ b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/ParentId.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.accessfilter; import org.hostsharing.hsadminng.service.IdToDtoResolver; @@ -11,9 +12,10 @@ import java.lang.annotation.*; * @see AccessFor */ @Documented -@Target({ElementType.FIELD}) +@Target({ ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface ParentId { + /// The service which can load the referenced DTO. Class> resolver(); } diff --git a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/Role.java b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/Role.java index 46e279f9..768e0d24 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/Role.java +++ b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/Role.java @@ -1,9 +1,10 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.accessfilter; -import java.lang.reflect.Field; - import static com.google.common.base.Verify.verify; +import java.lang.reflect.Field; + /** * These enum values are on the one hand used to define the minimum role required to grant access to resources, * but on the other hand also for the roles users can be assigned to. @@ -46,6 +47,7 @@ public enum Role { * This role is for financial contacts of a customer, e.g. for accessing billing data. */ FINANCIAL_CONTACT(22) { + @Override public boolean covers(final Role role) { if (role == ACTUAL_CUSTOMER_USER) { @@ -60,7 +62,6 @@ public enum Role { */ TECHNICAL_CONTACT(22), - /** * This meta-role is to specify that any kind of customer contact can get access to the resource. */ diff --git a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/SelfId.java b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/SelfId.java index 6c67b9fb..35725a9b 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/accessfilter/SelfId.java +++ b/src/main/java/org/hostsharing/hsadminng/service/accessfilter/SelfId.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.accessfilter; import org.hostsharing.hsadminng.service.IdToDtoResolver; @@ -13,9 +14,10 @@ import java.lang.annotation.*; * @see AccessFor */ @Documented -@Target({ElementType.FIELD}) +@Target({ ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface SelfId { + /// The service which can load the referenced DTO. Class> resolver(); } diff --git a/src/main/java/org/hostsharing/hsadminng/service/dto/AssetCriteria.java b/src/main/java/org/hostsharing/hsadminng/service/dto/AssetCriteria.java index fe0091fc..0fe2ed74 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/dto/AssetCriteria.java +++ b/src/main/java/org/hostsharing/hsadminng/service/dto/AssetCriteria.java @@ -1,17 +1,16 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.dto; +import org.hostsharing.hsadminng.domain.enumeration.AssetAction; + +import io.github.jhipster.service.filter.BigDecimalFilter; +import io.github.jhipster.service.filter.Filter; +import io.github.jhipster.service.filter.LocalDateFilter; +import io.github.jhipster.service.filter.LongFilter; +import io.github.jhipster.service.filter.StringFilter; + import java.io.Serializable; import java.util.Objects; -import org.hostsharing.hsadminng.domain.enumeration.AssetAction; -import io.github.jhipster.service.filter.BooleanFilter; -import io.github.jhipster.service.filter.DoubleFilter; -import io.github.jhipster.service.filter.Filter; -import io.github.jhipster.service.filter.FloatFilter; -import io.github.jhipster.service.filter.IntegerFilter; -import io.github.jhipster.service.filter.LongFilter; -import io.github.jhipster.service.filter.StringFilter; -import io.github.jhipster.service.filter.BigDecimalFilter; -import io.github.jhipster.service.filter.LocalDateFilter; /** * Criteria class for the Asset entity. This class is used in AssetResource to @@ -22,6 +21,7 @@ import io.github.jhipster.service.filter.LocalDateFilter; * fix type specific filters. */ public class AssetCriteria implements Serializable { + /** * Class for filtering AssetAction */ @@ -100,7 +100,6 @@ public class AssetCriteria implements Serializable { this.membershipId = membershipId; } - @Override public boolean equals(Object o) { if (this == o) { @@ -110,27 +109,25 @@ public class AssetCriteria implements Serializable { return false; } final AssetCriteria that = (AssetCriteria) o; - return - Objects.equals(id, that.id) && - Objects.equals(documentDate, that.documentDate) && - Objects.equals(valueDate, that.valueDate) && - Objects.equals(action, that.action) && - Objects.equals(amount, that.amount) && - Objects.equals(remark, that.remark) && - Objects.equals(membershipId, that.membershipId); + return Objects.equals(id, that.id) && + Objects.equals(documentDate, that.documentDate) && + Objects.equals(valueDate, that.valueDate) && + Objects.equals(action, that.action) && + Objects.equals(amount, that.amount) && + Objects.equals(remark, that.remark) && + Objects.equals(membershipId, that.membershipId); } @Override public int hashCode() { return Objects.hash( - id, - documentDate, - valueDate, - action, - amount, - remark, - membershipId - ); + id, + documentDate, + valueDate, + action, + amount, + remark, + membershipId); } @Override @@ -143,7 +140,7 @@ public class AssetCriteria implements Serializable { (amount != null ? "amount=" + amount + ", " : "") + (remark != null ? "remark=" + remark + ", " : "") + (membershipId != null ? "membershipId=" + membershipId + ", " : "") + - "}"; + "}"; } } diff --git a/src/main/java/org/hostsharing/hsadminng/service/dto/AssetDTO.java b/src/main/java/org/hostsharing/hsadminng/service/dto/AssetDTO.java index f80e0486..8fb08e80 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/dto/AssetDTO.java +++ b/src/main/java/org/hostsharing/hsadminng/service/dto/AssetDTO.java @@ -1,42 +1,45 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.dto; import org.hostsharing.hsadminng.domain.enumeration.AssetAction; import org.hostsharing.hsadminng.service.AssetService; import org.hostsharing.hsadminng.service.MembershipService; import org.hostsharing.hsadminng.service.accessfilter.*; + import org.springframework.boot.jackson.JsonComponent; import org.springframework.context.ApplicationContext; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; import java.io.Serializable; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Objects; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + /** * A DTO for the Asset entity. */ public class AssetDTO implements Serializable, AccessMappings { @SelfId(resolver = AssetService.class) - @AccessFor(read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private Long id; @NotNull - @AccessFor(init = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private LocalDate documentDate; @NotNull - @AccessFor(init = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private LocalDate valueDate; @NotNull - @AccessFor(init = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private AssetAction action; @NotNull - @AccessFor(init = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private BigDecimal amount; @Size(max = 160) @@ -44,10 +47,10 @@ public class AssetDTO implements Serializable, AccessMappings { private String remark; @ParentId(resolver = MembershipService.class) - @AccessFor(init = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private Long membershipId; - @AccessFor(update = Role.IGNORED, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(update = Role.IGNORED, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private String membershipDisplayLabel; public Long getId() { @@ -138,15 +141,15 @@ public class AssetDTO implements Serializable, AccessMappings { @Override public String toString() { return "AssetDTO{" + - "id=" + getId() + - ", documentDate='" + getDocumentDate() + "'" + - ", valueDate='" + getValueDate() + "'" + - ", action='" + getAction() + "'" + - ", amount=" + getAmount() + - ", remark='" + getRemark() + "'" + - ", membership=" + getMembershipId() + - ", membershipDisplayLabel='" + getMembershipDisplayLabel() + "'" + - "}"; + "id=" + getId() + + ", documentDate='" + getDocumentDate() + "'" + + ", valueDate='" + getValueDate() + "'" + + ", action='" + getAction() + "'" + + ", amount=" + getAmount() + + ", remark='" + getRemark() + "'" + + ", membership=" + getMembershipId() + + ", membershipDisplayLabel='" + getMembershipDisplayLabel() + "'" + + "}"; } @JsonComponent diff --git a/src/main/java/org/hostsharing/hsadminng/service/dto/CustomerCriteria.java b/src/main/java/org/hostsharing/hsadminng/service/dto/CustomerCriteria.java index 50fc2a0e..4638eaa8 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/dto/CustomerCriteria.java +++ b/src/main/java/org/hostsharing/hsadminng/service/dto/CustomerCriteria.java @@ -1,9 +1,11 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.dto; -import io.github.jhipster.service.filter.*; import org.hostsharing.hsadminng.domain.enumeration.CustomerKind; import org.hostsharing.hsadminng.domain.enumeration.VatRegion; +import io.github.jhipster.service.filter.*; + import java.io.Serializable; import java.util.Objects; @@ -16,11 +18,13 @@ import java.util.Objects; * fix type specific filters. */ public class CustomerCriteria implements Serializable { + /** * Class for filtering CustomerKind */ public static class CustomerKindFilter extends Filter { } + /** * Class for filtering VatRegion */ @@ -209,7 +213,6 @@ public class CustomerCriteria implements Serializable { this.sepamandateId = sepamandateId; } - @Override public boolean equals(Object o) { if (this == o) { @@ -219,49 +222,47 @@ public class CustomerCriteria implements Serializable { return false; } final CustomerCriteria that = (CustomerCriteria) o; - return - Objects.equals(id, that.id) && - Objects.equals(reference, that.reference) && - Objects.equals(prefix, that.prefix) && - Objects.equals(name, that.name) && - Objects.equals(kind, that.kind) && - Objects.equals(birthDate, that.birthDate) && - Objects.equals(birthPlace, that.birthPlace) && - Objects.equals(registrationCourt, that.registrationCourt) && - Objects.equals(registrationNumber, that.registrationNumber) && - Objects.equals(vatRegion, that.vatRegion) && - Objects.equals(vatNumber, that.vatNumber) && - Objects.equals(contractualSalutation, that.contractualSalutation) && - Objects.equals(contractualAddress, that.contractualAddress) && - Objects.equals(billingSalutation, that.billingSalutation) && - Objects.equals(billingAddress, that.billingAddress) && - Objects.equals(remark, that.remark) && - Objects.equals(membershipId, that.membershipId) && - Objects.equals(sepamandateId, that.sepamandateId); + return Objects.equals(id, that.id) && + Objects.equals(reference, that.reference) && + Objects.equals(prefix, that.prefix) && + Objects.equals(name, that.name) && + Objects.equals(kind, that.kind) && + Objects.equals(birthDate, that.birthDate) && + Objects.equals(birthPlace, that.birthPlace) && + Objects.equals(registrationCourt, that.registrationCourt) && + Objects.equals(registrationNumber, that.registrationNumber) && + Objects.equals(vatRegion, that.vatRegion) && + Objects.equals(vatNumber, that.vatNumber) && + Objects.equals(contractualSalutation, that.contractualSalutation) && + Objects.equals(contractualAddress, that.contractualAddress) && + Objects.equals(billingSalutation, that.billingSalutation) && + Objects.equals(billingAddress, that.billingAddress) && + Objects.equals(remark, that.remark) && + Objects.equals(membershipId, that.membershipId) && + Objects.equals(sepamandateId, that.sepamandateId); } @Override public int hashCode() { return Objects.hash( - id, - reference, - prefix, - name, - kind, - birthDate, - birthPlace, - registrationCourt, - registrationNumber, - vatRegion, - vatNumber, - contractualSalutation, - contractualAddress, - billingSalutation, - billingAddress, - remark, - membershipId, - sepamandateId - ); + id, + reference, + prefix, + name, + kind, + birthDate, + birthPlace, + registrationCourt, + registrationNumber, + vatRegion, + vatNumber, + contractualSalutation, + contractualAddress, + billingSalutation, + billingAddress, + remark, + membershipId, + sepamandateId); } @Override @@ -285,7 +286,7 @@ public class CustomerCriteria implements Serializable { (remark != null ? "remark=" + remark + ", " : "") + (membershipId != null ? "membershipId=" + membershipId + ", " : "") + (sepamandateId != null ? "sepamandateId=" + sepamandateId + ", " : "") + - "}"; + "}"; } } diff --git a/src/main/java/org/hostsharing/hsadminng/service/dto/CustomerDTO.java b/src/main/java/org/hostsharing/hsadminng/service/dto/CustomerDTO.java index 7713569f..e34813b2 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/dto/CustomerDTO.java +++ b/src/main/java/org/hostsharing/hsadminng/service/dto/CustomerDTO.java @@ -1,20 +1,23 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.dto; import org.hostsharing.hsadminng.domain.enumeration.CustomerKind; import org.hostsharing.hsadminng.domain.enumeration.VatRegion; import org.hostsharing.hsadminng.service.CustomerService; import org.hostsharing.hsadminng.service.accessfilter.*; + import org.springframework.boot.jackson.JsonComponent; import org.springframework.context.ApplicationContext; -import javax.validation.constraints.*; import java.time.LocalDate; import java.util.Objects; +import javax.validation.constraints.*; + /** * A DTO for the Customer entity. */ -public class CustomerDTO implements AccessMappings, FluentBuilder { +public class CustomerDTO implements AccessMappings, FluentBuilder { @SelfId(resolver = CustomerService.class) @AccessFor(read = Role.ANY_CUSTOMER_USER) @@ -41,27 +44,27 @@ public class CustomerDTO implements AccessMappings, FluentBuilder @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = Role.CONTRACTUAL_CONTACT) private CustomerKind kind; - @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private LocalDate birthDate; @Size(max = 80) - @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private String birthPlace; @Size(max = 80) - @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private String registrationCourt; @Size(max = 80) - @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private String registrationNumber; @NotNull - @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private VatRegion vatRegion; @Size(max = 40) - @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private String vatNumber; @Size(max = 80) @@ -74,18 +77,21 @@ public class CustomerDTO implements AccessMappings, FluentBuilder private String contractualAddress; @Size(max = 80) - @AccessFor(init = Role.ADMIN, update = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, read = Role.CONTRACTUAL_CONTACT) + @AccessFor( + init = Role.ADMIN, + update = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }, + read = Role.CONTRACTUAL_CONTACT) private String billingSalutation; @Size(max = 400) - @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private String billingAddress; @Size(max = 160) @AccessFor(init = Role.ADMIN, update = Role.SUPPORTER, read = Role.SUPPORTER) private String remark; - @AccessFor(init=Role.ANYBODY, update=Role.ANYBODY, read = Role.ANY_CUSTOMER_USER) + @AccessFor(init = Role.ANYBODY, update = Role.ANYBODY, read = Role.ANY_CUSTOMER_USER) private String displayLabel; public Long getId() { @@ -248,23 +254,23 @@ public class CustomerDTO implements AccessMappings, FluentBuilder @Override public String toString() { return "CustomerDTO{" + - "id=" + getId() + - ", reference=" + getReference() + - ", prefix='" + getPrefix() + "'" + - ", name='" + getName() + "'" + - ", kind='" + getKind() + "'" + - ", birthDate='" + getBirthDate() + "'" + - ", birthPlace='" + getBirthPlace() + "'" + - ", registrationCourt='" + getRegistrationCourt() + "'" + - ", registrationNumber='" + getRegistrationNumber() + "'" + - ", vatRegion='" + getVatRegion() + "'" + - ", vatNumber='" + getVatNumber() + "'" + - ", contractualSalutation='" + getContractualSalutation() + "'" + - ", contractualAddress='" + getContractualAddress() + "'" + - ", billingSalutation='" + getBillingSalutation() + "'" + - ", billingAddress='" + getBillingAddress() + "'" + - ", remark='" + getRemark() + "'" + - "}"; + "id=" + getId() + + ", reference=" + getReference() + + ", prefix='" + getPrefix() + "'" + + ", name='" + getName() + "'" + + ", kind='" + getKind() + "'" + + ", birthDate='" + getBirthDate() + "'" + + ", birthPlace='" + getBirthPlace() + "'" + + ", registrationCourt='" + getRegistrationCourt() + "'" + + ", registrationNumber='" + getRegistrationNumber() + "'" + + ", vatRegion='" + getVatRegion() + "'" + + ", vatNumber='" + getVatNumber() + "'" + + ", contractualSalutation='" + getContractualSalutation() + "'" + + ", contractualAddress='" + getContractualAddress() + "'" + + ", billingSalutation='" + getBillingSalutation() + "'" + + ", billingAddress='" + getBillingAddress() + "'" + + ", remark='" + getRemark() + "'" + + "}"; } @JsonComponent @@ -283,4 +289,3 @@ public class CustomerDTO implements AccessMappings, FluentBuilder } } } - diff --git a/src/main/java/org/hostsharing/hsadminng/service/dto/FluentBuilder.java b/src/main/java/org/hostsharing/hsadminng/service/dto/FluentBuilder.java index 7ae8e26b..55b6e87e 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/dto/FluentBuilder.java +++ b/src/main/java/org/hostsharing/hsadminng/service/dto/FluentBuilder.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.dto; import java.util.function.Consumer; @@ -17,18 +18,18 @@ public interface FluentBuilder { * *

Example

* {code - * // adding a fluent builder to your class - * class YourClass implements FluentBuilder { - * public int someField; - * public String anotherField; - * // ... - * } + * // adding a fluent builder to your class + * class YourClass implements FluentBuilder { + * public int someField; + * public String anotherField; + * // ... + * } * - * // using the fluent builder somewhere else - * someMethod( new YourClass().with( it -> { - * it.someField = 5; - * it.anotherField = "Hello"; - * })); + * // using the fluent builder somewhere else + * someMethod( new YourClass().with( it -> { + * it.someField = 5; + * it.anotherField = "Hello"; + * })); * } * * @param builderFunction statements to apply to 'this' @@ -37,10 +38,9 @@ public interface FluentBuilder { */ @SuppressWarnings("unchecked") default T with( - Consumer builderFunction) { + Consumer builderFunction) { builderFunction.accept((T) this); return (T) this; } - } diff --git a/src/main/java/org/hostsharing/hsadminng/service/dto/MembershipCriteria.java b/src/main/java/org/hostsharing/hsadminng/service/dto/MembershipCriteria.java index 14d42ed3..c8ec2bf8 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/dto/MembershipCriteria.java +++ b/src/main/java/org/hostsharing/hsadminng/service/dto/MembershipCriteria.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.dto; import io.github.jhipster.service.filter.Filter; @@ -110,7 +111,6 @@ public class MembershipCriteria implements Serializable { this.customerId = customerId; } - @Override public boolean equals(Object o) { if (this == o) { @@ -120,31 +120,29 @@ public class MembershipCriteria implements Serializable { return false; } final MembershipCriteria that = (MembershipCriteria) o; - return - Objects.equals(id, that.id) && - Objects.equals(admissionDocumentDate, that.admissionDocumentDate) && - Objects.equals(cancellationDocumentDate, that.cancellationDocumentDate) && - Objects.equals(memberFromDate, that.memberFromDate) && - Objects.equals(memberUntilDate, that.memberUntilDate) && - Objects.equals(remark, that.remark) && - Objects.equals(shareId, that.shareId) && - Objects.equals(assetId, that.assetId) && - Objects.equals(customerId, that.customerId); + return Objects.equals(id, that.id) && + Objects.equals(admissionDocumentDate, that.admissionDocumentDate) && + Objects.equals(cancellationDocumentDate, that.cancellationDocumentDate) && + Objects.equals(memberFromDate, that.memberFromDate) && + Objects.equals(memberUntilDate, that.memberUntilDate) && + Objects.equals(remark, that.remark) && + Objects.equals(shareId, that.shareId) && + Objects.equals(assetId, that.assetId) && + Objects.equals(customerId, that.customerId); } @Override public int hashCode() { return Objects.hash( - id, - admissionDocumentDate, - cancellationDocumentDate, - memberFromDate, - memberUntilDate, - remark, - shareId, - assetId, - customerId - ); + id, + admissionDocumentDate, + cancellationDocumentDate, + memberFromDate, + memberUntilDate, + remark, + shareId, + assetId, + customerId); } @Override @@ -159,7 +157,7 @@ public class MembershipCriteria implements Serializable { (shareId != null ? "shareId=" + shareId + ", " : "") + (assetId != null ? "assetId=" + assetId + ", " : "") + (customerId != null ? "customerId=" + customerId + ", " : "") + - "}"; + "}"; } } diff --git a/src/main/java/org/hostsharing/hsadminng/service/dto/MembershipDTO.java b/src/main/java/org/hostsharing/hsadminng/service/dto/MembershipDTO.java index c931ce94..389d9ea4 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/dto/MembershipDTO.java +++ b/src/main/java/org/hostsharing/hsadminng/service/dto/MembershipDTO.java @@ -1,37 +1,40 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.dto; import org.hostsharing.hsadminng.service.CustomerService; import org.hostsharing.hsadminng.service.MembershipService; import org.hostsharing.hsadminng.service.accessfilter.*; + import org.springframework.boot.jackson.JsonComponent; import org.springframework.context.ApplicationContext; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; import java.time.LocalDate; import java.util.Objects; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + /** * A DTO for the Membership entity. */ -public class MembershipDTO implements AccessMappings, FluentBuilder { +public class MembershipDTO implements AccessMappings, FluentBuilder { @SelfId(resolver = MembershipService.class) - @AccessFor(read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private Long id; @NotNull - @AccessFor(init = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private LocalDate admissionDocumentDate; - @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private LocalDate cancellationDocumentDate; @NotNull - @AccessFor(init = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private LocalDate memberFromDate; - @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private LocalDate memberUntilDate; @Size(max = 160) @@ -39,10 +42,10 @@ public class MembershipDTO implements AccessMappings, FluentBuilder { @SelfId(resolver = SepaMandateService.class) - @AccessFor(read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private Long id; @NotNull @Size(max = 40) - @AccessFor(init = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor( + init = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }, + read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private String reference; @Size(max = 34) - @AccessFor(init = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor( + init = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }, + read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private String iban; @Size(max = 11) - @AccessFor(init = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor( + init = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }, + read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private String bic; @NotNull - @AccessFor(init = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor( + init = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }, + read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private LocalDate grantingDocumentDate; - @AccessFor(init = Role.ADMIN, update = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor( + init = Role.ADMIN, + update = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }, + read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private LocalDate revokationDocumentDate; @NotNull - @AccessFor(init = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor( + init = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }, + read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private LocalDate validFromDate; - @AccessFor(init = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, update = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor( + init = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }, + update = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }, + read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private LocalDate validUntilDate; - @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}) + @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = { Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT }) private LocalDate lastUsedDate; @Size(max = 160) @@ -55,10 +74,12 @@ public class SepaMandateDTO implements AccessMappings, FluentBuilder { @Mapping(source = "membership.id", target = "membershipId") diff --git a/src/main/java/org/hostsharing/hsadminng/service/mapper/CustomerMapper.java b/src/main/java/org/hostsharing/hsadminng/service/mapper/CustomerMapper.java index ced8f394..8664992c 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/mapper/CustomerMapper.java +++ b/src/main/java/org/hostsharing/hsadminng/service/mapper/CustomerMapper.java @@ -1,7 +1,9 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.mapper; import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.service.dto.CustomerDTO; + import org.mapstruct.AfterMapping; import org.mapstruct.Mapper; import org.mapstruct.Mapping; @@ -14,8 +16,8 @@ import org.mapstruct.MappingTarget; public interface CustomerMapper extends EntityMapper { static String displayLabel(Customer customer) { - return customer.getName() - + " [" + customer.getReference() + ":" + customer.getPrefix() +"]"; + return customer.getName() + + " [" + customer.getReference() + ":" + customer.getPrefix() + "]"; } @Mapping(target = "displayLabel", ignore = true) diff --git a/src/main/java/org/hostsharing/hsadminng/service/mapper/EntityMapper.java b/src/main/java/org/hostsharing/hsadminng/service/mapper/EntityMapper.java index 65955272..323e6639 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/mapper/EntityMapper.java +++ b/src/main/java/org/hostsharing/hsadminng/service/mapper/EntityMapper.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.mapper; import java.util.List; @@ -9,13 +10,13 @@ import java.util.List; * @param - Entity type parameter. */ -public interface EntityMapper { +public interface EntityMapper { E toEntity(D dto); D toDto(E entity); - List toEntity(List dtoList); + List toEntity(List dtoList); - List toDto(List entityList); + List toDto(List entityList); } diff --git a/src/main/java/org/hostsharing/hsadminng/service/mapper/MembershipMapper.java b/src/main/java/org/hostsharing/hsadminng/service/mapper/MembershipMapper.java index 0ae815e1..36f731f7 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/mapper/MembershipMapper.java +++ b/src/main/java/org/hostsharing/hsadminng/service/mapper/MembershipMapper.java @@ -1,8 +1,10 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.mapper; import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.domain.Membership; import org.hostsharing.hsadminng.service.dto.MembershipDTO; + import org.mapstruct.AfterMapping; import org.mapstruct.Mapper; import org.mapstruct.Mapping; @@ -13,14 +15,14 @@ import java.util.Objects; /** * Mapper for the entity Membership and its DTO MembershipDTO. */ -@Mapper(componentModel = "spring", uses = {CustomerMapper.class}) +@Mapper(componentModel = "spring", uses = { CustomerMapper.class }) public interface MembershipMapper extends EntityMapper { static String displayLabel(final Membership entity) { final Customer customer = entity.getCustomer(); return CustomerMapper.displayLabel(customer) + " " - + Objects.toString(entity.getMemberFromDate(), "") + " - " - + Objects.toString(entity.getMemberUntilDate(), "..."); + + Objects.toString(entity.getMemberFromDate(), "") + " - " + + Objects.toString(entity.getMemberUntilDate(), "..."); } @Mapping(source = "customer.id", target = "customerId") @@ -30,7 +32,7 @@ public interface MembershipMapper extends EntityMapper { @Mapping(source = "customer.id", target = "customerId") diff --git a/src/main/java/org/hostsharing/hsadminng/service/mapper/ShareMapper.java b/src/main/java/org/hostsharing/hsadminng/service/mapper/ShareMapper.java index 80ddc52b..7ec02dca 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/mapper/ShareMapper.java +++ b/src/main/java/org/hostsharing/hsadminng/service/mapper/ShareMapper.java @@ -1,7 +1,9 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.mapper; import org.hostsharing.hsadminng.domain.Share; import org.hostsharing.hsadminng.service.dto.ShareDTO; + import org.mapstruct.AfterMapping; import org.mapstruct.Mapper; import org.mapstruct.Mapping; @@ -10,7 +12,7 @@ import org.mapstruct.MappingTarget; /** * Mapper for the entity Share and its DTO ShareDTO. */ -@Mapper(componentModel = "spring", uses = {MembershipMapper.class}) +@Mapper(componentModel = "spring", uses = { MembershipMapper.class }) public interface ShareMapper extends EntityMapper { @Mapping(source = "membership.id", target = "membershipId") diff --git a/src/main/java/org/hostsharing/hsadminng/service/mapper/UserMapper.java b/src/main/java/org/hostsharing/hsadminng/service/mapper/UserMapper.java index 6bd4de24..5165f884 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/mapper/UserMapper.java +++ b/src/main/java/org/hostsharing/hsadminng/service/mapper/UserMapper.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.mapper; import org.hostsharing.hsadminng.domain.Authority; @@ -20,9 +21,9 @@ public class UserMapper { public List usersToUserDTOs(List users) { return users.stream() - .filter(Objects::nonNull) - .map(this::userToUserDTO) - .collect(Collectors.toList()); + .filter(Objects::nonNull) + .map(this::userToUserDTO) + .collect(Collectors.toList()); } public UserDTO userToUserDTO(User user) { @@ -31,9 +32,9 @@ public class UserMapper { public List userDTOsToUsers(List userDTOs) { return userDTOs.stream() - .filter(Objects::nonNull) - .map(this::userDTOToUser) - .collect(Collectors.toList()); + .filter(Objects::nonNull) + .map(this::userDTOToUser) + .collect(Collectors.toList()); } public User userDTOToUser(UserDTO userDTO) { @@ -55,11 +56,10 @@ public class UserMapper { } } - private Set authoritiesFromStrings(Set authoritiesAsString) { Set authorities = new HashSet<>(); - if(authoritiesAsString != null){ + if (authoritiesAsString != null) { authorities = authoritiesAsString.stream().map(string -> { Authority auth = new Authority(); auth.setName(string); diff --git a/src/main/java/org/hostsharing/hsadminng/service/util/RandomUtil.java b/src/main/java/org/hostsharing/hsadminng/service/util/RandomUtil.java index 122a5cd1..c1f914a4 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/util/RandomUtil.java +++ b/src/main/java/org/hostsharing/hsadminng/service/util/RandomUtil.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.util; import org.apache.commons.lang3.RandomStringUtils; @@ -45,8 +46,8 @@ public final class RandomUtil { * * @return the generated enum value */ - public static > E generateEnumValue(final Class enumType) { + public static > E generateEnumValue(final Class enumType) { final E[] enumValues = enumType.getEnumConstants(); - return enumValues[RandomUtils.nextInt(0, enumValues.length-1)]; + return enumValues[RandomUtils.nextInt(0, enumValues.length - 1)]; } } diff --git a/src/main/java/org/hostsharing/hsadminng/service/util/ReflectionUtil.java b/src/main/java/org/hostsharing/hsadminng/service/util/ReflectionUtil.java index b1cf6e5d..574e098f 100644 --- a/src/main/java/org/hostsharing/hsadminng/service/util/ReflectionUtil.java +++ b/src/main/java/org/hostsharing/hsadminng/service/util/ReflectionUtil.java @@ -1,10 +1,10 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.util; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; - public class ReflectionUtil { public static Field getField(final Class aClass, final String fieldName) { @@ -38,24 +38,32 @@ public class ReflectionUtil { } /** - * Searches the annotations of 'clazz' for an implemented interface 'rawInterface' and returns the class of the actual generics parameter at the specified index. + * Searches the annotations of 'clazz' for an implemented interface 'rawInterface' and returns the class of the actual + * generics parameter at the specified index. * - * @param clazz a class which implements the generic interface 'rawInterface' + * @param clazz a class which implements the generic interface 'rawInterface' * @param rawInterface a generic interface - * @param paramIndex the index of the generics parameter within 'rawInterface' - * @param the expected class of the generics parameter at position 'index' in 'rawInterface' + * @param paramIndex the index of the generics parameter within 'rawInterface' + * @param the expected class of the generics parameter at position 'index' in 'rawInterface' * @return the actual generics parameter */ - public static Class determineGenericInterfaceParameter(final Class clazz, final Class rawInterface, final int paramIndex) { + public static Class determineGenericInterfaceParameter( + final Class clazz, + final Class rawInterface, + final int paramIndex) { final Class found = determineGenericInterfaceParameterImpl(clazz, rawInterface, paramIndex); if (found == null) { - throw new AssertionError(clazz.getSimpleName() + " expected to implement " + rawInterface.getSimpleName() + "<...>"); + throw new AssertionError( + clazz.getSimpleName() + " expected to implement " + rawInterface.getSimpleName() + "<...>"); } return found; } @SuppressWarnings("unchecked") - private static Class determineGenericInterfaceParameterImpl(final Class clazz, final Class rawInterface, final int paramIndex) { + private static Class determineGenericInterfaceParameterImpl( + final Class clazz, + final Class rawInterface, + final int paramIndex) { for (Type genericInterface : clazz.getGenericInterfaces()) { if (genericInterface instanceof ParameterizedType) { final ParameterizedType parameterizedType = (ParameterizedType) genericInterface; @@ -80,15 +88,19 @@ public class ReflectionUtil { } /** - * Searches the annotations of 'clazz' for an extended class 'rawClass' and returns the class of the actual generics parameter at the specified index. + * Searches the annotations of 'clazz' for an extended class 'rawClass' and returns the class of the actual generics + * parameter at the specified index. * - * @param clazz a class which implements the generic interface 'rawClass' - * @param rawClass a generic class + * @param clazz a class which implements the generic interface 'rawClass' + * @param rawClass a generic class * @param paramIndex the index of the generics parameter within 'rawClass' - * @param the expected class of the generics parameter at position 'index' in 'rawClass' + * @param the expected class of the generics parameter at position 'index' in 'rawClass' * @return the actual generics parameter */ - public static Class determineGenericClassParameter(final Class clazz, final Class rawClass, final int paramIndex) { + public static Class determineGenericClassParameter( + final Class clazz, + final Class rawClass, + final int paramIndex) { final Class found = determineGenericClassParameterImpl(clazz, rawClass, paramIndex); if (found == null) { throw new AssertionError(clazz.getSimpleName() + " expected to extend " + rawClass.getSimpleName() + "<...>"); @@ -97,7 +109,10 @@ public class ReflectionUtil { } @SuppressWarnings("unchecked") - private static Class determineGenericClassParameterImpl(final Class clazz, final Class rawClass, final int paramIndex) { + private static Class determineGenericClassParameterImpl( + final Class clazz, + final Class rawClass, + final int paramIndex) { final Type genericClass = clazz.getGenericSuperclass(); if (genericClass instanceof ParameterizedType) { final ParameterizedType parameterizedType = (ParameterizedType) genericClass; @@ -118,6 +133,7 @@ public class ReflectionUtil { @FunctionalInterface public interface ThrowingSupplier { + T get() throws Exception; } diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/AccountResource.java b/src/main/java/org/hostsharing/hsadminng/web/rest/AccountResource.java index f949bd7e..4c0924d2 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/AccountResource.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/AccountResource.java @@ -1,6 +1,6 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; - import org.hostsharing.hsadminng.domain.User; import org.hostsharing.hsadminng.repository.UserRepository; import org.hostsharing.hsadminng.security.SecurityUtils; @@ -18,9 +18,10 @@ import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; +import java.util.*; + import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; -import java.util.*; /** * REST controller for managing the current user's account. @@ -45,7 +46,7 @@ public class AccountResource { } /** - * POST /register : register the user. + * POST /register : register the user. * * @param managedUserVM the managed user View Model * @throws InvalidPasswordException 400 (Bad Request) if the password is incorrect @@ -63,7 +64,7 @@ public class AccountResource { } /** - * GET /activate : activate the registered user. + * GET /activate : activate the registered user. * * @param key the activation key * @throws RuntimeException 500 (Internal Server Error) if the user couldn't be activated @@ -77,7 +78,7 @@ public class AccountResource { } /** - * GET /authenticate : check if the user is authenticated, and return its login. + * GET /authenticate : check if the user is authenticated, and return its login. * * @param request the HTTP request * @return the login if the user is authenticated @@ -89,7 +90,7 @@ public class AccountResource { } /** - * GET /account : get the current user. + * GET /account : get the current user. * * @return the current user * @throws RuntimeException 500 (Internal Server Error) if the user couldn't be returned @@ -97,12 +98,12 @@ public class AccountResource { @GetMapping("/account") public UserDTO getAccount() { return userService.getUserWithAuthorities() - .map(UserDTO::new) - .orElseThrow(() -> new InternalServerErrorException("User could not be found")); + .map(UserDTO::new) + .orElseThrow(() -> new InternalServerErrorException("User could not be found")); } /** - * POST /account : update the current user information. + * POST /account : update the current user information. * * @param userDTO the current user information * @throws EmailAlreadyUsedException 400 (Bad Request) if the email is already used @@ -110,7 +111,8 @@ public class AccountResource { */ @PostMapping("/account") public void saveAccount(@Valid @RequestBody UserDTO userDTO) { - String userLogin = SecurityUtils.getCurrentUserLogin().orElseThrow(() -> new InternalServerErrorException("Current user login not found")); + String userLogin = SecurityUtils.getCurrentUserLogin() + .orElseThrow(() -> new InternalServerErrorException("Current user login not found")); Optional existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userLogin))) { throw new EmailAlreadyUsedException(); @@ -119,12 +121,16 @@ public class AccountResource { if (!user.isPresent()) { throw new InternalServerErrorException("User could not be found"); } - userService.updateUser(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), - userDTO.getLangKey(), userDTO.getImageUrl()); + userService.updateUser( + userDTO.getFirstName(), + userDTO.getLastName(), + userDTO.getEmail(), + userDTO.getLangKey(), + userDTO.getImageUrl()); } /** - * POST /account/change-password : changes the current user's password + * POST /account/change-password : changes the current user's password * * @param passwordChangeDto current and new password * @throws InvalidPasswordException 400 (Bad Request) if the new password is incorrect @@ -138,21 +144,20 @@ public class AccountResource { } /** - * POST /account/reset-password/init : Send an email to reset the password of the user + * POST /account/reset-password/init : Send an email to reset the password of the user * * @param mail the mail of the user * @throws EmailNotFoundException 400 (Bad Request) if the email address is not registered */ @PostMapping(path = "/account/reset-password/init") public void requestPasswordReset(@RequestBody String mail) { - mailService.sendPasswordResetMail( - userService.requestPasswordReset(mail) - .orElseThrow(EmailNotFoundException::new) - ); + mailService.sendPasswordResetMail( + userService.requestPasswordReset(mail) + .orElseThrow(EmailNotFoundException::new)); } /** - * POST /account/reset-password/finish : Finish to reset the password of the user + * POST /account/reset-password/finish : Finish to reset the password of the user * * @param keyAndPassword the generated key and the new password * @throws InvalidPasswordException 400 (Bad Request) if the password is incorrect @@ -163,8 +168,7 @@ public class AccountResource { if (!checkPasswordLength(keyAndPassword.getNewPassword())) { throw new InvalidPasswordException(); } - Optional user = - userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey()); + Optional user = userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey()); if (!user.isPresent()) { throw new InternalServerErrorException("No user was found for this reset key"); @@ -173,7 +177,7 @@ public class AccountResource { private static boolean checkPasswordLength(String password) { return !StringUtils.isEmpty(password) && - password.length() >= ManagedUserVM.PASSWORD_MIN_LENGTH && - password.length() <= ManagedUserVM.PASSWORD_MAX_LENGTH; + password.length() >= ManagedUserVM.PASSWORD_MIN_LENGTH && + password.length() <= ManagedUserVM.PASSWORD_MAX_LENGTH; } } diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/AssetResource.java b/src/main/java/org/hostsharing/hsadminng/web/rest/AssetResource.java index c82ad9a1..ef5ebb17 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/AssetResource.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/AssetResource.java @@ -1,6 +1,6 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; -import io.github.jhipster.web.util.ResponseUtil; import org.hostsharing.hsadminng.service.AssetQueryService; import org.hostsharing.hsadminng.service.AssetService; import org.hostsharing.hsadminng.service.dto.AssetCriteria; @@ -8,6 +8,9 @@ import org.hostsharing.hsadminng.service.dto.AssetDTO; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; import org.hostsharing.hsadminng.web.rest.util.HeaderUtil; import org.hostsharing.hsadminng.web.rest.util.PaginationUtil; + +import io.github.jhipster.web.util.ResponseUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; @@ -16,12 +19,13 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; +import javax.validation.Valid; + /** * REST controller for managing Asset. */ @@ -43,10 +47,11 @@ public class AssetResource { } /** - * POST /assets : Create a new asset. + * POST /assets : Create a new asset. * * @param assetDTO the assetDTO to create - * @return the ResponseEntity with status 201 (Created) and with body the new assetDTO, or with status 400 (Bad Request) if the asset has already an ID + * @return the ResponseEntity with status 201 (Created) and with body the new assetDTO, or with status 400 (Bad Request) if + * the asset has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/assets") @@ -57,17 +62,17 @@ public class AssetResource { } AssetDTO result = assetService.save(assetDTO); return ResponseEntity.created(new URI("/api/assets/" + result.getId())) - .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) - .body(result); + .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) + .body(result); } /** - * PUT /assets : Updates an existing asset. + * PUT /assets : Updates an existing asset. * * @param assetDTO the assetDTO to update * @return the ResponseEntity with status 200 (OK) and with body the updated assetDTO, - * or with status 400 (Bad Request) if the assetDTO is not valid, - * or with status 500 (Internal Server Error) if the assetDTO couldn't be updated + * or with status 400 (Bad Request) if the assetDTO is not valid, + * or with status 500 (Internal Server Error) if the assetDTO couldn't be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/assets") @@ -78,7 +83,7 @@ public class AssetResource { } /** - * GET /assets : get all the assets. + * GET /assets : get all the assets. * * @param pageable the pagination information * @param criteria the criterias which the requested entities should match @@ -93,11 +98,11 @@ public class AssetResource { } /** - * GET /assets/count : count all the assets. - * - * @param criteria the criterias which the requested entities should match - * @return the ResponseEntity with status 200 (OK) and the count in body - */ + * GET /assets/count : count all the assets. + * + * @param criteria the criterias which the requested entities should match + * @return the ResponseEntity with status 200 (OK) and the count in body + */ @GetMapping("/assets/count") public ResponseEntity countAssets(AssetCriteria criteria) { log.debug("REST request to count Assets by criteria: {}", criteria); @@ -105,7 +110,7 @@ public class AssetResource { } /** - * GET /assets/:id : get the "id" asset. + * GET /assets/:id : get the "id" asset. * * @param id the id of the assetDTO to retrieve * @return the ResponseEntity with status 200 (OK) and with body the assetDTO, or with status 404 (Not Found) @@ -118,7 +123,7 @@ public class AssetResource { } /** - * DELETE /assets/:id : delete the "id" asset. + * DELETE /assets/:id : delete the "id" asset. * * @param id the id of the assetDTO to delete * @return the ResponseEntity with status 200 (OK) diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/AuditResource.java b/src/main/java/org/hostsharing/hsadminng/web/rest/AuditResource.java index 91047d1a..e723bf88 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/AuditResource.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/AuditResource.java @@ -1,9 +1,11 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; import org.hostsharing.hsadminng.service.AuditEventService; import org.hostsharing.hsadminng.web.rest.util.PaginationUtil; import io.github.jhipster.web.util.ResponseUtil; + import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -43,29 +45,29 @@ public class AuditResource { } /** - * GET /audits : get a page of AuditEvents between the fromDate and toDate. + * GET /audits : get a page of AuditEvents between the fromDate and toDate. * * @param fromDate the start of the time period of AuditEvents to get * @param toDate the end of the time period of AuditEvents to get * @param pageable the pagination information * @return the ResponseEntity with status 200 (OK) and the list of AuditEvents in body */ - @GetMapping(params = {"fromDate", "toDate"}) + @GetMapping(params = { "fromDate", "toDate" }) public ResponseEntity> getByDates( - @RequestParam(value = "fromDate") LocalDate fromDate, - @RequestParam(value = "toDate") LocalDate toDate, - Pageable pageable) { + @RequestParam(value = "fromDate") LocalDate fromDate, + @RequestParam(value = "toDate") LocalDate toDate, + Pageable pageable) { Page page = auditEventService.findByDates( - fromDate.atStartOfDay(ZoneId.systemDefault()).toInstant(), - toDate.atStartOfDay(ZoneId.systemDefault()).plusDays(1).toInstant(), - pageable); + fromDate.atStartOfDay(ZoneId.systemDefault()).toInstant(), + toDate.atStartOfDay(ZoneId.systemDefault()).plusDays(1).toInstant(), + pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/management/audits"); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } /** - * GET /audits/:id : get an AuditEvent by id. + * GET /audits/:id : get an AuditEvent by id. * * @param id the id of the entity to get * @return the ResponseEntity with status 200 (OK) and the AuditEvent in body, or status 404 (Not Found) diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/CustomerResource.java b/src/main/java/org/hostsharing/hsadminng/web/rest/CustomerResource.java index 6e7e3a81..fe7ee8d7 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/CustomerResource.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/CustomerResource.java @@ -1,6 +1,6 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; -import io.github.jhipster.web.util.ResponseUtil; import org.hostsharing.hsadminng.service.CustomerQueryService; import org.hostsharing.hsadminng.service.CustomerService; import org.hostsharing.hsadminng.service.dto.CustomerCriteria; @@ -8,6 +8,9 @@ import org.hostsharing.hsadminng.service.dto.CustomerDTO; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; import org.hostsharing.hsadminng.web.rest.util.HeaderUtil; import org.hostsharing.hsadminng.web.rest.util.PaginationUtil; + +import io.github.jhipster.web.util.ResponseUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; @@ -16,12 +19,13 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; +import javax.validation.Valid; + /** * REST controller for managing Customer. */ @@ -43,10 +47,11 @@ public class CustomerResource { } /** - * POST /customers : Create a new customer. + * POST /customers : Create a new customer. * * @param customerDTO the customerDTO to create - * @return the ResponseEntity with status 201 (Created) and with body the new customerDTO, or with status 400 (Bad Request) if the customer has already an ID + * @return the ResponseEntity with status 201 (Created) and with body the new customerDTO, or with status 400 (Bad Request) + * if the customer has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/customers") @@ -57,17 +62,17 @@ public class CustomerResource { } CustomerDTO result = customerService.save(customerDTO); return ResponseEntity.created(new URI("/api/customers/" + result.getId())) - .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) - .body(result); + .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) + .body(result); } /** - * PUT /customers : Updates an existing customer. + * PUT /customers : Updates an existing customer. * * @param customerDTO the customerDTO to update * @return the ResponseEntity with status 200 (OK) and with body the updated customerDTO, - * or with status 400 (Bad Request) if the customerDTO is not valid, - * or with status 500 (Internal Server Error) if the customerDTO couldn't be updated + * or with status 400 (Bad Request) if the customerDTO is not valid, + * or with status 500 (Internal Server Error) if the customerDTO couldn't be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/customers") @@ -78,12 +83,12 @@ public class CustomerResource { } CustomerDTO result = customerService.save(customerDTO); return ResponseEntity.ok() - .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, customerDTO.getId().toString())) - .body(result); + .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, customerDTO.getId().toString())) + .body(result); } /** - * GET /customers : get all the customers. + * GET /customers : get all the customers. * * @param pageable the pagination information * @param criteria the criterias which the requested entities should match @@ -98,11 +103,11 @@ public class CustomerResource { } /** - * GET /customers/count : count all the customers. - * - * @param criteria the criterias which the requested entities should match - * @return the ResponseEntity with status 200 (OK) and the count in body - */ + * GET /customers/count : count all the customers. + * + * @param criteria the criterias which the requested entities should match + * @return the ResponseEntity with status 200 (OK) and the count in body + */ @GetMapping("/customers/count") public ResponseEntity countCustomers(CustomerCriteria criteria) { log.debug("REST request to count Customers by criteria: {}", criteria); @@ -110,7 +115,7 @@ public class CustomerResource { } /** - * GET /customers/:id : get the "id" customer. + * GET /customers/:id : get the "id" customer. * * @param id the id of the customerDTO to retrieve * @return the ResponseEntity with status 200 (OK) and with body the customerDTO, or with status 404 (Not Found) @@ -123,7 +128,7 @@ public class CustomerResource { } /** - * DELETE /customers/:id : delete the "id" customer. + * DELETE /customers/:id : delete the "id" customer. * * @param id the id of the customerDTO to delete * @return the ResponseEntity with status 200 (OK) diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/LogsResource.java b/src/main/java/org/hostsharing/hsadminng/web/rest/LogsResource.java index 0c2a0d8a..08315c87 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/LogsResource.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/LogsResource.java @@ -1,9 +1,11 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; import org.hostsharing.hsadminng.web.rest.vm.LoggerVM; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; + import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; @@ -22,9 +24,9 @@ public class LogsResource { public List getList() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); return context.getLoggerList() - .stream() - .map(LoggerVM::new) - .collect(Collectors.toList()); + .stream() + .map(LoggerVM::new) + .collect(Collectors.toList()); } @PutMapping("/logs") diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/MembershipResource.java b/src/main/java/org/hostsharing/hsadminng/web/rest/MembershipResource.java index 795cd59e..ff7d38c2 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/MembershipResource.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/MembershipResource.java @@ -1,6 +1,6 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; -import io.github.jhipster.web.util.ResponseUtil; import org.hostsharing.hsadminng.service.MembershipQueryService; import org.hostsharing.hsadminng.service.MembershipService; import org.hostsharing.hsadminng.service.dto.MembershipCriteria; @@ -8,6 +8,9 @@ import org.hostsharing.hsadminng.service.dto.MembershipDTO; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; import org.hostsharing.hsadminng.web.rest.util.HeaderUtil; import org.hostsharing.hsadminng.web.rest.util.PaginationUtil; + +import io.github.jhipster.web.util.ResponseUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; @@ -16,12 +19,13 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; +import javax.validation.Valid; + /** * REST controller for managing Membership. */ @@ -43,47 +47,50 @@ public class MembershipResource { } /** - * POST /memberships : Create a new membership. + * POST /memberships : Create a new membership. * * @param membershipDTO the membershipDTO to create - * @return the ResponseEntity with status 201 (Created) and with body the new membershipDTO, or with status 400 (Bad Request) if the membership has already an ID + * @return the ResponseEntity with status 201 (Created) and with body the new membershipDTO, or with status 400 (Bad + * Request) if the membership has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/memberships") - public ResponseEntity createMembership(@Valid @RequestBody MembershipDTO membershipDTO) throws URISyntaxException { + public ResponseEntity createMembership(@Valid @RequestBody MembershipDTO membershipDTO) + throws URISyntaxException { log.debug("REST request to save Membership : {}", membershipDTO); if (membershipDTO.getId() != null) { throw new BadRequestAlertException("A new membership cannot already have an ID", ENTITY_NAME, "idexists"); } MembershipDTO result = membershipService.save(membershipDTO); return ResponseEntity.created(new URI("/api/memberships/" + result.getId())) - .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) - .body(result); + .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) + .body(result); } /** - * PUT /memberships : Updates an existing membership. + * PUT /memberships : Updates an existing membership. * * @param membershipDTO the membershipDTO to update * @return the ResponseEntity with status 200 (OK) and with body the updated membershipDTO, - * or with status 400 (Bad Request) if the membershipDTO is not valid, - * or with status 500 (Internal Server Error) if the membershipDTO couldn't be updated + * or with status 400 (Bad Request) if the membershipDTO is not valid, + * or with status 500 (Internal Server Error) if the membershipDTO couldn't be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/memberships") - public ResponseEntity updateMembership(@Valid @RequestBody MembershipDTO membershipDTO) throws URISyntaxException { + public ResponseEntity updateMembership(@Valid @RequestBody MembershipDTO membershipDTO) + throws URISyntaxException { log.debug("REST request to update Membership : {}", membershipDTO); if (membershipDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } MembershipDTO result = membershipService.save(membershipDTO); return ResponseEntity.ok() - .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, membershipDTO.getId().toString())) - .body(result); + .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, membershipDTO.getId().toString())) + .body(result); } /** - * GET /memberships : get all the memberships. + * GET /memberships : get all the memberships. * * @param pageable the pagination information * @param criteria the criterias which the requested entities should match @@ -98,11 +105,11 @@ public class MembershipResource { } /** - * GET /memberships/count : count all the memberships. - * - * @param criteria the criterias which the requested entities should match - * @return the ResponseEntity with status 200 (OK) and the count in body - */ + * GET /memberships/count : count all the memberships. + * + * @param criteria the criterias which the requested entities should match + * @return the ResponseEntity with status 200 (OK) and the count in body + */ @GetMapping("/memberships/count") public ResponseEntity countMemberships(MembershipCriteria criteria) { log.debug("REST request to count Memberships by criteria: {}", criteria); @@ -110,7 +117,7 @@ public class MembershipResource { } /** - * GET /memberships/:id : get the "id" membership. + * GET /memberships/:id : get the "id" membership. * * @param id the id of the membershipDTO to retrieve * @return the ResponseEntity with status 200 (OK) and with body the membershipDTO, or with status 404 (Not Found) @@ -123,7 +130,7 @@ public class MembershipResource { } /** - * DELETE /memberships/:id : delete the "id" membership. + * DELETE /memberships/:id : delete the "id" membership. * * @param id the id of the membershipDTO to delete * @return the ResponseEntity with status 200 (OK) diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/SepaMandateResource.java b/src/main/java/org/hostsharing/hsadminng/web/rest/SepaMandateResource.java index 246d845e..58a1dd27 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/SepaMandateResource.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/SepaMandateResource.java @@ -1,28 +1,31 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; + +import org.hostsharing.hsadminng.service.SepaMandateQueryService; import org.hostsharing.hsadminng.service.SepaMandateService; +import org.hostsharing.hsadminng.service.dto.SepaMandateCriteria; +import org.hostsharing.hsadminng.service.dto.SepaMandateDTO; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; import org.hostsharing.hsadminng.web.rest.util.HeaderUtil; import org.hostsharing.hsadminng.web.rest.util.PaginationUtil; -import org.hostsharing.hsadminng.service.dto.SepaMandateDTO; -import org.hostsharing.hsadminng.service.dto.SepaMandateCriteria; -import org.hostsharing.hsadminng.service.SepaMandateQueryService; + import io.github.jhipster.web.util.ResponseUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; - import java.util.List; import java.util.Optional; +import javax.validation.Valid; + /** * REST controller for managing SepaMandate. */ @@ -44,47 +47,50 @@ public class SepaMandateResource { } /** - * POST /sepa-mandates : Create a new sepaMandate. + * POST /sepa-mandates : Create a new sepaMandate. * * @param sepaMandateDTO the sepaMandateDTO to create - * @return the ResponseEntity with status 201 (Created) and with body the new sepaMandateDTO, or with status 400 (Bad Request) if the sepaMandate has already an ID + * @return the ResponseEntity with status 201 (Created) and with body the new sepaMandateDTO, or with status 400 (Bad + * Request) if the sepaMandate has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/sepa-mandates") - public ResponseEntity createSepaMandate(@Valid @RequestBody SepaMandateDTO sepaMandateDTO) throws URISyntaxException { + public ResponseEntity createSepaMandate(@Valid @RequestBody SepaMandateDTO sepaMandateDTO) + throws URISyntaxException { log.debug("REST request to save SepaMandate : {}", sepaMandateDTO); if (sepaMandateDTO.getId() != null) { throw new BadRequestAlertException("A new sepaMandate cannot already have an ID", ENTITY_NAME, "idexists"); } SepaMandateDTO result = sepaMandateService.save(sepaMandateDTO); return ResponseEntity.created(new URI("/api/sepa-mandates/" + result.getId())) - .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) - .body(result); + .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) + .body(result); } /** - * PUT /sepa-mandates : Updates an existing sepaMandate. + * PUT /sepa-mandates : Updates an existing sepaMandate. * * @param sepaMandateDTO the sepaMandateDTO to update * @return the ResponseEntity with status 200 (OK) and with body the updated sepaMandateDTO, - * or with status 400 (Bad Request) if the sepaMandateDTO is not valid, - * or with status 500 (Internal Server Error) if the sepaMandateDTO couldn't be updated + * or with status 400 (Bad Request) if the sepaMandateDTO is not valid, + * or with status 500 (Internal Server Error) if the sepaMandateDTO couldn't be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/sepa-mandates") - public ResponseEntity updateSepaMandate(@Valid @RequestBody SepaMandateDTO sepaMandateDTO) throws URISyntaxException { + public ResponseEntity updateSepaMandate(@Valid @RequestBody SepaMandateDTO sepaMandateDTO) + throws URISyntaxException { log.debug("REST request to update SepaMandate : {}", sepaMandateDTO); if (sepaMandateDTO.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } SepaMandateDTO result = sepaMandateService.save(sepaMandateDTO); return ResponseEntity.ok() - .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, sepaMandateDTO.getId().toString())) - .body(result); + .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, sepaMandateDTO.getId().toString())) + .body(result); } /** - * GET /sepa-mandates : get all the sepaMandates. + * GET /sepa-mandates : get all the sepaMandates. * * @param pageable the pagination information * @param criteria the criterias which the requested entities should match @@ -99,11 +105,11 @@ public class SepaMandateResource { } /** - * GET /sepa-mandates/count : count all the sepaMandates. - * - * @param criteria the criterias which the requested entities should match - * @return the ResponseEntity with status 200 (OK) and the count in body - */ + * GET /sepa-mandates/count : count all the sepaMandates. + * + * @param criteria the criterias which the requested entities should match + * @return the ResponseEntity with status 200 (OK) and the count in body + */ @GetMapping("/sepa-mandates/count") public ResponseEntity countSepaMandates(SepaMandateCriteria criteria) { log.debug("REST request to count SepaMandates by criteria: {}", criteria); @@ -111,7 +117,7 @@ public class SepaMandateResource { } /** - * GET /sepa-mandates/:id : get the "id" sepaMandate. + * GET /sepa-mandates/:id : get the "id" sepaMandate. * * @param id the id of the sepaMandateDTO to retrieve * @return the ResponseEntity with status 200 (OK) and with body the sepaMandateDTO, or with status 404 (Not Found) @@ -124,7 +130,7 @@ public class SepaMandateResource { } /** - * DELETE /sepa-mandates/:id : delete the "id" sepaMandate. + * DELETE /sepa-mandates/:id : delete the "id" sepaMandate. * * @param id the id of the sepaMandateDTO to delete * @return the ResponseEntity with status 200 (OK) diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/ShareResource.java b/src/main/java/org/hostsharing/hsadminng/web/rest/ShareResource.java index 64bc8430..f34d0ccb 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/ShareResource.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/ShareResource.java @@ -1,6 +1,6 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; -import io.github.jhipster.web.util.ResponseUtil; import org.hostsharing.hsadminng.service.ShareQueryService; import org.hostsharing.hsadminng.service.ShareService; import org.hostsharing.hsadminng.service.dto.ShareCriteria; @@ -8,6 +8,9 @@ import org.hostsharing.hsadminng.service.dto.ShareDTO; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; import org.hostsharing.hsadminng.web.rest.util.HeaderUtil; import org.hostsharing.hsadminng.web.rest.util.PaginationUtil; + +import io.github.jhipster.web.util.ResponseUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; @@ -16,12 +19,13 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; +import javax.validation.Valid; + /** * REST controller for managing Share. */ @@ -43,10 +47,11 @@ public class ShareResource { } /** - * POST /shares : Create a new share. + * POST /shares : Create a new share. * * @param shareDTO the shareDTO to create - * @return the ResponseEntity with status 201 (Created) and with body the new shareDTO, or with status 400 (Bad Request) if the share has already an ID + * @return the ResponseEntity with status 201 (Created) and with body the new shareDTO, or with status 400 (Bad Request) if + * the share has already an ID * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/shares") @@ -57,17 +62,17 @@ public class ShareResource { } ShareDTO result = shareService.save(shareDTO); return ResponseEntity.created(new URI("/api/shares/" + result.getId())) - .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) - .body(result); + .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString())) + .body(result); } /** - * PUT /shares : Updates an existing share. + * PUT /shares : Updates an existing share. * * @param shareDTO the shareDTO to update * @return the ResponseEntity with status 200 (OK) and with body the updated shareDTO, - * or with status 400 (Bad Request) if the shareDTO is not valid, - * or with status 500 (Internal Server Error) if the shareDTO couldn't be updated + * or with status 400 (Bad Request) if the shareDTO is not valid, + * or with status 500 (Internal Server Error) if the shareDTO couldn't be updated * @throws URISyntaxException if the Location URI syntax is incorrect */ @PutMapping("/shares") @@ -78,7 +83,7 @@ public class ShareResource { } /** - * GET /shares : get all the shares. + * GET /shares : get all the shares. * * @param pageable the pagination information * @param criteria the criterias which the requested entities should match @@ -93,11 +98,11 @@ public class ShareResource { } /** - * GET /shares/count : count all the shares. - * - * @param criteria the criterias which the requested entities should match - * @return the ResponseEntity with status 200 (OK) and the count in body - */ + * GET /shares/count : count all the shares. + * + * @param criteria the criterias which the requested entities should match + * @return the ResponseEntity with status 200 (OK) and the count in body + */ @GetMapping("/shares/count") public ResponseEntity countShares(ShareCriteria criteria) { log.debug("REST request to count Shares by criteria: {}", criteria); @@ -105,7 +110,7 @@ public class ShareResource { } /** - * GET /shares/:id : get the "id" share. + * GET /shares/:id : get the "id" share. * * @param id the id of the shareDTO to retrieve * @return the ResponseEntity with status 200 (OK) and with body the shareDTO, or with status 404 (Not Found) @@ -118,7 +123,7 @@ public class ShareResource { } /** - * DELETE /shares/:id : delete the "id" share. + * DELETE /shares/:id : delete the "id" share. * * @param id the id of the shareDTO to delete * @return the ResponseEntity with status 200 (OK) diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/UserJWTController.java b/src/main/java/org/hostsharing/hsadminng/web/rest/UserJWTController.java index b2d33946..db3ef0ff 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/UserJWTController.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/UserJWTController.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; import org.hostsharing.hsadminng.security.jwt.JWTFilter; @@ -36,8 +37,9 @@ public class UserJWTController { @PostMapping("/authenticate") public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM) { - UsernamePasswordAuthenticationToken authenticationToken = - new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword()); + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( + loginVM.getUsername(), + loginVM.getPassword()); Authentication authentication = this.authenticationManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/UserResource.java b/src/main/java/org/hostsharing/hsadminng/web/rest/UserResource.java index 97edaedd..eaff107e 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/UserResource.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/UserResource.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; import org.hostsharing.hsadminng.config.Constants; @@ -12,6 +13,7 @@ import org.hostsharing.hsadminng.web.rest.errors.EmailAlreadyUsedException; import org.hostsharing.hsadminng.web.rest.errors.LoginAlreadyUsedException; import org.hostsharing.hsadminng.web.rest.util.HeaderUtil; import org.hostsharing.hsadminng.web.rest.util.PaginationUtil; + import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; @@ -24,11 +26,12 @@ import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; -import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.*; +import javax.validation.Valid; + /** * REST controller for managing users. *

@@ -44,11 +47,11 @@ import java.util.*; * quite often do relationships with the user, and we don't want them to get the authorities all * the time for nothing (for performance reasons). This is the #1 goal: we should not impact our users' * application because of this use-case. - *

  • Not having an outer join causes n+1 requests to the database. This is not a real issue as + *
  • Not having an outer join causes n+1 requests to the database. This is not a real issue as * we have by default a second-level cache. This means on the first HTTP call we do the n+1 requests, * but then all authorities come from the cache, so in fact it's much better than doing an outer join * (which will get lots of data from the database, for each HTTP call).
  • - *
  • As this manages users, for security reasons, we'd rather have a DTO layer.
  • + *
  • As this manages users, for security reasons, we'd rather have a DTO layer.
  • * *

    * Another option would be to have a specific JPA entity graph to handle this case. @@ -73,14 +76,15 @@ public class UserResource { } /** - * POST /users : Creates a new user. + * POST /users : Creates a new user. *

    * Creates a new user if the login and email are not already used, and sends an * mail with an activation link. * The user needs to be activated on creation. * * @param userDTO the user to create - * @return the ResponseEntity with status 201 (Created) and with body the new user, or with status 400 (Bad Request) if the login or email is already in use + * @return the ResponseEntity with status 201 (Created) and with body the new user, or with status 400 (Bad Request) if the + * login or email is already in use * @throws URISyntaxException if the Location URI syntax is incorrect * @throws BadRequestAlertException 400 (Bad Request) if the login or email is already in use */ @@ -100,8 +104,8 @@ public class UserResource { User newUser = userService.createUser(userDTO); mailService.sendCreationEmail(newUser); return ResponseEntity.created(new URI("/api/users/" + newUser.getLogin())) - .headers(HeaderUtil.createAlert( "userManagement.created", newUser.getLogin())) - .body(newUser); + .headers(HeaderUtil.createAlert("userManagement.created", newUser.getLogin())) + .body(newUser); } } @@ -127,8 +131,9 @@ public class UserResource { } Optional updatedUser = userService.updateUser(userDTO); - return ResponseUtil.wrapOrNotFound(updatedUser, - HeaderUtil.createAlert("userManagement.updated", userDTO.getLogin())); + return ResponseUtil.wrapOrNotFound( + updatedUser, + HeaderUtil.createAlert("userManagement.updated", userDTO.getLogin())); } /** @@ -163,8 +168,8 @@ public class UserResource { public ResponseEntity getUser(@PathVariable String login) { log.debug("REST request to get User : {}", login); return ResponseUtil.wrapOrNotFound( - userService.getUserWithAuthoritiesByLogin(login) - .map(UserDTO::new)); + userService.getUserWithAuthoritiesByLogin(login) + .map(UserDTO::new)); } /** @@ -178,6 +183,6 @@ public class UserResource { public ResponseEntity deleteUser(@PathVariable String login) { log.debug("REST request to delete User: {}", login); userService.deleteUser(login); - return ResponseEntity.ok().headers(HeaderUtil.createAlert( "userManagement.deleted", login)).build(); + return ResponseEntity.ok().headers(HeaderUtil.createAlert("userManagement.deleted", login)).build(); } } diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/BadRequestAlertException.java b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/BadRequestAlertException.java index f395377a..eb87b2ef 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/BadRequestAlertException.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/BadRequestAlertException.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/CustomParameterizedException.java b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/CustomParameterizedException.java index 8b7fb8e9..359e1d8b 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/CustomParameterizedException.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/CustomParameterizedException.java @@ -1,12 +1,13 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.errors; +import static org.zalando.problem.Status.BAD_REQUEST; + import org.zalando.problem.AbstractThrowableProblem; import java.util.HashMap; import java.util.Map; -import static org.zalando.problem.Status.BAD_REQUEST; - /** * Custom, parameterized exception, which can be translated on the client side. * For example: @@ -32,7 +33,13 @@ public class CustomParameterizedException extends AbstractThrowableProblem { } public CustomParameterizedException(String message, Map paramMap) { - super(ErrorConstants.PARAMETERIZED_TYPE, "Parameterized Exception", BAD_REQUEST, null, null, null, toProblemParameters(message, paramMap)); + super(ErrorConstants.PARAMETERIZED_TYPE, + "Parameterized Exception", + BAD_REQUEST, + null, + null, + null, + toProblemParameters(message, paramMap)); } public static Map toParamMap(String... params) { diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/EmailAlreadyUsedException.java b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/EmailAlreadyUsedException.java index 1ec0f3c1..473297c1 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/EmailAlreadyUsedException.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/EmailAlreadyUsedException.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.errors; public class EmailAlreadyUsedException extends BadRequestAlertException { diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/EmailNotFoundException.java b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/EmailNotFoundException.java index c4393c60..31ffcade 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/EmailNotFoundException.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/EmailNotFoundException.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/ErrorConstants.java b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/ErrorConstants.java index 2a9f016f..fff79e48 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/ErrorConstants.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/ErrorConstants.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.errors; import java.net.URI; diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/ExceptionTranslator.java b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/ExceptionTranslator.java index ea414e84..5aa2a5b9 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/ExceptionTranslator.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/ExceptionTranslator.java @@ -1,5 +1,8 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.errors; +import static org.hostsharing.hsadminng.web.rest.errors.ErrorConstants.*; + import org.hostsharing.hsadminng.web.rest.util.HeaderUtil; import org.springframework.dao.ConcurrencyFailureException; @@ -20,14 +23,13 @@ import org.zalando.problem.Status; import org.zalando.problem.spring.web.advice.ProblemHandling; import org.zalando.problem.violations.ConstraintViolationProblem; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.NoSuchElementException; import java.util.stream.Collectors; -import static org.hostsharing.hsadminng.web.rest.errors.ErrorConstants.*; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.servlet.http.HttpServletRequest; /** * Controller advice to translate the server side exceptions to client-friendly json structures. @@ -54,20 +56,20 @@ public class ExceptionTranslator implements ProblemHandling { return entity; } ProblemBuilder builder = Problem.builder() - .withType(Problem.DEFAULT_TYPE.equals(problem.getType()) ? DEFAULT_TYPE : problem.getType()) - .withStatus(problem.getStatus()) - .withTitle(problem.getTitle()) - .with(PATH_KEY, request.getNativeRequest(HttpServletRequest.class).getRequestURI()); + .withType(Problem.DEFAULT_TYPE.equals(problem.getType()) ? DEFAULT_TYPE : problem.getType()) + .withStatus(problem.getStatus()) + .withTitle(problem.getTitle()) + .with(PATH_KEY, request.getNativeRequest(HttpServletRequest.class).getRequestURI()); if (problem instanceof ConstraintViolationProblem) { builder - .with(VIOLATIONS_KEY, ((ConstraintViolationProblem) problem).getViolations()) - .with(MESSAGE_KEY, ERR_VALIDATION); + .with(VIOLATIONS_KEY, ((ConstraintViolationProblem) problem).getViolations()) + .with(MESSAGE_KEY, ERR_VALIDATION); } else { builder - .withCause(((DefaultProblem) problem).getCause()) - .withDetail(problem.getDetail()) - .withInstance(problem.getInstance()); + .withCause(((DefaultProblem) problem).getCause()) + .withDetail(problem.getDetail()) + .withInstance(problem.getInstance()); problem.getParameters().forEach(builder::with); if (!problem.getParameters().containsKey(MESSAGE_KEY) && problem.getStatus() != null) { builder.with(MESSAGE_KEY, "error.http." + problem.getStatus().getStatusCode()); @@ -77,28 +79,31 @@ public class ExceptionTranslator implements ProblemHandling { } @Override - public ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) { + public ResponseEntity handleMethodArgumentNotValid( + MethodArgumentNotValidException ex, + @Nonnull NativeWebRequest request) { BindingResult result = ex.getBindingResult(); - List fieldErrors = result.getFieldErrors().stream() - .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode())) - .collect(Collectors.toList()); + List fieldErrors = result.getFieldErrors() + .stream() + .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode())) + .collect(Collectors.toList()); Problem problem = Problem.builder() - .withType(CONSTRAINT_VIOLATION_TYPE) - .withTitle("Method argument not valid") - .withStatus(defaultConstraintViolationStatus()) - .with(MESSAGE_KEY, ERR_VALIDATION) - .with(FIELD_ERRORS_KEY, fieldErrors) - .build(); + .withType(CONSTRAINT_VIOLATION_TYPE) + .withTitle("Method argument not valid") + .withStatus(defaultConstraintViolationStatus()) + .with(MESSAGE_KEY, ERR_VALIDATION) + .with(FIELD_ERRORS_KEY, fieldErrors) + .build(); return create(ex, problem, request); } @ExceptionHandler public ResponseEntity handleNoSuchElementException(NoSuchElementException ex, NativeWebRequest request) { Problem problem = Problem.builder() - .withStatus(Status.NOT_FOUND) - .with(MESSAGE_KEY, ENTITY_NOT_FOUND_TYPE) - .build(); + .withStatus(Status.NOT_FOUND) + .with(MESSAGE_KEY, ENTITY_NOT_FOUND_TYPE) + .build(); return create(ex, problem, request); } @@ -110,21 +115,23 @@ public class ExceptionTranslator implements ProblemHandling { @ExceptionHandler public ResponseEntity handleConcurrencyFailure(ConcurrencyFailureException ex, NativeWebRequest request) { Problem problem = Problem.builder() - .withStatus(Status.CONFLICT) - .with(MESSAGE_KEY, ERR_CONCURRENCY_FAILURE) - .build(); + .withStatus(Status.CONFLICT) + .with(MESSAGE_KEY, ERR_CONCURRENCY_FAILURE) + .build(); return create(ex, problem, request); } @ExceptionHandler(DataIntegrityViolationException.class) @ResponseBody @ResponseStatus(HttpStatus.CONFLICT) - public ResponseEntity processDataIntegrityViolationException(DataIntegrityViolationException exception, NativeWebRequest request) { + public ResponseEntity processDataIntegrityViolationException( + DataIntegrityViolationException exception, + NativeWebRequest request) { // UX_CUSTOMER_JHI_NUMBER_INDEX_5 Problem problem = Problem.builder() - .withStatus(Status.CONFLICT) - .with(MESSAGE_KEY, ERR_VALIDATION_DUPLICATE) - .build(); + .withStatus(Status.CONFLICT) + .with(MESSAGE_KEY, ERR_VALIDATION_DUPLICATE) + .build(); return create(exception, problem, request); } } diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/FieldErrorVM.java b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/FieldErrorVM.java index e95700c4..353102ec 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/FieldErrorVM.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/FieldErrorVM.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.errors; import java.io.Serializable; diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/InternalServerErrorException.java b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/InternalServerErrorException.java index f8bb283f..3221fcca 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/InternalServerErrorException.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/InternalServerErrorException.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/InvalidPasswordException.java b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/InvalidPasswordException.java index 56297f16..e04b0b98 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/InvalidPasswordException.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/InvalidPasswordException.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.errors; import org.zalando.problem.AbstractThrowableProblem; diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/LoginAlreadyUsedException.java b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/LoginAlreadyUsedException.java index e28fc705..44d82faf 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/errors/LoginAlreadyUsedException.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/errors/LoginAlreadyUsedException.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.errors; public class LoginAlreadyUsedException extends BadRequestAlertException { diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/util/HeaderUtil.java b/src/main/java/org/hostsharing/hsadminng/web/rest/util/HeaderUtil.java index 4f977822..3771468d 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/util/HeaderUtil.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/util/HeaderUtil.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.util; import org.slf4j.Logger; diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/util/PaginationUtil.java b/src/main/java/org/hostsharing/hsadminng/web/rest/util/PaginationUtil.java index 2c2c15b3..bcd04789 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/util/PaginationUtil.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/util/PaginationUtil.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.util; import org.springframework.data.domain.Page; diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/vm/KeyAndPasswordVM.java b/src/main/java/org/hostsharing/hsadminng/web/rest/vm/KeyAndPasswordVM.java index c2aad359..8d85d8ef 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/vm/KeyAndPasswordVM.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/vm/KeyAndPasswordVM.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.vm; /** diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/vm/LoggerVM.java b/src/main/java/org/hostsharing/hsadminng/web/rest/vm/LoggerVM.java index cc2ed9eb..edc032c2 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/vm/LoggerVM.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/vm/LoggerVM.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.vm; import ch.qos.logback.classic.Logger; @@ -39,8 +40,8 @@ public class LoggerVM { @Override public String toString() { return "LoggerVM{" + - "name='" + name + '\'' + - ", level='" + level + '\'' + - '}'; + "name='" + name + '\'' + + ", level='" + level + '\'' + + '}'; } } diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/vm/LoginVM.java b/src/main/java/org/hostsharing/hsadminng/web/rest/vm/LoginVM.java index c04410d9..951c7d46 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/vm/LoginVM.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/vm/LoginVM.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.vm; import javax.validation.constraints.NotNull; @@ -45,8 +46,8 @@ public class LoginVM { @Override public String toString() { return "LoginVM{" + - "username='" + username + '\'' + - ", rememberMe=" + rememberMe + - '}'; + "username='" + username + '\'' + + ", rememberMe=" + rememberMe + + '}'; } } diff --git a/src/main/java/org/hostsharing/hsadminng/web/rest/vm/ManagedUserVM.java b/src/main/java/org/hostsharing/hsadminng/web/rest/vm/ManagedUserVM.java index 39f7bd25..08005ceb 100644 --- a/src/main/java/org/hostsharing/hsadminng/web/rest/vm/ManagedUserVM.java +++ b/src/main/java/org/hostsharing/hsadminng/web/rest/vm/ManagedUserVM.java @@ -1,6 +1,8 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.vm; import org.hostsharing.hsadminng.service.dto.UserDTO; + import javax.validation.constraints.Size; /** @@ -30,6 +32,6 @@ public class ManagedUserVM extends UserDTO { @Override public String toString() { return "ManagedUserVM{" + - "} " + super.toString(); + "} " + super.toString(); } } diff --git a/src/test/java/org/hostsharing/hsadminng/config/WebConfigurerTest.java b/src/test/java/org/hostsharing/hsadminng/config/WebConfigurerTest.java index 0bdc442b..bd2b6447 100644 --- a/src/test/java/org/hostsharing/hsadminng/config/WebConfigurerTest.java +++ b/src/test/java/org/hostsharing/hsadminng/config/WebConfigurerTest.java @@ -1,13 +1,23 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.JHipsterProperties; import io.github.jhipster.web.filter.CachingHttpHeadersFilter; import io.undertow.Undertow; import io.undertow.Undertow.Builder; import io.undertow.UndertowOptions; -import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.FilenameUtils; import org.h2.server.web.WebServlet; import org.junit.Before; import org.junit.Test; @@ -20,17 +30,9 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.xnio.OptionMap; -import javax.servlet.*; import java.util.*; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import javax.servlet.*; /** * Unit tests for the WebConfigurer class. @@ -51,9 +53,11 @@ public class WebConfigurerTest { public void setup() { servletContext = spy(new MockServletContext()); doReturn(mock(FilterRegistration.Dynamic.class)) - .when(servletContext).addFilter(anyString(), any(Filter.class)); + .when(servletContext) + .addFilter(anyString(), any(Filter.class)); doReturn(mock(ServletRegistration.Dynamic.class)) - .when(servletContext).addServlet(anyString(), any(Servlet.class)); + .when(servletContext) + .addServlet(anyString(), any(Servlet.class)); env = new MockEnvironment(); props = new JHipsterProperties(); @@ -117,25 +121,25 @@ public class WebConfigurerTest { props.getCors().setAllowCredentials(true); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) - .addFilters(webConfigurer.corsFilter()) - .build(); + .addFilters(webConfigurer.corsFilter()) + .build(); mockMvc.perform( - options("/api/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")) - .andExpect(status().isOk()) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")) - .andExpect(header().string(HttpHeaders.VARY, "Origin")) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); + options("/api/test-cors") + .header(HttpHeaders.ORIGIN, "other.domain.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")) + .andExpect(header().string(HttpHeaders.VARY, "Origin")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); mockMvc.perform( - get("/api/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com")) - .andExpect(status().isOk()) - .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")); + get("/api/test-cors") + .header(HttpHeaders.ORIGIN, "other.domain.com")) + .andExpect(status().isOk()) + .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")); } @Test @@ -147,14 +151,14 @@ public class WebConfigurerTest { props.getCors().setAllowCredentials(true); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) - .addFilters(webConfigurer.corsFilter()) - .build(); + .addFilters(webConfigurer.corsFilter()) + .build(); mockMvc.perform( - get("/test/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com")) - .andExpect(status().isOk()) - .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + get("/test/test-cors") + .header(HttpHeaders.ORIGIN, "other.domain.com")) + .andExpect(status().isOk()) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); } @Test @@ -162,14 +166,14 @@ public class WebConfigurerTest { props.getCors().setAllowedOrigins(null); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) - .addFilters(webConfigurer.corsFilter()) - .build(); + .addFilters(webConfigurer.corsFilter()) + .build(); mockMvc.perform( - get("/api/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com")) - .andExpect(status().isOk()) - .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + get("/api/test-cors") + .header(HttpHeaders.ORIGIN, "other.domain.com")) + .andExpect(status().isOk()) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); } @Test @@ -177,13 +181,13 @@ public class WebConfigurerTest { props.getCors().setAllowedOrigins(new ArrayList<>()); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) - .addFilters(webConfigurer.corsFilter()) - .build(); + .addFilters(webConfigurer.corsFilter()) + .build(); mockMvc.perform( - get("/api/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com")) - .andExpect(status().isOk()) - .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); + get("/api/test-cors") + .header(HttpHeaders.ORIGIN, "other.domain.com")) + .andExpect(status().isOk()) + .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); } } diff --git a/src/test/java/org/hostsharing/hsadminng/config/WebConfigurerTestController.java b/src/test/java/org/hostsharing/hsadminng/config/WebConfigurerTestController.java index 1bd28fba..c866cd51 100644 --- a/src/test/java/org/hostsharing/hsadminng/config/WebConfigurerTestController.java +++ b/src/test/java/org/hostsharing/hsadminng/config/WebConfigurerTestController.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config; import org.springframework.web.bind.annotation.GetMapping; diff --git a/src/test/java/org/hostsharing/hsadminng/config/timezone/HibernateTimeZoneTest.java b/src/test/java/org/hostsharing/hsadminng/config/timezone/HibernateTimeZoneTest.java index d25dc34d..bc81adb9 100644 --- a/src/test/java/org/hostsharing/hsadminng/config/timezone/HibernateTimeZoneTest.java +++ b/src/test/java/org/hostsharing/hsadminng/config/timezone/HibernateTimeZoneTest.java @@ -1,8 +1,13 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.config.timezone; +import static java.lang.String.format; +import static org.assertj.core.api.Assertions.assertThat; + import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.repository.timezone.DateTimeWrapper; import org.hostsharing.hsadminng.repository.timezone.DateTimeWrapperRepository; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,9 +21,6 @@ import org.springframework.transaction.annotation.Transactional; import java.time.*; import java.time.format.DateTimeFormatter; -import static java.lang.String.format; -import static org.assertj.core.api.Assertions.assertThat; - /** * Unit tests for the UTC Hibernate configuration. */ @@ -48,15 +50,15 @@ public class HibernateTimeZoneTest { dateTimeWrapper.setLocalDate(LocalDate.parse("2016-09-10")); dateTimeFormatter = DateTimeFormatter - .ofPattern("yyyy-MM-dd HH:mm:ss.S") - .withZone(ZoneId.of("UTC")); + .ofPattern("yyyy-MM-dd HH:mm:ss.S") + .withZone(ZoneId.of("UTC")); timeFormatter = DateTimeFormatter - .ofPattern("HH:mm:ss") - .withZone(ZoneId.of("UTC")); + .ofPattern("HH:mm:ss") + .withZone(ZoneId.of("UTC")); dateFormatter = DateTimeFormatter - .ofPattern("yyyy-MM-dd"); + .ofPattern("yyyy-MM-dd"); } @Test @@ -79,9 +81,9 @@ public class HibernateTimeZoneTest { String request = generateSqlRequest("local_date_time", dateTimeWrapper.getId()); SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); String expectedValue = dateTimeWrapper - .getLocalDateTime() - .atZone(ZoneId.systemDefault()) - .format(dateTimeFormatter); + .getLocalDateTime() + .atZone(ZoneId.systemDefault()) + .format(dateTimeFormatter); assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); } @@ -94,8 +96,8 @@ public class HibernateTimeZoneTest { String request = generateSqlRequest("offset_date_time", dateTimeWrapper.getId()); SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); String expectedValue = dateTimeWrapper - .getOffsetDateTime() - .format(dateTimeFormatter); + .getOffsetDateTime() + .format(dateTimeFormatter); assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); } @@ -108,8 +110,8 @@ public class HibernateTimeZoneTest { String request = generateSqlRequest("zoned_date_time", dateTimeWrapper.getId()); SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); String expectedValue = dateTimeWrapper - .getZonedDateTime() - .format(dateTimeFormatter); + .getZonedDateTime() + .format(dateTimeFormatter); assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); } @@ -122,10 +124,10 @@ public class HibernateTimeZoneTest { String request = generateSqlRequest("local_time", dateTimeWrapper.getId()); SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); String expectedValue = dateTimeWrapper - .getLocalTime() - .atDate(LocalDate.of(1970, Month.JANUARY, 1)) - .atZone(ZoneId.systemDefault()) - .format(timeFormatter); + .getLocalTime() + .atDate(LocalDate.of(1970, Month.JANUARY, 1)) + .atZone(ZoneId.systemDefault()) + .format(timeFormatter); assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); } @@ -138,11 +140,11 @@ public class HibernateTimeZoneTest { String request = generateSqlRequest("offset_time", dateTimeWrapper.getId()); SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); String expectedValue = dateTimeWrapper - .getOffsetTime() - .toLocalTime() - .atDate(LocalDate.of(1970, Month.JANUARY, 1)) - .atZone(ZoneId.systemDefault()) - .format(timeFormatter); + .getOffsetTime() + .toLocalTime() + .atDate(LocalDate.of(1970, Month.JANUARY, 1)) + .atZone(ZoneId.systemDefault()) + .format(timeFormatter); assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); } @@ -155,8 +157,8 @@ public class HibernateTimeZoneTest { String request = generateSqlRequest("local_date", dateTimeWrapper.getId()); SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); String expectedValue = dateTimeWrapper - .getLocalDate() - .format(dateFormatter); + .getLocalDate() + .format(dateFormatter); assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue); } diff --git a/src/test/java/org/hostsharing/hsadminng/cucumber/CucumberContextConfiguration.java b/src/test/java/org/hostsharing/hsadminng/cucumber/CucumberContextConfiguration.java index cf6a0726..09ebc4bc 100644 --- a/src/test/java/org/hostsharing/hsadminng/cucumber/CucumberContextConfiguration.java +++ b/src/test/java/org/hostsharing/hsadminng/cucumber/CucumberContextConfiguration.java @@ -1,7 +1,10 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.cucumber; import org.hostsharing.hsadminng.HsadminNgApp; + import cucumber.api.java.Before; + import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.web.WebAppConfiguration; @@ -12,7 +15,7 @@ import org.springframework.test.context.web.WebAppConfiguration; public class CucumberContextConfiguration { @Before - public void setup_cucumber_spring_context(){ + public void setup_cucumber_spring_context() { // Dummy method so cucumber will recognize this class as glue // and use its context configuration. } diff --git a/src/test/java/org/hostsharing/hsadminng/cucumber/CucumberTest.java b/src/test/java/org/hostsharing/hsadminng/cucumber/CucumberTest.java index c70c13c3..5d292157 100644 --- a/src/test/java/org/hostsharing/hsadminng/cucumber/CucumberTest.java +++ b/src/test/java/org/hostsharing/hsadminng/cucumber/CucumberTest.java @@ -1,13 +1,13 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.cucumber; -import org.junit.runner.RunWith; - - import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; +import org.junit.runner.RunWith; + @RunWith(Cucumber.class) @CucumberOptions(plugin = "pretty", features = "src/test/features") -public class CucumberTest { +public class CucumberTest { } diff --git a/src/test/java/org/hostsharing/hsadminng/cucumber/stepdefs/StepDefs.java b/src/test/java/org/hostsharing/hsadminng/cucumber/stepdefs/StepDefs.java index 65ee919c..1d0ea7a4 100644 --- a/src/test/java/org/hostsharing/hsadminng/cucumber/stepdefs/StepDefs.java +++ b/src/test/java/org/hostsharing/hsadminng/cucumber/stepdefs/StepDefs.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.cucumber.stepdefs; import org.springframework.test.web.servlet.ResultActions; diff --git a/src/test/java/org/hostsharing/hsadminng/cucumber/stepdefs/UserStepDefs.java b/src/test/java/org/hostsharing/hsadminng/cucumber/stepdefs/UserStepDefs.java index 2feecffb..fc5f77de 100644 --- a/src/test/java/org/hostsharing/hsadminng/cucumber/stepdefs/UserStepDefs.java +++ b/src/test/java/org/hostsharing/hsadminng/cucumber/stepdefs/UserStepDefs.java @@ -1,5 +1,11 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.cucumber.stepdefs; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import org.hostsharing.hsadminng.web.rest.UserResource; + import cucumber.api.java.Before; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; @@ -9,11 +15,6 @@ import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.hostsharing.hsadminng.web.rest.UserResource; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - public class UserStepDefs extends StepDefs { @Autowired @@ -28,15 +29,16 @@ public class UserStepDefs extends StepDefs { @When("I search user {string}") public void i_search_user(String userId) throws Throwable { - actions = restUserMockMvc.perform(get("/api/users/" + userId) - .accept(MediaType.APPLICATION_JSON)); + actions = restUserMockMvc.perform( + get("/api/users/" + userId) + .accept(MediaType.APPLICATION_JSON)); } @Then("the user is found") public void the_user_is_found() throws Throwable { actions - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)); } @Then("his last name is {string}") diff --git a/src/test/java/org/hostsharing/hsadminng/repository/CustomAuditEventRepositoryIntTest.java b/src/test/java/org/hostsharing/hsadminng/repository/CustomAuditEventRepositoryIntTest.java index 73bac548..a66d3a6d 100644 --- a/src/test/java/org/hostsharing/hsadminng/repository/CustomAuditEventRepositoryIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/repository/CustomAuditEventRepositoryIntTest.java @@ -1,9 +1,14 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.repository; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hostsharing.hsadminng.repository.CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH; + import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.config.Constants; import org.hostsharing.hsadminng.config.audit.AuditEventConverter; import org.hostsharing.hsadminng.domain.PersistentAuditEvent; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -16,14 +21,12 @@ import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; -import javax.servlet.http.HttpSession; import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hostsharing.hsadminng.repository.CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH; +import javax.servlet.http.HttpSession; /** * Test class for the CustomAuditEventRepository class. diff --git a/src/test/java/org/hostsharing/hsadminng/repository/MembershipRepositoryIntTest.java b/src/test/java/org/hostsharing/hsadminng/repository/MembershipRepositoryIntTest.java index d9a09878..4f0c22f6 100644 --- a/src/test/java/org/hostsharing/hsadminng/repository/MembershipRepositoryIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/repository/MembershipRepositoryIntTest.java @@ -1,12 +1,16 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.repository; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.RandomUtils; +import static org.assertj.core.api.Assertions.assertThat; + import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.domain.Membership; import org.hostsharing.hsadminng.domain.enumeration.CustomerKind; import org.hostsharing.hsadminng.domain.enumeration.VatRegion; + +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.RandomUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -16,13 +20,10 @@ import org.springframework.transaction.annotation.Transactional; import java.time.LocalDate; -import static org.assertj.core.api.Assertions.assertThat; - - @RunWith(SpringRunner.class) @SpringBootTest(classes = HsadminNgApp.class) @Transactional -public class MembershipRepositoryIntTest { +public class MembershipRepositoryIntTest { @Autowired private CustomerRepository customerRepository; @@ -36,7 +37,8 @@ public class MembershipRepositoryIntTest { final Customer givenCustomerWithUncancelledMembership = createCustomerWithMembership("2011-08-18", null); // when - boolean actual = membershipRepository.hasUncancelledMembershipForCustomer(givenCustomerWithUncancelledMembership.getId()); + boolean actual = membershipRepository + .hasUncancelledMembershipForCustomer(givenCustomerWithUncancelledMembership.getId()); // then assertThat(actual).isTrue(); diff --git a/src/test/java/org/hostsharing/hsadminng/repository/timezone/DateTimeWrapper.java b/src/test/java/org/hostsharing/hsadminng/repository/timezone/DateTimeWrapper.java index f1804ade..c3d86649 100644 --- a/src/test/java/org/hostsharing/hsadminng/repository/timezone/DateTimeWrapper.java +++ b/src/test/java/org/hostsharing/hsadminng/repository/timezone/DateTimeWrapper.java @@ -1,10 +1,12 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.repository.timezone; -import javax.persistence.*; import java.io.Serializable; import java.time.*; import java.util.Objects; +import javax.persistence.*; + @Entity @Table(name = "jhi_date_time_wrapper") public class DateTimeWrapper implements Serializable { @@ -122,11 +124,11 @@ public class DateTimeWrapper implements Serializable { @Override public String toString() { return "TimeZoneTest{" + - "id=" + id + - ", instant=" + instant + - ", localDateTime=" + localDateTime + - ", offsetDateTime=" + offsetDateTime + - ", zonedDateTime=" + zonedDateTime + - '}'; + "id=" + id + + ", instant=" + instant + + ", localDateTime=" + localDateTime + + ", offsetDateTime=" + offsetDateTime + + ", zonedDateTime=" + zonedDateTime + + '}'; } } diff --git a/src/test/java/org/hostsharing/hsadminng/repository/timezone/DateTimeWrapperRepository.java b/src/test/java/org/hostsharing/hsadminng/repository/timezone/DateTimeWrapperRepository.java index 91fff378..1eea9b1d 100644 --- a/src/test/java/org/hostsharing/hsadminng/repository/timezone/DateTimeWrapperRepository.java +++ b/src/test/java/org/hostsharing/hsadminng/repository/timezone/DateTimeWrapperRepository.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.repository.timezone; import org.springframework.data.jpa.repository.JpaRepository; diff --git a/src/test/java/org/hostsharing/hsadminng/security/DomainUserDetailsServiceIntTest.java b/src/test/java/org/hostsharing/hsadminng/security/DomainUserDetailsServiceIntTest.java index 1d542ef5..78bfa455 100644 --- a/src/test/java/org/hostsharing/hsadminng/security/DomainUserDetailsServiceIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/security/DomainUserDetailsServiceIntTest.java @@ -1,5 +1,8 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.security; +import static org.assertj.core.api.Assertions.assertThat; + import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.domain.User; import org.hostsharing.hsadminng.repository.UserRepository; @@ -18,8 +21,6 @@ import org.springframework.transaction.annotation.Transactional; import java.util.Locale; -import static org.assertj.core.api.Assertions.assertThat; - /** * Test class for DomainUserDetailsService. * @@ -107,7 +108,7 @@ public class DomainUserDetailsServiceIntTest { @Test(expected = UsernameNotFoundException.class) @Transactional public void assertThatUserCanNotBeFoundByEmailIgnoreCase() { - domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL.toUpperCase(Locale.ENGLISH)); + domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL.toUpperCase(Locale.ENGLISH)); } @Test diff --git a/src/test/java/org/hostsharing/hsadminng/security/SecurityUtilsUnitTest.java b/src/test/java/org/hostsharing/hsadminng/security/SecurityUtilsUnitTest.java index 8e527851..05769287 100644 --- a/src/test/java/org/hostsharing/hsadminng/security/SecurityUtilsUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/security/SecurityUtilsUnitTest.java @@ -1,5 +1,8 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.security; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; @@ -11,8 +14,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Optional; -import static org.assertj.core.api.Assertions.assertThat; - /** * Test class for the SecurityUtils utility class. * diff --git a/src/test/java/org/hostsharing/hsadminng/security/jwt/JWTFilterTest.java b/src/test/java/org/hostsharing/hsadminng/security/jwt/JWTFilterTest.java index 35dfb386..ac77496a 100644 --- a/src/test/java/org/hostsharing/hsadminng/security/jwt/JWTFilterTest.java +++ b/src/test/java/org/hostsharing/hsadminng/security/jwt/JWTFilterTest.java @@ -1,6 +1,10 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.security.jwt; +import static org.assertj.core.api.Assertions.assertThat; + import org.hostsharing.hsadminng.security.AuthoritiesConstants; + import io.github.jhipster.config.JHipsterProperties; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; @@ -18,8 +22,6 @@ import org.springframework.test.util.ReflectionTestUtils; import java.util.Collections; -import static org.assertj.core.api.Assertions.assertThat; - public class JWTFilterTest { private TokenProvider tokenProvider; @@ -30,9 +32,13 @@ public class JWTFilterTest { public void setup() { JHipsterProperties jHipsterProperties = new JHipsterProperties(); tokenProvider = new TokenProvider(jHipsterProperties); - ReflectionTestUtils.setField(tokenProvider, "key", - Keys.hmacShaKeyFor(Decoders.BASE64 - .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"))); + ReflectionTestUtils.setField( + tokenProvider, + "key", + Keys.hmacShaKeyFor( + Decoders.BASE64 + .decode( + "fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"))); ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000); jwtFilter = new JWTFilter(tokenProvider); @@ -42,10 +48,9 @@ public class JWTFilterTest { @Test public void testJWTFilter() throws Exception { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( - "test-user", - "test-password", - Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) - ); + "test-user", + "test-password", + Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))); String jwt = tokenProvider.createToken(authentication, false); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); @@ -97,10 +102,9 @@ public class JWTFilterTest { @Test public void testJWTFilterWrongScheme() throws Exception { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( - "test-user", - "test-password", - Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) - ); + "test-user", + "test-password", + Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))); String jwt = tokenProvider.createToken(authentication, false); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt); diff --git a/src/test/java/org/hostsharing/hsadminng/security/jwt/TokenProviderTest.java b/src/test/java/org/hostsharing/hsadminng/security/jwt/TokenProviderTest.java index 9908b235..d1e6934a 100644 --- a/src/test/java/org/hostsharing/hsadminng/security/jwt/TokenProviderTest.java +++ b/src/test/java/org/hostsharing/hsadminng/security/jwt/TokenProviderTest.java @@ -1,9 +1,15 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.security.jwt; +import static org.assertj.core.api.Assertions.assertThat; + import org.hostsharing.hsadminng.security.AuthoritiesConstants; -import java.security.Key; -import java.util.*; +import io.github.jhipster.config.JHipsterProperties; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.security.Keys; import org.junit.Before; import org.junit.Test; @@ -14,13 +20,8 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.test.util.ReflectionTestUtils; -import io.github.jhipster.config.JHipsterProperties; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import io.jsonwebtoken.io.Decoders; -import io.jsonwebtoken.security.Keys; - -import static org.assertj.core.api.Assertions.assertThat; +import java.security.Key; +import java.util.*; public class TokenProviderTest { @@ -33,8 +34,10 @@ public class TokenProviderTest { public void setup() { jHipsterProperties = Mockito.mock(JHipsterProperties.class); tokenProvider = new TokenProvider(jHipsterProperties); - key = Keys.hmacShaKeyFor(Decoders.BASE64 - .decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")); + key = Keys.hmacShaKeyFor( + Decoders.BASE64 + .decode( + "fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")); ReflectionTestUtils.setField(tokenProvider, "key", key); ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE); @@ -93,19 +96,21 @@ public class TokenProviderTest { private String createUnsupportedToken() { return Jwts.builder() - .setPayload("payload") - .signWith(key, SignatureAlgorithm.HS512) - .compact(); + .setPayload("payload") + .signWith(key, SignatureAlgorithm.HS512) + .compact(); } private String createTokenWithDifferentSignature() { - Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64 - .decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")); + Key otherKey = Keys.hmacShaKeyFor( + Decoders.BASE64 + .decode( + "Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")); return Jwts.builder() - .setSubject("anonymous") - .signWith(otherKey, SignatureAlgorithm.HS512) - .setExpiration(new Date(new Date().getTime() + ONE_MINUTE)) - .compact(); + .setSubject("anonymous") + .signWith(otherKey, SignatureAlgorithm.HS512) + .setExpiration(new Date(new Date().getTime() + ONE_MINUTE)) + .compact(); } } diff --git a/src/test/java/org/hostsharing/hsadminng/service/AssetServiceUnitTest.java b/src/test/java/org/hostsharing/hsadminng/service/AssetServiceUnitTest.java index 02e59b4f..dd7eb4e2 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/AssetServiceUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/AssetServiceUnitTest.java @@ -1,12 +1,20 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; -import org.apache.commons.lang3.RandomUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowableOfType; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.*; + import org.hostsharing.hsadminng.domain.Asset; import org.hostsharing.hsadminng.domain.enumeration.AssetAction; import org.hostsharing.hsadminng.repository.AssetRepository; import org.hostsharing.hsadminng.service.dto.AssetDTO; import org.hostsharing.hsadminng.service.mapper.AssetMapper; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + +import org.apache.commons.lang3.RandomUtils; import org.junit.Rule; import org.junit.Test; import org.mockito.InjectMocks; @@ -15,15 +23,9 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; -import javax.persistence.EntityManager; import java.math.BigDecimal; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowableOfType; -import static org.mockito.ArgumentMatchers.same; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.*; - +import javax.persistence.EntityManager; // HINT: In IntelliJ IDEA such unit test classes can be created with Shift-Ctrl-T. // Do not forget to amend the class name (.e.g. ...UnitTest / ...IntTest)! @@ -55,13 +57,15 @@ public class AssetServiceUnitTest { @Test public void deleteIsRejectedForAssetTransactions() { // when - final Throwable throwException = catchThrowableOfType(() -> assetService.delete(RandomUtils.nextLong()), BadRequestAlertException.class); + final Throwable throwException = catchThrowableOfType( + () -> assetService.delete(RandomUtils.nextLong()), + BadRequestAlertException.class); // then // HINT: When using auto-import for assertions (e.g. via Alt-Enter in IntelliJ IDEA), // beware to use the correct candidate from org.assertj.core.api.Assertions. assertThat(throwException).isEqualToComparingFieldByField( - new BadRequestAlertException("Asset transactions are immutable", "asset", "assetTransactionImmutable")); + new BadRequestAlertException("Asset transactions are immutable", "asset", "assetTransactionImmutable")); } @Test @@ -84,14 +88,18 @@ public class AssetServiceUnitTest { public void saveShouldNotPersistInvalidTransactions() { // given final AssetDTO givenAssetDTO = givenAssetDTO(null, AssetAction.PAYMENT, anyNegativeAmount()); - doThrow(new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy")).when(assetValidator).validate(givenAssetDTO); + doThrow(new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy")) + .when(assetValidator) + .validate(givenAssetDTO); // when - final Throwable throwException = catchThrowableOfType(() -> assetService.save(givenAssetDTO), BadRequestAlertException.class); + final Throwable throwException = catchThrowableOfType( + () -> assetService.save(givenAssetDTO), + BadRequestAlertException.class); // then assertThat(throwException).isEqualToComparingFieldByField( - new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy")); + new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy")); } @Test @@ -114,14 +122,18 @@ public class AssetServiceUnitTest { // given final AssetDTO givenAssetDTO = givenAssetDTO(anyNonNullId(), AssetAction.PAYMENT, anyNegativeAmount()); // HINT: given(...) can't be used for void methods, in that case use Mockito's do...() methods - doThrow(new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy")).when(assetValidator).validate(givenAssetDTO); + doThrow(new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy")) + .when(assetValidator) + .validate(givenAssetDTO); // when - final Throwable throwException = catchThrowableOfType(() -> assetService.save(givenAssetDTO), BadRequestAlertException.class); + final Throwable throwException = catchThrowableOfType( + () -> assetService.save(givenAssetDTO), + BadRequestAlertException.class); // then assertThat(throwException).isEqualToComparingFieldByField( - new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy")); + new BadRequestAlertException("Some Dummy Test Violation", "asset", "assetInvalidTestDummy")); } // --- only test fixture code below --- @@ -130,7 +142,8 @@ public class AssetServiceUnitTest { return RandomUtils.nextInt(); } - // HINT: This rather complicated setup indicates that the method AssetService::save breaks the single responsibility principle. + // HINT: This rather complicated setup indicates that the method AssetService::save breaks the single responsibility + // principle. private AssetDTO givenAssetDTO(final Long id, final AssetAction givenAction, final BigDecimal givenQuantity) { final AssetDTO givenAssetDTO = createAssetDTO(id, givenAction, givenQuantity); diff --git a/src/test/java/org/hostsharing/hsadminng/service/AssetValidatorUnitTest.java b/src/test/java/org/hostsharing/hsadminng/service/AssetValidatorUnitTest.java index d3b4c06a..69442072 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/AssetValidatorUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/AssetValidatorUnitTest.java @@ -1,20 +1,23 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; -import com.google.common.collect.ImmutableList; -import org.apache.commons.lang3.RandomUtils; -import org.assertj.core.api.AbstractThrowableAssert; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowableOfType; + import org.hostsharing.hsadminng.domain.enumeration.AssetAction; import org.hostsharing.hsadminng.service.dto.AssetDTO; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + +import com.google.common.collect.ImmutableList; + +import org.apache.commons.lang3.RandomUtils; +import org.assertj.core.api.AbstractThrowableAssert; import org.junit.Test; import java.math.BigDecimal; import java.time.LocalDate; import java.util.function.Consumer; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowableOfType; - public class AssetValidatorUnitTest { private AssetValidator assetValidator = new AssetValidator(); @@ -23,173 +26,250 @@ public class AssetValidatorUnitTest { public void shouldAcceptValidIncreasingTransaction() { for (AssetAction action : ImmutableList.of(AssetAction.PAYMENT, AssetAction.ADOPTION)) { new GivenAssetValidationTestCase() - .withAnyValidDateValues() - .withAction(action).withAmount("64.00") - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isNull(); + .withAnyValidDateValues() + .withAction(action) + .withAmount("64.00") + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isNull(); } } @Test public void shouldAcceptValidDecreasingTransaction() { - for (AssetAction action : ImmutableList.of(AssetAction.PAYBACK, AssetAction.HANDOVER, AssetAction.CLEARING, AssetAction.LOSS)) { + for (AssetAction action : ImmutableList + .of(AssetAction.PAYBACK, AssetAction.HANDOVER, AssetAction.CLEARING, AssetAction.LOSS)) { new GivenAssetValidationTestCase() - .withAnyValidDateValues() - .withAction(action).withAmount("-64.00") - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isNull(); + .withAnyValidDateValues() + .withAction(action) + .withAmount("-64.00") + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isNull(); } } @Test public void shouldAcceptIfDocumentDateEqualsValueDate() { new GivenAssetValidationTestCase() - .withDocumentDate("2019-04-11").withValueDate("2019-04-11") - .withAction(AssetAction.PAYMENT).withAmount("64.00") - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isNull(); + .withDocumentDate("2019-04-11") + .withValueDate("2019-04-11") + .withAction(AssetAction.PAYMENT) + .withAmount("64.00") + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isNull(); } @Test public void shouldRejectUpdates() { new GivenAssetValidationTestCase() - .withId(RandomUtils.nextLong()) - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Asset transactions are immutable", "asset", "assetTransactionImmutable")); + .withId(RandomUtils.nextLong()) + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Asset transactions are immutable", + "asset", + "assetTransactionImmutable")); } @Test public void shouldRejectIfDocumentDateAfterValueDate() { new GivenAssetValidationTestCase() - .withDocumentDate("2019-04-13").withValueDate("2019-04-12") - .withAction(AssetAction.PAYMENT).withAmount("64.00") - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Document date may not be after value date", "asset", "documentDateMayNotBeAfterValueDate")); + .withDocumentDate("2019-04-13") + .withValueDate("2019-04-12") + .withAction(AssetAction.PAYMENT) + .withAmount("64.00") + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Document date may not be after value date", + "asset", + "documentDateMayNotBeAfterValueDate")); } @Test public void shouldRejectIfPaymentWithNegativeAmount() { new GivenAssetValidationTestCase() - .withAnyValidDateValues() - .withAction(AssetAction.PAYMENT).withAmount("-64.00") - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Asset payments require a positive amount", "asset", "assetPaymentsPositiveAmount")); + .withAnyValidDateValues() + .withAction(AssetAction.PAYMENT) + .withAmount("-64.00") + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Asset payments require a positive amount", + "asset", + "assetPaymentsPositiveAmount")); } @Test public void shouldRejectIfPaymentWithZeroAmount() { new GivenAssetValidationTestCase() - .withAnyValidDateValues() - .withAction(AssetAction.PAYMENT).withAmount("0.00") - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Asset payments require a positive amount", "asset", "assetPaymentsPositiveAmount")); + .withAnyValidDateValues() + .withAction(AssetAction.PAYMENT) + .withAmount("0.00") + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Asset payments require a positive amount", + "asset", + "assetPaymentsPositiveAmount")); } @Test public void shouldRejectIfAdoptionWithNegativeAmount() { new GivenAssetValidationTestCase() - .withAnyValidDateValues() - .withAction(AssetAction.ADOPTION).withAmount("-64.00") - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Asset adoptions require a positive amount", "asset", "assetAdoptionsPositiveAmount")); + .withAnyValidDateValues() + .withAction(AssetAction.ADOPTION) + .withAmount("-64.00") + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Asset adoptions require a positive amount", + "asset", + "assetAdoptionsPositiveAmount")); } @Test public void shouldRejectIfAdoptionWithZeroAmount() { new GivenAssetValidationTestCase() - .withAnyValidDateValues() - .withAction(AssetAction.ADOPTION).withAmount("0.00") - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Asset adoptions require a positive amount", "asset", "assetAdoptionsPositiveAmount")); + .withAnyValidDateValues() + .withAction(AssetAction.ADOPTION) + .withAmount("0.00") + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Asset adoptions require a positive amount", + "asset", + "assetAdoptionsPositiveAmount")); } @Test public void shouldRejectIfPaybackWithPositiveAmount() { new GivenAssetValidationTestCase() - .withAnyValidDateValues() - .withAction(AssetAction.PAYBACK).withAmount("64.00") - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Asset paybacks require a negative amount", "asset", "assetPaybacksNegativeAmount")); + .withAnyValidDateValues() + .withAction(AssetAction.PAYBACK) + .withAmount("64.00") + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Asset paybacks require a negative amount", + "asset", + "assetPaybacksNegativeAmount")); } @Test public void shouldRejectIfPaybackWithZeroAmount() { new GivenAssetValidationTestCase() - .withAnyValidDateValues() - .withAction(AssetAction.PAYBACK).withAmount("0.00") - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Asset paybacks require a negative amount", "asset", "assetPaybacksNegativeAmount")); + .withAnyValidDateValues() + .withAction(AssetAction.PAYBACK) + .withAmount("0.00") + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Asset paybacks require a negative amount", + "asset", + "assetPaybacksNegativeAmount")); } @Test public void shouldRejectIfHandoverWithPositiveAmount() { new GivenAssetValidationTestCase() - .withAnyValidDateValues() - .withAction(AssetAction.HANDOVER).withAmount("64.00") - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Asset handovers require a negative amount", "asset", "assetHandoversNegativeAmount")); + .withAnyValidDateValues() + .withAction(AssetAction.HANDOVER) + .withAmount("64.00") + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Asset handovers require a negative amount", + "asset", + "assetHandoversNegativeAmount")); } @Test public void shouldRejectIfHandoverWithZeroAmount() { new GivenAssetValidationTestCase() - .withAnyValidDateValues() - .withAction(AssetAction.HANDOVER).withAmount("0.00") - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Asset handovers require a negative amount", "asset", "assetHandoversNegativeAmount")); + .withAnyValidDateValues() + .withAction(AssetAction.HANDOVER) + .withAmount("0.00") + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Asset handovers require a negative amount", + "asset", + "assetHandoversNegativeAmount")); } @Test public void shouldRejectIfLossWithPositiveAmount() { new GivenAssetValidationTestCase() - .withAnyValidDateValues() - .withAction(AssetAction.LOSS).withAmount("64.00") - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Asset losses require a negative amount", "asset", "assetLossesNegativeAmount")); + .withAnyValidDateValues() + .withAction(AssetAction.LOSS) + .withAmount("64.00") + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Asset losses require a negative amount", + "asset", + "assetLossesNegativeAmount")); } @Test public void shouldRejectIfLossWithZeroAmount() { new GivenAssetValidationTestCase() - .withAnyValidDateValues() - .withAction(AssetAction.LOSS).withAmount("0.00") - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Asset losses require a negative amount", "asset", "assetLossesNegativeAmount")); + .withAnyValidDateValues() + .withAction(AssetAction.LOSS) + .withAmount("0.00") + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Asset losses require a negative amount", + "asset", + "assetLossesNegativeAmount")); } @Test public void shouldRejectIfClearingWithPositiveAmount() { new GivenAssetValidationTestCase() - .withAnyValidDateValues() - .withAction(AssetAction.CLEARING).withAmount("64.00") - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Asset clearings require a negative amount", "asset", "assetClearingsNegativeAmount")); + .withAnyValidDateValues() + .withAction(AssetAction.CLEARING) + .withAmount("64.00") + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Asset clearings require a negative amount", + "asset", + "assetClearingsNegativeAmount")); } @Test public void shouldRejectIfClearingWithZeroAmount() { new GivenAssetValidationTestCase() - .withAnyValidDateValues() - .withAction(AssetAction.CLEARING).withAmount("0.00") - .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Asset clearings require a negative amount", "asset", "assetClearingsNegativeAmount")); + .withAnyValidDateValues() + .withAction(AssetAction.CLEARING) + .withAmount("0.00") + .when((AssetDTO assetDto) -> assetValidator.validate(assetDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Asset clearings require a negative amount", + "asset", + "assetClearingsNegativeAmount")); } - // -- only test fixture below --- private class GivenAssetValidationTestCase { @@ -226,7 +306,7 @@ public class AssetValidatorUnitTest { return this; } - GivenAssetValidationTestCase when(final Consumer statement) { + GivenAssetValidationTestCase when(final Consumer statement) { actualException = catchThrowableOfType(() -> assetValidator.validate(assetDto), BadRequestAlertException.class); return this; } diff --git a/src/test/java/org/hostsharing/hsadminng/service/MailServiceIntTest.java b/src/test/java/org/hostsharing/hsadminng/service/MailServiceIntTest.java index c7dd8409..70022a1a 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/MailServiceIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/MailServiceIntTest.java @@ -1,9 +1,16 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; -import org.hostsharing.hsadminng.config.Constants; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; import org.hostsharing.hsadminng.HsadminNgApp; +import org.hostsharing.hsadminng.config.Constants; import org.hostsharing.hsadminng.domain.User; + import io.github.jhipster.config.JHipsterProperties; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -19,15 +26,12 @@ import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.test.context.junit4.SpringRunner; import org.thymeleaf.spring5.SpringTemplateEngine; +import java.io.ByteArrayOutputStream; + import javax.mail.Multipart; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; -import java.io.ByteArrayOutputStream; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; @RunWith(SpringRunner.class) @SpringBootTest(classes = HsadminNgApp.class) @@ -129,7 +133,8 @@ public class MailServiceIntTest { assertThat(message.getSubject()).isEqualTo("test title"); assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); - assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("test title, http://127.0.0.1:8080, john\n"); + assertThat(message.getContent().toString()) + .isEqualToNormalizingNewlines("test title, http://127.0.0.1:8080, john\n"); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } diff --git a/src/test/java/org/hostsharing/hsadminng/service/MembershipServiceUnitTest.java b/src/test/java/org/hostsharing/hsadminng/service/MembershipServiceUnitTest.java index 2fbabce1..1b5452d6 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/MembershipServiceUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/MembershipServiceUnitTest.java @@ -1,10 +1,17 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; -import org.apache.commons.lang3.RandomUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowableOfType; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + import org.hostsharing.hsadminng.domain.Membership; import org.hostsharing.hsadminng.repository.MembershipRepository; import org.hostsharing.hsadminng.service.dto.MembershipDTO; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + +import org.apache.commons.lang3.RandomUtils; import org.junit.Rule; import org.junit.Test; import org.mockito.InjectMocks; @@ -12,11 +19,6 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowableOfType; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - public class MembershipServiceUnitTest { @Rule @@ -34,22 +36,29 @@ public class MembershipServiceUnitTest { @Test public void deleteIsRejectedForMembership() { // when - final Throwable throwException = catchThrowableOfType(() -> membershipService.delete(RandomUtils.nextLong()), BadRequestAlertException.class); + final Throwable throwException = catchThrowableOfType( + () -> membershipService.delete(RandomUtils.nextLong()), + BadRequestAlertException.class); // then assertThat(throwException).isEqualToComparingFieldByField( - new BadRequestAlertException("Membership cannot be deleted", "membership", "membershipNotDeletable")); + new BadRequestAlertException("Membership cannot be deleted", "membership", "membershipNotDeletable")); } @Test public void saveRejectsInvalidMembershipDTO() { // given final MembershipDTO givenMembershipDTO = new MembershipDTO(); - final BadRequestAlertException givenBadRequestAlertException = new BadRequestAlertException("Invalid Membership", Membership.ENTITY_NAME, "invalidMembership"); + final BadRequestAlertException givenBadRequestAlertException = new BadRequestAlertException( + "Invalid Membership", + Membership.ENTITY_NAME, + "invalidMembership"); doThrow(givenBadRequestAlertException).when(membershipValidator).validate(givenMembershipDTO); // when - final Throwable throwException = catchThrowableOfType(() -> membershipService.save(givenMembershipDTO), BadRequestAlertException.class); + final Throwable throwException = catchThrowableOfType( + () -> membershipService.save(givenMembershipDTO), + BadRequestAlertException.class); // then assertThat(throwException).isSameAs(givenBadRequestAlertException); diff --git a/src/test/java/org/hostsharing/hsadminng/service/MembershipValidatorUnitTest.java b/src/test/java/org/hostsharing/hsadminng/service/MembershipValidatorUnitTest.java index df080721..a1327412 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/MembershipValidatorUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/MembershipValidatorUnitTest.java @@ -1,9 +1,16 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; -import org.assertj.core.api.AbstractThrowableAssert; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowableOfType; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.BDDMockito.given; + import org.hostsharing.hsadminng.repository.MembershipRepository; import org.hostsharing.hsadminng.service.dto.MembershipDTO; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + +import org.assertj.core.api.AbstractThrowableAssert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -15,11 +22,6 @@ import org.mockito.junit.MockitoRule; import java.time.LocalDate; import java.util.function.Consumer; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowableOfType; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.BDDMockito.given; - public class MembershipValidatorUnitTest { @Rule @@ -39,47 +41,69 @@ public class MembershipValidatorUnitTest { @Test public void shouldAcceptNewMembershipIfUntilDateAfterSinceDate() { new GivenMembershipValidationTestCase() - .withNewMembershipForCustomer(1L).since("2019-04-11").until("2019-04-12") - .when((MembershipDTO membershipDto) -> membershipValidator.validate(membershipDto)) - .thenActualException().isNull(); + .withNewMembershipForCustomer(1L) + .since("2019-04-11") + .until("2019-04-12") + .when((MembershipDTO membershipDto) -> membershipValidator.validate(membershipDto)) + .thenActualException() + .isNull(); } @Test public void shouldRejectNewMembershipIfUntilDateEqualToSinceDate() { new GivenMembershipValidationTestCase() - .withNewMembershipForCustomer(1L).since("2019-04-11").until("2019-04-11") - .when((MembershipDTO membershipDto) -> membershipValidator.validate(membershipDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Invalid untilDate", "membership", "untilDateMustBeAfterSinceDate")); + .withNewMembershipForCustomer(1L) + .since("2019-04-11") + .until("2019-04-11") + .when((MembershipDTO membershipDto) -> membershipValidator.validate(membershipDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Invalid untilDate", + "membership", + "untilDateMustBeAfterSinceDate")); } @Test public void shouldRejectNewMembershipIfUntilDateAfterSinceDate() { new GivenMembershipValidationTestCase() - .withNewMembershipForCustomer(1L).since("2019-04-12").until("2019-04-11") - .when((MembershipDTO membershipDto) -> membershipValidator.validate(membershipDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Invalid untilDate", "membership", "untilDateMustBeAfterSinceDate")); + .withNewMembershipForCustomer(1L) + .since("2019-04-12") + .until("2019-04-11") + .when((MembershipDTO membershipDto) -> membershipValidator.validate(membershipDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Invalid untilDate", + "membership", + "untilDateMustBeAfterSinceDate")); } @Test public void shouldAcceptNewUncancelledMembershipIfNoUncancelledMembershipExistsForSameCustomer() { new GivenMembershipValidationTestCase() - .withUncancelledMembershipForCustomer(1L, false) - .withNewMembershipForCustomer(1L).since("2019-04-12") - .when((MembershipDTO membershipDto) -> membershipValidator.validate(membershipDto)) - .thenActualException().isNull(); + .withUncancelledMembershipForCustomer(1L, false) + .withNewMembershipForCustomer(1L) + .since("2019-04-12") + .when((MembershipDTO membershipDto) -> membershipValidator.validate(membershipDto)) + .thenActualException() + .isNull(); } @Test public void shouldRejectNewMembershipIfAnyUncancelledMembershipExistsForSameCustomer() { new GivenMembershipValidationTestCase() - .withUncancelledMembershipForCustomer(1L, true) - .withNewMembershipForCustomer(1L).since("2019-04-12") - .when((MembershipDTO membershipDto) -> membershipValidator.validate(membershipDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Another uncancelled membership exists", "membership", "anotherUncancelledMembershipExists")); + .withUncancelledMembershipForCustomer(1L, true) + .withNewMembershipForCustomer(1L) + .since("2019-04-12") + .when((MembershipDTO membershipDto) -> membershipValidator.validate(membershipDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Another uncancelled membership exists", + "membership", + "anotherUncancelledMembershipExists")); } // -- only test fixture below --- @@ -89,7 +113,9 @@ public class MembershipValidatorUnitTest { private final MembershipDTO membershipDto = new MembershipDTO(); private BadRequestAlertException actualException; - GivenMembershipValidationTestCase withUncancelledMembershipForCustomer(final long customerId, final boolean hasUncancelledMembership) { + GivenMembershipValidationTestCase withUncancelledMembershipForCustomer( + final long customerId, + final boolean hasUncancelledMembership) { given(membershipRepository.hasUncancelledMembershipForCustomer(customerId)).willReturn(hasUncancelledMembership); return this; } @@ -99,7 +125,6 @@ public class MembershipValidatorUnitTest { return this; } - GivenMembershipValidationTestCase since(final String sinceDate) { membershipDto.setMemberFromDate(LocalDate.parse(sinceDate)); return this; @@ -111,7 +136,9 @@ public class MembershipValidatorUnitTest { } GivenMembershipValidationTestCase when(final Consumer statement) { - actualException = catchThrowableOfType(() -> membershipValidator.validate(membershipDto), BadRequestAlertException.class); + actualException = catchThrowableOfType( + () -> membershipValidator.validate(membershipDto), + BadRequestAlertException.class); return this; } diff --git a/src/test/java/org/hostsharing/hsadminng/service/ShareServiceUnitTest.java b/src/test/java/org/hostsharing/hsadminng/service/ShareServiceUnitTest.java index 34150e4c..3d44236f 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/ShareServiceUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/ShareServiceUnitTest.java @@ -1,12 +1,20 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; -import org.apache.commons.lang3.RandomUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowableOfType; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.*; + import org.hostsharing.hsadminng.domain.Share; import org.hostsharing.hsadminng.domain.enumeration.ShareAction; import org.hostsharing.hsadminng.repository.ShareRepository; import org.hostsharing.hsadminng.service.dto.ShareDTO; import org.hostsharing.hsadminng.service.mapper.ShareMapper; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + +import org.apache.commons.lang3.RandomUtils; import org.junit.Rule; import org.junit.Test; import org.mockito.InjectMocks; @@ -17,13 +25,6 @@ import org.mockito.junit.MockitoRule; import javax.persistence.EntityManager; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowableOfType; -import static org.mockito.ArgumentMatchers.same; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.*; - - // HINT: In IntelliJ IDEA such unit test classes can be created with Shift-Ctrl-T. // Do not forget to amend the class name (.e.g. ...UnitTest / ...IntTest)! public class ShareServiceUnitTest { @@ -54,13 +55,15 @@ public class ShareServiceUnitTest { @Test public void deleteIsRejectedForShareTransactions() { // when - final Throwable throwException = catchThrowableOfType(() -> shareService.delete(RandomUtils.nextLong()), BadRequestAlertException.class); + final Throwable throwException = catchThrowableOfType( + () -> shareService.delete(RandomUtils.nextLong()), + BadRequestAlertException.class); // then // HINT: When using auto-import for assertions (e.g. via Alt-Enter in IntelliJ IDEA), // beware to use the correct candidate from org.assertj.core.api.Assertions. assertThat(throwException).isEqualToComparingFieldByField( - new BadRequestAlertException("Share transactions are immutable", "share", "shareTransactionImmutable")); + new BadRequestAlertException("Share transactions are immutable", "share", "shareTransactionImmutable")); } @Test @@ -83,14 +86,18 @@ public class ShareServiceUnitTest { public void saveShouldNotPersistInvalidTransactions() { // given final ShareDTO givenShareDTO = givenShareDTO(null, ShareAction.SUBSCRIPTION, anyNegativeNumber()); - doThrow(new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy")).when(shareValidator).validate(givenShareDTO); + doThrow(new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy")) + .when(shareValidator) + .validate(givenShareDTO); // when - final Throwable throwException = catchThrowableOfType(() -> shareService.save(givenShareDTO), BadRequestAlertException.class); + final Throwable throwException = catchThrowableOfType( + () -> shareService.save(givenShareDTO), + BadRequestAlertException.class); // then assertThat(throwException).isEqualToComparingFieldByField( - new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy")); + new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy")); } @Test @@ -113,14 +120,18 @@ public class ShareServiceUnitTest { // given final ShareDTO givenShareDTO = givenShareDTO(anyNonNullId(), ShareAction.SUBSCRIPTION, anyNegativeNumber()); // HINT: given(...) can't be used for void methods, in that case use Mockito's do...() methods - doThrow(new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy")).when(shareValidator).validate(givenShareDTO); + doThrow(new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy")) + .when(shareValidator) + .validate(givenShareDTO); // when - final Throwable throwException = catchThrowableOfType(() -> shareService.save(givenShareDTO), BadRequestAlertException.class); + final Throwable throwException = catchThrowableOfType( + () -> shareService.save(givenShareDTO), + BadRequestAlertException.class); // then assertThat(throwException).isEqualToComparingFieldByField( - new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy")); + new BadRequestAlertException("Some Dummy Test Violation", "share", "shareInvalidTestDummy")); } // --- only test fixture code below --- @@ -129,7 +140,8 @@ public class ShareServiceUnitTest { return RandomUtils.nextInt(); } - // HINT: This rather complicated setup indicates that the method ShareService::save breaks the single responsibility principle. + // HINT: This rather complicated setup indicates that the method ShareService::save breaks the single responsibility + // principle. private ShareDTO givenShareDTO(final Long id, final ShareAction givenAction, final int givenQuantity) { final ShareDTO givenShareDTO = createShareDTO(id, givenAction, givenQuantity); diff --git a/src/test/java/org/hostsharing/hsadminng/service/ShareValidatorUnitTest.java b/src/test/java/org/hostsharing/hsadminng/service/ShareValidatorUnitTest.java index d521f510..6f8993b7 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/ShareValidatorUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/ShareValidatorUnitTest.java @@ -1,18 +1,20 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; -import org.apache.commons.lang3.RandomUtils; -import org.assertj.core.api.AbstractThrowableAssert; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowableOfType; + import org.hostsharing.hsadminng.domain.enumeration.ShareAction; import org.hostsharing.hsadminng.service.dto.ShareDTO; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + +import org.apache.commons.lang3.RandomUtils; +import org.assertj.core.api.AbstractThrowableAssert; import org.junit.Test; import java.time.LocalDate; import java.util.function.Consumer; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowableOfType; - public class ShareValidatorUnitTest { private ShareValidator shareValidator = new ShareValidator(); @@ -20,90 +22,126 @@ public class ShareValidatorUnitTest { @Test public void shouldAcceptValidSubscription() { new GivenShareValidationTestCase() - .withAnyValidDateValues() - .withAction(ShareAction.SUBSCRIPTION).withQuantity(1) - .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) - .thenActualException().isNull(); + .withAnyValidDateValues() + .withAction(ShareAction.SUBSCRIPTION) + .withQuantity(1) + .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) + .thenActualException() + .isNull(); } @Test public void shouldAcceptValidCancellation() { new GivenShareValidationTestCase() - .withAnyValidDateValues() - .withAction(ShareAction.CANCELLATION).withQuantity(-1) - .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) - .thenActualException().isNull(); + .withAnyValidDateValues() + .withAction(ShareAction.CANCELLATION) + .withQuantity(-1) + .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) + .thenActualException() + .isNull(); } @Test public void shouldAcceptIfDocumentDateEqualsValueDate() { new GivenShareValidationTestCase() - .withDocumentDate("2019-04-11").withValueDate("2019-04-11") - .withAction(ShareAction.SUBSCRIPTION).withQuantity(1) - .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) - .thenActualException().isNull(); + .withDocumentDate("2019-04-11") + .withValueDate("2019-04-11") + .withAction(ShareAction.SUBSCRIPTION) + .withQuantity(1) + .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) + .thenActualException() + .isNull(); } @Test public void shouldRejectUpdates() { new GivenShareValidationTestCase() - .withId(RandomUtils.nextLong()) - .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Share transactions are immutable", "share", "shareTransactionImmutable")); + .withId(RandomUtils.nextLong()) + .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Share transactions are immutable", + "share", + "shareTransactionImmutable")); } @Test public void shouldRejectIfDocumentDateAfterValueDate() { new GivenShareValidationTestCase() - .withDocumentDate("2019-04-13").withValueDate("2019-04-12") - .withAction(ShareAction.SUBSCRIPTION).withQuantity(1) - .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Document date may not be after value date", "share", "documentDateMayNotBeAfterValueDate")); + .withDocumentDate("2019-04-13") + .withValueDate("2019-04-12") + .withAction(ShareAction.SUBSCRIPTION) + .withQuantity(1) + .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Document date may not be after value date", + "share", + "documentDateMayNotBeAfterValueDate")); } @Test public void shouldRejectIfSubscriptionWithNegativeQuantity() { new GivenShareValidationTestCase() - .withAnyValidDateValues() - .withAction(ShareAction.SUBSCRIPTION).withQuantity(-1) - .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Share subscriptions require a positive quantity", "share", "shareSubscriptionPositiveQuantity")); + .withAnyValidDateValues() + .withAction(ShareAction.SUBSCRIPTION) + .withQuantity(-1) + .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Share subscriptions require a positive quantity", + "share", + "shareSubscriptionPositiveQuantity")); } @Test public void shouldRejectIfSubscriptionWithZeroQuantity() { new GivenShareValidationTestCase() - .withAnyValidDateValues() - .withAction(ShareAction.SUBSCRIPTION).withQuantity(0) - .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Share subscriptions require a positive quantity", "share", "shareSubscriptionPositiveQuantity")); + .withAnyValidDateValues() + .withAction(ShareAction.SUBSCRIPTION) + .withQuantity(0) + .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Share subscriptions require a positive quantity", + "share", + "shareSubscriptionPositiveQuantity")); } @Test public void shouldRejectIfCancellationWithPositiveQuantity() { new GivenShareValidationTestCase() - .withAnyValidDateValues() - .withAction(ShareAction.CANCELLATION).withQuantity(1) - .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Share cancellations require a negative quantity", "share", "shareCancellationNegativeQuantity")); + .withAnyValidDateValues() + .withAction(ShareAction.CANCELLATION) + .withQuantity(1) + .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Share cancellations require a negative quantity", + "share", + "shareCancellationNegativeQuantity")); } @Test public void shouldRejectIfCancellationWithZeroQuantity() { new GivenShareValidationTestCase() - .withAnyValidDateValues() - .withAction(ShareAction.CANCELLATION).withQuantity(0) - .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) - .thenActualException().isEqualToComparingFieldByField(new BadRequestAlertException( - "Share cancellations require a negative quantity", "share", "shareCancellationNegativeQuantity")); + .withAnyValidDateValues() + .withAction(ShareAction.CANCELLATION) + .withQuantity(0) + .when((ShareDTO shareDto) -> shareValidator.validate(shareDto)) + .thenActualException() + .isEqualToComparingFieldByField( + new BadRequestAlertException( + "Share cancellations require a negative quantity", + "share", + "shareCancellationNegativeQuantity")); } - // -- only test fixture below --- private class GivenShareValidationTestCase { @@ -140,7 +178,7 @@ public class ShareValidatorUnitTest { return this; } - GivenShareValidationTestCase when(final Consumer statement) { + GivenShareValidationTestCase when(final Consumer statement) { actualException = catchThrowableOfType(() -> shareValidator.validate(shareDto), BadRequestAlertException.class); return this; } @@ -150,5 +188,3 @@ public class ShareValidatorUnitTest { } } } - - diff --git a/src/test/java/org/hostsharing/hsadminng/service/UserServiceIntTest.java b/src/test/java/org/hostsharing/hsadminng/service/UserServiceIntTest.java index e80fb6c5..d872bf32 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/UserServiceIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/UserServiceIntTest.java @@ -1,5 +1,9 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.config.Constants; import org.hostsharing.hsadminng.domain.User; @@ -22,13 +26,10 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; -import java.time.temporal.ChronoUnit; import java.time.LocalDateTime; -import java.util.Optional; +import java.time.temporal.ChronoUnit; import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; +import java.util.Optional; /** * Test class for the UserResource REST controller. @@ -169,12 +170,13 @@ public class UserServiceIntTest { } final PageRequest pageable = PageRequest.of(0, (int) userRepository.count()); final Page allManagedUsers = userService.getAllManagedUsers(pageable); - assertThat(allManagedUsers.getContent().stream() - .noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin()))) - .isTrue(); + assertThat( + allManagedUsers.getContent() + .stream() + .noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin()))) + .isTrue(); } - @Test @Transactional public void testRemoveNotActivatedUsers() { diff --git a/src/test/java/org/hostsharing/hsadminng/service/accessfilter/JSonAccessFilterTestFixture.java b/src/test/java/org/hostsharing/hsadminng/service/accessfilter/JSonAccessFilterTestFixture.java index 29501f65..5ecc0368 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/accessfilter/JSonAccessFilterTestFixture.java +++ b/src/test/java/org/hostsharing/hsadminng/service/accessfilter/JSonAccessFilterTestFixture.java @@ -1,15 +1,17 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.accessfilter; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.RandomUtils; +import static org.hostsharing.hsadminng.service.accessfilter.Role.*; + import org.hostsharing.hsadminng.service.IdToDtoResolver; import org.hostsharing.hsadminng.service.dto.FluentBuilder; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.RandomUtils; + import java.math.BigDecimal; import java.time.LocalDate; -import static org.hostsharing.hsadminng.service.accessfilter.Role.*; - public class JSonAccessFilterTestFixture { static GivenDto createSampleDto() { @@ -32,6 +34,7 @@ public class JSonAccessFilterTestFixture { } static class GivenCustomerDto implements FluentBuilder { + @SelfId(resolver = GivenService.class) @AccessFor(read = ANYBODY) Long id; @@ -45,6 +48,7 @@ public class JSonAccessFilterTestFixture { } static class GivenDto implements FluentBuilder { + @SelfId(resolver = GivenService.class) @AccessFor(read = ANYBODY) Long id; @@ -53,7 +57,10 @@ public class JSonAccessFilterTestFixture { @AccessFor(init = ACTUAL_CUSTOMER_USER, update = ACTUAL_CUSTOMER_USER, read = ACTUAL_CUSTOMER_USER) Long customerId; - @AccessFor(init = {TECHNICAL_CONTACT, FINANCIAL_CONTACT}, update = {TECHNICAL_CONTACT, FINANCIAL_CONTACT}, read = {TECHNICAL_CONTACT, FINANCIAL_CONTACT}) + @AccessFor( + init = { TECHNICAL_CONTACT, FINANCIAL_CONTACT }, + update = { TECHNICAL_CONTACT, FINANCIAL_CONTACT }, + read = { TECHNICAL_CONTACT, FINANCIAL_CONTACT }) String restrictedField; @AccessFor(init = ANYBODY, update = ANYBODY, read = ANYBODY) @@ -103,7 +110,8 @@ public class JSonAccessFilterTestFixture { } enum TestEnum { - BLUE, GREEN + BLUE, + GREEN } static abstract class GivenChildService implements IdToDtoResolver { @@ -119,7 +127,7 @@ public class JSonAccessFilterTestFixture { @ParentId(resolver = GivenService.class) Long parentId; - @AccessFor(init = {TECHNICAL_CONTACT, FINANCIAL_CONTACT}, update = {TECHNICAL_CONTACT, FINANCIAL_CONTACT}) + @AccessFor(init = { TECHNICAL_CONTACT, FINANCIAL_CONTACT }, update = { TECHNICAL_CONTACT, FINANCIAL_CONTACT }) String restrictedField; } diff --git a/src/test/java/org/hostsharing/hsadminng/service/accessfilter/JSonBuilder.java b/src/test/java/org/hostsharing/hsadminng/service/accessfilter/JSonBuilder.java index be661d66..4935eaac 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/accessfilter/JSonBuilder.java +++ b/src/test/java/org/hostsharing/hsadminng/service/accessfilter/JSonBuilder.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.accessfilter; import org.apache.commons.lang3.StringUtils; @@ -70,7 +71,6 @@ public class JSonBuilder { return jsonArray.toString() + "]"; } - private static String inQuotes(Object value) { return value != null ? "\"" + value.toString() + "\"" : "null"; } diff --git a/src/test/java/org/hostsharing/hsadminng/service/accessfilter/JSonDeserializationWithAccessFilterUnitTest.java b/src/test/java/org/hostsharing/hsadminng/service/accessfilter/JSonDeserializationWithAccessFilterUnitTest.java index bd97d358..1f894e15 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/accessfilter/JSonDeserializationWithAccessFilterUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/accessfilter/JSonDeserializationWithAccessFilterUnitTest.java @@ -1,13 +1,25 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.accessfilter; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.assertj.core.api.Assumptions.assumeThat; +import static org.hostsharing.hsadminng.service.accessfilter.JSonAccessFilterTestFixture.*; +import static org.hostsharing.hsadminng.service.accessfilter.JSonBuilder.asJSon; +import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser; +import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole; +import static org.mockito.BDDMockito.given; + +import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.core.TreeNode; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; + import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -23,21 +35,14 @@ import java.time.LocalDate; import java.util.Arrays; import java.util.Optional; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; -import static org.assertj.core.api.Assumptions.assumeThat; -import static org.hostsharing.hsadminng.service.accessfilter.JSonAccessFilterTestFixture.*; -import static org.hostsharing.hsadminng.service.accessfilter.JSonBuilder.asJSon; -import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser; -import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole; -import static org.mockito.BDDMockito.given; - @SuppressWarnings("ALL") public class JSonDeserializationWithAccessFilterUnitTest { public static final String SOME_BIG_DECIMAL_AS_STRING = "5432191234888.1"; - public static final BigDecimal SOME_BIG_DECIMAL = new BigDecimal(SOME_BIG_DECIMAL_AS_STRING).setScale(2, BigDecimal.ROUND_HALF_UP); - public static final BigDecimal SOME_BIG_DECIMAL_WITH_ANOTHER_SCALE = new BigDecimal(SOME_BIG_DECIMAL_AS_STRING).setScale(5, BigDecimal.ROUND_HALF_UP); + public static final BigDecimal SOME_BIG_DECIMAL = new BigDecimal(SOME_BIG_DECIMAL_AS_STRING) + .setScale(2, BigDecimal.ROUND_HALF_UP); + public static final BigDecimal SOME_BIG_DECIMAL_WITH_ANOTHER_SCALE = new BigDecimal(SOME_BIG_DECIMAL_AS_STRING) + .setScale(5, BigDecimal.ROUND_HALF_UP); @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); @@ -72,26 +77,28 @@ public class JSonDeserializationWithAccessFilterUnitTest { given(ctx.getAutowireCapableBeanFactory()).willReturn(autowireCapableBeanFactory); given(autowireCapableBeanFactory.createBean(GivenService.class)).willReturn(givenService); - given(givenService.findOne(1234L)).willReturn(Optional.of(new GivenDto() - .with( dto -> { - dto.id = 1234L; - dto.customerId = 888L; - dto.openIntegerField = 11111; - dto.openPrimitiveIntField = 2222; - dto.openLongField = 33333333333333L; - dto.openPrimitiveLongField = 44444444L; - dto.openBooleanField = true; - dto.openPrimitiveBooleanField = false; - dto.openBigDecimalField = SOME_BIG_DECIMAL; - dto.openStringField = "3333"; - dto.restrictedField = "initial value of restricted field"; - dto.restrictedBigDecimalField = SOME_BIG_DECIMAL; - }) - )); + given(givenService.findOne(1234L)).willReturn( + Optional.of( + new GivenDto() + .with(dto -> { + dto.id = 1234L; + dto.customerId = 888L; + dto.openIntegerField = 11111; + dto.openPrimitiveIntField = 2222; + dto.openLongField = 33333333333333L; + dto.openPrimitiveLongField = 44444444L; + dto.openBooleanField = true; + dto.openPrimitiveBooleanField = false; + dto.openBigDecimalField = SOME_BIG_DECIMAL; + dto.openStringField = "3333"; + dto.restrictedField = "initial value of restricted field"; + dto.restrictedBigDecimalField = SOME_BIG_DECIMAL; + }))); given(autowireCapableBeanFactory.createBean(GivenCustomerService.class)).willReturn(givenCustomerService); - given(givenCustomerService.findOne(888L)).willReturn(Optional.of(new GivenCustomerDto() - .with(dto -> dto.id = 888L) - )); + given(givenCustomerService.findOne(888L)).willReturn( + Optional.of( + new GivenCustomerDto() + .with(dto -> dto.id = 888L))); given(jsonParser.getCodec()).willReturn(codec); } @@ -99,10 +106,11 @@ public class JSonDeserializationWithAccessFilterUnitTest { @Test public void shouldDeserializeNullField() throws IOException { // given - givenJSonTree(asJSon( - ImmutablePair.of("id", 1234L), - ImmutablePair.of("customerId", 888L), - ImmutablePair.of("openStringField", null))); + givenJSonTree( + asJSon( + ImmutablePair.of("id", 1234L), + ImmutablePair.of("customerId", 888L), + ImmutablePair.of("openStringField", null))); // when GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize(); @@ -114,10 +122,11 @@ public class JSonDeserializationWithAccessFilterUnitTest { @Test public void shouldDeserializeStringField() throws IOException { // given - givenJSonTree(asJSon( - ImmutablePair.of("id", 1234L), - ImmutablePair.of("customerId", 888L), - ImmutablePair.of("openStringField", "String Value"))); + givenJSonTree( + asJSon( + ImmutablePair.of("id", 1234L), + ImmutablePair.of("customerId", 888L), + ImmutablePair.of("openStringField", "String Value"))); // when GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize(); @@ -129,10 +138,11 @@ public class JSonDeserializationWithAccessFilterUnitTest { @Test public void shouldDeserializeIntegerField() throws IOException { // given - givenJSonTree(asJSon( - ImmutablePair.of("id", 1234L), - ImmutablePair.of("customerId", 888L), - ImmutablePair.of("openIntegerField", 1234))); + givenJSonTree( + asJSon( + ImmutablePair.of("id", 1234L), + ImmutablePair.of("customerId", 888L), + ImmutablePair.of("openIntegerField", 1234))); // when GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize(); @@ -141,15 +151,15 @@ public class JSonDeserializationWithAccessFilterUnitTest { assertThat(actualDto.openIntegerField).isEqualTo(1234); } - @Test public void shouldDeserializeRestrictedBigDecimalFieldIfUnchangedByCompareTo() throws IOException { // given assumeThat(SOME_BIG_DECIMAL_WITH_ANOTHER_SCALE).isNotEqualTo(SOME_BIG_DECIMAL); - givenJSonTree(asJSon( - ImmutablePair.of("id", 1234L), - ImmutablePair.of("customerId", 888L), - ImmutablePair.of("restrictedBigDecimalField", SOME_BIG_DECIMAL_WITH_ANOTHER_SCALE))); + givenJSonTree( + asJSon( + ImmutablePair.of("id", 1234L), + ImmutablePair.of("customerId", 888L), + ImmutablePair.of("restrictedBigDecimalField", SOME_BIG_DECIMAL_WITH_ANOTHER_SCALE))); // when GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize(); @@ -160,26 +170,26 @@ public class JSonDeserializationWithAccessFilterUnitTest { } @Test - // TODO: split in separate tests for each type, you see all errors at once (if any) and it's easier to debug when there are problems + // TODO: split in separate tests for each type, you see all errors at once (if any) and it's easier to debug when there are + // problems public void shouldDeserializeAcessibleFieldOfAnyType() throws IOException { // given - givenJSonTree(asJSon( - ImmutablePair.of("id", 1234L), - ImmutablePair.of("customerId", 888L), - ImmutablePair.of("openIntegerField", 11), - ImmutablePair.of("openPrimitiveIntField", 22), - ImmutablePair.of("openLongField", 333333333333333333L), - ImmutablePair.of("openPrimitiveLongField", 44444L), - ImmutablePair.of("openBooleanField", true), - ImmutablePair.of("openPrimitiveBooleanField", false), - // TODO: ImmutablePair.of("openBigDecimalField", new BigDecimal("99999999999999999999.1")), - // check why DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS is not working! - ImmutablePair.of("openBigDecimalField", new BigDecimal("99999999999999.1")), - ImmutablePair.of("openLocalDateField", LocalDate.parse("2019-04-25")), - ImmutablePair.of("openLocalDateField2", Arrays.asList(2019, 4, 24)), - ImmutablePair.of("openEnumField", TestEnum.GREEN) - ) - ); + givenJSonTree( + asJSon( + ImmutablePair.of("id", 1234L), + ImmutablePair.of("customerId", 888L), + ImmutablePair.of("openIntegerField", 11), + ImmutablePair.of("openPrimitiveIntField", 22), + ImmutablePair.of("openLongField", 333333333333333333L), + ImmutablePair.of("openPrimitiveLongField", 44444L), + ImmutablePair.of("openBooleanField", true), + ImmutablePair.of("openPrimitiveBooleanField", false), + // TODO: ImmutablePair.of("openBigDecimalField", new BigDecimal("99999999999999999999.1")), + // check why DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS is not working! + ImmutablePair.of("openBigDecimalField", new BigDecimal("99999999999999.1")), + ImmutablePair.of("openLocalDateField", LocalDate.parse("2019-04-25")), + ImmutablePair.of("openLocalDateField2", Arrays.asList(2019, 4, 24)), + ImmutablePair.of("openEnumField", TestEnum.GREEN))); // when GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize(); @@ -200,15 +210,15 @@ public class JSonDeserializationWithAccessFilterUnitTest { @Test public void shouldNotDeserializeFieldWithUnknownJSonNodeType() throws IOException { // given - givenJSonTree(asJSon( - ImmutablePair.of("id", 1234L), - ImmutablePair.of("customerId", 888L), - ImmutablePair.of("openArrayField", Arrays.asList(11, 22, 33)) - ) - ); + givenJSonTree( + asJSon( + ImmutablePair.of("id", 1234L), + ImmutablePair.of("customerId", 888L), + ImmutablePair.of("openArrayField", Arrays.asList(11, 22, 33)))); // when - Throwable exception = catchThrowable(() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize()); + Throwable exception = catchThrowable( + () -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize()); // then assertThat(exception).isInstanceOf(NotImplementedException.class); @@ -219,10 +229,11 @@ public class JSonDeserializationWithAccessFilterUnitTest { // given givenAuthenticatedUser(); givenUserHavingRole(GivenCustomerDto.class, 888L, Role.FINANCIAL_CONTACT); - givenJSonTree(asJSon( - ImmutablePair.of("id", 1234L), - ImmutablePair.of("customerId", 888L), - ImmutablePair.of("restrictedField", "update value of restricted field"))); + givenJSonTree( + asJSon( + ImmutablePair.of("id", 1234L), + ImmutablePair.of("customerId", 888L), + ImmutablePair.of("restrictedField", "update value of restricted field"))); // when GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize(); @@ -236,10 +247,11 @@ public class JSonDeserializationWithAccessFilterUnitTest { // given givenAuthenticatedUser(); givenUserHavingRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER); - givenJSonTree(asJSon( - ImmutablePair.of("id", 1234L), - ImmutablePair.of("customerId", 888L), - ImmutablePair.of("restrictedField", "initial value of restricted field"))); + givenJSonTree( + asJSon( + ImmutablePair.of("id", 1234L), + ImmutablePair.of("customerId", 888L), + ImmutablePair.of("restrictedField", "initial value of restricted field"))); // when GivenDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize(); @@ -253,13 +265,14 @@ public class JSonDeserializationWithAccessFilterUnitTest { // given givenAuthenticatedUser(); givenUserHavingRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER); - givenJSonTree(asJSon( - ImmutablePair.of("customerId", 888L), - ImmutablePair.of("restrictedField", "updated value of restricted field")) - ); + givenJSonTree( + asJSon( + ImmutablePair.of("customerId", 888L), + ImmutablePair.of("restrictedField", "updated value of restricted field"))); // when - Throwable exception = catchThrowable(() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize()); + Throwable exception = catchThrowable( + () -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize()); // then assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> { @@ -273,13 +286,14 @@ public class JSonDeserializationWithAccessFilterUnitTest { // given givenAuthenticatedUser(); givenUserHavingRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER); - givenJSonTree(asJSon( - ImmutablePair.of("customerId", 888L), - ImmutablePair.of("restrictedField", "another value of restricted field")) - ); + givenJSonTree( + asJSon( + ImmutablePair.of("customerId", 888L), + ImmutablePair.of("restrictedField", "another value of restricted field"))); // when - Throwable exception = catchThrowable(() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize()); + Throwable exception = catchThrowable( + () -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize()); // then assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> { @@ -293,12 +307,13 @@ public class JSonDeserializationWithAccessFilterUnitTest { // given givenAuthenticatedUser(); givenUserHavingRole(GivenDto.class, 9999L, Role.CONTRACTUAL_CONTACT); - givenJSonTree(asJSon( - ImmutablePair.of("parentId", 1234L)) - ); + givenJSonTree( + asJSon( + ImmutablePair.of("parentId", 1234L))); // when - Throwable exception = catchThrowable(() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenChildDto.class).deserialize()); + Throwable exception = catchThrowable( + () -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenChildDto.class).deserialize()); // then assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> { @@ -312,12 +327,13 @@ public class JSonDeserializationWithAccessFilterUnitTest { // given givenAuthenticatedUser(); givenUserHavingRole(GivenDto.class, 1234L, Role.CONTRACTUAL_CONTACT); - givenJSonTree(asJSon( - ImmutablePair.of("parentId", 1234L)) - ); + givenJSonTree( + asJSon( + ImmutablePair.of("parentId", 1234L))); // when - final GivenChildDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenChildDto.class).deserialize(); + final GivenChildDto actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenChildDto.class) + .deserialize(); // then assertThat(actualDto.parentId).isEqualTo(1234L); @@ -328,13 +344,15 @@ public class JSonDeserializationWithAccessFilterUnitTest { // given givenAuthenticatedUser(); givenUserHavingRole(GivenCustomerDto.class, 888L, Role.ACTUAL_CUSTOMER_USER); - givenJSonTree(asJSon( - ImmutablePair.of("id", 1234L), - ImmutablePair.of("customerId", 888L), - ImmutablePair.of("restrictedField", "Restricted String Value"))); + givenJSonTree( + asJSon( + ImmutablePair.of("id", 1234L), + ImmutablePair.of("customerId", 888L), + ImmutablePair.of("restrictedField", "Restricted String Value"))); // when - Throwable exception = catchThrowable(() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize()); + Throwable exception = catchThrowable( + () -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDto.class).deserialize()); // then assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> { @@ -349,10 +367,13 @@ public class JSonDeserializationWithAccessFilterUnitTest { givenJSonTree(asJSon(ImmutablePair.of("id", 1111L))); // when - Throwable exception = catchThrowable(() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDtoWithMultipleSelfId.class).deserialize()); + Throwable exception = catchThrowable( + () -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDtoWithMultipleSelfId.class) + .deserialize()); // then - assertThat(exception).isInstanceOf(AssertionError.class).hasMessage("multiple @SelfId detected in GivenDtoWithMultipleSelfId"); + assertThat(exception).isInstanceOf(AssertionError.class) + .hasMessage("multiple @SelfId detected in GivenDtoWithMultipleSelfId"); } @Test @@ -363,13 +384,15 @@ public class JSonDeserializationWithAccessFilterUnitTest { givenJSonTree(asJSon(ImmutablePair.of("unknown", new Arbitrary()))); // when - Throwable exception = catchThrowable(() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDtoWithUnknownFieldType.class).deserialize()); + Throwable exception = catchThrowable( + () -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, GivenDtoWithUnknownFieldType.class) + .deserialize()); // then assertThat(exception).isInstanceOf(NotImplementedException.class) - .hasMessageStartingWith("property type not yet implemented: ") - .hasMessageContaining("Arbitrary") - .hasMessageContaining("GivenDtoWithUnknownFieldType.unknown"); + .hasMessageStartingWith("property type not yet implemented: ") + .hasMessageContaining("Arbitrary") + .hasMessageContaining("GivenDtoWithUnknownFieldType.unknown"); } // --- only fixture code below --- diff --git a/src/test/java/org/hostsharing/hsadminng/service/accessfilter/JSonSerializationWithAccessFilterUnitTest.java b/src/test/java/org/hostsharing/hsadminng/service/accessfilter/JSonSerializationWithAccessFilterUnitTest.java index 4841d729..451c086e 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/accessfilter/JSonSerializationWithAccessFilterUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/accessfilter/JSonSerializationWithAccessFilterUnitTest.java @@ -1,6 +1,15 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.accessfilter; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.hostsharing.hsadminng.service.accessfilter.JSonAccessFilterTestFixture.*; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + import com.fasterxml.jackson.core.JsonGenerator; + import org.apache.commons.lang3.NotImplementedException; import org.junit.Before; import org.junit.Rule; @@ -14,13 +23,6 @@ import org.springframework.context.ApplicationContext; import java.io.IOException; import java.util.Optional; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; -import static org.hostsharing.hsadminng.service.accessfilter.JSonAccessFilterTestFixture.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - public class JSonSerializationWithAccessFilterUnitTest { @Rule @@ -47,9 +49,10 @@ public class JSonSerializationWithAccessFilterUnitTest { given(ctx.getAutowireCapableBeanFactory()).willReturn(autowireCapableBeanFactory); given(autowireCapableBeanFactory.createBean(GivenCustomerService.class)).willReturn(givenCustomerService); - given(givenCustomerService.findOne(888L)).willReturn(Optional.of(new GivenCustomerDto() - .with(dto -> dto.id = 888L) - )); + given(givenCustomerService.findOne(888L)).willReturn( + Optional.of( + new GivenCustomerDto() + .with(dto -> dto.id = 888L))); } @Test @@ -177,13 +180,16 @@ public class JSonSerializationWithAccessFilterUnitTest { class Arbitrary { } class GivenDtoWithUnimplementedFieldType { + @AccessFor(read = Role.ANYBODY) Arbitrary fieldWithUnimplementedType = new Arbitrary(); } final GivenDtoWithUnimplementedFieldType givenDtoWithUnimplementedFieldType = new GivenDtoWithUnimplementedFieldType(); // when - final Throwable actual = catchThrowable(() -> new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDtoWithUnimplementedFieldType).serialize()); + final Throwable actual = catchThrowable( + () -> new JSonSerializationWithAccessFilter<>(ctx, jsonGenerator, null, givenDtoWithUnimplementedFieldType) + .serialize()); // then assertThat(actual).isInstanceOf(NotImplementedException.class); diff --git a/src/test/java/org/hostsharing/hsadminng/service/accessfilter/MockSecurityContext.java b/src/test/java/org/hostsharing/hsadminng/service/accessfilter/MockSecurityContext.java index da028ca4..a110627b 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/accessfilter/MockSecurityContext.java +++ b/src/test/java/org/hostsharing/hsadminng/service/accessfilter/MockSecurityContext.java @@ -1,12 +1,14 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.accessfilter; +import static org.assertj.core.api.Assumptions.assumeThat; + import org.hostsharing.hsadminng.security.SecurityUtils; + import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; -import static org.assertj.core.api.Assumptions.assumeThat; - public class MockSecurityContext { public static void givenAuthenticatedUser() { diff --git a/src/test/java/org/hostsharing/hsadminng/service/accessfilter/RoleUnitTest.java b/src/test/java/org/hostsharing/hsadminng/service/accessfilter/RoleUnitTest.java index ce6a16f8..54807f98 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/accessfilter/RoleUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/accessfilter/RoleUnitTest.java @@ -1,13 +1,15 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.accessfilter; -import com.google.common.base.VerifyException; -import org.junit.Test; - -import java.lang.reflect.Field; - import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.ThrowableAssert.catchThrowable; +import com.google.common.base.VerifyException; + +import org.junit.Test; + +import java.lang.reflect.Field; + public class RoleUnitTest { @Test @@ -20,7 +22,6 @@ public class RoleUnitTest { assertThat(Role.FINANCIAL_CONTACT.covers(Role.FINANCIAL_CONTACT)).isTrue(); assertThat(Role.TECHNICAL_CONTACT.covers(Role.TECHNICAL_CONTACT)).isTrue(); - assertThat(Role.ACTUAL_CUSTOMER_USER.covers((Role.ACTUAL_CUSTOMER_USER))).isTrue(); assertThat(Role.ANY_CUSTOMER_USER.covers((Role.ANY_CUSTOMER_USER))).isTrue(); } @@ -153,13 +154,14 @@ public class RoleUnitTest { // --- only test fixture below --- static class TestDto { + @AccessFor(init = Role.ADMIN, update = Role.SUPPORTER, read = Role.ANY_CUSTOMER_CONTACT) private Integer someFieldWithAccessForAnnotation; @AccessFor(update = Role.IGNORED, read = Role.ANY_CUSTOMER_CONTACT) private Integer someFieldWithAccessForAnnotationToBeIgnoredForUpdates; - @AccessFor(update = {Role.IGNORED, Role.SUPPORTER}, read = Role.ANY_CUSTOMER_CONTACT) + @AccessFor(update = { Role.IGNORED, Role.SUPPORTER }, read = Role.ANY_CUSTOMER_CONTACT) private Integer someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers; private Integer someFieldWithoutAccessForAnnotation; @@ -173,8 +175,10 @@ public class RoleUnitTest { static { try { someFieldWithoutAccessForAnnotation = TestDto.class.getDeclaredField("someFieldWithoutAccessForAnnotation"); - someFieldWithAccessForAnnotationToBeIgnoredForUpdates = TestDto.class.getDeclaredField("someFieldWithAccessForAnnotationToBeIgnoredForUpdates"); - someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers = TestDto.class.getDeclaredField("someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers"); + someFieldWithAccessForAnnotationToBeIgnoredForUpdates = TestDto.class + .getDeclaredField("someFieldWithAccessForAnnotationToBeIgnoredForUpdates"); + someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers = TestDto.class + .getDeclaredField("someFieldWithAccessForAnnotationToBeIgnoredForUpdatesAmongOthers"); someFieldWithAccessForAnnotation = TestDto.class.getDeclaredField("someFieldWithAccessForAnnotation"); } catch (NoSuchFieldException e) { throw new AssertionError("precondition failed", e); diff --git a/src/test/java/org/hostsharing/hsadminng/service/dto/AccessMappingsUnitTestBase.java b/src/test/java/org/hostsharing/hsadminng/service/dto/AccessMappingsUnitTestBase.java index 3992ea27..a458a839 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/dto/AccessMappingsUnitTestBase.java +++ b/src/test/java/org/hostsharing/hsadminng/service/dto/AccessMappingsUnitTestBase.java @@ -1,8 +1,14 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.dto; -import org.apache.commons.lang3.RandomUtils; +import static org.apache.commons.lang3.StringUtils.removeEnd; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; + import org.hostsharing.hsadminng.service.accessfilter.*; import org.hostsharing.hsadminng.service.util.ReflectionUtil; + +import org.apache.commons.lang3.RandomUtils; import org.junit.Test; import org.springframework.boot.jackson.JsonComponent; @@ -15,10 +21,6 @@ import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; -import static org.apache.commons.lang3.StringUtils.removeEnd; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; - /** * Usually base classes for unit tests are not a good idea, but because * DTOs which implement AccessMapping are more like a DSL, @@ -30,7 +32,10 @@ public abstract class AccessMappingsUnitTestBase { private final BiFunction createSampleDTO; private final BiFunction createRandomDTO; - public AccessMappingsUnitTestBase(Class dtoClass, final BiFunction createSampleDTO, final BiFunction createRandomDTO) { + public AccessMappingsUnitTestBase( + Class dtoClass, + final BiFunction createSampleDTO, + final BiFunction createRandomDTO) { this.dtoClass = dtoClass; this.createSampleDTO = createSampleDTO; this.createRandomDTO = createRandomDTO; @@ -105,6 +110,7 @@ public abstract class AccessMappingsUnitTestBase { // This class should have the same generics as the outer class, but then the // method references (AccessFor::*) can't be resolved anymore by the Java compiler. protected static class AccessRightsMatcher { + private final Object dtoClass; private final Role role; @@ -117,9 +123,14 @@ public abstract class AccessMappingsUnitTestBase { final Set fieldsWithAccessForAnnotation = determineFieldsWithAccessForAnnotation(dtoClass); this.namesOfFieldsWithAccessForAnnotation = fieldsWithAccessForAnnotation.stream() - .map(Field::getName).collect(Collectors.toList()).toArray(new String[]{}); + .map(Field::getName) + .collect(Collectors.toList()) + .toArray(new String[] {}); this.namesOfAccessibleFields = fieldsWithAccessForAnnotation.stream() - .filter(f -> allows(f, access, role)).map(Field::getName).collect(Collectors.toList()).toArray(new String[]{}); + .filter(f -> allows(f, access, role)) + .map(Field::getName) + .collect(Collectors.toList()) + .toArray(new String[] {}); } public void shouldBeExactlyFor(final String... expectedFields) { @@ -134,7 +145,6 @@ public abstract class AccessMappingsUnitTestBase { assertThat(namesOfAccessibleFields).containsExactlyInAnyOrder(namesOfFieldsWithAccessForAnnotation); } - private static Set determineFieldsWithAccessForAnnotation(final Class dtoClass) { final Set fieldsWithAccessForAnnotation = new HashSet<>(); @@ -205,13 +215,16 @@ public abstract class AccessMappingsUnitTestBase { for (Class declaredClass : dtoClass.getDeclaredClasses()) { if (expectedSuperclass.isAssignableFrom(declaredClass)) { assertThat(declaredClass.isAnnotationPresent(JsonComponent.class)) - .as(declaredClass + " requires @" + JsonComponent.class.getSimpleName()).isTrue(); + .as(declaredClass + " requires @" + JsonComponent.class.getSimpleName()) + .isTrue(); assertThat(ReflectionUtil.determineGenericClassParameter(declaredClass, expectedSuperclass, 0)) - .as(declaredClass + " must resolve generic parameter of " + expectedSuperclass + " to type of DTO").isEqualTo(dtoClass); + .as(declaredClass + " must resolve generic parameter of " + expectedSuperclass + " to type of DTO") + .isEqualTo(dtoClass); assertThat(Modifier.isPublic(declaredClass.getModifiers())).as(declaredClass + " must be public").isTrue(); assertThat(Modifier.isStatic(declaredClass.getModifiers())).as(declaredClass + " must be static").isTrue(); assertThat(Modifier.isFinal(declaredClass.getModifiers())).as(declaredClass + " must not be final").isFalse(); - assertThat(Modifier.isAbstract(declaredClass.getModifiers())).as(declaredClass + " must not be abstract").isFalse(); + assertThat(Modifier.isAbstract(declaredClass.getModifiers())).as(declaredClass + " must not be abstract") + .isFalse(); return; } } diff --git a/src/test/java/org/hostsharing/hsadminng/service/dto/AssetDTOIntTest.java b/src/test/java/org/hostsharing/hsadminng/service/dto/AssetDTOIntTest.java index b0c1f6f9..6f32c382 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/dto/AssetDTOIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/dto/AssetDTOIntTest.java @@ -1,8 +1,13 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.dto; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.lang3.RandomUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser; +import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole; +import static org.junit.Assert.assertEquals; +import static org.mockito.BDDMockito.given; + import org.hostsharing.hsadminng.domain.Asset; import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.domain.Membership; @@ -20,6 +25,11 @@ import org.hostsharing.hsadminng.service.mapper.AssetMapperImpl; import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl; import org.hostsharing.hsadminng.service.mapper.MembershipMapperImpl; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.apache.commons.lang3.RandomUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -32,27 +42,22 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; -import javax.persistence.EntityManager; import java.io.IOException; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Optional; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; -import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser; -import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole; -import static org.junit.Assert.assertEquals; -import static org.mockito.BDDMockito.given; +import javax.persistence.EntityManager; @JsonTest -@SpringBootTest(classes = { - CustomerMapperImpl.class, - MembershipMapperImpl.class, - AssetMapperImpl.class, - AssetDTO.JsonSerializer.class, - AssetDTO.JsonDeserializer.class -}) +@SpringBootTest( + classes = { + CustomerMapperImpl.class, + MembershipMapperImpl.class, + AssetMapperImpl.class, + AssetDTO.JsonSerializer.class, + AssetDTO.JsonDeserializer.class + }) @RunWith(SpringRunner.class) public class AssetDTOIntTest { @@ -61,12 +66,15 @@ public class AssetDTOIntTest { private static final String SOME_CUSTOMER_PREFIX = "abc"; private static final String SOME_CUSTOMER_NAME = "Some Customer Name"; private static final Customer SOME_CUSTOMER = new Customer().id(SOME_CUSTOMER_ID) - .reference(SOME_CUSTOMER_REFERENCE).prefix(SOME_CUSTOMER_PREFIX).name(SOME_CUSTOMER_NAME); + .reference(SOME_CUSTOMER_REFERENCE) + .prefix(SOME_CUSTOMER_PREFIX) + .name(SOME_CUSTOMER_NAME); private static final Long SOME_MEMBERSHIP_ID = RandomUtils.nextLong(200, 299); private static final LocalDate SOME_MEMBER_FROM_DATE = LocalDate.parse("2000-12-06"); private static final Membership SOME_MEMBERSHIP = new Membership().id(SOME_MEMBERSHIP_ID) - .customer(SOME_CUSTOMER).memberFromDate(SOME_MEMBER_FROM_DATE); + .customer(SOME_CUSTOMER) + .memberFromDate(SOME_MEMBER_FROM_DATE); private static final String SOME_MEMBERSHIP_DISPLAY_LABEL = "Some Customer Name [10001:abc] 2000-12-06 - ..."; private static final Long SOME_ASSET_ID = RandomUtils.nextLong(300, 399); @@ -146,17 +154,18 @@ public class AssetDTOIntTest { givenAuthenticatedUser(); givenUserHavingRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CONTRACTUAL_CONTACT); final String json = new JSonBuilder() - .withFieldValue("id", SOME_ASSET_ID) - .withFieldValue("remark", "Updated Remark") - .toString(); + .withFieldValue("id", SOME_ASSET_ID) + .withFieldValue("remark", "Updated Remark") + .toString(); // when final Throwable actual = catchThrowable(() -> objectMapper.readValue(json, AssetDTO.class)); // then - assertThat(actual).isInstanceOfSatisfying(BadRequestAlertException.class, bre -> - assertThat(bre.getMessage()).isEqualTo("Update of field AssetDTO.remark prohibited for current user role CONTRACTUAL_CONTACT") - ); + assertThat(actual).isInstanceOfSatisfying( + BadRequestAlertException.class, + bre -> assertThat(bre.getMessage()) + .isEqualTo("Update of field AssetDTO.remark prohibited for current user role CONTRACTUAL_CONTACT")); } @Test @@ -165,9 +174,9 @@ public class AssetDTOIntTest { givenAuthenticatedUser(); givenUserHavingRole(Role.ADMIN); final String json = new JSonBuilder() - .withFieldValue("id", SOME_ASSET_ID) - .withFieldValue("remark", "Updated Remark") - .toString(); + .withFieldValue("id", SOME_ASSET_ID) + .withFieldValue("remark", "Updated Remark") + .toString(); // when final AssetDTO actual = objectMapper.readValue(json, AssetDTO.class); @@ -185,18 +194,17 @@ public class AssetDTOIntTest { private String createExpectedJSon(AssetDTO dto) { return new JSonBuilder() - .withFieldValueIfPresent("id", dto.getId()) - .withFieldValueIfPresent("documentDate", dto.getDocumentDate().toString()) - .withFieldValueIfPresent("valueDate", dto.getValueDate().toString()) - .withFieldValueIfPresent("action", dto.getAction().name()) - .withFieldValueIfPresent("amount", dto.getAmount().doubleValue()) - .withFieldValueIfPresent("remark", dto.getRemark()) - .withFieldValueIfPresent("membershipId", dto.getMembershipId()) - .withFieldValue("membershipDisplayLabel", dto.getMembershipDisplayLabel()) - .toString(); + .withFieldValueIfPresent("id", dto.getId()) + .withFieldValueIfPresent("documentDate", dto.getDocumentDate().toString()) + .withFieldValueIfPresent("valueDate", dto.getValueDate().toString()) + .withFieldValueIfPresent("action", dto.getAction().name()) + .withFieldValueIfPresent("amount", dto.getAmount().doubleValue()) + .withFieldValueIfPresent("remark", dto.getRemark()) + .withFieldValueIfPresent("membershipId", dto.getMembershipId()) + .withFieldValue("membershipDisplayLabel", dto.getMembershipDisplayLabel()) + .toString(); } - private AssetDTO createSomeAssetDTO(final long id) { final AssetDTO given = new AssetDTO(); given.setId(id); diff --git a/src/test/java/org/hostsharing/hsadminng/service/dto/AssetDTOUnitTest.java b/src/test/java/org/hostsharing/hsadminng/service/dto/AssetDTOUnitTest.java index 5ccea384..578778ab 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/dto/AssetDTOUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/dto/AssetDTOUnitTest.java @@ -1,10 +1,12 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.dto; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.RandomUtils; import org.hostsharing.hsadminng.domain.enumeration.AssetAction; import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.util.RandomUtil; + +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.RandomUtils; import org.junit.Test; import java.math.BigDecimal; @@ -19,7 +21,12 @@ public class AssetDTOUnitTest extends AccessMappingsUnitTestBase { @Test public void shouldHaveProperAccessForAdmin() { initAccessFor(AssetDTO.class, Role.ADMIN).shouldBeExactlyFor( - "membershipId", "documentDate", "amount", "action", "valueDate", "remark"); + "membershipId", + "documentDate", + "amount", + "action", + "valueDate", + "remark"); updateAccessFor(AssetDTO.class, Role.ADMIN).shouldBeExactlyFor("remark"); readAccessFor(AssetDTO.class, Role.ADMIN).shouldBeForAllFields(); } @@ -29,7 +36,13 @@ public class AssetDTOUnitTest extends AccessMappingsUnitTestBase { initAccessFor(AssetDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeForNothing(); updateAccessFor(AssetDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeForNothing(); readAccessFor(AssetDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeExactlyFor( - "id", "membershipId", "documentDate", "amount", "action", "valueDate", "membershipDisplayLabel"); + "id", + "membershipId", + "documentDate", + "amount", + "action", + "valueDate", + "membershipDisplayLabel"); } @Test diff --git a/src/test/java/org/hostsharing/hsadminng/service/dto/CustomerDTOUnitTest.java b/src/test/java/org/hostsharing/hsadminng/service/dto/CustomerDTOUnitTest.java index 22368d88..75d8e84d 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/dto/CustomerDTOUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/dto/CustomerDTOUnitTest.java @@ -1,7 +1,12 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.dto; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser; +import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole; +import static org.junit.Assert.assertEquals; +import static org.mockito.BDDMockito.given; + import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.domain.enumeration.CustomerKind; import org.hostsharing.hsadminng.domain.enumeration.VatRegion; @@ -11,6 +16,10 @@ import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder; import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.mapper.CustomerMapper; import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -25,14 +34,14 @@ import org.springframework.test.context.junit4.SpringRunner; import java.io.IOException; import java.util.Optional; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser; -import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole; -import static org.junit.Assert.assertEquals; -import static org.mockito.BDDMockito.given; - @JsonTest -@SpringBootTest(classes = {CustomerMapperImpl.class, CustomerRepository.class, CustomerService.class, CustomerDTO.CustomerJsonSerializer.class, CustomerDTO.CustomerJsonDeserializer.class}) +@SpringBootTest( + classes = { + CustomerMapperImpl.class, + CustomerRepository.class, + CustomerService.class, + CustomerDTO.CustomerJsonSerializer.class, + CustomerDTO.CustomerJsonDeserializer.class }) @RunWith(SpringRunner.class) public class CustomerDTOUnitTest { @@ -80,11 +89,12 @@ public class CustomerDTOUnitTest { // then final String expectedJSon = new JSonBuilder() - .withFieldValue("id", given.getId()) - .withFieldValue("reference", given.getReference()) - .withFieldValue("prefix", given.getPrefix()) - .withFieldValue("name", given.getName()) - .withFieldValue("displayLabel", given.getDisplayLabel()).toString(); + .withFieldValue("id", given.getId()) + .withFieldValue("reference", given.getReference()) + .withFieldValue("prefix", given.getPrefix()) + .withFieldValue("name", given.getName()) + .withFieldValue("displayLabel", given.getDisplayLabel()) + .toString(); assertEquals(expectedJSon, actual); } @@ -126,23 +136,24 @@ public class CustomerDTOUnitTest { private String createExpectedJSon(CustomerDTO dto) { return new JSonBuilder() - .withFieldValueIfPresent("id", dto.getId()) - .withFieldValueIfPresent("reference", dto.getReference()) - .withFieldValueIfPresent("prefix", dto.getPrefix()) - .withFieldValueIfPresent("name", dto.getName()) - .withFieldValueIfPresent("kind", "LEGAL") - .toJSonNullFieldDefinition("birthDate") - .toJSonNullFieldDefinition("birthPlace") - .withFieldValueIfPresent("registrationCourt", "Registergericht") - .withFieldValueIfPresent("registrationNumber", "Registernummer") - .withFieldValueIfPresent("vatRegion", "DOMESTIC") - .withFieldValueIfPresent("vatNumber", "DE1234") - .withFieldValueIfPresent("contractualSalutation", dto.getContractualSalutation()) - .withFieldValueIfPresent("contractualAddress", dto.getContractualAddress()) - .withFieldValueIfPresent("billingSalutation", dto.getBillingSalutation()) - .withFieldValueIfPresent("billingAddress", dto.getBillingAddress()) - .withFieldValueIfPresent("remark", dto.getRemark()) - .withFieldValueIfPresent("displayLabel", dto.getDisplayLabel()).toString(); + .withFieldValueIfPresent("id", dto.getId()) + .withFieldValueIfPresent("reference", dto.getReference()) + .withFieldValueIfPresent("prefix", dto.getPrefix()) + .withFieldValueIfPresent("name", dto.getName()) + .withFieldValueIfPresent("kind", "LEGAL") + .toJSonNullFieldDefinition("birthDate") + .toJSonNullFieldDefinition("birthPlace") + .withFieldValueIfPresent("registrationCourt", "Registergericht") + .withFieldValueIfPresent("registrationNumber", "Registernummer") + .withFieldValueIfPresent("vatRegion", "DOMESTIC") + .withFieldValueIfPresent("vatNumber", "DE1234") + .withFieldValueIfPresent("contractualSalutation", dto.getContractualSalutation()) + .withFieldValueIfPresent("contractualAddress", dto.getContractualAddress()) + .withFieldValueIfPresent("billingSalutation", dto.getBillingSalutation()) + .withFieldValueIfPresent("billingAddress", dto.getBillingAddress()) + .withFieldValueIfPresent("remark", dto.getRemark()) + .withFieldValueIfPresent("displayLabel", dto.getDisplayLabel()) + .toString(); } private CustomerDTO createSomeCustomerDTO(final long id) { diff --git a/src/test/java/org/hostsharing/hsadminng/service/dto/MembershipDTOTest.java b/src/test/java/org/hostsharing/hsadminng/service/dto/MembershipDTOTest.java index ffcec115..2c03c8af 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/dto/MembershipDTOTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/dto/MembershipDTOTest.java @@ -1,9 +1,10 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.dto; -import org.junit.Test; - import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + public class MembershipDTOTest { @Test diff --git a/src/test/java/org/hostsharing/hsadminng/service/dto/MembershipDTOUnitTest.java b/src/test/java/org/hostsharing/hsadminng/service/dto/MembershipDTOUnitTest.java index da6e4131..db2cb976 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/dto/MembershipDTOUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/dto/MembershipDTOUnitTest.java @@ -1,15 +1,25 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.dto; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.ObjectCodec; -import com.fasterxml.jackson.core.TreeNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.lang3.tuple.ImmutablePair; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.hostsharing.hsadminng.service.accessfilter.JSonBuilder.asJSon; +import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser; +import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole; +import static org.mockito.BDDMockito.given; + import org.hostsharing.hsadminng.service.CustomerService; import org.hostsharing.hsadminng.service.MembershipService; import org.hostsharing.hsadminng.service.accessfilter.JSonDeserializationWithAccessFilter; import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.core.TreeNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -22,13 +32,6 @@ import org.springframework.context.ApplicationContext; import java.io.IOException; import java.util.Optional; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; -import static org.hostsharing.hsadminng.service.accessfilter.JSonBuilder.asJSon; -import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser; -import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole; -import static org.mockito.BDDMockito.given; - public class MembershipDTOUnitTest { @Rule @@ -59,12 +62,13 @@ public class MembershipDTOUnitTest { public void init() { given(jsonParser.getCodec()).willReturn(codec); - given (ctx.getAutowireCapableBeanFactory()).willReturn(autowireCapableBeanFactory); + given(ctx.getAutowireCapableBeanFactory()).willReturn(autowireCapableBeanFactory); given(autowireCapableBeanFactory.createBean(MembershipService.class)).willReturn(membershipService); given(autowireCapableBeanFactory.createBean(CustomerService.class)).willReturn(customerService); - given(customerService.findOne(1234L)).willReturn(Optional.of(new CustomerDTO() - .with(dto -> dto.setId(1234L)) - )); + given(customerService.findOne(1234L)).willReturn( + Optional.of( + new CustomerDTO() + .with(dto -> dto.setId(1234L)))); } @Test @@ -74,7 +78,8 @@ public class MembershipDTOUnitTest { givenJSonTree(asJSon(ImmutablePair.of("customerId", 1234L))); // when - final MembershipDTO actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, MembershipDTO.class).deserialize(); + final MembershipDTO actualDto = new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, MembershipDTO.class) + .deserialize(); // then assertThat(actualDto.getCustomerId()).isEqualTo(1234L); @@ -87,7 +92,8 @@ public class MembershipDTOUnitTest { givenJSonTree(asJSon(ImmutablePair.of("customerId", 1234L))); // when - Throwable exception = catchThrowable(() -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, MembershipDTO.class).deserialize()); + Throwable exception = catchThrowable( + () -> new JSonDeserializationWithAccessFilter<>(ctx, jsonParser, null, MembershipDTO.class).deserialize()); // then assertThat(exception).isInstanceOfSatisfying(BadRequestAlertException.class, badRequestAlertException -> { diff --git a/src/test/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTOIntTest.java b/src/test/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTOIntTest.java index 648ff43b..46ac0a26 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTOIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTOIntTest.java @@ -1,8 +1,14 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.dto; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.lang3.RandomUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser; +import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole; +import static org.hostsharing.hsadminng.service.dto.SepaMandateDTOUnitTest.createSampleDTO; +import static org.junit.Assert.assertEquals; +import static org.mockito.BDDMockito.given; + import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.domain.SepaMandate; import org.hostsharing.hsadminng.repository.CustomerRepository; @@ -17,6 +23,11 @@ import org.hostsharing.hsadminng.service.mapper.MembershipMapperImpl; import org.hostsharing.hsadminng.service.mapper.SepaMandateMapper; import org.hostsharing.hsadminng.service.mapper.SepaMandateMapperImpl; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.apache.commons.lang3.RandomUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -29,27 +40,21 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; -import javax.persistence.EntityManager; import java.io.IOException; import java.util.Objects; import java.util.Optional; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.catchThrowable; -import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser; -import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole; -import static org.hostsharing.hsadminng.service.dto.SepaMandateDTOUnitTest.createSampleDTO; -import static org.junit.Assert.assertEquals; -import static org.mockito.BDDMockito.given; +import javax.persistence.EntityManager; @JsonTest -@SpringBootTest(classes = { - CustomerMapperImpl.class, - MembershipMapperImpl.class, - SepaMandateMapperImpl.class, - SepaMandateDTO.JsonSerializer.class, - SepaMandateDTO.JsonDeserializer.class -}) +@SpringBootTest( + classes = { + CustomerMapperImpl.class, + MembershipMapperImpl.class, + SepaMandateMapperImpl.class, + SepaMandateDTO.JsonSerializer.class, + SepaMandateDTO.JsonDeserializer.class + }) @RunWith(SpringRunner.class) public class SepaMandateDTOIntTest { @@ -59,7 +64,9 @@ public class SepaMandateDTOIntTest { private static final String SOME_CUSTOMER_NAME = "Some Customer Name"; private static final String SOME_CUSTOMER_DISPLAY_LABEL = "Some Customer Name [10001:abc]"; private static final Customer SOME_CUSTOMER = new Customer().id(SOME_CUSTOMER_ID) - .reference(SOME_CUSTOMER_REFERENCE).prefix(SOME_CUSTOMER_PREFIX).name(SOME_CUSTOMER_NAME); + .reference(SOME_CUSTOMER_REFERENCE) + .prefix(SOME_CUSTOMER_PREFIX) + .name(SOME_CUSTOMER_NAME); private static final Long SOME_SEPA_MANDATE_ID = RandomUtils.nextLong(300, 399); private static final SepaMandate SOME_SEPA_MANDATE = new SepaMandate().id(SOME_SEPA_MANDATE_ID).customer(SOME_CUSTOMER); @@ -134,17 +141,18 @@ public class SepaMandateDTOIntTest { givenAuthenticatedUser(); givenUserHavingRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CONTRACTUAL_CONTACT); final String json = new JSonBuilder() - .withFieldValue("id", SOME_SEPA_MANDATE_ID) - .withFieldValue("remark", "Updated Remark") - .toString(); + .withFieldValue("id", SOME_SEPA_MANDATE_ID) + .withFieldValue("remark", "Updated Remark") + .toString(); // when final Throwable actual = catchThrowable(() -> objectMapper.readValue(json, SepaMandateDTO.class)); // then - assertThat(actual).isInstanceOfSatisfying(BadRequestAlertException.class, bre -> - assertThat(bre.getMessage()).isEqualTo("Update of field SepaMandateDTO.remark prohibited for current user role CONTRACTUAL_CONTACT") - ); + assertThat(actual).isInstanceOfSatisfying( + BadRequestAlertException.class, + bre -> assertThat(bre.getMessage()).isEqualTo( + "Update of field SepaMandateDTO.remark prohibited for current user role CONTRACTUAL_CONTACT")); } @Test @@ -153,9 +161,9 @@ public class SepaMandateDTOIntTest { givenAuthenticatedUser(); givenUserHavingRole(Role.ADMIN); final String json = new JSonBuilder() - .withFieldValue("id", SOME_SEPA_MANDATE_ID) - .withFieldValue("remark", "Updated Remark") - .toString(); + .withFieldValue("id", SOME_SEPA_MANDATE_ID) + .withFieldValue("remark", "Updated Remark") + .toString(); // when final SepaMandateDTO actual = objectMapper.readValue(json, SepaMandateDTO.class); @@ -173,18 +181,18 @@ public class SepaMandateDTOIntTest { private String createExpectedJSon(SepaMandateDTO dto) { return new JSonBuilder() - .withFieldValueIfPresent("id", dto.getId()) - .withFieldValueIfPresent("reference", dto.getReference()) - .withFieldValueIfPresent("iban", dto.getIban()) - .withFieldValueIfPresent("bic", dto.getBic()) - .withFieldValueIfPresent("grantingDocumentDate", Objects.toString(dto.getGrantingDocumentDate())) - .withFieldValueIfPresent("revokationDocumentDate", Objects.toString(dto.getRevokationDocumentDate())) - .withFieldValueIfPresent("validFromDate", Objects.toString(dto.getValidFromDate())) - .withFieldValueIfPresent("validUntilDate", Objects.toString(dto.getValidUntilDate())) - .withFieldValueIfPresent("lastUsedDate", Objects.toString(dto.getLastUsedDate())) - .withFieldValueIfPresent("remark", dto.getRemark()) - .withFieldValueIfPresent("customerId", dto.getCustomerId()) - .withFieldValue("customerDisplayLabel", dto.getCustomerDisplayLabel()) - .toString(); + .withFieldValueIfPresent("id", dto.getId()) + .withFieldValueIfPresent("reference", dto.getReference()) + .withFieldValueIfPresent("iban", dto.getIban()) + .withFieldValueIfPresent("bic", dto.getBic()) + .withFieldValueIfPresent("grantingDocumentDate", Objects.toString(dto.getGrantingDocumentDate())) + .withFieldValueIfPresent("revokationDocumentDate", Objects.toString(dto.getRevokationDocumentDate())) + .withFieldValueIfPresent("validFromDate", Objects.toString(dto.getValidFromDate())) + .withFieldValueIfPresent("validUntilDate", Objects.toString(dto.getValidUntilDate())) + .withFieldValueIfPresent("lastUsedDate", Objects.toString(dto.getLastUsedDate())) + .withFieldValueIfPresent("remark", dto.getRemark()) + .withFieldValueIfPresent("customerId", dto.getCustomerId()) + .withFieldValue("customerDisplayLabel", dto.getCustomerDisplayLabel()) + .toString(); } } diff --git a/src/test/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTOUnitTest.java b/src/test/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTOUnitTest.java index d0db7861..be7babf9 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTOUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTOUnitTest.java @@ -1,8 +1,10 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.dto; +import org.hostsharing.hsadminng.service.accessfilter.Role; + import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomUtils; -import org.hostsharing.hsadminng.service.accessfilter.Role; import org.junit.Test; import java.time.LocalDate; @@ -16,31 +18,66 @@ public class SepaMandateDTOUnitTest extends AccessMappingsUnitTestBase objectMapper.readValue(json, ShareDTO.class)); // then - assertThat(actual).isInstanceOfSatisfying(BadRequestAlertException.class, bre -> - assertThat(bre.getMessage()).isEqualTo("Update of field ShareDTO.remark prohibited for current user role CONTRACTUAL_CONTACT") - ); + assertThat(actual).isInstanceOfSatisfying( + BadRequestAlertException.class, + bre -> assertThat(bre.getMessage()) + .isEqualTo("Update of field ShareDTO.remark prohibited for current user role CONTRACTUAL_CONTACT")); } @Test @@ -164,9 +173,9 @@ public class ShareDTOIntTest { givenAuthenticatedUser(); givenUserHavingRole(Role.ADMIN); final String json = new JSonBuilder() - .withFieldValue("id", SOME_SHARE_ID) - .withFieldValue("remark", "Updated Remark") - .toString(); + .withFieldValue("id", SOME_SHARE_ID) + .withFieldValue("remark", "Updated Remark") + .toString(); // when final ShareDTO actual = objectMapper.readValue(json, ShareDTO.class); @@ -184,15 +193,15 @@ public class ShareDTOIntTest { private String createExpectedJSon(ShareDTO dto) { return new JSonBuilder() - .withFieldValueIfPresent("id", dto.getId()) - .withFieldValueIfPresent("documentDate", dto.getDocumentDate().toString()) - .withFieldValueIfPresent("valueDate", dto.getValueDate().toString()) - .withFieldValueIfPresent("action", dto.getAction().name()) - .withFieldValueIfPresent("quantity", dto.getQuantity()) - .withFieldValueIfPresent("remark", dto.getRemark()) - .withFieldValueIfPresent("membershipId", dto.getMembershipId()) - .withFieldValue("membershipDisplayLabel", dto.getMembershipDisplayLabel()) - .toString(); + .withFieldValueIfPresent("id", dto.getId()) + .withFieldValueIfPresent("documentDate", dto.getDocumentDate().toString()) + .withFieldValueIfPresent("valueDate", dto.getValueDate().toString()) + .withFieldValueIfPresent("action", dto.getAction().name()) + .withFieldValueIfPresent("quantity", dto.getQuantity()) + .withFieldValueIfPresent("remark", dto.getRemark()) + .withFieldValueIfPresent("membershipId", dto.getMembershipId()) + .withFieldValue("membershipDisplayLabel", dto.getMembershipDisplayLabel()) + .toString(); } private ShareDTO createSomeShareDTO(final long id) { diff --git a/src/test/java/org/hostsharing/hsadminng/service/dto/ShareDTOUnitTest.java b/src/test/java/org/hostsharing/hsadminng/service/dto/ShareDTOUnitTest.java index 91fb8a77..65bbd153 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/dto/ShareDTOUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/dto/ShareDTOUnitTest.java @@ -1,10 +1,12 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.dto; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.RandomUtils; import org.hostsharing.hsadminng.domain.enumeration.ShareAction; import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.util.RandomUtil; + +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.RandomUtils; import org.junit.Test; import java.time.LocalDate; @@ -18,7 +20,12 @@ public class ShareDTOUnitTest extends AccessMappingsUnitTestBase { @Test public void shouldHaveProperAccessForAdmin() { initAccessFor(ShareDTO.class, Role.ADMIN).shouldBeExactlyFor( - "membershipId", "documentDate", "quantity", "action", "valueDate", "remark"); + "membershipId", + "documentDate", + "quantity", + "action", + "valueDate", + "remark"); updateAccessFor(ShareDTO.class, Role.ADMIN).shouldBeExactlyFor("remark"); readAccessFor(ShareDTO.class, Role.ADMIN).shouldBeForAllFields(); } @@ -28,7 +35,13 @@ public class ShareDTOUnitTest extends AccessMappingsUnitTestBase { initAccessFor(ShareDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeForNothing(); updateAccessFor(ShareDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeForNothing(); readAccessFor(ShareDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeExactlyFor( - "id", "membershipId", "documentDate", "quantity", "action", "valueDate", "membershipDisplayLabel"); + "id", + "membershipId", + "documentDate", + "quantity", + "action", + "valueDate", + "membershipDisplayLabel"); } @Test @@ -74,4 +87,3 @@ public class ShareDTOUnitTest extends AccessMappingsUnitTestBase { return dto; } } - diff --git a/src/test/java/org/hostsharing/hsadminng/service/mapper/UserMapperTest.java b/src/test/java/org/hostsharing/hsadminng/service/mapper/UserMapperTest.java index 007ca933..69bd23c3 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/mapper/UserMapperTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/mapper/UserMapperTest.java @@ -1,9 +1,12 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.mapper; +import static org.assertj.core.api.Assertions.assertThat; import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.domain.User; import org.hostsharing.hsadminng.service.dto.UserDTO; + import org.apache.commons.lang3.RandomStringUtils; import org.junit.Before; import org.junit.Test; @@ -17,8 +20,6 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import static org.assertj.core.api.Assertions.assertThat; - /** * Test class for the UserMapper. * @@ -54,7 +55,7 @@ public class UserMapperTest { } @Test - public void usersToUserDTOsShouldMapOnlyNonNullUsers(){ + public void usersToUserDTOsShouldMapOnlyNonNullUsers() { List users = new ArrayList<>(); users.add(user); users.add(null); @@ -66,7 +67,7 @@ public class UserMapperTest { } @Test - public void userDTOsToUsersShouldMapOnlyNonNullUsers(){ + public void userDTOsToUsersShouldMapOnlyNonNullUsers() { List usersDto = new ArrayList<>(); usersDto.add(userDto); usersDto.add(null); @@ -78,7 +79,7 @@ public class UserMapperTest { } @Test - public void userDTOsToUsersWithAuthoritiesStringShouldMapToUsersWithAuthoritiesDomain(){ + public void userDTOsToUsersWithAuthoritiesStringShouldMapToUsersWithAuthoritiesDomain() { Set authoritiesAsString = new HashSet<>(); authoritiesAsString.add("ADMIN"); userDto.setAuthorities(authoritiesAsString); @@ -96,7 +97,7 @@ public class UserMapperTest { } @Test - public void userDTOsToUsersMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities(){ + public void userDTOsToUsersMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() { userDto.setAuthorities(null); List usersDto = new ArrayList<>(); @@ -111,7 +112,7 @@ public class UserMapperTest { } @Test - public void userDTOToUserMapWithAuthoritiesStringShouldReturnUserWithAuthorities(){ + public void userDTOToUserMapWithAuthoritiesStringShouldReturnUserWithAuthorities() { Set authoritiesAsString = new HashSet<>(); authoritiesAsString.add("ADMIN"); userDto.setAuthorities(authoritiesAsString); @@ -127,7 +128,7 @@ public class UserMapperTest { } @Test - public void userDTOToUserMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities(){ + public void userDTOToUserMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() { userDto.setAuthorities(null); User user = userMapper.userDTOToUser(userDto); @@ -138,7 +139,7 @@ public class UserMapperTest { } @Test - public void userDTOToUserMapWithNullUserShouldReturnNull(){ + public void userDTOToUserMapWithNullUserShouldReturnNull() { assertThat(userMapper.userDTOToUser(null)).isNull(); } diff --git a/src/test/java/org/hostsharing/hsadminng/service/util/ReflectionUtilUnitTest.java b/src/test/java/org/hostsharing/hsadminng/service/util/ReflectionUtilUnitTest.java index 637f5b0b..43013560 100644 --- a/src/test/java/org/hostsharing/hsadminng/service/util/ReflectionUtilUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/service/util/ReflectionUtilUnitTest.java @@ -1,18 +1,19 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.service.util; -import org.junit.Test; - import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.ThrowableAssert.catchThrowable; import static org.hostsharing.hsadminng.service.util.ReflectionUtil.unchecked; +import org.junit.Test; public class ReflectionUtilUnitTest { @Test public void getUknownFieldThrowsIllegalArgumentException() { final Throwable actual = catchThrowable(() -> ReflectionUtil.getField(SomeClass.class, "unknownField")); - assertThat(actual).isInstanceOf(IllegalArgumentException.class).hasMessage("java.lang.NoSuchFieldException: unknownField"); + assertThat(actual).isInstanceOf(IllegalArgumentException.class) + .hasMessage("java.lang.NoSuchFieldException: unknownField"); } @Test @@ -57,8 +58,10 @@ public class ReflectionUtilUnitTest { @Test public void throwsExceptionIfGenericInterfaceNotImplemented() { - final Throwable actual = catchThrowable(() -> ReflectionUtil.determineGenericInterfaceParameter(SomeClass.class, UnusedGenericInterface.class, 1)); - assertThat(actual).isInstanceOf(AssertionError.class).hasMessageContaining("SomeClass expected to implement UnusedGenericInterface<...>"); + final Throwable actual = catchThrowable( + () -> ReflectionUtil.determineGenericInterfaceParameter(SomeClass.class, UnusedGenericInterface.class, 1)); + assertThat(actual).isInstanceOf(AssertionError.class) + .hasMessageContaining("SomeClass expected to implement UnusedGenericInterface<...>"); } @Test @@ -75,8 +78,10 @@ public class ReflectionUtilUnitTest { @Test public void throwsExceptionIfGenericClassNotExended() { - final Throwable actual = catchThrowable(() -> ReflectionUtil.determineGenericClassParameter(SomeClass.class, UnusedSuperClass.class, 1)); - assertThat(actual).isInstanceOf(AssertionError.class).hasMessageContaining("GenericClass expected to extend UnusedSuperClass<...>"); + final Throwable actual = catchThrowable( + () -> ReflectionUtil.determineGenericClassParameter(SomeClass.class, UnusedSuperClass.class, 1)); + assertThat(actual).isInstanceOf(AssertionError.class) + .hasMessageContaining("GenericClass expected to extend UnusedSuperClass<...>"); } @Test @@ -85,9 +90,8 @@ public class ReflectionUtilUnitTest { final Throwable actual = catchThrowable(() -> unchecked(() -> { throw givenException; })); - assertThat(actual).isInstanceOfSatisfying(RuntimeException.class, rte -> - assertThat(rte.getCause()).isSameAs(givenException) - ); + assertThat(actual) + .isInstanceOfSatisfying(RuntimeException.class, rte -> assertThat(rte.getCause()).isSameAs(givenException)); } @Test @@ -98,6 +102,7 @@ public class ReflectionUtilUnitTest { // --- only test fixture below --- private static class TestDto { + int intVal; TestDto(final int intval) { @@ -118,7 +123,8 @@ public class ReflectionUtilUnitTest { private static class SuperClass extends GenericClass implements IntermediateInterfaces { } - private static class UnusedSuperClass extends GenericClass implements IntermediateInterfaces { + private static class UnusedSuperClass extends GenericClass + implements IntermediateInterfaces { } private static class GenericClass { @@ -134,6 +140,8 @@ public class ReflectionUtilUnitTest { } enum SomeEnum { - RED, BLUE, GREEN + RED, + BLUE, + GREEN } } diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/AccountResourceIntTest.java b/src/test/java/org/hostsharing/hsadminng/web/rest/AccountResourceIntTest.java index 1d48f09c..dcaf6a6c 100644 --- a/src/test/java/org/hostsharing/hsadminng/web/rest/AccountResourceIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/web/rest/AccountResourceIntTest.java @@ -1,5 +1,13 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.config.Constants; import org.hostsharing.hsadminng.domain.Authority; @@ -14,8 +22,8 @@ import org.hostsharing.hsadminng.service.dto.UserDTO; import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator; import org.hostsharing.hsadminng.web.rest.vm.KeyAndPasswordVM; import org.hostsharing.hsadminng.web.rest.vm.ManagedUserVM; -import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.RandomStringUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -35,13 +43,6 @@ import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import java.util.*; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - /** * Test class for the AccountResource REST controller. * @@ -83,38 +84,38 @@ public class AccountResourceIntTest { public void setup() { MockitoAnnotations.initMocks(this); doNothing().when(mockMailService).sendActivationEmail(any()); - AccountResource accountResource = - new AccountResource(userRepository, userService, mockMailService); + AccountResource accountResource = new AccountResource(userRepository, userService, mockMailService); - AccountResource accountUserMockResource = - new AccountResource(userRepository, mockUserService, mockMailService); + AccountResource accountUserMockResource = new AccountResource(userRepository, mockUserService, mockMailService); this.restMvc = MockMvcBuilders.standaloneSetup(accountResource) - .setMessageConverters(httpMessageConverters) - .setControllerAdvice(exceptionTranslator) - .build(); + .setMessageConverters(httpMessageConverters) + .setControllerAdvice(exceptionTranslator) + .build(); this.restUserMockMvc = MockMvcBuilders.standaloneSetup(accountUserMockResource) - .setControllerAdvice(exceptionTranslator) - .build(); + .setControllerAdvice(exceptionTranslator) + .build(); } @Test public void testNonAuthenticatedUser() throws Exception { - restUserMockMvc.perform(get("/api/authenticate") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string("")); + restUserMockMvc.perform( + get("/api/authenticate") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("")); } @Test public void testAuthenticatedUser() throws Exception { - restUserMockMvc.perform(get("/api/authenticate") - .with(request -> { - request.setRemoteUser("test"); - return request; - }) - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string("test")); + restUserMockMvc.perform( + get("/api/authenticate") + .with(request -> { + request.setRemoteUser("test"); + return request; + }) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().string("test")); } @Test @@ -134,26 +135,28 @@ public class AccountResourceIntTest { user.setAuthorities(authorities); when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.of(user)); - restUserMockMvc.perform(get("/api/account") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.login").value("test")) - .andExpect(jsonPath("$.firstName").value("john")) - .andExpect(jsonPath("$.lastName").value("doe")) - .andExpect(jsonPath("$.email").value("john.doe@jhipster.com")) - .andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50")) - .andExpect(jsonPath("$.langKey").value("en")) - .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); + restUserMockMvc.perform( + get("/api/account") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.login").value("test")) + .andExpect(jsonPath("$.firstName").value("john")) + .andExpect(jsonPath("$.lastName").value("doe")) + .andExpect(jsonPath("$.email").value("john.doe@jhipster.com")) + .andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50")) + .andExpect(jsonPath("$.langKey").value("en")) + .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); } @Test public void testGetUnknownAccount() throws Exception { when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.empty()); - restUserMockMvc.perform(get("/api/account") - .accept(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(status().isInternalServerError()); + restUserMockMvc.perform( + get("/api/account") + .accept(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(status().isInternalServerError()); } @Test @@ -171,10 +174,10 @@ public class AccountResourceIntTest { assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isFalse(); restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(validUser))) - .andExpect(status().isCreated()); + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(validUser))) + .andExpect(status().isCreated()); assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue(); } @@ -194,10 +197,10 @@ public class AccountResourceIntTest { invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(invalidUser))) - .andExpect(status().isBadRequest()); + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(invalidUser))) + .andExpect(status().isBadRequest()); Optional user = userRepository.findOneByEmailIgnoreCase("funky@example.com"); assertThat(user.isPresent()).isFalse(); @@ -218,10 +221,10 @@ public class AccountResourceIntTest { invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(invalidUser))) - .andExpect(status().isBadRequest()); + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(invalidUser))) + .andExpect(status().isBadRequest()); Optional user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); @@ -242,10 +245,10 @@ public class AccountResourceIntTest { invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(invalidUser))) - .andExpect(status().isBadRequest()); + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(invalidUser))) + .andExpect(status().isBadRequest()); Optional user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); @@ -266,10 +269,10 @@ public class AccountResourceIntTest { invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(invalidUser))) - .andExpect(status().isBadRequest()); + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(invalidUser))) + .andExpect(status().isBadRequest()); Optional user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); @@ -306,17 +309,17 @@ public class AccountResourceIntTest { // First user restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(firstUser))) - .andExpect(status().isCreated()); + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(firstUser))) + .andExpect(status().isCreated()); // Second (non activated) user restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(secondUser))) - .andExpect(status().isCreated()); + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(secondUser))) + .andExpect(status().isCreated()); Optional testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com"); assertThat(testUser.isPresent()).isTrue(); @@ -325,10 +328,10 @@ public class AccountResourceIntTest { // Second (already activated) user restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(secondUser))) - .andExpect(status().is4xxClientError()); + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(secondUser))) + .andExpect(status().is4xxClientError()); } @Test @@ -347,10 +350,10 @@ public class AccountResourceIntTest { // Register first user restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(firstUser))) - .andExpect(status().isCreated()); + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(firstUser))) + .andExpect(status().isCreated()); Optional testUser1 = userRepository.findOneByLogin("test-register-duplicate-email"); assertThat(testUser1.isPresent()).isTrue(); @@ -368,10 +371,10 @@ public class AccountResourceIntTest { // Register second (non activated) user restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(secondUser))) - .andExpect(status().isCreated()); + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(secondUser))) + .andExpect(status().isCreated()); Optional testUser2 = userRepository.findOneByLogin("test-register-duplicate-email"); assertThat(testUser2.isPresent()).isFalse(); @@ -393,10 +396,10 @@ public class AccountResourceIntTest { // Register third (not activated) user restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail))) - .andExpect(status().isCreated()); + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail))) + .andExpect(status().isCreated()); Optional testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3"); assertThat(testUser4.isPresent()).isTrue(); @@ -407,10 +410,10 @@ public class AccountResourceIntTest { // Register 4th (already activated) user restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(secondUser))) - .andExpect(status().is4xxClientError()); + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(secondUser))) + .andExpect(status().is4xxClientError()); } @Test @@ -428,15 +431,15 @@ public class AccountResourceIntTest { validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( - post("/api/register") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(validUser))) - .andExpect(status().isCreated()); + post("/api/register") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(validUser))) + .andExpect(status().isCreated()); Optional userDup = userRepository.findOneByLogin("badguy"); assertThat(userDup.isPresent()).isTrue(); assertThat(userDup.get().getAuthorities()).hasSize(1) - .containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get()); + .containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get()); } @Test @@ -453,7 +456,7 @@ public class AccountResourceIntTest { userRepository.saveAndFlush(user); restMvc.perform(get("/api/activate?key={activationKey}", activationKey)) - .andExpect(status().isOk()); + .andExpect(status().isOk()); user = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(user.getActivated()).isTrue(); @@ -463,7 +466,7 @@ public class AccountResourceIntTest { @Transactional public void testActivateAccountWithWrongKey() throws Exception { restMvc.perform(get("/api/activate?key=wrongActivationKey")) - .andExpect(status().isInternalServerError()); + .andExpect(status().isInternalServerError()); } @Test @@ -489,10 +492,10 @@ public class AccountResourceIntTest { userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( - post("/api/account") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(userDTO))) - .andExpect(status().isOk()); + post("/api/account") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userDTO))) + .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName()); @@ -528,10 +531,10 @@ public class AccountResourceIntTest { userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( - post("/api/account") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(userDTO))) - .andExpect(status().isBadRequest()); + post("/api/account") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userDTO))) + .andExpect(status().isBadRequest()); assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent(); } @@ -567,10 +570,10 @@ public class AccountResourceIntTest { userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( - post("/api/account") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(userDTO))) - .andExpect(status().isBadRequest()); + post("/api/account") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userDTO))) + .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null); assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com"); @@ -599,10 +602,10 @@ public class AccountResourceIntTest { userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( - post("/api/account") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(userDTO))) - .andExpect(status().isOk()); + post("/api/account") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(userDTO))) + .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null); assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email-and-login@example.com"); @@ -619,10 +622,13 @@ public class AccountResourceIntTest { user.setEmail("change-password-wrong-existing-password@example.com"); userRepository.saveAndFlush(user); - restMvc.perform(post("/api/account/change-password") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password")))) - .andExpect(status().isBadRequest()); + restMvc.perform( + post("/api/account/change-password") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content( + TestUtil.convertObjectToJsonBytes( + new PasswordChangeDTO("1" + currentPassword, "new password")))) + .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null); assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse(); @@ -640,10 +646,11 @@ public class AccountResourceIntTest { user.setEmail("change-password@example.com"); userRepository.saveAndFlush(user); - restMvc.perform(post("/api/account/change-password") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password")))) - .andExpect(status().isOk()); + restMvc.perform( + post("/api/account/change-password") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password")))) + .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin("change-password").orElse(null); assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue(); @@ -662,10 +669,11 @@ public class AccountResourceIntTest { String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1); - restMvc.perform(post("/api/account/change-password") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) - .andExpect(status().isBadRequest()); + restMvc.perform( + post("/api/account/change-password") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) + .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); @@ -684,10 +692,11 @@ public class AccountResourceIntTest { String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1); - restMvc.perform(post("/api/account/change-password") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) - .andExpect(status().isBadRequest()); + restMvc.perform( + post("/api/account/change-password") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) + .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); @@ -704,10 +713,11 @@ public class AccountResourceIntTest { user.setEmail("change-password-empty@example.com"); userRepository.saveAndFlush(user); - restMvc.perform(post("/api/account/change-password") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "")))) - .andExpect(status().isBadRequest()); + restMvc.perform( + post("/api/account/change-password") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "")))) + .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); @@ -723,9 +733,10 @@ public class AccountResourceIntTest { user.setEmail("password-reset@example.com"); userRepository.saveAndFlush(user); - restMvc.perform(post("/api/account/reset-password/init") - .content("password-reset@example.com")) - .andExpect(status().isOk()); + restMvc.perform( + post("/api/account/reset-password/init") + .content("password-reset@example.com")) + .andExpect(status().isOk()); } @Test @@ -738,17 +749,18 @@ public class AccountResourceIntTest { user.setEmail("password-reset@example.com"); userRepository.saveAndFlush(user); - restMvc.perform(post("/api/account/reset-password/init") - .content("password-reset@EXAMPLE.COM")) - .andExpect(status().isOk()); + restMvc.perform( + post("/api/account/reset-password/init") + .content("password-reset@EXAMPLE.COM")) + .andExpect(status().isOk()); } @Test public void testRequestPasswordResetWrongEmail() throws Exception { restMvc.perform( - post("/api/account/reset-password/init") - .content("password-reset-wrong-email@example.com")) - .andExpect(status().isBadRequest()); + post("/api/account/reset-password/init") + .content("password-reset-wrong-email@example.com")) + .andExpect(status().isBadRequest()); } @Test @@ -767,10 +779,10 @@ public class AccountResourceIntTest { keyAndPassword.setNewPassword("new password"); restMvc.perform( - post("/api/account/reset-password/finish") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) - .andExpect(status().isOk()); + post("/api/account/reset-password/finish") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) + .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue(); @@ -792,16 +804,15 @@ public class AccountResourceIntTest { keyAndPassword.setNewPassword("foo"); restMvc.perform( - post("/api/account/reset-password/finish") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) - .andExpect(status().isBadRequest()); + post("/api/account/reset-password/finish") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) + .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse(); } - @Test @Transactional public void testFinishPasswordResetWrongKey() throws Exception { @@ -810,9 +821,9 @@ public class AccountResourceIntTest { keyAndPassword.setNewPassword("new password"); restMvc.perform( - post("/api/account/reset-password/finish") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) - .andExpect(status().isInternalServerError()); + post("/api/account/reset-password/finish") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) + .andExpect(status().isInternalServerError()); } } diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/AssetResourceIntTest.java b/src/test/java/org/hostsharing/hsadminng/web/rest/AssetResourceIntTest.java index 1475a9a8..05f50ff2 100644 --- a/src/test/java/org/hostsharing/hsadminng/web/rest/AssetResourceIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/web/rest/AssetResourceIntTest.java @@ -1,5 +1,12 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.domain.Asset; import org.hostsharing.hsadminng.domain.Membership; @@ -12,6 +19,7 @@ import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.dto.AssetDTO; import org.hostsharing.hsadminng.service.mapper.AssetMapper; import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,18 +35,14 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.Validator; -import javax.persistence.EntityManager; import java.math.BigDecimal; import java.math.RoundingMode; import java.time.LocalDate; import java.time.ZoneId; import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import javax.persistence.EntityManager; + /** * Test class for the AssetResource REST controller. * @@ -102,11 +106,12 @@ public class AssetResourceIntTest { MockitoAnnotations.initMocks(this); final AssetResource assetResource = new AssetResource(assetService, assetQueryService); this.restAssetMockMvc = MockMvcBuilders.standaloneSetup(assetResource) - .setCustomArgumentResolvers(pageableArgumentResolver) - .setControllerAdvice(exceptionTranslator) - .setConversionService(createFormattingConversionService()) - .setMessageConverters(jacksonMessageConverter) - .setValidator(validator).build(); + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setConversionService(createFormattingConversionService()) + .setMessageConverters(jacksonMessageConverter) + .setValidator(validator) + .build(); } /** @@ -117,11 +122,11 @@ public class AssetResourceIntTest { */ public static Asset createEntity(EntityManager em) { Asset asset = new Asset() - .documentDate(DEFAULT_DOCUMENT_DATE) - .valueDate(DEFAULT_VALUE_DATE) - .action(DEFAULT_ACTION) - .amount(DEFAULT_AMOUNT) - .remark(DEFAULT_REMARK); + .documentDate(DEFAULT_DOCUMENT_DATE) + .valueDate(DEFAULT_VALUE_DATE) + .action(DEFAULT_ACTION) + .amount(DEFAULT_AMOUNT) + .remark(DEFAULT_REMARK); // Add required entity Membership membership = MembershipResourceIntTest.createEntity(em); em.persist(membership); @@ -138,11 +143,11 @@ public class AssetResourceIntTest { */ public static Asset createPersistentEntity(EntityManager em, final Membership membership) { Asset asset = new Asset() - .documentDate(DEFAULT_DOCUMENT_DATE) - .valueDate(DEFAULT_VALUE_DATE) - .action(DEFAULT_ACTION) - .amount(DEFAULT_AMOUNT) - .remark(DEFAULT_REMARK); + .documentDate(DEFAULT_DOCUMENT_DATE) + .valueDate(DEFAULT_VALUE_DATE) + .action(DEFAULT_ACTION) + .amount(DEFAULT_AMOUNT) + .remark(DEFAULT_REMARK); // Add required entity asset.setMembership(membership); membership.addAsset(asset); @@ -150,6 +155,7 @@ public class AssetResourceIntTest { em.flush(); return asset; } + @Before public void initTest() { asset = createEntity(em); @@ -163,10 +169,11 @@ public class AssetResourceIntTest { // Create the Asset AssetDTO assetDTO = assetMapper.toDto(asset); assetDTO.setMembershipDisplayLabel(null); - restAssetMockMvc.perform(post("/api/assets") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(assetDTO))) - .andExpect(status().isCreated()); + restAssetMockMvc.perform( + post("/api/assets") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(assetDTO))) + .andExpect(status().isCreated()); // Validate the Asset in the database List assetList = assetRepository.findAll(); @@ -189,10 +196,11 @@ public class AssetResourceIntTest { AssetDTO assetDTO = assetMapper.toDto(asset); // An entity with an existing ID cannot be created, so this API call must fail - restAssetMockMvc.perform(post("/api/assets") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(assetDTO))) - .andExpect(status().isBadRequest()); + restAssetMockMvc.perform( + post("/api/assets") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(assetDTO))) + .andExpect(status().isBadRequest()); // Validate the Asset in the database List assetList = assetRepository.findAll(); @@ -210,10 +218,11 @@ public class AssetResourceIntTest { AssetDTO assetDTO = assetMapper.toDto(asset); // An entity with an existing ID cannot be created, so this API call must fail - restAssetMockMvc.perform(post("/api/assets") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(assetDTO))) - .andExpect(status().isBadRequest()); + restAssetMockMvc.perform( + post("/api/assets") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(assetDTO))) + .andExpect(status().isBadRequest()); // Validate the Asset in the database List assetList = assetRepository.findAll(); @@ -230,10 +239,11 @@ public class AssetResourceIntTest { // Create the Asset, which fails. AssetDTO assetDTO = assetMapper.toDto(asset); - restAssetMockMvc.perform(post("/api/assets") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(assetDTO))) - .andExpect(status().isBadRequest()); + restAssetMockMvc.perform( + post("/api/assets") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(assetDTO))) + .andExpect(status().isBadRequest()); List assetList = assetRepository.findAll(); assertThat(assetList).hasSize(databaseSizeBeforeTest); @@ -249,10 +259,11 @@ public class AssetResourceIntTest { // Create the Asset, which fails. AssetDTO assetDTO = assetMapper.toDto(asset); - restAssetMockMvc.perform(post("/api/assets") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(assetDTO))) - .andExpect(status().isBadRequest()); + restAssetMockMvc.perform( + post("/api/assets") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(assetDTO))) + .andExpect(status().isBadRequest()); List assetList = assetRepository.findAll(); assertThat(assetList).hasSize(databaseSizeBeforeTest); @@ -268,10 +279,11 @@ public class AssetResourceIntTest { // Create the Asset, which fails. AssetDTO assetDTO = assetMapper.toDto(asset); - restAssetMockMvc.perform(post("/api/assets") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(assetDTO))) - .andExpect(status().isBadRequest()); + restAssetMockMvc.perform( + post("/api/assets") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(assetDTO))) + .andExpect(status().isBadRequest()); List assetList = assetRepository.findAll(); assertThat(assetList).hasSize(databaseSizeBeforeTest); @@ -287,10 +299,11 @@ public class AssetResourceIntTest { // Create the Asset, which fails. AssetDTO assetDTO = assetMapper.toDto(asset); - restAssetMockMvc.perform(post("/api/assets") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(assetDTO))) - .andExpect(status().isBadRequest()); + restAssetMockMvc.perform( + post("/api/assets") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(assetDTO))) + .andExpect(status().isBadRequest()); List assetList = assetRepository.findAll(); assertThat(assetList).hasSize(databaseSizeBeforeTest); @@ -304,16 +317,16 @@ public class AssetResourceIntTest { // Get all the assetList restAssetMockMvc.perform(get("/api/assets?sort=id,desc")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].id").value(hasItem(asset.getId().intValue()))) - .andExpect(jsonPath("$.[*].documentDate").value(hasItem(DEFAULT_DOCUMENT_DATE.toString()))) - .andExpect(jsonPath("$.[*].valueDate").value(hasItem(DEFAULT_VALUE_DATE.toString()))) - .andExpect(jsonPath("$.[*].action").value(hasItem(DEFAULT_ACTION.toString()))) - .andExpect(jsonPath("$.[*].amount").value(hasItem(DEFAULT_AMOUNT.intValue()))) - .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(asset.getId().intValue()))) + .andExpect(jsonPath("$.[*].documentDate").value(hasItem(DEFAULT_DOCUMENT_DATE.toString()))) + .andExpect(jsonPath("$.[*].valueDate").value(hasItem(DEFAULT_VALUE_DATE.toString()))) + .andExpect(jsonPath("$.[*].action").value(hasItem(DEFAULT_ACTION.toString()))) + .andExpect(jsonPath("$.[*].amount").value(hasItem(DEFAULT_AMOUNT.intValue()))) + .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); } - + @Test @Transactional public void getAsset() throws Exception { @@ -322,14 +335,14 @@ public class AssetResourceIntTest { // Get the asset restAssetMockMvc.perform(get("/api/assets/{id}", asset.getId())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.id").value(asset.getId().intValue())) - .andExpect(jsonPath("$.documentDate").value(DEFAULT_DOCUMENT_DATE.toString())) - .andExpect(jsonPath("$.valueDate").value(DEFAULT_VALUE_DATE.toString())) - .andExpect(jsonPath("$.action").value(DEFAULT_ACTION.toString())) - .andExpect(jsonPath("$.amount").value(DEFAULT_AMOUNT.intValue())) - .andExpect(jsonPath("$.remark").value(DEFAULT_REMARK)); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(asset.getId().intValue())) + .andExpect(jsonPath("$.documentDate").value(DEFAULT_DOCUMENT_DATE.toString())) + .andExpect(jsonPath("$.valueDate").value(DEFAULT_VALUE_DATE.toString())) + .andExpect(jsonPath("$.action").value(DEFAULT_ACTION.toString())) + .andExpect(jsonPath("$.amount").value(DEFAULT_AMOUNT.intValue())) + .andExpect(jsonPath("$.remark").value(DEFAULT_REMARK)); } @Test @@ -397,7 +410,6 @@ public class AssetResourceIntTest { defaultAssetShouldBeFound("documentDate.lessThan=" + UPDATED_DOCUMENT_DATE); } - @Test @Transactional public void getAllAssetsByValueDateIsEqualToSomething() throws Exception { @@ -463,7 +475,6 @@ public class AssetResourceIntTest { defaultAssetShouldBeFound("valueDate.lessThan=" + UPDATED_VALUE_DATE); } - @Test @Transactional public void getAllAssetsByActionIsEqualToSomething() throws Exception { @@ -585,7 +596,8 @@ public class AssetResourceIntTest { @Transactional public void getAllAssetsByMembershipIsEqualToSomething() throws Exception { // Initialize the database - Membership membership = MembershipResourceIntTest.createPersistentEntity(em, CustomerResourceIntTest.createPersistentEntity(em)); + Membership membership = MembershipResourceIntTest + .createPersistentEntity(em, CustomerResourceIntTest.createPersistentEntity(em)); asset.setMembership(membership); assetRepository.saveAndFlush(asset); Long membershipId = membership.getId(); @@ -602,20 +614,20 @@ public class AssetResourceIntTest { */ private void defaultAssetShouldBeFound(String filter) throws Exception { restAssetMockMvc.perform(get("/api/assets?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].id").value(hasItem(asset.getId().intValue()))) - .andExpect(jsonPath("$.[*].documentDate").value(hasItem(DEFAULT_DOCUMENT_DATE.toString()))) - .andExpect(jsonPath("$.[*].valueDate").value(hasItem(DEFAULT_VALUE_DATE.toString()))) - .andExpect(jsonPath("$.[*].action").value(hasItem(DEFAULT_ACTION.toString()))) - .andExpect(jsonPath("$.[*].amount").value(hasItem(DEFAULT_AMOUNT.intValue()))) - .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(asset.getId().intValue()))) + .andExpect(jsonPath("$.[*].documentDate").value(hasItem(DEFAULT_DOCUMENT_DATE.toString()))) + .andExpect(jsonPath("$.[*].valueDate").value(hasItem(DEFAULT_VALUE_DATE.toString()))) + .andExpect(jsonPath("$.[*].action").value(hasItem(DEFAULT_ACTION.toString()))) + .andExpect(jsonPath("$.[*].amount").value(hasItem(DEFAULT_AMOUNT.intValue()))) + .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); // Check, that the count call also returns 1 restAssetMockMvc.perform(get("/api/assets/count?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(content().string("1")); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(content().string("1")); } /** @@ -623,25 +635,24 @@ public class AssetResourceIntTest { */ private void defaultAssetShouldNotBeFound(String filter) throws Exception { restAssetMockMvc.perform(get("/api/assets?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$").isArray()) - .andExpect(jsonPath("$").isEmpty()); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$").isArray()) + .andExpect(jsonPath("$").isEmpty()); // Check, that the count call also returns 0 restAssetMockMvc.perform(get("/api/assets/count?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(content().string("0")); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(content().string("0")); } - @Test @Transactional public void getNonExistingAsset() throws Exception { // Get the asset restAssetMockMvc.perform(get("/api/assets/{id}", Long.MAX_VALUE)) - .andExpect(status().isNotFound()); + .andExpect(status().isNotFound()); } @Test @@ -657,17 +668,18 @@ public class AssetResourceIntTest { // Disconnect from session so that the updates on updatedAsset are not directly saved in db em.detach(updatedAsset); updatedAsset - .documentDate(UPDATED_DOCUMENT_DATE) - .valueDate(UPDATED_VALUE_DATE) - .action(UPDATED_ACTION) - .amount(UPDATED_AMOUNT) - .remark(UPDATED_REMARK); + .documentDate(UPDATED_DOCUMENT_DATE) + .valueDate(UPDATED_VALUE_DATE) + .action(UPDATED_ACTION) + .amount(UPDATED_AMOUNT) + .remark(UPDATED_REMARK); AssetDTO assetDTO = assetMapper.toDto(updatedAsset); - restAssetMockMvc.perform(put("/api/assets") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(assetDTO))) - .andExpect(status().isBadRequest()); + restAssetMockMvc.perform( + put("/api/assets") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(assetDTO))) + .andExpect(status().isBadRequest()); // Validate the Asset in the database List assetList = assetRepository.findAll(); @@ -689,10 +701,11 @@ public class AssetResourceIntTest { AssetDTO assetDTO = assetMapper.toDto(asset); // If the entity doesn't have an ID, it will throw BadRequestAlertException - restAssetMockMvc.perform(put("/api/assets") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(assetDTO))) - .andExpect(status().isBadRequest()); + restAssetMockMvc.perform( + put("/api/assets") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(assetDTO))) + .andExpect(status().isBadRequest()); // Validate the Asset in the database List assetList = assetRepository.findAll(); @@ -708,9 +721,10 @@ public class AssetResourceIntTest { int databaseSizeBeforeDelete = assetRepository.findAll().size(); // Delete the asset - restAssetMockMvc.perform(delete("/api/assets/{id}", asset.getId()) - .accept(TestUtil.APPLICATION_JSON_UTF8)) - .andExpect(status().isBadRequest()); + restAssetMockMvc.perform( + delete("/api/assets/{id}", asset.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isBadRequest()); // Validate the database still contains the same number of assets List assetList = assetRepository.findAll(); diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/AuditResourceIntTest.java b/src/test/java/org/hostsharing/hsadminng/web/rest/AuditResourceIntTest.java index b0eadf7a..b2ca196d 100644 --- a/src/test/java/org/hostsharing/hsadminng/web/rest/AuditResourceIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/web/rest/AuditResourceIntTest.java @@ -1,10 +1,17 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.config.audit.AuditEventConverter; import org.hostsharing.hsadminng.domain.PersistentAuditEvent; import org.hostsharing.hsadminng.repository.PersistenceAuditEventRepository; import org.hostsharing.hsadminng.service.AuditEventService; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -22,11 +29,6 @@ import org.springframework.transaction.annotation.Transactional; import java.time.Instant; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - /** * Test class for the AuditResource REST controller. * @@ -64,13 +66,13 @@ public class AuditResourceIntTest { @Before public void setup() { MockitoAnnotations.initMocks(this); - AuditEventService auditEventService = - new AuditEventService(auditEventRepository, auditEventConverter); + AuditEventService auditEventService = new AuditEventService(auditEventRepository, auditEventConverter); AuditResource auditResource = new AuditResource(auditEventService); this.restAuditMockMvc = MockMvcBuilders.standaloneSetup(auditResource) - .setCustomArgumentResolvers(pageableArgumentResolver) - .setConversionService(formattingConversionService) - .setMessageConverters(jacksonMessageConverter).build(); + .setCustomArgumentResolvers(pageableArgumentResolver) + .setConversionService(formattingConversionService) + .setMessageConverters(jacksonMessageConverter) + .build(); } @Before @@ -89,9 +91,9 @@ public class AuditResourceIntTest { // Get all the audits restAuditMockMvc.perform(get("/management/audits")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); } @Test @@ -101,9 +103,9 @@ public class AuditResourceIntTest { // Get the audit restAuditMockMvc.perform(get("/management/audits/{id}", auditEvent.getId())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.principal").value(SAMPLE_PRINCIPAL)); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.principal").value(SAMPLE_PRINCIPAL)); } @Test @@ -112,14 +114,14 @@ public class AuditResourceIntTest { auditEventRepository.save(auditEvent); // Generate dates for selecting audits by date, making sure the period will contain the audit - String fromDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); + String fromDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); String toDate = SAMPLE_TIMESTAMP.plusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); // Get the audit - restAuditMockMvc.perform(get("/management/audits?fromDate="+fromDate+"&toDate="+toDate)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); + restAuditMockMvc.perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); } @Test @@ -128,21 +130,21 @@ public class AuditResourceIntTest { auditEventRepository.save(auditEvent); // Generate dates for selecting audits by date, making sure the period will not contain the sample audit - String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2*SECONDS_PER_DAY).toString().substring(0, 10); + String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2 * SECONDS_PER_DAY).toString().substring(0, 10); String toDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); // Query audits but expect no results restAuditMockMvc.perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(header().string("X-Total-Count", "0")); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(header().string("X-Total-Count", "0")); } @Test public void getNonExistingAudit() throws Exception { // Get the audit restAuditMockMvc.perform(get("/management/audits/{id}", Long.MAX_VALUE)) - .andExpect(status().isNotFound()); + .andExpect(status().isNotFound()); } @Test diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/CustomerResourceIntTest.java b/src/test/java/org/hostsharing/hsadminng/web/rest/CustomerResourceIntTest.java index c0e5a6e1..aca16349 100644 --- a/src/test/java/org/hostsharing/hsadminng/web/rest/CustomerResourceIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/web/rest/CustomerResourceIntTest.java @@ -1,5 +1,14 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser; +import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole; +import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.domain.Membership; @@ -14,6 +23,7 @@ import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.dto.CustomerDTO; import org.hostsharing.hsadminng.service.mapper.CustomerMapper; import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -29,18 +39,11 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.Validator; -import javax.persistence.EntityManager; import java.time.LocalDate; import java.time.ZoneId; import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser; -import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole; -import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import javax.persistence.EntityManager; /** * Test class for the CustomerResource REST controller. @@ -147,11 +150,12 @@ public class CustomerResourceIntTest { final CustomerResource customerResource = new CustomerResource(customerService, customerQueryService); this.restCustomerMockMvc = MockMvcBuilders.standaloneSetup(customerResource) - .setCustomArgumentResolvers(pageableArgumentResolver) - .setControllerAdvice(exceptionTranslator) - .setConversionService(createFormattingConversionService()) - .setMessageConverters(jacksonMessageConverter) - .setValidator(validator).build(); + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setConversionService(createFormattingConversionService()) + .setMessageConverters(jacksonMessageConverter) + .setValidator(validator) + .build(); } /** @@ -162,21 +166,21 @@ public class CustomerResourceIntTest { */ public static Customer createEntity(EntityManager em) { Customer customer = new Customer() - .reference(DEFAULT_REFERENCE) - .prefix(DEFAULT_PREFIX) - .name(DEFAULT_NAME) - .kind(DEFAULT_KIND) - .birthDate(DEFAULT_BIRTH_DATE) - .birthPlace(DEFAULT_BIRTH_PLACE) - .registrationCourt(DEFAULT_REGISTRATION_COURT) - .registrationNumber(DEFAULT_REGISTRATION_NUMBER) - .vatRegion(DEFAULT_VAT_REGION) - .vatNumber(DEFAULT_VAT_NUMBER) - .contractualSalutation(DEFAULT_CONTRACTUAL_SALUTATION) - .contractualAddress(DEFAULT_CONTRACTUAL_ADDRESS) - .billingSalutation(DEFAULT_BILLING_SALUTATION) - .billingAddress(DEFAULT_BILLING_ADDRESS) - .remark(DEFAULT_REMARK); + .reference(DEFAULT_REFERENCE) + .prefix(DEFAULT_PREFIX) + .name(DEFAULT_NAME) + .kind(DEFAULT_KIND) + .birthDate(DEFAULT_BIRTH_DATE) + .birthPlace(DEFAULT_BIRTH_PLACE) + .registrationCourt(DEFAULT_REGISTRATION_COURT) + .registrationNumber(DEFAULT_REGISTRATION_NUMBER) + .vatRegion(DEFAULT_VAT_REGION) + .vatNumber(DEFAULT_VAT_NUMBER) + .contractualSalutation(DEFAULT_CONTRACTUAL_SALUTATION) + .contractualAddress(DEFAULT_CONTRACTUAL_ADDRESS) + .billingSalutation(DEFAULT_BILLING_SALUTATION) + .billingAddress(DEFAULT_BILLING_ADDRESS) + .remark(DEFAULT_REMARK); return customer; } @@ -188,12 +192,12 @@ public class CustomerResourceIntTest { */ public static Customer createPersistentEntity(EntityManager em) { Customer customer = new Customer() - .reference(OTHER_REFERENCE_BASE + otherCounter) - .prefix(OTHER_PREFIX_BASE + String.format("%02d", otherCounter)) - .name(OTHER_NAME_BASE + otherCounter) - .kind(OTHER_KIND) - .vatRegion(OTHER_VAT_REGION) - .contractualAddress(OTHER_CONTRACTUAL_ADDRESS_BASE + otherCounter); + .reference(OTHER_REFERENCE_BASE + otherCounter) + .prefix(OTHER_PREFIX_BASE + String.format("%02d", otherCounter)) + .name(OTHER_NAME_BASE + otherCounter) + .kind(OTHER_KIND) + .vatRegion(OTHER_VAT_REGION) + .contractualAddress(OTHER_CONTRACTUAL_ADDRESS_BASE + otherCounter); em.persist(customer); em.flush(); ++otherCounter; @@ -212,10 +216,11 @@ public class CustomerResourceIntTest { // Create the Customer CustomerDTO customerDTO = customerMapper.toDto(customer); - restCustomerMockMvc.perform(post("/api/customers") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(customerDTO))) - .andExpect(status().isCreated()); + restCustomerMockMvc.perform( + post("/api/customers") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(customerDTO))) + .andExpect(status().isCreated()); // Validate the Customer in the database List customerList = customerRepository.findAll(); @@ -250,10 +255,11 @@ public class CustomerResourceIntTest { CustomerDTO customerDTO = customerMapper.toDto(customer); // An entity with an existing ID cannot be created, so this API call must fail - restCustomerMockMvc.perform(post("/api/customers") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(customerDTO))) - .andExpect(status().isBadRequest()); + restCustomerMockMvc.perform( + post("/api/customers") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(customerDTO))) + .andExpect(status().isBadRequest()); // Validate the Customer in the database List customerList = customerRepository.findAll(); @@ -270,10 +276,11 @@ public class CustomerResourceIntTest { CustomerDTO customerDTO = customerMapper.toDto(customer); // An entity with an existing ID cannot be created, so this API call must fail - restCustomerMockMvc.perform(post("/api/customers") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(customerDTO))) - .andExpect(status().isBadRequest()); + restCustomerMockMvc.perform( + post("/api/customers") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(customerDTO))) + .andExpect(status().isBadRequest()); // Validate the Customer in the database List customerList = customerRepository.findAll(); @@ -290,10 +297,11 @@ public class CustomerResourceIntTest { // Create the Customer, which fails. CustomerDTO customerDTO = customerMapper.toDto(customer); - restCustomerMockMvc.perform(post("/api/customers") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(customerDTO))) - .andExpect(status().isBadRequest()); + restCustomerMockMvc.perform( + post("/api/customers") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(customerDTO))) + .andExpect(status().isBadRequest()); List customerList = customerRepository.findAll(); assertThat(customerList).hasSize(databaseSizeBeforeTest); @@ -309,10 +317,11 @@ public class CustomerResourceIntTest { // Create the Customer, which fails. CustomerDTO customerDTO = customerMapper.toDto(customer); - restCustomerMockMvc.perform(post("/api/customers") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(customerDTO))) - .andExpect(status().isBadRequest()); + restCustomerMockMvc.perform( + post("/api/customers") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(customerDTO))) + .andExpect(status().isBadRequest()); List customerList = customerRepository.findAll(); assertThat(customerList).hasSize(databaseSizeBeforeTest); @@ -328,10 +337,11 @@ public class CustomerResourceIntTest { // Create the Customer, which fails. CustomerDTO customerDTO = customerMapper.toDto(customer); - restCustomerMockMvc.perform(post("/api/customers") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(customerDTO))) - .andExpect(status().isBadRequest()); + restCustomerMockMvc.perform( + post("/api/customers") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(customerDTO))) + .andExpect(status().isBadRequest()); List customerList = customerRepository.findAll(); assertThat(customerList).hasSize(databaseSizeBeforeTest); @@ -347,10 +357,11 @@ public class CustomerResourceIntTest { // Create the Customer, which fails. CustomerDTO customerDTO = customerMapper.toDto(customer); - restCustomerMockMvc.perform(post("/api/customers") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(customerDTO))) - .andExpect(status().isBadRequest()); + restCustomerMockMvc.perform( + post("/api/customers") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(customerDTO))) + .andExpect(status().isBadRequest()); List customerList = customerRepository.findAll(); assertThat(customerList).hasSize(databaseSizeBeforeTest); @@ -366,10 +377,11 @@ public class CustomerResourceIntTest { // Create the Customer, which fails. CustomerDTO customerDTO = customerMapper.toDto(customer); - restCustomerMockMvc.perform(post("/api/customers") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(customerDTO))) - .andExpect(status().isBadRequest()); + restCustomerMockMvc.perform( + post("/api/customers") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(customerDTO))) + .andExpect(status().isBadRequest()); List customerList = customerRepository.findAll(); assertThat(customerList).hasSize(databaseSizeBeforeTest); @@ -385,10 +397,11 @@ public class CustomerResourceIntTest { // Create the Customer, which fails. CustomerDTO customerDTO = customerMapper.toDto(customer); - restCustomerMockMvc.perform(post("/api/customers") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(customerDTO))) - .andExpect(status().isBadRequest()); + restCustomerMockMvc.perform( + post("/api/customers") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(customerDTO))) + .andExpect(status().isBadRequest()); List customerList = customerRepository.findAll(); assertThat(customerList).hasSize(databaseSizeBeforeTest); @@ -402,24 +415,24 @@ public class CustomerResourceIntTest { // Get all the customerList restCustomerMockMvc.perform(get("/api/customers?sort=id,desc")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].id").value(hasItem(customer.getId().intValue()))) - .andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE))) - .andExpect(jsonPath("$.[*].prefix").value(hasItem(DEFAULT_PREFIX))) - .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME))) - .andExpect(jsonPath("$.[*].kind").value(hasItem(DEFAULT_KIND.toString()))) - .andExpect(jsonPath("$.[*].birthDate").value(hasItem(DEFAULT_BIRTH_DATE.toString()))) - .andExpect(jsonPath("$.[*].birthPlace").value(hasItem(DEFAULT_BIRTH_PLACE))) - .andExpect(jsonPath("$.[*].registrationCourt").value(hasItem(DEFAULT_REGISTRATION_COURT))) - .andExpect(jsonPath("$.[*].registrationNumber").value(hasItem(DEFAULT_REGISTRATION_NUMBER))) - .andExpect(jsonPath("$.[*].vatRegion").value(hasItem(DEFAULT_VAT_REGION.toString()))) - .andExpect(jsonPath("$.[*].vatNumber").value(hasItem(DEFAULT_VAT_NUMBER))) - .andExpect(jsonPath("$.[*].contractualSalutation").value(hasItem(DEFAULT_CONTRACTUAL_SALUTATION))) - .andExpect(jsonPath("$.[*].contractualAddress").value(hasItem(DEFAULT_CONTRACTUAL_ADDRESS))) - .andExpect(jsonPath("$.[*].billingSalutation").value(hasItem(DEFAULT_BILLING_SALUTATION))) - .andExpect(jsonPath("$.[*].billingAddress").value(hasItem(DEFAULT_BILLING_ADDRESS))) - .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(customer.getId().intValue()))) + .andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE))) + .andExpect(jsonPath("$.[*].prefix").value(hasItem(DEFAULT_PREFIX))) + .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME))) + .andExpect(jsonPath("$.[*].kind").value(hasItem(DEFAULT_KIND.toString()))) + .andExpect(jsonPath("$.[*].birthDate").value(hasItem(DEFAULT_BIRTH_DATE.toString()))) + .andExpect(jsonPath("$.[*].birthPlace").value(hasItem(DEFAULT_BIRTH_PLACE))) + .andExpect(jsonPath("$.[*].registrationCourt").value(hasItem(DEFAULT_REGISTRATION_COURT))) + .andExpect(jsonPath("$.[*].registrationNumber").value(hasItem(DEFAULT_REGISTRATION_NUMBER))) + .andExpect(jsonPath("$.[*].vatRegion").value(hasItem(DEFAULT_VAT_REGION.toString()))) + .andExpect(jsonPath("$.[*].vatNumber").value(hasItem(DEFAULT_VAT_NUMBER))) + .andExpect(jsonPath("$.[*].contractualSalutation").value(hasItem(DEFAULT_CONTRACTUAL_SALUTATION))) + .andExpect(jsonPath("$.[*].contractualAddress").value(hasItem(DEFAULT_CONTRACTUAL_ADDRESS))) + .andExpect(jsonPath("$.[*].billingSalutation").value(hasItem(DEFAULT_BILLING_SALUTATION))) + .andExpect(jsonPath("$.[*].billingAddress").value(hasItem(DEFAULT_BILLING_ADDRESS))) + .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); } @Test @@ -430,24 +443,24 @@ public class CustomerResourceIntTest { // Get the customer restCustomerMockMvc.perform(get("/api/customers/{id}", customer.getId())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.id").value(customer.getId().intValue())) - .andExpect(jsonPath("$.reference").value(DEFAULT_REFERENCE)) - .andExpect(jsonPath("$.prefix").value(DEFAULT_PREFIX)) - .andExpect(jsonPath("$.name").value(DEFAULT_NAME)) - .andExpect(jsonPath("$.kind").value(DEFAULT_KIND.toString())) - .andExpect(jsonPath("$.birthDate").value(DEFAULT_BIRTH_DATE.toString())) - .andExpect(jsonPath("$.birthPlace").value(DEFAULT_BIRTH_PLACE)) - .andExpect(jsonPath("$.registrationCourt").value(DEFAULT_REGISTRATION_COURT)) - .andExpect(jsonPath("$.registrationNumber").value(DEFAULT_REGISTRATION_NUMBER)) - .andExpect(jsonPath("$.vatRegion").value(DEFAULT_VAT_REGION.toString())) - .andExpect(jsonPath("$.vatNumber").value(DEFAULT_VAT_NUMBER)) - .andExpect(jsonPath("$.contractualSalutation").value(DEFAULT_CONTRACTUAL_SALUTATION)) - .andExpect(jsonPath("$.contractualAddress").value(DEFAULT_CONTRACTUAL_ADDRESS)) - .andExpect(jsonPath("$.billingSalutation").value(DEFAULT_BILLING_SALUTATION)) - .andExpect(jsonPath("$.billingAddress").value(DEFAULT_BILLING_ADDRESS)) - .andExpect(jsonPath("$.remark").value(DEFAULT_REMARK)); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(customer.getId().intValue())) + .andExpect(jsonPath("$.reference").value(DEFAULT_REFERENCE)) + .andExpect(jsonPath("$.prefix").value(DEFAULT_PREFIX)) + .andExpect(jsonPath("$.name").value(DEFAULT_NAME)) + .andExpect(jsonPath("$.kind").value(DEFAULT_KIND.toString())) + .andExpect(jsonPath("$.birthDate").value(DEFAULT_BIRTH_DATE.toString())) + .andExpect(jsonPath("$.birthPlace").value(DEFAULT_BIRTH_PLACE)) + .andExpect(jsonPath("$.registrationCourt").value(DEFAULT_REGISTRATION_COURT)) + .andExpect(jsonPath("$.registrationNumber").value(DEFAULT_REGISTRATION_NUMBER)) + .andExpect(jsonPath("$.vatRegion").value(DEFAULT_VAT_REGION.toString())) + .andExpect(jsonPath("$.vatNumber").value(DEFAULT_VAT_NUMBER)) + .andExpect(jsonPath("$.contractualSalutation").value(DEFAULT_CONTRACTUAL_SALUTATION)) + .andExpect(jsonPath("$.contractualAddress").value(DEFAULT_CONTRACTUAL_ADDRESS)) + .andExpect(jsonPath("$.billingSalutation").value(DEFAULT_BILLING_SALUTATION)) + .andExpect(jsonPath("$.billingAddress").value(DEFAULT_BILLING_ADDRESS)) + .andExpect(jsonPath("$.remark").value(DEFAULT_REMARK)); } @Test @@ -515,7 +528,6 @@ public class CustomerResourceIntTest { defaultCustomerShouldBeFound("reference.lessThan=" + (DEFAULT_REFERENCE + 1)); } - @Test @Transactional public void getAllCustomersByPrefixIsEqualToSomething() throws Exception { @@ -698,7 +710,6 @@ public class CustomerResourceIntTest { defaultCustomerShouldBeFound("birthDate.lessThan=" + UPDATED_BIRTH_DATE); } - @Test @Transactional public void getAllCustomersByBirthPlaceIsEqualToSomething() throws Exception { @@ -797,7 +808,8 @@ public class CustomerResourceIntTest { customerRepository.saveAndFlush(customer); // Get all the customerList where registrationNumber in DEFAULT_REGISTRATION_NUMBER or UPDATED_REGISTRATION_NUMBER - defaultCustomerShouldBeFound("registrationNumber.in=" + DEFAULT_REGISTRATION_NUMBER + "," + UPDATED_REGISTRATION_NUMBER); + defaultCustomerShouldBeFound( + "registrationNumber.in=" + DEFAULT_REGISTRATION_NUMBER + "," + UPDATED_REGISTRATION_NUMBER); // Get all the customerList where registrationNumber equals to UPDATED_REGISTRATION_NUMBER defaultCustomerShouldNotBeFound("registrationNumber.in=" + UPDATED_REGISTRATION_NUMBER); @@ -913,8 +925,10 @@ public class CustomerResourceIntTest { // Initialize the database customerRepository.saveAndFlush(customer); - // Get all the customerList where contractualSalutation in DEFAULT_CONTRACTUAL_SALUTATION or UPDATED_CONTRACTUAL_SALUTATION - defaultCustomerShouldBeFound("contractualSalutation.in=" + DEFAULT_CONTRACTUAL_SALUTATION + "," + UPDATED_CONTRACTUAL_SALUTATION); + // Get all the customerList where contractualSalutation in DEFAULT_CONTRACTUAL_SALUTATION or + // UPDATED_CONTRACTUAL_SALUTATION + defaultCustomerShouldBeFound( + "contractualSalutation.in=" + DEFAULT_CONTRACTUAL_SALUTATION + "," + UPDATED_CONTRACTUAL_SALUTATION); // Get all the customerList where contractualSalutation equals to UPDATED_CONTRACTUAL_SALUTATION defaultCustomerShouldNotBeFound("contractualSalutation.in=" + UPDATED_CONTRACTUAL_SALUTATION); @@ -953,7 +967,8 @@ public class CustomerResourceIntTest { customerRepository.saveAndFlush(customer); // Get all the customerList where contractualAddress in DEFAULT_CONTRACTUAL_ADDRESS or UPDATED_CONTRACTUAL_ADDRESS - defaultCustomerShouldBeFound("contractualAddress.in=" + DEFAULT_CONTRACTUAL_ADDRESS + "," + UPDATED_CONTRACTUAL_ADDRESS); + defaultCustomerShouldBeFound( + "contractualAddress.in=" + DEFAULT_CONTRACTUAL_ADDRESS + "," + UPDATED_CONTRACTUAL_ADDRESS); // Get all the customerList where contractualAddress equals to UPDATED_CONTRACTUAL_ADDRESS defaultCustomerShouldNotBeFound("contractualAddress.in=" + UPDATED_CONTRACTUAL_ADDRESS); @@ -1107,7 +1122,6 @@ public class CustomerResourceIntTest { defaultCustomerShouldNotBeFound("membershipId.equals=" + (membershipId + 1)); } - @Test @Transactional public void getAllCustomersBySepamandateIsEqualToSomething() throws Exception { @@ -1131,30 +1145,30 @@ public class CustomerResourceIntTest { */ private void defaultCustomerShouldBeFound(String filter) throws Exception { restCustomerMockMvc.perform(get("/api/customers?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].id").value(hasItem(customer.getId().intValue()))) - .andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE))) - .andExpect(jsonPath("$.[*].prefix").value(hasItem(DEFAULT_PREFIX))) - .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME))) - .andExpect(jsonPath("$.[*].kind").value(hasItem(DEFAULT_KIND.toString()))) - .andExpect(jsonPath("$.[*].birthDate").value(hasItem(DEFAULT_BIRTH_DATE.toString()))) - .andExpect(jsonPath("$.[*].birthPlace").value(hasItem(DEFAULT_BIRTH_PLACE))) - .andExpect(jsonPath("$.[*].registrationCourt").value(hasItem(DEFAULT_REGISTRATION_COURT))) - .andExpect(jsonPath("$.[*].registrationNumber").value(hasItem(DEFAULT_REGISTRATION_NUMBER))) - .andExpect(jsonPath("$.[*].vatRegion").value(hasItem(DEFAULT_VAT_REGION.toString()))) - .andExpect(jsonPath("$.[*].vatNumber").value(hasItem(DEFAULT_VAT_NUMBER))) - .andExpect(jsonPath("$.[*].contractualSalutation").value(hasItem(DEFAULT_CONTRACTUAL_SALUTATION))) - .andExpect(jsonPath("$.[*].contractualAddress").value(hasItem(DEFAULT_CONTRACTUAL_ADDRESS))) - .andExpect(jsonPath("$.[*].billingSalutation").value(hasItem(DEFAULT_BILLING_SALUTATION))) - .andExpect(jsonPath("$.[*].billingAddress").value(hasItem(DEFAULT_BILLING_ADDRESS))) - .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(customer.getId().intValue()))) + .andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE))) + .andExpect(jsonPath("$.[*].prefix").value(hasItem(DEFAULT_PREFIX))) + .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME))) + .andExpect(jsonPath("$.[*].kind").value(hasItem(DEFAULT_KIND.toString()))) + .andExpect(jsonPath("$.[*].birthDate").value(hasItem(DEFAULT_BIRTH_DATE.toString()))) + .andExpect(jsonPath("$.[*].birthPlace").value(hasItem(DEFAULT_BIRTH_PLACE))) + .andExpect(jsonPath("$.[*].registrationCourt").value(hasItem(DEFAULT_REGISTRATION_COURT))) + .andExpect(jsonPath("$.[*].registrationNumber").value(hasItem(DEFAULT_REGISTRATION_NUMBER))) + .andExpect(jsonPath("$.[*].vatRegion").value(hasItem(DEFAULT_VAT_REGION.toString()))) + .andExpect(jsonPath("$.[*].vatNumber").value(hasItem(DEFAULT_VAT_NUMBER))) + .andExpect(jsonPath("$.[*].contractualSalutation").value(hasItem(DEFAULT_CONTRACTUAL_SALUTATION))) + .andExpect(jsonPath("$.[*].contractualAddress").value(hasItem(DEFAULT_CONTRACTUAL_ADDRESS))) + .andExpect(jsonPath("$.[*].billingSalutation").value(hasItem(DEFAULT_BILLING_SALUTATION))) + .andExpect(jsonPath("$.[*].billingAddress").value(hasItem(DEFAULT_BILLING_ADDRESS))) + .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); // Check, that the count call also returns 1 restCustomerMockMvc.perform(get("/api/customers/count?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(content().string("1")); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(content().string("1")); } /** @@ -1162,25 +1176,24 @@ public class CustomerResourceIntTest { */ private void defaultCustomerShouldNotBeFound(String filter) throws Exception { restCustomerMockMvc.perform(get("/api/customers?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$").isArray()) - .andExpect(jsonPath("$").isEmpty()); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$").isArray()) + .andExpect(jsonPath("$").isEmpty()); // Check, that the count call also returns 0 restCustomerMockMvc.perform(get("/api/customers/count?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(content().string("0")); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(content().string("0")); } - @Test @Transactional public void getNonExistingCustomer() throws Exception { // Get the customer restCustomerMockMvc.perform(get("/api/customers/{id}", Long.MAX_VALUE)) - .andExpect(status().isNotFound()); + .andExpect(status().isNotFound()); } @Test @@ -1196,27 +1209,28 @@ public class CustomerResourceIntTest { // Disconnect from session so that the updates on updatedCustomer are not directly saved in db em.detach(updatedCustomer); updatedCustomer - .reference(null) - .prefix(null) - .name(UPDATED_NAME) - .kind(UPDATED_KIND) - .birthDate(UPDATED_BIRTH_DATE) - .birthPlace(UPDATED_BIRTH_PLACE) - .registrationCourt(UPDATED_REGISTRATION_COURT) - .registrationNumber(UPDATED_REGISTRATION_NUMBER) - .vatRegion(UPDATED_VAT_REGION) - .vatNumber(UPDATED_VAT_NUMBER) - .contractualSalutation(UPDATED_CONTRACTUAL_SALUTATION) - .contractualAddress(UPDATED_CONTRACTUAL_ADDRESS) - .billingSalutation(UPDATED_BILLING_SALUTATION) - .billingAddress(UPDATED_BILLING_ADDRESS) - .remark(UPDATED_REMARK); + .reference(null) + .prefix(null) + .name(UPDATED_NAME) + .kind(UPDATED_KIND) + .birthDate(UPDATED_BIRTH_DATE) + .birthPlace(UPDATED_BIRTH_PLACE) + .registrationCourt(UPDATED_REGISTRATION_COURT) + .registrationNumber(UPDATED_REGISTRATION_NUMBER) + .vatRegion(UPDATED_VAT_REGION) + .vatNumber(UPDATED_VAT_NUMBER) + .contractualSalutation(UPDATED_CONTRACTUAL_SALUTATION) + .contractualAddress(UPDATED_CONTRACTUAL_ADDRESS) + .billingSalutation(UPDATED_BILLING_SALUTATION) + .billingAddress(UPDATED_BILLING_ADDRESS) + .remark(UPDATED_REMARK); CustomerDTO customerDTO = customerMapper.toDto(updatedCustomer); - restCustomerMockMvc.perform(put("/api/customers") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(customerDTO))) - .andExpect(status().isOk()); + restCustomerMockMvc.perform( + put("/api/customers") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(customerDTO))) + .andExpect(status().isOk()); // Validate the Customer in the database List customerList = customerRepository.findAll(); @@ -1248,10 +1262,11 @@ public class CustomerResourceIntTest { CustomerDTO customerDTO = customerMapper.toDto(customer); // If the entity doesn't have an ID, it will throw BadRequestAlertException - restCustomerMockMvc.perform(put("/api/customers") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(customerDTO))) - .andExpect(status().isBadRequest()); + restCustomerMockMvc.perform( + put("/api/customers") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(customerDTO))) + .andExpect(status().isBadRequest()); // Validate the Customer in the database List customerList = customerRepository.findAll(); @@ -1267,9 +1282,10 @@ public class CustomerResourceIntTest { int databaseSizeBeforeDelete = customerRepository.findAll().size(); // Delete the customer - restCustomerMockMvc.perform(delete("/api/customers/{id}", customer.getId()) - .accept(TestUtil.APPLICATION_JSON_UTF8)) - .andExpect(status().isBadRequest()); + restCustomerMockMvc.perform( + delete("/api/customers/{id}", customer.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isBadRequest()); // Validate the database is unchanged List customerList = customerRepository.findAll(); diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/LogsResourceIntTest.java b/src/test/java/org/hostsharing/hsadminng/web/rest/LogsResourceIntTest.java index 70268354..c6a0093c 100644 --- a/src/test/java/org/hostsharing/hsadminng/web/rest/LogsResourceIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/web/rest/LogsResourceIntTest.java @@ -1,9 +1,18 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.web.rest.vm.LoggerVM; + import ch.qos.logback.classic.AsyncAppender; import ch.qos.logback.classic.LoggerContext; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -14,12 +23,6 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - /** * Test class for the LogsResource REST controller. * @@ -35,15 +38,15 @@ public class LogsResourceIntTest { public void setup() { LogsResource logsResource = new LogsResource(); this.restLogsMockMvc = MockMvcBuilders - .standaloneSetup(logsResource) - .build(); + .standaloneSetup(logsResource) + .build(); } @Test public void getAllLogs() throws Exception { restLogsMockMvc.perform(get("/management/logs")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)); } @Test @@ -52,10 +55,11 @@ public class LogsResourceIntTest { logger.setLevel("INFO"); logger.setName("ROOT"); - restLogsMockMvc.perform(put("/management/logs") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(logger))) - .andExpect(status().isNoContent()); + restLogsMockMvc.perform( + put("/management/logs") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(logger))) + .andExpect(status().isNoContent()); } @Test diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/MembershipResourceIntTest.java b/src/test/java/org/hostsharing/hsadminng/web/rest/MembershipResourceIntTest.java index f0513341..9fa53732 100644 --- a/src/test/java/org/hostsharing/hsadminng/web/rest/MembershipResourceIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/web/rest/MembershipResourceIntTest.java @@ -1,5 +1,12 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.domain.Asset; import org.hostsharing.hsadminng.domain.Customer; @@ -13,6 +20,7 @@ import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.dto.MembershipDTO; import org.hostsharing.hsadminng.service.mapper.MembershipMapper; import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -28,16 +36,11 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.Validator; -import javax.persistence.EntityManager; import java.time.LocalDate; import java.time.ZoneId; import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import javax.persistence.EntityManager; /** * Test class for the MembershipResource REST controller. @@ -54,8 +57,12 @@ public class MembershipResourceIntTest { private static final LocalDate DEFAULT_MEMBER_FROM_DATE = DEFAULT_DOCUMENT_DATE.plusDays(2); private static final LocalDate UPDATED_MEMBER_FROM_DATE = UPDATED_DOCUMENT_DATE.plusDays(8); - private static final LocalDate DEFAULT_MEMBER_UNTIL_DATE = DEFAULT_MEMBER_FROM_DATE.plusYears(1).withMonth(12).withDayOfMonth(31); - private static final LocalDate UPDATED_MEMBER_UNTIL_DATE = UPDATED_MEMBER_FROM_DATE.plusYears(7).withMonth(12).withDayOfMonth(31); + private static final LocalDate DEFAULT_MEMBER_UNTIL_DATE = DEFAULT_MEMBER_FROM_DATE.plusYears(1) + .withMonth(12) + .withDayOfMonth(31); + private static final LocalDate UPDATED_MEMBER_UNTIL_DATE = UPDATED_MEMBER_FROM_DATE.plusYears(7) + .withMonth(12) + .withDayOfMonth(31); private static final LocalDate DEFAULT_ADMISSION_DOCUMENT_DATE = LocalDate.ofEpochDay(0L); private static final LocalDate UPDATED_ADMISSION_DOCUMENT_DATE = LocalDate.now(ZoneId.systemDefault()); @@ -105,11 +112,12 @@ public class MembershipResourceIntTest { MockitoAnnotations.initMocks(this); final MembershipResource membershipResource = new MembershipResource(membershipService, membershipQueryService); this.restMembershipMockMvc = MockMvcBuilders.standaloneSetup(membershipResource) - .setCustomArgumentResolvers(pageableArgumentResolver) - .setControllerAdvice(exceptionTranslator) - .setConversionService(createFormattingConversionService()) - .setMessageConverters(jacksonMessageConverter) - .setValidator(validator).build(); + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setConversionService(createFormattingConversionService()) + .setMessageConverters(jacksonMessageConverter) + .setValidator(validator) + .build(); } /** @@ -120,11 +128,11 @@ public class MembershipResourceIntTest { */ public static Membership createEntity(EntityManager em) { Membership membership = new Membership() - .admissionDocumentDate(DEFAULT_ADMISSION_DOCUMENT_DATE) - .cancellationDocumentDate(DEFAULT_CANCELLATION_DOCUMENT_DATE) - .memberFromDate(DEFAULT_MEMBER_FROM_DATE) - .memberUntilDate(DEFAULT_MEMBER_UNTIL_DATE) - .remark(DEFAULT_REMARK); + .admissionDocumentDate(DEFAULT_ADMISSION_DOCUMENT_DATE) + .cancellationDocumentDate(DEFAULT_CANCELLATION_DOCUMENT_DATE) + .memberFromDate(DEFAULT_MEMBER_FROM_DATE) + .memberUntilDate(DEFAULT_MEMBER_UNTIL_DATE) + .remark(DEFAULT_REMARK); // Add required entity Customer customer = CustomerResourceIntTest.createEntity(em); em.persist(customer); @@ -141,10 +149,10 @@ public class MembershipResourceIntTest { */ public static Membership createPersistentEntity(EntityManager em, final Customer customer) { Membership membership = new Membership() - .admissionDocumentDate(DEFAULT_ADMISSION_DOCUMENT_DATE) - .memberFromDate(DEFAULT_MEMBER_FROM_DATE) - .memberUntilDate(DEFAULT_MEMBER_UNTIL_DATE) - .remark(DEFAULT_REMARK); + .admissionDocumentDate(DEFAULT_ADMISSION_DOCUMENT_DATE) + .memberFromDate(DEFAULT_MEMBER_FROM_DATE) + .memberUntilDate(DEFAULT_MEMBER_UNTIL_DATE) + .remark(DEFAULT_REMARK); // Add required entity membership.setCustomer(customer); em.persist(membership); @@ -164,10 +172,11 @@ public class MembershipResourceIntTest { // Create the Membership MembershipDTO membershipDTO = membershipMapper.toDto(membership); - restMembershipMockMvc.perform(post("/api/memberships") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(membershipDTO))) - .andExpect(status().isCreated()); + restMembershipMockMvc.perform( + post("/api/memberships") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(membershipDTO))) + .andExpect(status().isCreated()); // Validate the Membership in the database List membershipList = membershipRepository.findAll(); @@ -192,10 +201,11 @@ public class MembershipResourceIntTest { MembershipDTO membershipDTO = membershipMapper.toDto(membership); // An entity with an existing ID cannot be created, so this API call must fail - restMembershipMockMvc.perform(post("/api/memberships") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(membershipDTO))) - .andExpect(status().isBadRequest()); + restMembershipMockMvc.perform( + post("/api/memberships") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(membershipDTO))) + .andExpect(status().isBadRequest()); // Validate the Customer in the database List membershipList = membershipRepository.findAll(); @@ -212,10 +222,11 @@ public class MembershipResourceIntTest { MembershipDTO membershipDTO = membershipMapper.toDto(membership); // An entity with an existing ID cannot be created, so this API call must fail - restMembershipMockMvc.perform(post("/api/memberships") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(membershipDTO))) - .andExpect(status().isBadRequest()); + restMembershipMockMvc.perform( + post("/api/memberships") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(membershipDTO))) + .andExpect(status().isBadRequest()); // Validate the Membership in the database List membershipList = membershipRepository.findAll(); @@ -232,10 +243,11 @@ public class MembershipResourceIntTest { // Create the Membership, which fails. MembershipDTO membershipDTO = membershipMapper.toDto(membership); - restMembershipMockMvc.perform(post("/api/memberships") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(membershipDTO))) - .andExpect(status().isBadRequest()); + restMembershipMockMvc.perform( + post("/api/memberships") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(membershipDTO))) + .andExpect(status().isBadRequest()); List membershipList = membershipRepository.findAll(); assertThat(membershipList).hasSize(databaseSizeBeforeTest); @@ -251,10 +263,11 @@ public class MembershipResourceIntTest { // Create the Membership, which fails. MembershipDTO membershipDTO = membershipMapper.toDto(membership); - restMembershipMockMvc.perform(post("/api/memberships") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(membershipDTO))) - .andExpect(status().isBadRequest()); + restMembershipMockMvc.perform( + post("/api/memberships") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(membershipDTO))) + .andExpect(status().isBadRequest()); List membershipList = membershipRepository.findAll(); assertThat(membershipList).hasSize(databaseSizeBeforeTest); @@ -268,14 +281,16 @@ public class MembershipResourceIntTest { // Get all the membershipList restMembershipMockMvc.perform(get("/api/memberships?sort=id,desc")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].id").value(hasItem(membership.getId().intValue()))) - .andExpect(jsonPath("$.[*].admissionDocumentDate").value(hasItem(DEFAULT_ADMISSION_DOCUMENT_DATE.toString()))) - .andExpect(jsonPath("$.[*].cancellationDocumentDate").value(hasItem(DEFAULT_CANCELLATION_DOCUMENT_DATE.toString()))) - .andExpect(jsonPath("$.[*].memberFromDate").value(hasItem(DEFAULT_MEMBER_FROM_DATE.toString()))) - .andExpect(jsonPath("$.[*].memberUntilDate").value(hasItem(DEFAULT_MEMBER_UNTIL_DATE.toString()))) - .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(membership.getId().intValue()))) + .andExpect(jsonPath("$.[*].admissionDocumentDate").value(hasItem(DEFAULT_ADMISSION_DOCUMENT_DATE.toString()))) + .andExpect( + jsonPath("$.[*].cancellationDocumentDate") + .value(hasItem(DEFAULT_CANCELLATION_DOCUMENT_DATE.toString()))) + .andExpect(jsonPath("$.[*].memberFromDate").value(hasItem(DEFAULT_MEMBER_FROM_DATE.toString()))) + .andExpect(jsonPath("$.[*].memberUntilDate").value(hasItem(DEFAULT_MEMBER_UNTIL_DATE.toString()))) + .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); } @Test @@ -286,14 +301,14 @@ public class MembershipResourceIntTest { // Get the membership restMembershipMockMvc.perform(get("/api/memberships/{id}", membership.getId())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.id").value(membership.getId().intValue())) - .andExpect(jsonPath("$.admissionDocumentDate").value(DEFAULT_ADMISSION_DOCUMENT_DATE.toString())) - .andExpect(jsonPath("$.cancellationDocumentDate").value(DEFAULT_CANCELLATION_DOCUMENT_DATE.toString())) - .andExpect(jsonPath("$.memberFromDate").value(DEFAULT_MEMBER_FROM_DATE.toString())) - .andExpect(jsonPath("$.memberUntilDate").value(DEFAULT_MEMBER_UNTIL_DATE.toString())) - .andExpect(jsonPath("$.remark").value(DEFAULT_REMARK)); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(membership.getId().intValue())) + .andExpect(jsonPath("$.admissionDocumentDate").value(DEFAULT_ADMISSION_DOCUMENT_DATE.toString())) + .andExpect(jsonPath("$.cancellationDocumentDate").value(DEFAULT_CANCELLATION_DOCUMENT_DATE.toString())) + .andExpect(jsonPath("$.memberFromDate").value(DEFAULT_MEMBER_FROM_DATE.toString())) + .andExpect(jsonPath("$.memberUntilDate").value(DEFAULT_MEMBER_UNTIL_DATE.toString())) + .andExpect(jsonPath("$.remark").value(DEFAULT_REMARK)); } @Test @@ -315,8 +330,10 @@ public class MembershipResourceIntTest { // Initialize the database membershipRepository.saveAndFlush(membership); - // Get all the membershipList where admissionDocumentDate in DEFAULT_ADMISSION_DOCUMENT_DATE or UPDATED_ADMISSION_DOCUMENT_DATE - defaultMembershipShouldBeFound("admissionDocumentDate.in=" + DEFAULT_ADMISSION_DOCUMENT_DATE + "," + UPDATED_ADMISSION_DOCUMENT_DATE); + // Get all the membershipList where admissionDocumentDate in DEFAULT_ADMISSION_DOCUMENT_DATE or + // UPDATED_ADMISSION_DOCUMENT_DATE + defaultMembershipShouldBeFound( + "admissionDocumentDate.in=" + DEFAULT_ADMISSION_DOCUMENT_DATE + "," + UPDATED_ADMISSION_DOCUMENT_DATE); // Get all the membershipList where admissionDocumentDate equals to UPDATED_ADMISSION_DOCUMENT_DATE defaultMembershipShouldNotBeFound("admissionDocumentDate.in=" + UPDATED_ADMISSION_DOCUMENT_DATE); @@ -361,7 +378,6 @@ public class MembershipResourceIntTest { defaultMembershipShouldBeFound("admissionDocumentDate.lessThan=" + UPDATED_ADMISSION_DOCUMENT_DATE); } - @Test @Transactional public void getAllMembershipsByCancellationDocumentDateIsEqualToSomething() throws Exception { @@ -381,8 +397,10 @@ public class MembershipResourceIntTest { // Initialize the database membershipRepository.saveAndFlush(membership); - // Get all the membershipList where cancellationDocumentDate in DEFAULT_CANCELLATION_DOCUMENT_DATE or UPDATED_CANCELLATION_DOCUMENT_DATE - defaultMembershipShouldBeFound("cancellationDocumentDate.in=" + DEFAULT_CANCELLATION_DOCUMENT_DATE + "," + UPDATED_CANCELLATION_DOCUMENT_DATE); + // Get all the membershipList where cancellationDocumentDate in DEFAULT_CANCELLATION_DOCUMENT_DATE or + // UPDATED_CANCELLATION_DOCUMENT_DATE + defaultMembershipShouldBeFound( + "cancellationDocumentDate.in=" + DEFAULT_CANCELLATION_DOCUMENT_DATE + "," + UPDATED_CANCELLATION_DOCUMENT_DATE); // Get all the membershipList where cancellationDocumentDate equals to UPDATED_CANCELLATION_DOCUMENT_DATE defaultMembershipShouldNotBeFound("cancellationDocumentDate.in=" + UPDATED_CANCELLATION_DOCUMENT_DATE); @@ -407,10 +425,12 @@ public class MembershipResourceIntTest { // Initialize the database membershipRepository.saveAndFlush(membership); - // Get all the membershipList where cancellationDocumentDate greater than or equals to DEFAULT_CANCELLATION_DOCUMENT_DATE + // Get all the membershipList where cancellationDocumentDate greater than or equals to + // DEFAULT_CANCELLATION_DOCUMENT_DATE defaultMembershipShouldBeFound("cancellationDocumentDate.greaterOrEqualThan=" + DEFAULT_CANCELLATION_DOCUMENT_DATE); - // Get all the membershipList where cancellationDocumentDate greater than or equals to UPDATED_CANCELLATION_DOCUMENT_DATE + // Get all the membershipList where cancellationDocumentDate greater than or equals to + // UPDATED_CANCELLATION_DOCUMENT_DATE defaultMembershipShouldNotBeFound("cancellationDocumentDate.greaterOrEqualThan=" + UPDATED_CANCELLATION_DOCUMENT_DATE); } @@ -427,7 +447,6 @@ public class MembershipResourceIntTest { defaultMembershipShouldBeFound("cancellationDocumentDate.lessThan=" + UPDATED_CANCELLATION_DOCUMENT_DATE); } - @Test @Transactional public void getAllMembershipsByMemberFromDateIsEqualToSomething() throws Exception { @@ -493,7 +512,6 @@ public class MembershipResourceIntTest { defaultMembershipShouldBeFound("memberFromDate.lessThan=" + UPDATED_MEMBER_FROM_DATE); } - @Test @Transactional public void getAllMembershipsByMemberUntilDateIsEqualToSomething() throws Exception { @@ -559,7 +577,6 @@ public class MembershipResourceIntTest { defaultMembershipShouldBeFound("memberUntilDate.lessThan=" + UPDATED_MEMBER_UNTIL_DATE); } - @Test @Transactional public void getAllMembershipsByRemarkIsEqualToSomething() throws Exception { @@ -615,7 +632,6 @@ public class MembershipResourceIntTest { defaultMembershipShouldNotBeFound("shareId.equals=" + (shareId + 1)); } - @Test @Transactional public void getAllMembershipsByAssetIsEqualToSomething() throws Exception { @@ -632,7 +648,6 @@ public class MembershipResourceIntTest { defaultMembershipShouldNotBeFound("assetId.equals=" + (assetId + 1)); } - @Test @Transactional public void getAllMembershipsByCustomerIsEqualToSomething() throws Exception { @@ -654,20 +669,22 @@ public class MembershipResourceIntTest { */ private void defaultMembershipShouldBeFound(String filter) throws Exception { restMembershipMockMvc.perform(get("/api/memberships?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].id").value(hasItem(membership.getId().intValue()))) - .andExpect(jsonPath("$.[*].admissionDocumentDate").value(hasItem(DEFAULT_ADMISSION_DOCUMENT_DATE.toString()))) - .andExpect(jsonPath("$.[*].cancellationDocumentDate").value(hasItem(DEFAULT_CANCELLATION_DOCUMENT_DATE.toString()))) - .andExpect(jsonPath("$.[*].memberFromDate").value(hasItem(DEFAULT_MEMBER_FROM_DATE.toString()))) - .andExpect(jsonPath("$.[*].memberUntilDate").value(hasItem(DEFAULT_MEMBER_UNTIL_DATE.toString()))) - .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(membership.getId().intValue()))) + .andExpect(jsonPath("$.[*].admissionDocumentDate").value(hasItem(DEFAULT_ADMISSION_DOCUMENT_DATE.toString()))) + .andExpect( + jsonPath("$.[*].cancellationDocumentDate") + .value(hasItem(DEFAULT_CANCELLATION_DOCUMENT_DATE.toString()))) + .andExpect(jsonPath("$.[*].memberFromDate").value(hasItem(DEFAULT_MEMBER_FROM_DATE.toString()))) + .andExpect(jsonPath("$.[*].memberUntilDate").value(hasItem(DEFAULT_MEMBER_UNTIL_DATE.toString()))) + .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); // Check, that the count call also returns 1 restMembershipMockMvc.perform(get("/api/memberships/count?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(content().string("1")); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(content().string("1")); } /** @@ -675,25 +692,24 @@ public class MembershipResourceIntTest { */ private void defaultMembershipShouldNotBeFound(String filter) throws Exception { restMembershipMockMvc.perform(get("/api/memberships?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$").isArray()) - .andExpect(jsonPath("$").isEmpty()); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$").isArray()) + .andExpect(jsonPath("$").isEmpty()); // Check, that the count call also returns 0 restMembershipMockMvc.perform(get("/api/memberships/count?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(content().string("0")); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(content().string("0")); } - @Test @Transactional public void getNonExistingMembership() throws Exception { // Get the membership restMembershipMockMvc.perform(get("/api/memberships/{id}", Long.MAX_VALUE)) - .andExpect(status().isNotFound()); + .andExpect(status().isNotFound()); } @Test @@ -709,15 +725,16 @@ public class MembershipResourceIntTest { // Disconnect from session so that the updates on updatedMembership are not directly saved in db em.detach(updatedMembership); updatedMembership - .cancellationDocumentDate(UPDATED_CANCELLATION_DOCUMENT_DATE) - .memberUntilDate(UPDATED_MEMBER_UNTIL_DATE) - .remark(UPDATED_REMARK); + .cancellationDocumentDate(UPDATED_CANCELLATION_DOCUMENT_DATE) + .memberUntilDate(UPDATED_MEMBER_UNTIL_DATE) + .remark(UPDATED_REMARK); MembershipDTO membershipDTO = membershipMapper.toDto(updatedMembership); - restMembershipMockMvc.perform(put("/api/memberships") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(membershipDTO))) - .andExpect(status().isOk()); + restMembershipMockMvc.perform( + put("/api/memberships") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(membershipDTO))) + .andExpect(status().isOk()); // Validate the Membership in the database List membershipList = membershipRepository.findAll(); @@ -739,10 +756,11 @@ public class MembershipResourceIntTest { MembershipDTO membershipDTO = membershipMapper.toDto(membership); // If the entity doesn't have an ID, it will throw BadRequestAlertException - restMembershipMockMvc.perform(put("/api/memberships") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(membershipDTO))) - .andExpect(status().isBadRequest()); + restMembershipMockMvc.perform( + put("/api/memberships") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(membershipDTO))) + .andExpect(status().isBadRequest()); // Validate the Membership in the database List membershipList = membershipRepository.findAll(); @@ -758,9 +776,10 @@ public class MembershipResourceIntTest { int databaseSizeBeforeDelete = membershipRepository.findAll().size(); // Delete the membership - restMembershipMockMvc.perform(delete("/api/memberships/{id}", membership.getId()) - .accept(TestUtil.APPLICATION_JSON_UTF8)) - .andExpect(status().isBadRequest()); + restMembershipMockMvc.perform( + delete("/api/memberships/{id}", membership.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isBadRequest()); // Validate the database is unchanged List membershipList = membershipRepository.findAll(); diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/SepaMandateResourceIntTest.java b/src/test/java/org/hostsharing/hsadminng/web/rest/SepaMandateResourceIntTest.java index 356a55eb..fce4c551 100644 --- a/src/test/java/org/hostsharing/hsadminng/web/rest/SepaMandateResourceIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/web/rest/SepaMandateResourceIntTest.java @@ -1,5 +1,12 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.domain.Customer; import org.hostsharing.hsadminng.domain.SepaMandate; @@ -12,6 +19,7 @@ import org.hostsharing.hsadminng.service.dto.CustomerDTO; import org.hostsharing.hsadminng.service.dto.SepaMandateDTO; import org.hostsharing.hsadminng.service.mapper.SepaMandateMapper; import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,16 +35,11 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.Validator; -import javax.persistence.EntityManager; import java.time.LocalDate; import java.time.ZoneId; import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import javax.persistence.EntityManager; /** * Test class for the SepaMandateResource REST controller. @@ -113,11 +116,12 @@ public class SepaMandateResourceIntTest { MockitoAnnotations.initMocks(this); final SepaMandateResource sepaMandateResource = new SepaMandateResource(sepaMandateService, sepaMandateQueryService); this.restSepaMandateMockMvc = MockMvcBuilders.standaloneSetup(sepaMandateResource) - .setCustomArgumentResolvers(pageableArgumentResolver) - .setControllerAdvice(exceptionTranslator) - .setConversionService(createFormattingConversionService()) - .setMessageConverters(jacksonMessageConverter) - .setValidator(validator).build(); + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setConversionService(createFormattingConversionService()) + .setMessageConverters(jacksonMessageConverter) + .setValidator(validator) + .build(); } /** @@ -128,15 +132,15 @@ public class SepaMandateResourceIntTest { */ public static SepaMandate createEntity(EntityManager em) { SepaMandate sepaMandate = new SepaMandate() - .reference(DEFAULT_REFERENCE) - .iban(DEFAULT_IBAN) - .bic(DEFAULT_BIC) - .grantingDocumentDate(DEFAULT_GRANTING_DOCUMENT_DATE) - .revokationDocumentDate(DEFAULT_REVOKATION_DOCUMENT_DATE) - .validFromDate(DEFAULT_VALID_FROM_DATE) - .validUntilDate(DEFAULT_VALID_UNTIL_DATE) - .lastUsedDate(DEFAULT_LAST_USED_DATE) - .remark(DEFAULT_REMARK); + .reference(DEFAULT_REFERENCE) + .iban(DEFAULT_IBAN) + .bic(DEFAULT_BIC) + .grantingDocumentDate(DEFAULT_GRANTING_DOCUMENT_DATE) + .revokationDocumentDate(DEFAULT_REVOKATION_DOCUMENT_DATE) + .validFromDate(DEFAULT_VALID_FROM_DATE) + .validUntilDate(DEFAULT_VALID_UNTIL_DATE) + .lastUsedDate(DEFAULT_LAST_USED_DATE) + .remark(DEFAULT_REMARK); // Add required entity Customer customer = CustomerResourceIntTest.createEntity(em); em.persist(customer); @@ -153,15 +157,15 @@ public class SepaMandateResourceIntTest { */ public static SepaMandate createEntity(EntityManager em, final Customer customer) { SepaMandate sepaMandate = new SepaMandate() - .reference(DEFAULT_REFERENCE) - .iban(DEFAULT_IBAN) - .bic(DEFAULT_BIC) - .grantingDocumentDate(DEFAULT_GRANTING_DOCUMENT_DATE) - .validFromDate(DEFAULT_VALID_FROM_DATE) - .validUntilDate(DEFAULT_VALID_UNTIL_DATE) - .lastUsedDate(DEFAULT_LAST_USED_DATE) - .revokationDocumentDate(DEFAULT_REVOKATION_DOCUMENT_DATE) - .remark(DEFAULT_REMARK); + .reference(DEFAULT_REFERENCE) + .iban(DEFAULT_IBAN) + .bic(DEFAULT_BIC) + .grantingDocumentDate(DEFAULT_GRANTING_DOCUMENT_DATE) + .validFromDate(DEFAULT_VALID_FROM_DATE) + .validUntilDate(DEFAULT_VALID_UNTIL_DATE) + .lastUsedDate(DEFAULT_LAST_USED_DATE) + .revokationDocumentDate(DEFAULT_REVOKATION_DOCUMENT_DATE) + .remark(DEFAULT_REMARK); // Add required entity sepaMandate.setCustomer(customer); return sepaMandate; @@ -186,10 +190,11 @@ public class SepaMandateResourceIntTest { MockSecurityContext.givenAuthenticatedUser(); MockSecurityContext.givenUserHavingRole(CustomerDTO.class, sepaMandateDTO.getCustomerId(), Role.FINANCIAL_CONTACT); - restSepaMandateMockMvc.perform(post("/api/sepa-mandates") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO))) - .andExpect(status().isCreated()); + restSepaMandateMockMvc.perform( + post("/api/sepa-mandates") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO))) + .andExpect(status().isCreated()); // Validate the SepaMandate in the database List sepaMandateList = sepaMandateRepository.findAll(); @@ -216,10 +221,11 @@ public class SepaMandateResourceIntTest { SepaMandateDTO sepaMandateDTO = sepaMandateMapper.toDto(sepaMandate); // An entity with an existing ID cannot be created, so this API call must fail - restSepaMandateMockMvc.perform(post("/api/sepa-mandates") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO))) - .andExpect(status().isBadRequest()); + restSepaMandateMockMvc.perform( + post("/api/sepa-mandates") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO))) + .andExpect(status().isBadRequest()); // Validate the SepaMandate in the database List sepaMandateList = sepaMandateRepository.findAll(); @@ -236,10 +242,11 @@ public class SepaMandateResourceIntTest { // Create the SepaMandate, which fails. SepaMandateDTO sepaMandateDTO = sepaMandateMapper.toDto(sepaMandate); - restSepaMandateMockMvc.perform(post("/api/sepa-mandates") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO))) - .andExpect(status().isBadRequest()); + restSepaMandateMockMvc.perform( + post("/api/sepa-mandates") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO))) + .andExpect(status().isBadRequest()); List sepaMandateList = sepaMandateRepository.findAll(); assertThat(sepaMandateList).hasSize(databaseSizeBeforeTest); @@ -255,10 +262,11 @@ public class SepaMandateResourceIntTest { // Create the SepaMandate, which fails. SepaMandateDTO sepaMandateDTO = sepaMandateMapper.toDto(sepaMandate); - restSepaMandateMockMvc.perform(post("/api/sepa-mandates") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO))) - .andExpect(status().isBadRequest()); + restSepaMandateMockMvc.perform( + post("/api/sepa-mandates") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO))) + .andExpect(status().isBadRequest()); List sepaMandateList = sepaMandateRepository.findAll(); assertThat(sepaMandateList).hasSize(databaseSizeBeforeTest); @@ -274,10 +282,11 @@ public class SepaMandateResourceIntTest { // Create the SepaMandate, which fails. SepaMandateDTO sepaMandateDTO = sepaMandateMapper.toDto(sepaMandate); - restSepaMandateMockMvc.perform(post("/api/sepa-mandates") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO))) - .andExpect(status().isBadRequest()); + restSepaMandateMockMvc.perform( + post("/api/sepa-mandates") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO))) + .andExpect(status().isBadRequest()); List sepaMandateList = sepaMandateRepository.findAll(); assertThat(sepaMandateList).hasSize(databaseSizeBeforeTest); @@ -291,20 +300,20 @@ public class SepaMandateResourceIntTest { // Get all the sepaMandateList restSepaMandateMockMvc.perform(get("/api/sepa-mandates?sort=id,desc")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].id").value(hasItem(sepaMandate.getId().intValue()))) - .andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE))) - .andExpect(jsonPath("$.[*].iban").value(hasItem(DEFAULT_IBAN))) - .andExpect(jsonPath("$.[*].bic").value(hasItem(DEFAULT_BIC))) - .andExpect(jsonPath("$.[*].grantingDocumentDate").value(hasItem(DEFAULT_GRANTING_DOCUMENT_DATE.toString()))) - .andExpect(jsonPath("$.[*].revokationDocumentDate").value(hasItem(DEFAULT_REVOKATION_DOCUMENT_DATE.toString()))) - .andExpect(jsonPath("$.[*].validFromDate").value(hasItem(DEFAULT_VALID_FROM_DATE.toString()))) - .andExpect(jsonPath("$.[*].validUntilDate").value(hasItem(DEFAULT_VALID_UNTIL_DATE.toString()))) - .andExpect(jsonPath("$.[*].lastUsedDate").value(hasItem(DEFAULT_LAST_USED_DATE.toString()))) - .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(sepaMandate.getId().intValue()))) + .andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE))) + .andExpect(jsonPath("$.[*].iban").value(hasItem(DEFAULT_IBAN))) + .andExpect(jsonPath("$.[*].bic").value(hasItem(DEFAULT_BIC))) + .andExpect(jsonPath("$.[*].grantingDocumentDate").value(hasItem(DEFAULT_GRANTING_DOCUMENT_DATE.toString()))) + .andExpect(jsonPath("$.[*].revokationDocumentDate").value(hasItem(DEFAULT_REVOKATION_DOCUMENT_DATE.toString()))) + .andExpect(jsonPath("$.[*].validFromDate").value(hasItem(DEFAULT_VALID_FROM_DATE.toString()))) + .andExpect(jsonPath("$.[*].validUntilDate").value(hasItem(DEFAULT_VALID_UNTIL_DATE.toString()))) + .andExpect(jsonPath("$.[*].lastUsedDate").value(hasItem(DEFAULT_LAST_USED_DATE.toString()))) + .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); } - + @Test @Transactional public void getSepaMandate() throws Exception { @@ -313,18 +322,18 @@ public class SepaMandateResourceIntTest { // Get the sepaMandate restSepaMandateMockMvc.perform(get("/api/sepa-mandates/{id}", sepaMandate.getId())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.id").value(sepaMandate.getId().intValue())) - .andExpect(jsonPath("$.reference").value(DEFAULT_REFERENCE)) - .andExpect(jsonPath("$.iban").value(DEFAULT_IBAN)) - .andExpect(jsonPath("$.bic").value(DEFAULT_BIC)) - .andExpect(jsonPath("$.grantingDocumentDate").value(DEFAULT_GRANTING_DOCUMENT_DATE.toString())) - .andExpect(jsonPath("$.revokationDocumentDate").value(DEFAULT_REVOKATION_DOCUMENT_DATE.toString())) - .andExpect(jsonPath("$.validFromDate").value(DEFAULT_VALID_FROM_DATE.toString())) - .andExpect(jsonPath("$.validUntilDate").value(DEFAULT_VALID_UNTIL_DATE.toString())) - .andExpect(jsonPath("$.lastUsedDate").value(DEFAULT_LAST_USED_DATE.toString())) - .andExpect(jsonPath("$.remark").value(DEFAULT_REMARK)); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(sepaMandate.getId().intValue())) + .andExpect(jsonPath("$.reference").value(DEFAULT_REFERENCE)) + .andExpect(jsonPath("$.iban").value(DEFAULT_IBAN)) + .andExpect(jsonPath("$.bic").value(DEFAULT_BIC)) + .andExpect(jsonPath("$.grantingDocumentDate").value(DEFAULT_GRANTING_DOCUMENT_DATE.toString())) + .andExpect(jsonPath("$.revokationDocumentDate").value(DEFAULT_REVOKATION_DOCUMENT_DATE.toString())) + .andExpect(jsonPath("$.validFromDate").value(DEFAULT_VALID_FROM_DATE.toString())) + .andExpect(jsonPath("$.validUntilDate").value(DEFAULT_VALID_UNTIL_DATE.toString())) + .andExpect(jsonPath("$.lastUsedDate").value(DEFAULT_LAST_USED_DATE.toString())) + .andExpect(jsonPath("$.remark").value(DEFAULT_REMARK)); } @Test @@ -463,8 +472,10 @@ public class SepaMandateResourceIntTest { // Initialize the database sepaMandateRepository.saveAndFlush(sepaMandate); - // Get all the sepaMandateList where grantingDocumentDate in DEFAULT_GRANTING_DOCUMENT_DATE or UPDATED_GRANTING_DOCUMENT_DATE - defaultSepaMandateShouldBeFound("grantingDocumentDate.in=" + DEFAULT_GRANTING_DOCUMENT_DATE + "," + UPDATED_GRANTING_DOCUMENT_DATE); + // Get all the sepaMandateList where grantingDocumentDate in DEFAULT_GRANTING_DOCUMENT_DATE or + // UPDATED_GRANTING_DOCUMENT_DATE + defaultSepaMandateShouldBeFound( + "grantingDocumentDate.in=" + DEFAULT_GRANTING_DOCUMENT_DATE + "," + UPDATED_GRANTING_DOCUMENT_DATE); // Get all the sepaMandateList where grantingDocumentDate equals to UPDATED_GRANTING_DOCUMENT_DATE defaultSepaMandateShouldNotBeFound("grantingDocumentDate.in=" + UPDATED_GRANTING_DOCUMENT_DATE); @@ -509,7 +520,6 @@ public class SepaMandateResourceIntTest { defaultSepaMandateShouldBeFound("grantingDocumentDate.lessThan=" + UPDATED_GRANTING_DOCUMENT_DATE); } - @Test @Transactional public void getAllSepaMandatesByRevokationDocumentDateIsEqualToSomething() throws Exception { @@ -529,8 +539,10 @@ public class SepaMandateResourceIntTest { // Initialize the database sepaMandateRepository.saveAndFlush(sepaMandate); - // Get all the sepaMandateList where revokationDocumentDate in DEFAULT_REVOKATION_DOCUMENT_DATE or UPDATED_REVOKATION_DOCUMENT_DATE - defaultSepaMandateShouldBeFound("revokationDocumentDate.in=" + DEFAULT_REVOKATION_DOCUMENT_DATE + "," + UPDATED_REVOKATION_DOCUMENT_DATE); + // Get all the sepaMandateList where revokationDocumentDate in DEFAULT_REVOKATION_DOCUMENT_DATE or + // UPDATED_REVOKATION_DOCUMENT_DATE + defaultSepaMandateShouldBeFound( + "revokationDocumentDate.in=" + DEFAULT_REVOKATION_DOCUMENT_DATE + "," + UPDATED_REVOKATION_DOCUMENT_DATE); // Get all the sepaMandateList where revokationDocumentDate equals to UPDATED_REVOKATION_DOCUMENT_DATE defaultSepaMandateShouldNotBeFound("revokationDocumentDate.in=" + UPDATED_REVOKATION_DOCUMENT_DATE); @@ -575,7 +587,6 @@ public class SepaMandateResourceIntTest { defaultSepaMandateShouldBeFound("revokationDocumentDate.lessThan=" + UPDATED_REVOKATION_DOCUMENT_DATE); } - @Test @Transactional public void getAllSepaMandatesByValidFromDateIsEqualToSomething() throws Exception { @@ -641,7 +652,6 @@ public class SepaMandateResourceIntTest { defaultSepaMandateShouldBeFound("validFromDate.lessThan=" + UPDATED_VALID_FROM_DATE); } - @Test @Transactional public void getAllSepaMandatesByValidUntilDateIsEqualToSomething() throws Exception { @@ -707,7 +717,6 @@ public class SepaMandateResourceIntTest { defaultSepaMandateShouldBeFound("validUntilDate.lessThan=" + UPDATED_VALID_UNTIL_DATE); } - @Test @Transactional public void getAllSepaMandatesByLastUsedDateIsEqualToSomething() throws Exception { @@ -773,7 +782,6 @@ public class SepaMandateResourceIntTest { defaultSepaMandateShouldBeFound("lastUsedDate.lessThan=" + UPDATED_LAST_USED_DATE); } - @Test @Transactional public void getAllSepaMandatesByRemarkIsEqualToSomething() throws Exception { @@ -834,24 +842,24 @@ public class SepaMandateResourceIntTest { */ private void defaultSepaMandateShouldBeFound(String filter) throws Exception { restSepaMandateMockMvc.perform(get("/api/sepa-mandates?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].id").value(hasItem(sepaMandate.getId().intValue()))) - .andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE))) - .andExpect(jsonPath("$.[*].iban").value(hasItem(DEFAULT_IBAN))) - .andExpect(jsonPath("$.[*].bic").value(hasItem(DEFAULT_BIC))) - .andExpect(jsonPath("$.[*].grantingDocumentDate").value(hasItem(DEFAULT_GRANTING_DOCUMENT_DATE.toString()))) - .andExpect(jsonPath("$.[*].revokationDocumentDate").value(hasItem(DEFAULT_REVOKATION_DOCUMENT_DATE.toString()))) - .andExpect(jsonPath("$.[*].validFromDate").value(hasItem(DEFAULT_VALID_FROM_DATE.toString()))) - .andExpect(jsonPath("$.[*].validUntilDate").value(hasItem(DEFAULT_VALID_UNTIL_DATE.toString()))) - .andExpect(jsonPath("$.[*].lastUsedDate").value(hasItem(DEFAULT_LAST_USED_DATE.toString()))) - .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(sepaMandate.getId().intValue()))) + .andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE))) + .andExpect(jsonPath("$.[*].iban").value(hasItem(DEFAULT_IBAN))) + .andExpect(jsonPath("$.[*].bic").value(hasItem(DEFAULT_BIC))) + .andExpect(jsonPath("$.[*].grantingDocumentDate").value(hasItem(DEFAULT_GRANTING_DOCUMENT_DATE.toString()))) + .andExpect(jsonPath("$.[*].revokationDocumentDate").value(hasItem(DEFAULT_REVOKATION_DOCUMENT_DATE.toString()))) + .andExpect(jsonPath("$.[*].validFromDate").value(hasItem(DEFAULT_VALID_FROM_DATE.toString()))) + .andExpect(jsonPath("$.[*].validUntilDate").value(hasItem(DEFAULT_VALID_UNTIL_DATE.toString()))) + .andExpect(jsonPath("$.[*].lastUsedDate").value(hasItem(DEFAULT_LAST_USED_DATE.toString()))) + .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); // Check, that the count call also returns 1 restSepaMandateMockMvc.perform(get("/api/sepa-mandates/count?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(content().string("1")); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(content().string("1")); } /** @@ -859,25 +867,24 @@ public class SepaMandateResourceIntTest { */ private void defaultSepaMandateShouldNotBeFound(String filter) throws Exception { restSepaMandateMockMvc.perform(get("/api/sepa-mandates?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$").isArray()) - .andExpect(jsonPath("$").isEmpty()); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$").isArray()) + .andExpect(jsonPath("$").isEmpty()); // Check, that the count call also returns 0 restSepaMandateMockMvc.perform(get("/api/sepa-mandates/count?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(content().string("0")); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(content().string("0")); } - @Test @Transactional public void getNonExistingSepaMandate() throws Exception { // Get the sepaMandate restSepaMandateMockMvc.perform(get("/api/sepa-mandates/{id}", Long.MAX_VALUE)) - .andExpect(status().isNotFound()); + .andExpect(status().isNotFound()); } @Test @@ -893,16 +900,17 @@ public class SepaMandateResourceIntTest { // Disconnect from session so that the updates on updatedSepaMandate are not directly saved in db em.detach(updatedSepaMandate); updatedSepaMandate - .revokationDocumentDate(UPDATED_REVOKATION_DOCUMENT_DATE) - .validUntilDate(UPDATED_VALID_UNTIL_DATE) - .lastUsedDate(UPDATED_LAST_USED_DATE) - .remark(UPDATED_REMARK); + .revokationDocumentDate(UPDATED_REVOKATION_DOCUMENT_DATE) + .validUntilDate(UPDATED_VALID_UNTIL_DATE) + .lastUsedDate(UPDATED_LAST_USED_DATE) + .remark(UPDATED_REMARK); SepaMandateDTO sepaMandateDTO = sepaMandateMapper.toDto(updatedSepaMandate); - restSepaMandateMockMvc.perform(put("/api/sepa-mandates") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO))) - .andExpect(status().isOk()); + restSepaMandateMockMvc.perform( + put("/api/sepa-mandates") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO))) + .andExpect(status().isOk()); // Validate the SepaMandate in the database List sepaMandateList = sepaMandateRepository.findAll(); @@ -928,10 +936,11 @@ public class SepaMandateResourceIntTest { SepaMandateDTO sepaMandateDTO = sepaMandateMapper.toDto(sepaMandate); // If the entity doesn't have an ID, it will throw BadRequestAlertException - restSepaMandateMockMvc.perform(put("/api/sepa-mandates") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO))) - .andExpect(status().isBadRequest()); + restSepaMandateMockMvc.perform( + put("/api/sepa-mandates") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO))) + .andExpect(status().isBadRequest()); // Validate the SepaMandate in the database List sepaMandateList = sepaMandateRepository.findAll(); @@ -947,9 +956,10 @@ public class SepaMandateResourceIntTest { int databaseSizeBeforeDelete = sepaMandateRepository.findAll().size(); // Delete the sepaMandate - restSepaMandateMockMvc.perform(delete("/api/sepa-mandates/{id}", sepaMandate.getId()) - .accept(TestUtil.APPLICATION_JSON_UTF8)) - .andExpect(status().isOk()); + restSepaMandateMockMvc.perform( + delete("/api/sepa-mandates/{id}", sepaMandate.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isOk()); // Validate the database is empty List sepaMandateList = sepaMandateRepository.findAll(); diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/SepaMandateResourceUnitTest.java b/src/test/java/org/hostsharing/hsadminng/web/rest/SepaMandateResourceUnitTest.java index 6bf0d00e..d320486b 100644 --- a/src/test/java/org/hostsharing/hsadminng/web/rest/SepaMandateResourceUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/web/rest/SepaMandateResourceUnitTest.java @@ -1,17 +1,19 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.ThrowableAssert.catchThrowable; + import org.hostsharing.hsadminng.service.dto.SepaMandateDTO; import org.hostsharing.hsadminng.service.dto.SepaMandateDTOUnitTest; import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException; + import org.junit.Rule; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.assertj.core.api.ThrowableAssert.catchThrowable; - // Currently this class tests mostly special 'bad paths' // which make little sense to test in *ResourceIntTest. public class SepaMandateResourceUnitTest { diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/ShareResourceIntTest.java b/src/test/java/org/hostsharing/hsadminng/web/rest/ShareResourceIntTest.java index e4e99931..c5df9da4 100644 --- a/src/test/java/org/hostsharing/hsadminng/web/rest/ShareResourceIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/web/rest/ShareResourceIntTest.java @@ -1,5 +1,12 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.domain.Membership; import org.hostsharing.hsadminng.domain.Share; @@ -12,6 +19,7 @@ import org.hostsharing.hsadminng.service.accessfilter.Role; import org.hostsharing.hsadminng.service.dto.ShareDTO; import org.hostsharing.hsadminng.service.mapper.ShareMapper; import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,16 +35,11 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.Validator; -import javax.persistence.EntityManager; import java.time.LocalDate; import java.time.ZoneId; import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.hostsharing.hsadminng.web.rest.TestUtil.createFormattingConversionService; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import javax.persistence.EntityManager; /** * Test class for the ShareResource REST controller. @@ -101,11 +104,12 @@ public class ShareResourceIntTest { MockitoAnnotations.initMocks(this); final ShareResource shareResource = new ShareResource(shareService, shareQueryService); this.restShareMockMvc = MockMvcBuilders.standaloneSetup(shareResource) - .setCustomArgumentResolvers(pageableArgumentResolver) - .setControllerAdvice(exceptionTranslator) - .setConversionService(createFormattingConversionService()) - .setMessageConverters(jacksonMessageConverter) - .setValidator(validator).build(); + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setConversionService(createFormattingConversionService()) + .setMessageConverters(jacksonMessageConverter) + .setValidator(validator) + .build(); } /** @@ -116,11 +120,11 @@ public class ShareResourceIntTest { */ public static Share createEntity(EntityManager em) { Share share = new Share() - .documentDate(DEFAULT_DOCUMENT_DATE) - .valueDate(DEFAULT_VALUE_DATE) - .action(DEFAULT_ACTION) - .quantity(DEFAULT_QUANTITY) - .remark(DEFAULT_REMARK); + .documentDate(DEFAULT_DOCUMENT_DATE) + .valueDate(DEFAULT_VALUE_DATE) + .action(DEFAULT_ACTION) + .quantity(DEFAULT_QUANTITY) + .remark(DEFAULT_REMARK); // Add required entity Membership membership = MembershipResourceIntTest.createEntity(em); em.persist(membership); @@ -137,11 +141,11 @@ public class ShareResourceIntTest { */ public static Share createPersistentEntity(EntityManager em, final Membership membership) { Share share = new Share() - .documentDate(DEFAULT_DOCUMENT_DATE) - .valueDate(DEFAULT_VALUE_DATE) - .action(DEFAULT_ACTION) - .quantity(DEFAULT_QUANTITY) - .remark(DEFAULT_REMARK); + .documentDate(DEFAULT_DOCUMENT_DATE) + .valueDate(DEFAULT_VALUE_DATE) + .action(DEFAULT_ACTION) + .quantity(DEFAULT_QUANTITY) + .remark(DEFAULT_REMARK); // Add required entity share.setMembership(membership); membership.addShare(share); @@ -163,10 +167,11 @@ public class ShareResourceIntTest { // Create the Share ShareDTO shareDTO = shareMapper.toDto(share); shareDTO.setMembershipDisplayLabel(null); - restShareMockMvc.perform(post("/api/shares") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(shareDTO))) - .andExpect(status().isCreated()); + restShareMockMvc.perform( + post("/api/shares") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(shareDTO))) + .andExpect(status().isCreated()); // Validate the Share in the database List shareList = shareRepository.findAll(); @@ -189,10 +194,11 @@ public class ShareResourceIntTest { ShareDTO shareDTO = shareMapper.toDto(share); // An entity with an existing ID cannot be created, so this API call must fail - restShareMockMvc.perform(post("/api/shares") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(shareDTO))) - .andExpect(status().isBadRequest()); + restShareMockMvc.perform( + post("/api/shares") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(shareDTO))) + .andExpect(status().isBadRequest()); // Validate the Share in the database List shareList = shareRepository.findAll(); @@ -210,10 +216,11 @@ public class ShareResourceIntTest { ShareDTO shareDTO = shareMapper.toDto(share); // An entity with an existing ID cannot be created, so this API call must fail - restShareMockMvc.perform(post("/api/shares") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(shareDTO))) - .andExpect(status().isBadRequest()); + restShareMockMvc.perform( + post("/api/shares") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(shareDTO))) + .andExpect(status().isBadRequest()); // Validate the Share in the database List assetList = shareRepository.findAll(); @@ -230,10 +237,11 @@ public class ShareResourceIntTest { // Create the Share, which fails. ShareDTO shareDTO = shareMapper.toDto(share); - restShareMockMvc.perform(post("/api/shares") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(shareDTO))) - .andExpect(status().isBadRequest()); + restShareMockMvc.perform( + post("/api/shares") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(shareDTO))) + .andExpect(status().isBadRequest()); List shareList = shareRepository.findAll(); assertThat(shareList).hasSize(databaseSizeBeforeTest); @@ -249,10 +257,11 @@ public class ShareResourceIntTest { // Create the Share, which fails. ShareDTO shareDTO = shareMapper.toDto(share); - restShareMockMvc.perform(post("/api/shares") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(shareDTO))) - .andExpect(status().isBadRequest()); + restShareMockMvc.perform( + post("/api/shares") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(shareDTO))) + .andExpect(status().isBadRequest()); List shareList = shareRepository.findAll(); assertThat(shareList).hasSize(databaseSizeBeforeTest); @@ -268,10 +277,11 @@ public class ShareResourceIntTest { // Create the Share, which fails. ShareDTO shareDTO = shareMapper.toDto(share); - restShareMockMvc.perform(post("/api/shares") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(shareDTO))) - .andExpect(status().isBadRequest()); + restShareMockMvc.perform( + post("/api/shares") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(shareDTO))) + .andExpect(status().isBadRequest()); List shareList = shareRepository.findAll(); assertThat(shareList).hasSize(databaseSizeBeforeTest); @@ -287,10 +297,11 @@ public class ShareResourceIntTest { // Create the Share, which fails. ShareDTO shareDTO = shareMapper.toDto(share); - restShareMockMvc.perform(post("/api/shares") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(shareDTO))) - .andExpect(status().isBadRequest()); + restShareMockMvc.perform( + post("/api/shares") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(shareDTO))) + .andExpect(status().isBadRequest()); List shareList = shareRepository.findAll(); assertThat(shareList).hasSize(databaseSizeBeforeTest); @@ -304,14 +315,14 @@ public class ShareResourceIntTest { // Get all the shareList restShareMockMvc.perform(get("/api/shares?sort=id,desc")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].id").value(hasItem(share.getId().intValue()))) - .andExpect(jsonPath("$.[*].documentDate").value(hasItem(DEFAULT_DOCUMENT_DATE.toString()))) - .andExpect(jsonPath("$.[*].valueDate").value(hasItem(DEFAULT_VALUE_DATE.toString()))) - .andExpect(jsonPath("$.[*].action").value(hasItem(DEFAULT_ACTION.toString()))) - .andExpect(jsonPath("$.[*].quantity").value(hasItem(DEFAULT_QUANTITY))) - .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK.toString()))); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(share.getId().intValue()))) + .andExpect(jsonPath("$.[*].documentDate").value(hasItem(DEFAULT_DOCUMENT_DATE.toString()))) + .andExpect(jsonPath("$.[*].valueDate").value(hasItem(DEFAULT_VALUE_DATE.toString()))) + .andExpect(jsonPath("$.[*].action").value(hasItem(DEFAULT_ACTION.toString()))) + .andExpect(jsonPath("$.[*].quantity").value(hasItem(DEFAULT_QUANTITY))) + .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK.toString()))); } @Test @@ -322,14 +333,14 @@ public class ShareResourceIntTest { // Get the share restShareMockMvc.perform(get("/api/shares/{id}", share.getId())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.id").value(share.getId().intValue())) - .andExpect(jsonPath("$.documentDate").value(DEFAULT_DOCUMENT_DATE.toString())) - .andExpect(jsonPath("$.valueDate").value(DEFAULT_VALUE_DATE.toString())) - .andExpect(jsonPath("$.action").value(DEFAULT_ACTION.toString())) - .andExpect(jsonPath("$.quantity").value(DEFAULT_QUANTITY)) - .andExpect(jsonPath("$.remark").value(DEFAULT_REMARK.toString())); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.id").value(share.getId().intValue())) + .andExpect(jsonPath("$.documentDate").value(DEFAULT_DOCUMENT_DATE.toString())) + .andExpect(jsonPath("$.valueDate").value(DEFAULT_VALUE_DATE.toString())) + .andExpect(jsonPath("$.action").value(DEFAULT_ACTION.toString())) + .andExpect(jsonPath("$.quantity").value(DEFAULT_QUANTITY)) + .andExpect(jsonPath("$.remark").value(DEFAULT_REMARK.toString())); } @Test @@ -397,7 +408,6 @@ public class ShareResourceIntTest { defaultShareShouldBeFound("documentDate.lessThan=" + UPDATED_DOCUMENT_DATE); } - @Test @Transactional public void getAllSharesByValueDateIsEqualToSomething() throws Exception { @@ -463,7 +473,6 @@ public class ShareResourceIntTest { defaultShareShouldBeFound("valueDate.lessThan=" + UPDATED_VALUE_DATE); } - @Test @Transactional public void getAllSharesByActionIsEqualToSomething() throws Exception { @@ -568,7 +577,6 @@ public class ShareResourceIntTest { defaultShareShouldBeFound("quantity.lessThan=" + UPDATED_QUANTITY); } - @Test @Transactional public void getAllSharesByRemarkIsEqualToSomething() throws Exception { @@ -612,7 +620,8 @@ public class ShareResourceIntTest { @Transactional public void getAllSharesByMembershipIsEqualToSomething() throws Exception { // Initialize the database - Membership membership = MembershipResourceIntTest.createPersistentEntity(em, CustomerResourceIntTest.createPersistentEntity(em)); + Membership membership = MembershipResourceIntTest + .createPersistentEntity(em, CustomerResourceIntTest.createPersistentEntity(em)); share.setMembership(membership); shareRepository.saveAndFlush(share); Long membershipId = membership.getId(); @@ -629,20 +638,20 @@ public class ShareResourceIntTest { */ private void defaultShareShouldBeFound(String filter) throws Exception { restShareMockMvc.perform(get("/api/shares?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].id").value(hasItem(share.getId().intValue()))) - .andExpect(jsonPath("$.[*].documentDate").value(hasItem(DEFAULT_DOCUMENT_DATE.toString()))) - .andExpect(jsonPath("$.[*].valueDate").value(hasItem(DEFAULT_VALUE_DATE.toString()))) - .andExpect(jsonPath("$.[*].action").value(hasItem(DEFAULT_ACTION.toString()))) - .andExpect(jsonPath("$.[*].quantity").value(hasItem(DEFAULT_QUANTITY))) - .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].id").value(hasItem(share.getId().intValue()))) + .andExpect(jsonPath("$.[*].documentDate").value(hasItem(DEFAULT_DOCUMENT_DATE.toString()))) + .andExpect(jsonPath("$.[*].valueDate").value(hasItem(DEFAULT_VALUE_DATE.toString()))) + .andExpect(jsonPath("$.[*].action").value(hasItem(DEFAULT_ACTION.toString()))) + .andExpect(jsonPath("$.[*].quantity").value(hasItem(DEFAULT_QUANTITY))) + .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK))); // Check, that the count call also returns 1 restShareMockMvc.perform(get("/api/shares/count?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(content().string("1")); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(content().string("1")); } /** @@ -650,25 +659,24 @@ public class ShareResourceIntTest { */ private void defaultShareShouldNotBeFound(String filter) throws Exception { restShareMockMvc.perform(get("/api/shares?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$").isArray()) - .andExpect(jsonPath("$").isEmpty()); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$").isArray()) + .andExpect(jsonPath("$").isEmpty()); // Check, that the count call also returns 0 restShareMockMvc.perform(get("/api/shares/count?sort=id,desc&" + filter)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(content().string("0")); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(content().string("0")); } - @Test @Transactional public void getNonExistingShare() throws Exception { // Get the share restShareMockMvc.perform(get("/api/shares/{id}", Long.MAX_VALUE)) - .andExpect(status().isNotFound()); + .andExpect(status().isNotFound()); } @Test @@ -684,17 +692,18 @@ public class ShareResourceIntTest { // Disconnect from session so that the updates on updatedShare are not directly saved in db em.detach(updatedShare); updatedShare - .documentDate(UPDATED_DOCUMENT_DATE) - .valueDate(UPDATED_VALUE_DATE) - .action(UPDATED_ACTION) - .quantity(UPDATED_QUANTITY) - .remark(UPDATED_REMARK); + .documentDate(UPDATED_DOCUMENT_DATE) + .valueDate(UPDATED_VALUE_DATE) + .action(UPDATED_ACTION) + .quantity(UPDATED_QUANTITY) + .remark(UPDATED_REMARK); ShareDTO shareDTO = shareMapper.toDto(updatedShare); - restShareMockMvc.perform(put("/api/shares") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(shareDTO))) - .andExpect(status().isBadRequest()); + restShareMockMvc.perform( + put("/api/shares") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(shareDTO))) + .andExpect(status().isBadRequest()); // Validate the database is unchanged List shareList = shareRepository.findAll(); @@ -717,10 +726,11 @@ public class ShareResourceIntTest { ShareDTO shareDTO = shareMapper.toDto(share); // If the entity doesn't have an ID, it will throw BadRequestAlertException - restShareMockMvc.perform(put("/api/shares") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(shareDTO))) - .andExpect(status().isBadRequest()); + restShareMockMvc.perform( + put("/api/shares") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(shareDTO))) + .andExpect(status().isBadRequest()); // Validate the Share in the database List shareList = shareRepository.findAll(); @@ -736,9 +746,10 @@ public class ShareResourceIntTest { int databaseSizeBeforeDelete = shareRepository.findAll().size(); // Delete the share - restShareMockMvc.perform(delete("/api/shares/{id}", share.getId()) - .accept(TestUtil.APPLICATION_JSON_UTF8)) - .andExpect(status().isBadRequest()); + restShareMockMvc.perform( + delete("/api/shares/{id}", share.getId()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isBadRequest()); // Validate the database is unchanged List shareList = shareRepository.findAll(); diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/TestUtil.java b/src/test/java/org/hostsharing/hsadminng/web/rest/TestUtil.java index e69ca026..b4d22bed 100644 --- a/src/test/java/org/hostsharing/hsadminng/web/rest/TestUtil.java +++ b/src/test/java/org/hostsharing/hsadminng/web/rest/TestUtil.java @@ -1,8 +1,12 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; +import static org.assertj.core.api.Assertions.assertThat; + import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; + import org.hamcrest.Description; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; @@ -15,8 +19,6 @@ import java.nio.charset.StandardCharsets; import java.time.ZonedDateTime; import java.time.format.DateTimeParseException; -import static org.assertj.core.api.Assertions.assertThat; - /** * Utility class for testing REST controllers. */ @@ -27,8 +29,8 @@ public final class TestUtil { /** MediaType for JSON UTF8 */ public static final MediaType APPLICATION_JSON_UTF8 = new MediaType( MediaType.APPLICATION_JSON.getType(), - MediaType.APPLICATION_JSON.getSubtype(), StandardCharsets.UTF_8); - + MediaType.APPLICATION_JSON.getSubtype(), + StandardCharsets.UTF_8); private static ObjectMapper createObjectMapper() { ObjectMapper mapper = new ObjectMapper(); @@ -85,8 +87,9 @@ public final class TestUtil { } return true; } catch (DateTimeParseException e) { - mismatchDescription.appendText("was ").appendValue(item) - .appendText(", which could not be parsed as a ZonedDateTime"); + mismatchDescription.appendText("was ") + .appendValue(item) + .appendText(", which could not be parsed as a ZonedDateTime"); return false; } @@ -100,6 +103,7 @@ public final class TestUtil { /** * Creates a matcher that matches when the examined string reprensents the same instant as the reference datetime + * * @param date the reference datetime against which the examined string is checked */ public static ZonedDateTimeMatcher sameInstant(ZonedDateTime date) { @@ -127,15 +131,17 @@ public final class TestUtil { /** * Create a FormattingConversionService which use ISO date format, instead of the localized one. + * * @return the FormattingConversionService */ public static FormattingConversionService createFormattingConversionService() { - DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService (); + DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService(); DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); registrar.setUseIsoFormat(true); registrar.registerFormatters(dfcs); return dfcs; } - private TestUtil() {} + private TestUtil() { + } } diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/UserJWTControllerIntTest.java b/src/test/java/org/hostsharing/hsadminng/web/rest/UserJWTControllerIntTest.java index cb75fc99..43ea4434 100644 --- a/src/test/java/org/hostsharing/hsadminng/web/rest/UserJWTControllerIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/web/rest/UserJWTControllerIntTest.java @@ -1,11 +1,21 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; +import static org.hamcrest.Matchers.isEmptyString; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.domain.User; import org.hostsharing.hsadminng.repository.UserRepository; import org.hostsharing.hsadminng.security.jwt.TokenProvider; import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator; import org.hostsharing.hsadminng.web.rest.vm.LoginVM; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -18,14 +28,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.isEmptyString; -import static org.hamcrest.Matchers.not; - /** * Test class for the UserJWTController REST controller. * @@ -56,8 +58,8 @@ public class UserJWTControllerIntTest { public void setup() { UserJWTController userJWTController = new UserJWTController(tokenProvider, authenticationManager); this.mockMvc = MockMvcBuilders.standaloneSetup(userJWTController) - .setControllerAdvice(exceptionTranslator) - .build(); + .setControllerAdvice(exceptionTranslator) + .build(); } @Test @@ -74,14 +76,15 @@ public class UserJWTControllerIntTest { LoginVM login = new LoginVM(); login.setUsername("user-jwt-controller"); login.setPassword("test"); - mockMvc.perform(post("/api/authenticate") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(login))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.id_token").isString()) - .andExpect(jsonPath("$.id_token").isNotEmpty()) - .andExpect(header().string("Authorization", not(nullValue()))) - .andExpect(header().string("Authorization", not(isEmptyString()))); + mockMvc.perform( + post("/api/authenticate") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(login))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id_token").isString()) + .andExpect(jsonPath("$.id_token").isNotEmpty()) + .andExpect(header().string("Authorization", not(nullValue()))) + .andExpect(header().string("Authorization", not(isEmptyString()))); } @Test @@ -99,14 +102,15 @@ public class UserJWTControllerIntTest { login.setUsername("user-jwt-controller-remember-me"); login.setPassword("test"); login.setRememberMe(true); - mockMvc.perform(post("/api/authenticate") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(login))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.id_token").isString()) - .andExpect(jsonPath("$.id_token").isNotEmpty()) - .andExpect(header().string("Authorization", not(nullValue()))) - .andExpect(header().string("Authorization", not(isEmptyString()))); + mockMvc.perform( + post("/api/authenticate") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(login))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id_token").isString()) + .andExpect(jsonPath("$.id_token").isNotEmpty()) + .andExpect(header().string("Authorization", not(nullValue()))) + .andExpect(header().string("Authorization", not(isEmptyString()))); } @Test @@ -115,11 +119,12 @@ public class UserJWTControllerIntTest { LoginVM login = new LoginVM(); login.setUsername("wrong-user"); login.setPassword("wrong password"); - mockMvc.perform(post("/api/authenticate") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(login))) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.id_token").doesNotExist()) - .andExpect(header().doesNotExist("Authorization")); + mockMvc.perform( + post("/api/authenticate") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(login))) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.id_token").doesNotExist()) + .andExpect(header().doesNotExist("Authorization")); } } diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/UserResourceIntTest.java b/src/test/java/org/hostsharing/hsadminng/web/rest/UserResourceIntTest.java index 483ef082..07029e3a 100644 --- a/src/test/java/org/hostsharing/hsadminng/web/rest/UserResourceIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/web/rest/UserResourceIntTest.java @@ -1,5 +1,12 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasItems; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import org.hostsharing.hsadminng.HsadminNgApp; import org.hostsharing.hsadminng.domain.Authority; import org.hostsharing.hsadminng.domain.User; @@ -11,6 +18,7 @@ import org.hostsharing.hsadminng.service.dto.UserDTO; import org.hostsharing.hsadminng.service.mapper.UserMapper; import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator; import org.hostsharing.hsadminng.web.rest.vm.ManagedUserVM; + import org.apache.commons.lang3.RandomStringUtils; import org.junit.Before; import org.junit.Test; @@ -26,15 +34,10 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.EntityManager; import java.time.Instant; import java.util.*; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.hasItem; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import javax.persistence.EntityManager; /** * Test class for the UserResource REST controller. @@ -106,10 +109,10 @@ public class UserResourceIntTest { UserResource userResource = new UserResource(userService, userRepository, mailService); this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource) - .setCustomArgumentResolvers(pageableArgumentResolver) - .setControllerAdvice(exceptionTranslator) - .setMessageConverters(jacksonMessageConverter) - .build(); + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setMessageConverters(jacksonMessageConverter) + .build(); } /** @@ -155,10 +158,11 @@ public class UserResourceIntTest { managedUserVM.setLangKey(DEFAULT_LANGKEY); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - restUserMockMvc.perform(post("/api/users") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isCreated()); + restUserMockMvc.perform( + post("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isCreated()); // Validate the User in the database List userList = userRepository.findAll(); @@ -190,10 +194,11 @@ public class UserResourceIntTest { managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // An entity with an existing ID cannot be created, so this API call must fail - restUserMockMvc.perform(post("/api/users") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isBadRequest()); + restUserMockMvc.perform( + post("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); // Validate the User in the database List userList = userRepository.findAll(); @@ -219,10 +224,11 @@ public class UserResourceIntTest { managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Create the User - restUserMockMvc.perform(post("/api/users") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isBadRequest()); + restUserMockMvc.perform( + post("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); // Validate the User in the database List userList = userRepository.findAll(); @@ -248,10 +254,11 @@ public class UserResourceIntTest { managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Create the User - restUserMockMvc.perform(post("/api/users") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isBadRequest()); + restUserMockMvc.perform( + post("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); // Validate the User in the database List userList = userRepository.findAll(); @@ -265,16 +272,17 @@ public class UserResourceIntTest { userRepository.saveAndFlush(user); // Get all the users - restUserMockMvc.perform(get("/api/users?sort=id,desc") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN))) - .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME))) - .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME))) - .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL))) - .andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL))) - .andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY))); + restUserMockMvc.perform( + get("/api/users?sort=id,desc") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN))) + .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME))) + .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME))) + .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL))) + .andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL))) + .andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY))); } @Test @@ -287,14 +295,14 @@ public class UserResourceIntTest { // Get the user restUserMockMvc.perform(get("/api/users/{login}", user.getLogin())) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$.login").value(user.getLogin())) - .andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME)) - .andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME)) - .andExpect(jsonPath("$.email").value(DEFAULT_EMAIL)) - .andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL)) - .andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY)); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$.login").value(user.getLogin())) + .andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME)) + .andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME)) + .andExpect(jsonPath("$.email").value(DEFAULT_EMAIL)) + .andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL)) + .andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY)); assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNotNull(); } @@ -303,7 +311,7 @@ public class UserResourceIntTest { @Transactional public void getNonExistingUser() throws Exception { restUserMockMvc.perform(get("/api/users/unknown")) - .andExpect(status().isNotFound()); + .andExpect(status().isNotFound()); } @Test @@ -332,10 +340,11 @@ public class UserResourceIntTest { managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - restUserMockMvc.perform(put("/api/users") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isOk()); + restUserMockMvc.perform( + put("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isOk()); // Validate the User in the database List userList = userRepository.findAll(); @@ -374,10 +383,11 @@ public class UserResourceIntTest { managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - restUserMockMvc.perform(put("/api/users") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isOk()); + restUserMockMvc.perform( + put("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isOk()); // Validate the User in the database List userList = userRepository.findAll(); @@ -427,10 +437,11 @@ public class UserResourceIntTest { managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - restUserMockMvc.perform(put("/api/users") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isBadRequest()); + restUserMockMvc.perform( + put("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); } @Test @@ -469,10 +480,11 @@ public class UserResourceIntTest { managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - restUserMockMvc.perform(put("/api/users") - .contentType(TestUtil.APPLICATION_JSON_UTF8) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) - .andExpect(status().isBadRequest()); + restUserMockMvc.perform( + put("/api/users") + .contentType(TestUtil.APPLICATION_JSON_UTF8) + .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + .andExpect(status().isBadRequest()); } @Test @@ -483,9 +495,10 @@ public class UserResourceIntTest { int databaseSizeBeforeDelete = userRepository.findAll().size(); // Delete the user - restUserMockMvc.perform(delete("/api/users/{login}", user.getLogin()) - .accept(TestUtil.APPLICATION_JSON_UTF8)) - .andExpect(status().isOk()); + restUserMockMvc.perform( + delete("/api/users/{login}", user.getLogin()) + .accept(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isOk()); assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNull(); @@ -497,13 +510,14 @@ public class UserResourceIntTest { @Test @Transactional public void getAllAuthorities() throws Exception { - restUserMockMvc.perform(get("/api/users/authorities") - .accept(TestUtil.APPLICATION_JSON_UTF8) - .contentType(TestUtil.APPLICATION_JSON_UTF8)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) - .andExpect(jsonPath("$").isArray()) - .andExpect(jsonPath("$").value(hasItems(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN))); + restUserMockMvc.perform( + get("/api/users/authorities") + .accept(TestUtil.APPLICATION_JSON_UTF8) + .contentType(TestUtil.APPLICATION_JSON_UTF8)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(jsonPath("$").isArray()) + .andExpect(jsonPath("$").value(hasItems(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN))); } @Test diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/errors/ExceptionTranslatorIntTest.java b/src/test/java/org/hostsharing/hsadminng/web/rest/errors/ExceptionTranslatorIntTest.java index 37cac2fd..d99a9669 100644 --- a/src/test/java/org/hostsharing/hsadminng/web/rest/errors/ExceptionTranslatorIntTest.java +++ b/src/test/java/org/hostsharing/hsadminng/web/rest/errors/ExceptionTranslatorIntTest.java @@ -1,6 +1,14 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.errors; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.hostsharing.hsadminng.HsadminNgApp; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -12,12 +20,6 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - /** * Test class for the ExceptionTranslator controller advice. * @@ -41,110 +43,110 @@ public class ExceptionTranslatorIntTest { @Before public void setup() { mockMvc = MockMvcBuilders.standaloneSetup(controller) - .setControllerAdvice(exceptionTranslator) - .setMessageConverters(jacksonMessageConverter) - .build(); + .setControllerAdvice(exceptionTranslator) + .setMessageConverters(jacksonMessageConverter) + .build(); } @Test public void testConcurrencyFailure() throws Exception { mockMvc.perform(get("/test/concurrency-failure")) - .andExpect(status().isConflict()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE)); + .andExpect(status().isConflict()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE)); } @Test public void testMethodArgumentNotValid() throws Exception { - mockMvc.perform(post("/test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION)) - .andExpect(jsonPath("$.fieldErrors.[0].objectName").value("testDTO")) - .andExpect(jsonPath("$.fieldErrors.[0].field").value("test")) - .andExpect(jsonPath("$.fieldErrors.[0].message").value("NotNull")); + mockMvc.perform(post("/test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION)) + .andExpect(jsonPath("$.fieldErrors.[0].objectName").value("testDTO")) + .andExpect(jsonPath("$.fieldErrors.[0].field").value("test")) + .andExpect(jsonPath("$.fieldErrors.[0].message").value("NotNull")); } @Test public void testParameterizedError() throws Exception { mockMvc.perform(get("/test/parameterized-error")) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("test parameterized error")) - .andExpect(jsonPath("$.params.param0").value("param0_value")) - .andExpect(jsonPath("$.params.param1").value("param1_value")); + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("test parameterized error")) + .andExpect(jsonPath("$.params.param0").value("param0_value")) + .andExpect(jsonPath("$.params.param1").value("param1_value")); } @Test public void testParameterizedError2() throws Exception { mockMvc.perform(get("/test/parameterized-error2")) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("test parameterized error")) - .andExpect(jsonPath("$.params.foo").value("foo_value")) - .andExpect(jsonPath("$.params.bar").value("bar_value")); + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("test parameterized error")) + .andExpect(jsonPath("$.params.foo").value("foo_value")) + .andExpect(jsonPath("$.params.bar").value("bar_value")); } @Test public void testMissingServletRequestPartException() throws Exception { mockMvc.perform(get("/test/missing-servlet-request-part")) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.400")); + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")); } @Test public void testMissingServletRequestParameterException() throws Exception { mockMvc.perform(get("/test/missing-servlet-request-parameter")) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.400")); + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")); } @Test public void testAccessDenied() throws Exception { mockMvc.perform(get("/test/access-denied")) - .andExpect(status().isForbidden()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.403")) - .andExpect(jsonPath("$.detail").value("test access denied!")); + .andExpect(status().isForbidden()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.403")) + .andExpect(jsonPath("$.detail").value("test access denied!")); } @Test public void testUnauthorized() throws Exception { mockMvc.perform(get("/test/unauthorized")) - .andExpect(status().isUnauthorized()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.401")) - .andExpect(jsonPath("$.path").value("/test/unauthorized")) - .andExpect(jsonPath("$.detail").value("test authentication failed!")); + .andExpect(status().isUnauthorized()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.401")) + .andExpect(jsonPath("$.path").value("/test/unauthorized")) + .andExpect(jsonPath("$.detail").value("test authentication failed!")); } @Test public void testMethodNotSupported() throws Exception { mockMvc.perform(post("/test/access-denied")) - .andExpect(status().isMethodNotAllowed()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.405")) - .andExpect(jsonPath("$.detail").value("Request method 'POST' not supported")); + .andExpect(status().isMethodNotAllowed()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.405")) + .andExpect(jsonPath("$.detail").value("Request method 'POST' not supported")); } @Test public void testExceptionWithResponseStatus() throws Exception { mockMvc.perform(get("/test/response-status")) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.400")) - .andExpect(jsonPath("$.title").value("test response status")); + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.400")) + .andExpect(jsonPath("$.title").value("test response status")); } @Test public void testInternalServerError() throws Exception { mockMvc.perform(get("/test/internal-server-error")) - .andExpect(status().isInternalServerError()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value("error.http.500")) - .andExpect(jsonPath("$.title").value("Internal Server Error")); + .andExpect(status().isInternalServerError()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value("error.http.500")) + .andExpect(jsonPath("$.title").value("Internal Server Error")); } } diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/errors/ExceptionTranslatorTestController.java b/src/test/java/org/hostsharing/hsadminng/web/rest/errors/ExceptionTranslatorTestController.java index 9ec0b91c..4465a55a 100644 --- a/src/test/java/org/hostsharing/hsadminng/web/rest/errors/ExceptionTranslatorTestController.java +++ b/src/test/java/org/hostsharing/hsadminng/web/rest/errors/ExceptionTranslatorTestController.java @@ -1,3 +1,4 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.errors; import org.springframework.dao.ConcurrencyFailureException; @@ -6,11 +7,12 @@ import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.web.bind.annotation.*; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; import java.util.HashMap; import java.util.Map; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + @RestController public class ExceptionTranslatorTestController { diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/util/PaginationUtilUnitTest.java b/src/test/java/org/hostsharing/hsadminng/web/rest/util/PaginationUtilUnitTest.java index b824d35d..6cabf756 100644 --- a/src/test/java/org/hostsharing/hsadminng/web/rest/util/PaginationUtilUnitTest.java +++ b/src/test/java/org/hostsharing/hsadminng/web/rest/util/PaginationUtilUnitTest.java @@ -1,18 +1,19 @@ +// Licensed under Apache-2.0 package org.hostsharing.hsadminng.web.rest.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import java.util.ArrayList; -import java.util.List; - import org.junit.Test; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpHeaders; +import java.util.ArrayList; +import java.util.List; + /** * Tests based on parsing algorithm in app/components/util/pagination-util.service.js *