repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/security/package-info.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/security/package-info.java
/** * Application security utilities. */ package com.baeldung.jhipster8.security;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/security/SpringSecurityAuditorAware.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/security/SpringSecurityAuditorAware.java
package com.baeldung.jhipster8.security; import com.baeldung.jhipster8.config.Constants; import java.util.Optional; import org.springframework.data.domain.AuditorAware; import org.springframework.stereotype.Component; /** * Implementation of {@link AuditorAware} based on Spring Security. */ @Component public class SpringSecurityAuditorAware implements AuditorAware<String> { @Override public Optional<String> getCurrentAuditor() { return Optional.of(SecurityUtils.getCurrentUserLogin().orElse(Constants.SYSTEM)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/security/UserNotActivatedException.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/security/UserNotActivatedException.java
package com.baeldung.jhipster8.security; import org.springframework.security.core.AuthenticationException; /** * This exception is thrown in case of a not activated user trying to authenticate. */ public class UserNotActivatedException extends AuthenticationException { private static final long serialVersionUID = 1L; public UserNotActivatedException(String message) { super(message); } public UserNotActivatedException(String message, Throwable t) { super(message, t); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/security/SecurityUtils.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/security/SecurityUtils.java
package com.baeldung.jhipster8.security; import java.util.Arrays; import java.util.Optional; import java.util.stream.Stream; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.oauth2.jose.jws.MacAlgorithm; import org.springframework.security.oauth2.jwt.Jwt; /** * Utility class for Spring Security. */ public final class SecurityUtils { public static final MacAlgorithm JWT_ALGORITHM = MacAlgorithm.HS512; public static final String AUTHORITIES_KEY = "auth"; private SecurityUtils() {} /** * Get the login of the current user. * * @return the login of the current user. */ public static Optional<String> getCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(extractPrincipal(securityContext.getAuthentication())); } private static String extractPrincipal(Authentication authentication) { if (authentication == null) { return null; } else if (authentication.getPrincipal() instanceof UserDetails springSecurityUser) { return springSecurityUser.getUsername(); } else if (authentication.getPrincipal() instanceof Jwt jwt) { return jwt.getSubject(); } else if (authentication.getPrincipal() instanceof String s) { return s; } return null; } /** * Get the JWT of the current user. * * @return the JWT of the current user. */ public static Optional<String> getCurrentUserJWT() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .filter(authentication -> authentication.getCredentials() instanceof String) .map(authentication -> (String) authentication.getCredentials()); } /** * Check if a user is authenticated. * * @return true if the user is authenticated, false otherwise. */ public static boolean isAuthenticated() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return authentication != null && getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals); } /** * Checks if the current user has any of the authorities. * * @param authorities the authorities to check. * @return true if the current user has any of the authorities, false otherwise. */ public static boolean hasCurrentUserAnyOfAuthorities(String... authorities) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return ( authentication != null && getAuthorities(authentication).anyMatch(authority -> Arrays.asList(authorities).contains(authority)) ); } /** * Checks if the current user has none of the authorities. * * @param authorities the authorities to check. * @return true if the current user has none of the authorities, false otherwise. */ public static boolean hasCurrentUserNoneOfAuthorities(String... authorities) { return !hasCurrentUserAnyOfAuthorities(authorities); } /** * Checks if the current user has a specific authority. * * @param authority the authority to check. * @return true if the current user has the authority, false otherwise. */ public static boolean hasCurrentUserThisAuthority(String authority) { return hasCurrentUserAnyOfAuthorities(authority); } private static Stream<String> getAuthorities(Authentication authentication) { return authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/security/AuthoritiesConstants.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/security/AuthoritiesConstants.java
package com.baeldung.jhipster8.security; /** * Constants for Spring Security authorities. */ public final class AuthoritiesConstants { public static final String ADMIN = "ROLE_ADMIN"; public static final String USER = "ROLE_USER"; public static final String ANONYMOUS = "ROLE_ANONYMOUS"; private AuthoritiesConstants() {} }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/security/DomainUserDetailsService.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/security/DomainUserDetailsService.java
package com.baeldung.jhipster8.security; import com.baeldung.jhipster8.domain.Authority; import com.baeldung.jhipster8.domain.User; import com.baeldung.jhipster8.repository.UserRepository; import java.util.*; import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; /** * Authenticate a user from the database. */ @Component("userDetailsService") public class DomainUserDetailsService implements UserDetailsService { private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class); private final UserRepository userRepository; public DomainUserDetailsService(UserRepository userRepository) { this.userRepository = userRepository; } @Override @Transactional(readOnly = true) public UserDetails loadUserByUsername(final String login) { log.debug("Authenticating {}", login); if (new EmailValidator().isValid(login, null)) { return userRepository .findOneWithAuthoritiesByEmailIgnoreCase(login) .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")); } private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) { if (!user.isActivated()) { throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated"); } List<SimpleGrantedAuthority> grantedAuthorities = user .getAuthorities() .stream() .map(Authority::getName) .map(SimpleGrantedAuthority::new) .toList(); return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), grantedAuthorities); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/SecurityConfiguration.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/SecurityConfiguration.java
package com.baeldung.jhipster8.config; import static org.springframework.security.config.Customizer.withDefaults; import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; import com.baeldung.jhipster8.security.*; import com.baeldung.jhipster8.web.filter.SpaWebFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.env.Profiles; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer.FrameOptionsConfig; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint; import org.springframework.security.oauth2.server.resource.web.access.BearerTokenAccessDeniedHandler; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter; import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher; import org.springframework.web.servlet.handler.HandlerMappingIntrospector; import tech.jhipster.config.JHipsterConstants; import tech.jhipster.config.JHipsterProperties; @Configuration @EnableMethodSecurity(securedEnabled = true) public class SecurityConfiguration { private final Environment env; private final JHipsterProperties jHipsterProperties; public SecurityConfiguration(Environment env, JHipsterProperties jHipsterProperties) { this.env = env; this.jHipsterProperties = jHipsterProperties; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http, MvcRequestMatcher.Builder mvc) throws Exception { http .cors(withDefaults()) .csrf(csrf -> csrf.disable()) .addFilterAfter(new SpaWebFilter(), BasicAuthenticationFilter.class) .headers( headers -> headers .contentSecurityPolicy(csp -> csp.policyDirectives(jHipsterProperties.getSecurity().getContentSecurityPolicy())) .frameOptions(FrameOptionsConfig::sameOrigin) .referrerPolicy( referrer -> referrer.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN) ) .permissionsPolicy( permissions -> permissions.policy( "camera=(), fullscreen=(self), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), sync-xhr=()" ) ) ) .authorizeHttpRequests( authz -> // prettier-ignore authz .requestMatchers(mvc.pattern("/index.html"), mvc.pattern("/*.js"), mvc.pattern("/*.txt"), mvc.pattern("/*.json"), mvc.pattern("/*.map"), mvc.pattern("/*.css")).permitAll() .requestMatchers(mvc.pattern("/*.ico"), mvc.pattern("/*.png"), mvc.pattern("/*.svg"), mvc.pattern("/*.webapp")).permitAll() .requestMatchers(mvc.pattern("/app/**")).permitAll() .requestMatchers(mvc.pattern("/i18n/**")).permitAll() .requestMatchers(mvc.pattern("/content/**")).permitAll() .requestMatchers(mvc.pattern("/swagger-ui/**")).permitAll() .requestMatchers(mvc.pattern(HttpMethod.POST, "/api/authenticate")).permitAll() .requestMatchers(mvc.pattern(HttpMethod.GET, "/api/authenticate")).permitAll() .requestMatchers(mvc.pattern("/api/register")).permitAll() .requestMatchers(mvc.pattern("/api/activate")).permitAll() .requestMatchers(mvc.pattern("/api/account/reset-password/init")).permitAll() .requestMatchers(mvc.pattern("/api/account/reset-password/finish")).permitAll() .requestMatchers(mvc.pattern("/api/admin/**")).hasAuthority(AuthoritiesConstants.ADMIN) .requestMatchers(mvc.pattern("/api/**")).authenticated() .requestMatchers(mvc.pattern("/v3/api-docs/**")).hasAuthority(AuthoritiesConstants.ADMIN) .requestMatchers(mvc.pattern("/management/health")).permitAll() .requestMatchers(mvc.pattern("/management/health/**")).permitAll() .requestMatchers(mvc.pattern("/management/info")).permitAll() .requestMatchers(mvc.pattern("/management/prometheus")).permitAll() .requestMatchers(mvc.pattern("/management/**")).hasAuthority(AuthoritiesConstants.ADMIN) ) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .exceptionHandling( exceptions -> exceptions .authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint()) .accessDeniedHandler(new BearerTokenAccessDeniedHandler()) ) .oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults())); if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) { http.authorizeHttpRequests(authz -> authz.requestMatchers(antMatcher("/h2-console/**")).permitAll()); } return http.build(); } @Bean MvcRequestMatcher.Builder mvc(HandlerMappingIntrospector introspector) { return new MvcRequestMatcher.Builder(introspector); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/ApplicationProperties.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/ApplicationProperties.java
package com.baeldung.jhipster8.config; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Properties specific to Jhipster 8 Monolithic. * <p> * Properties are configured in the {@code application.yml} file. * See {@link tech.jhipster.config.JHipsterProperties} for a good example. */ @ConfigurationProperties(prefix = "application", ignoreUnknownFields = false) public class ApplicationProperties { private final Liquibase liquibase = new Liquibase(); // jhipster-needle-application-properties-property public Liquibase getLiquibase() { return liquibase; } // jhipster-needle-application-properties-property-getter public static class Liquibase { private Boolean asyncStart; public Boolean getAsyncStart() { return asyncStart; } public void setAsyncStart(Boolean asyncStart) { this.asyncStart = asyncStart; } } // jhipster-needle-application-properties-property-class }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/DatabaseConfiguration.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/DatabaseConfiguration.java
package com.baeldung.jhipster8.config; import java.sql.SQLException; 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; import org.springframework.transaction.annotation.EnableTransactionManagement; import tech.jhipster.config.JHipsterConstants; import tech.jhipster.config.h2.H2ConfigurationHelper; @Configuration @EnableJpaRepositories({ "com.baeldung.jhipster8.repository" }) @EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware") @EnableTransactionManagement public class DatabaseConfiguration { private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class); private final Environment env; public DatabaseConfiguration(Environment env) { this.env = env; } /** * Open the TCP port for the H2 database, so it is available remotely. * * @return the H2 database TCP server. * @throws SQLException if the server failed to start. */ @Bean(initMethod = "start", destroyMethod = "stop") @Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) public Object h2TCPServer() throws SQLException { String port = getValidPortForH2(); 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) { port = 10000 + port; } else { if (port < 63536) { port = port + 2000; } else { port = port - 2000; } } return String.valueOf(port); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/package-info.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/package-info.java
/** * Application configuration. */ package com.baeldung.jhipster8.config;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/DateTimeFormatConfiguration.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/DateTimeFormatConfiguration.java
package com.baeldung.jhipster8.config; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * Configure the converters to use the ISO format for dates by default. */ @Configuration public class DateTimeFormatConfiguration implements WebMvcConfigurer { @Override public void addFormatters(FormatterRegistry registry) { DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); registrar.setUseIsoFormat(true); registrar.registerFormatters(registry); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/CRLFLogConverter.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/CRLFLogConverter.java
package com.baeldung.jhipster8.config; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.pattern.CompositeConverter; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Marker; import org.slf4j.MarkerFactory; import org.springframework.boot.ansi.AnsiColor; import org.springframework.boot.ansi.AnsiElement; import org.springframework.boot.ansi.AnsiOutput; import org.springframework.boot.ansi.AnsiStyle; /** * Log filter to prevent attackers from forging log entries by submitting input containing CRLF characters. * CRLF characters are replaced with a red colored _ character. * * @see <a href="https://owasp.org/www-community/attacks/Log_Injection">Log Forging Description</a> * @see <a href="https://github.com/jhipster/generator-jhipster/issues/14949">JHipster issue</a> */ public class CRLFLogConverter extends CompositeConverter<ILoggingEvent> { public static final Marker CRLF_SAFE_MARKER = MarkerFactory.getMarker("CRLF_SAFE"); private static final String[] SAFE_LOGGERS = { "org.hibernate", "org.springframework.boot.autoconfigure", "org.springframework.boot.diagnostics", }; private static final Map<String, AnsiElement> ELEMENTS; static { Map<String, AnsiElement> ansiElements = new HashMap<>(); ansiElements.put("faint", AnsiStyle.FAINT); ansiElements.put("red", AnsiColor.RED); ansiElements.put("green", AnsiColor.GREEN); ansiElements.put("yellow", AnsiColor.YELLOW); ansiElements.put("blue", AnsiColor.BLUE); ansiElements.put("magenta", AnsiColor.MAGENTA); ansiElements.put("cyan", AnsiColor.CYAN); ELEMENTS = Collections.unmodifiableMap(ansiElements); } @Override protected String transform(ILoggingEvent event, String in) { AnsiElement element = ELEMENTS.get(getFirstOption()); List<Marker> markers = event.getMarkerList(); if ((markers != null && !markers.isEmpty() && markers.get(0).contains(CRLF_SAFE_MARKER)) || isLoggerSafe(event)) { return in; } String replacement = element == null ? "_" : toAnsiString("_", element); return in.replaceAll("[\n\r\t]", replacement); } protected boolean isLoggerSafe(ILoggingEvent event) { for (String safeLogger : SAFE_LOGGERS) { if (event.getLoggerName().startsWith(safeLogger)) { return true; } } return false; } protected String toAnsiString(String in, AnsiElement element) { return AnsiOutput.toString(element, in); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/AsyncConfiguration.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/AsyncConfiguration.java
package com.baeldung.jhipster8.config; import java.util.concurrent.Executor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; import org.springframework.boot.autoconfigure.task.TaskExecutionProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import tech.jhipster.async.ExceptionHandlingAsyncTaskExecutor; @Configuration @EnableAsync @EnableScheduling @Profile("!testdev & !testprod") public class AsyncConfiguration implements AsyncConfigurer { private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class); private final TaskExecutionProperties taskExecutionProperties; public AsyncConfiguration(TaskExecutionProperties taskExecutionProperties) { this.taskExecutionProperties = taskExecutionProperties; } @Override @Bean(name = "taskExecutor") public Executor getAsyncExecutor() { log.debug("Creating Async Task Executor"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(taskExecutionProperties.getPool().getCoreSize()); executor.setMaxPoolSize(taskExecutionProperties.getPool().getMaxSize()); executor.setQueueCapacity(taskExecutionProperties.getPool().getQueueCapacity()); executor.setThreadNamePrefix(taskExecutionProperties.getThreadNamePrefix()); return new ExceptionHandlingAsyncTaskExecutor(executor); } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new SimpleAsyncUncaughtExceptionHandler(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/WebConfigurer.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/WebConfigurer.java
package com.baeldung.jhipster8.config; import static java.net.URLDecoder.decode; import jakarta.servlet.*; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.web.server.*; import org.springframework.boot.web.servlet.ServletContextInitializer; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.env.Profiles; import org.springframework.util.CollectionUtils; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import tech.jhipster.config.JHipsterConstants; import tech.jhipster.config.JHipsterProperties; import tech.jhipster.config.h2.H2ConfigurationHelper; /** * Configuration of web application with Servlet 3.0 APIs. */ @Configuration public class WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { private final Logger log = LoggerFactory.getLogger(WebConfigurer.class); private final Environment env; private final JHipsterProperties jHipsterProperties; public WebConfigurer(Environment env, JHipsterProperties jHipsterProperties) { this.env = env; this.jHipsterProperties = jHipsterProperties; } @Override public void onStartup(ServletContext servletContext) { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) { initH2Console(servletContext); } log.info("Web application fully configured"); } /** * Customize the Servlet engine: Mime types, the document root, the cache. */ @Override public void customize(WebServerFactory server) { // When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets. setLocationForStaticAssets(server); } private void setLocationForStaticAssets(WebServerFactory server) { if (server instanceof ConfigurableServletWebServerFactory servletWebServer) { File root; String prefixPath = resolvePathPrefix(); root = new File(prefixPath + "target/classes/static/"); if (root.exists() && root.isDirectory()) { servletWebServer.setDocumentRoot(root); } } } /** * Resolve path prefix to static resources. */ private String resolvePathPrefix() { String fullExecutablePath = decode(this.getClass().getResource("").getPath(), StandardCharsets.UTF_8); String rootPath = Paths.get(".").toUri().normalize().getPath(); String extractedPath = fullExecutablePath.replace(rootPath, ""); int extractionEndIndex = extractedPath.indexOf("target/"); if (extractionEndIndex <= 0) { return ""; } return extractedPath.substring(0, extractionEndIndex); } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (!CollectionUtils.isEmpty(config.getAllowedOrigins()) || !CollectionUtils.isEmpty(config.getAllowedOriginPatterns())) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v3/api-docs", config); source.registerCorsConfiguration("/swagger-ui/**", config); } return new CorsFilter(source); } /** * Initializes H2 console. */ private void initH2Console(ServletContext servletContext) { log.debug("Initialize H2 console"); H2ConfigurationHelper.initH2Console(servletContext); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/JacksonConfiguration.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/JacksonConfiguration.java
package com.baeldung.jhipster8.config; import com.fasterxml.jackson.datatype.hibernate6.Hibernate6Module; import com.fasterxml.jackson.datatype.hibernate6.Hibernate6Module.Feature; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class JacksonConfiguration { /** * Support for Java date and time API. * @return the corresponding Jackson module. */ @Bean public JavaTimeModule javaTimeModule() { return new JavaTimeModule(); } @Bean public Jdk8Module jdk8TimeModule() { return new Jdk8Module(); } /* * Support for Hibernate types in Jackson. */ @Bean public Hibernate6Module hibernate6Module() { return new Hibernate6Module().configure(Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS, true); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/LoggingConfiguration.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/LoggingConfiguration.java
package com.baeldung.jhipster8.config; import static tech.jhipster.config.logging.LoggingUtils.*; import ch.qos.logback.classic.LoggerContext; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.HashMap; import java.util.Map; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import tech.jhipster.config.JHipsterProperties; /* * Configures the console and Logstash log appenders from the app properties */ @Configuration public class LoggingConfiguration { public LoggingConfiguration( @Value("${spring.application.name}") String appName, @Value("${server.port}") String serverPort, JHipsterProperties jHipsterProperties, ObjectMapper mapper ) throws JsonProcessingException { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); Map<String, String> map = new HashMap<>(); map.put("app_name", appName); map.put("app_port", serverPort); String customFields = mapper.writeValueAsString(map); JHipsterProperties.Logging loggingProperties = jHipsterProperties.getLogging(); JHipsterProperties.Logging.Logstash logstashProperties = loggingProperties.getLogstash(); if (loggingProperties.isUseJsonFormat()) { addJsonConsoleAppender(context, customFields); } if (logstashProperties.isEnabled()) { addLogstashTcpSocketAppender(context, customFields, logstashProperties); } if (loggingProperties.isUseJsonFormat() || logstashProperties.isEnabled()) { addContextListener(context, customFields, loggingProperties); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/SecurityJwtConfiguration.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/SecurityJwtConfiguration.java
package com.baeldung.jhipster8.config; import static com.baeldung.jhipster8.security.SecurityUtils.AUTHORITIES_KEY; import static com.baeldung.jhipster8.security.SecurityUtils.JWT_ALGORITHM; import com.baeldung.jhipster8.management.SecurityMetersService; import com.nimbusds.jose.jwk.source.ImmutableSecret; import com.nimbusds.jose.util.Base64; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtEncoder; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; import org.springframework.security.oauth2.jwt.NimbusJwtEncoder; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; @Configuration public class SecurityJwtConfiguration { private final Logger log = LoggerFactory.getLogger(SecurityJwtConfiguration.class); @Value("${jhipster.security.authentication.jwt.base64-secret}") private String jwtKey; @Bean public JwtDecoder jwtDecoder(SecurityMetersService metersService) { NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withSecretKey(getSecretKey()).macAlgorithm(JWT_ALGORITHM).build(); return token -> { try { return jwtDecoder.decode(token); } catch (Exception e) { if (e.getMessage().contains("Invalid signature")) { metersService.trackTokenInvalidSignature(); } else if (e.getMessage().contains("Jwt expired at")) { metersService.trackTokenExpired(); } else if ( e.getMessage().contains("Invalid JWT serialization") || e.getMessage().contains("Malformed token") || e.getMessage().contains("Invalid unsecured/JWS/JWE") ) { metersService.trackTokenMalformed(); } else { log.error("Unknown JWT error {}", e.getMessage()); } throw e; } }; } @Bean public JwtEncoder jwtEncoder() { return new NimbusJwtEncoder(new ImmutableSecret<>(getSecretKey())); } @Bean public JwtAuthenticationConverter jwtAuthenticationConverter() { JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); grantedAuthoritiesConverter.setAuthorityPrefix(""); grantedAuthoritiesConverter.setAuthoritiesClaimName(AUTHORITIES_KEY); JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter); return jwtAuthenticationConverter; } private SecretKey getSecretKey() { byte[] keyBytes = Base64.from(jwtKey).decode(); return new SecretKeySpec(keyBytes, 0, keyBytes.length, JWT_ALGORITHM.getName()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/LiquibaseConfiguration.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/LiquibaseConfiguration.java
package com.baeldung.jhipster8.config; import java.util.concurrent.Executor; import javax.sql.DataSource; import liquibase.integration.spring.SpringLiquibase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.autoconfigure.liquibase.LiquibaseDataSource; import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.env.Profiles; import tech.jhipster.config.JHipsterConstants; import tech.jhipster.config.liquibase.SpringLiquibaseUtil; @Configuration public class LiquibaseConfiguration { private final Logger log = LoggerFactory.getLogger(LiquibaseConfiguration.class); private final Environment env; public LiquibaseConfiguration(Environment env) { this.env = env; } @Value("${application.liquibase.async-start:true}") private Boolean asyncStart; @Bean public SpringLiquibase liquibase( @Qualifier("taskExecutor") Executor executor, LiquibaseProperties liquibaseProperties, @LiquibaseDataSource ObjectProvider<DataSource> liquibaseDataSource, ObjectProvider<DataSource> dataSource, DataSourceProperties dataSourceProperties ) { SpringLiquibase liquibase; if (Boolean.TRUE.equals(asyncStart)) { liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase( this.env, executor, liquibaseDataSource.getIfAvailable(), liquibaseProperties, dataSource.getIfUnique(), dataSourceProperties ); } else { liquibase = SpringLiquibaseUtil.createSpringLiquibase( liquibaseDataSource.getIfAvailable(), liquibaseProperties, dataSource.getIfUnique(), dataSourceProperties ); } liquibase.setChangeLog("classpath:config/liquibase/master.xml"); liquibase.setContexts(liquibaseProperties.getContexts()); liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema()); liquibase.setLiquibaseSchema(liquibaseProperties.getLiquibaseSchema()); liquibase.setLiquibaseTablespace(liquibaseProperties.getLiquibaseTablespace()); liquibase.setDatabaseChangeLogLockTable(liquibaseProperties.getDatabaseChangeLogLockTable()); liquibase.setDatabaseChangeLogTable(liquibaseProperties.getDatabaseChangeLogTable()); liquibase.setDropFirst(liquibaseProperties.isDropFirst()); liquibase.setLabelFilter(liquibaseProperties.getLabelFilter()); liquibase.setChangeLogParameters(liquibaseProperties.getParameters()); liquibase.setRollbackFile(liquibaseProperties.getRollbackFile()); liquibase.setTestRollbackOnUpdate(liquibaseProperties.isTestRollbackOnUpdate()); if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE))) { liquibase.setShouldRun(false); } else { liquibase.setShouldRun(liquibaseProperties.isEnabled()); log.debug("Configuring Liquibase"); } return liquibase; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/StaticResourcesWebConfiguration.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/StaticResourcesWebConfiguration.java
package com.baeldung.jhipster8.config; import java.util.concurrent.TimeUnit; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.http.CacheControl; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import tech.jhipster.config.JHipsterConstants; import tech.jhipster.config.JHipsterProperties; @Configuration @Profile({ JHipsterConstants.SPRING_PROFILE_PRODUCTION }) public class StaticResourcesWebConfiguration implements WebMvcConfigurer { protected static final String[] RESOURCE_LOCATIONS = { "classpath:/static/", "classpath:/static/content/", "classpath:/static/i18n/" }; protected static final String[] RESOURCE_PATHS = { "/*.js", "/*.css", "/*.svg", "/*.png", "*.ico", "/content/**", "/i18n/*" }; private final JHipsterProperties jhipsterProperties; public StaticResourcesWebConfiguration(JHipsterProperties jHipsterProperties) { this.jhipsterProperties = jHipsterProperties; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { ResourceHandlerRegistration resourceHandlerRegistration = appendResourceHandler(registry); initializeResourceHandler(resourceHandlerRegistration); } protected ResourceHandlerRegistration appendResourceHandler(ResourceHandlerRegistry registry) { return registry.addResourceHandler(RESOURCE_PATHS); } protected void initializeResourceHandler(ResourceHandlerRegistration resourceHandlerRegistration) { resourceHandlerRegistration.addResourceLocations(RESOURCE_LOCATIONS).setCacheControl(getCacheControl()); } protected CacheControl getCacheControl() { return CacheControl.maxAge(getJHipsterHttpCacheProperty(), TimeUnit.DAYS).cachePublic(); } private int getJHipsterHttpCacheProperty() { return jhipsterProperties.getHttp().getCache().getTimeToLiveInDays(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/Constants.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/Constants.java
package com.baeldung.jhipster8.config; /** * Application constants. */ public final class Constants { // Regex for acceptable logins public static final String LOGIN_REGEX = "^(?>[a-zA-Z0-9!$&*+=?^_`{|}~.-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*)|(?>[_.@A-Za-z0-9-]+)$"; public static final String SYSTEM = "system"; public static final String DEFAULT_LANGUAGE = "en"; private Constants() {} }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/LoggingAspectConfiguration.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/config/LoggingAspectConfiguration.java
package com.baeldung.jhipster8.config; import com.baeldung.jhipster8.aop.logging.LoggingAspect; import org.springframework.context.annotation.*; import org.springframework.core.env.Environment; import tech.jhipster.config.JHipsterConstants; @Configuration @EnableAspectJAutoProxy public class LoggingAspectConfiguration { @Bean @Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) public LoggingAspect loggingAspect(Environment env) { return new LoggingAspect(env); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/filter/SpaWebFilter.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/filter/SpaWebFilter.java
package com.baeldung.jhipster8.web.filter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import org.springframework.web.filter.OncePerRequestFilter; public class SpaWebFilter extends OncePerRequestFilter { /** * Forwards any unmapped paths (except those containing a period) to the client {@code index.html}. */ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // Request URI includes the contextPath if any, removed it. String path = request.getRequestURI().substring(request.getContextPath().length()); if ( !path.startsWith("/api") && !path.startsWith("/management") && !path.startsWith("/v3/api-docs") && !path.startsWith("/h2-console") && !path.contains(".") && path.matches("/(.*)") ) { request.getRequestDispatcher("/index.html").forward(request, response); return; } filterChain.doFilter(request, response); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/filter/package-info.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/filter/package-info.java
/** * Request chain filters. */ package com.baeldung.jhipster8.web.filter;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/AccountResource.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/AccountResource.java
package com.baeldung.jhipster8.web.rest; import com.baeldung.jhipster8.domain.User; import com.baeldung.jhipster8.repository.UserRepository; import com.baeldung.jhipster8.security.SecurityUtils; import com.baeldung.jhipster8.service.MailService; import com.baeldung.jhipster8.service.UserService; import com.baeldung.jhipster8.service.dto.AdminUserDTO; import com.baeldung.jhipster8.service.dto.PasswordChangeDTO; import com.baeldung.jhipster8.web.rest.errors.*; import com.baeldung.jhipster8.web.rest.vm.KeyAndPasswordVM; import com.baeldung.jhipster8.web.rest.vm.ManagedUserVM; import jakarta.validation.Valid; import java.util.*; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; /** * REST controller for managing the current user's account. */ @RestController @RequestMapping("/api") public class AccountResource { private static class AccountResourceException extends RuntimeException { private AccountResourceException(String message) { super(message); } } private final Logger log = LoggerFactory.getLogger(AccountResource.class); private final UserRepository userRepository; private final UserService userService; private final MailService mailService; public AccountResource(UserRepository userRepository, UserService userService, MailService mailService) { this.userRepository = userRepository; this.userService = userService; this.mailService = mailService; } /** * {@code POST /register} : register the user. * * @param managedUserVM the managed user View Model. * @throws InvalidPasswordException {@code 400 (Bad Request)} if the password is incorrect. * @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already used. * @throws LoginAlreadyUsedException {@code 400 (Bad Request)} if the login is already used. */ @PostMapping("/register") @ResponseStatus(HttpStatus.CREATED) public void registerAccount(@Valid @RequestBody ManagedUserVM managedUserVM) { if (isPasswordLengthInvalid(managedUserVM.getPassword())) { throw new InvalidPasswordException(); } User user = userService.registerUser(managedUserVM, managedUserVM.getPassword()); mailService.sendActivationEmail(user); } /** * {@code GET /activate} : activate the registered user. * * @param key the activation key. * @throws RuntimeException {@code 500 (Internal Server Error)} if the user couldn't be activated. */ @GetMapping("/activate") public void activateAccount(@RequestParam(value = "key") String key) { Optional<User> user = userService.activateRegistration(key); if (!user.isPresent()) { throw new AccountResourceException("No user was found for this activation key"); } } /** * {@code GET /account} : get the current user. * * @return the current user. * @throws RuntimeException {@code 500 (Internal Server Error)} if the user couldn't be returned. */ @GetMapping("/account") public AdminUserDTO getAccount() { return userService .getUserWithAuthorities() .map(AdminUserDTO::new) .orElseThrow(() -> new AccountResourceException("User could not be found")); } /** * {@code POST /account} : update the current user information. * * @param userDTO the current user information. * @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already used. * @throws RuntimeException {@code 500 (Internal Server Error)} if the user login wasn't found. */ @PostMapping("/account") public void saveAccount(@Valid @RequestBody AdminUserDTO userDTO) { String userLogin = SecurityUtils.getCurrentUserLogin() .orElseThrow(() -> new AccountResourceException("Current user login not found")); Optional<User> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); if (existingUser.isPresent() && (!existingUser.orElseThrow().getLogin().equalsIgnoreCase(userLogin))) { throw new EmailAlreadyUsedException(); } Optional<User> user = userRepository.findOneByLogin(userLogin); if (!user.isPresent()) { throw new AccountResourceException("User could not be found"); } userService.updateUser( userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), userDTO.getLangKey(), userDTO.getImageUrl() ); } /** * {@code POST /account/change-password} : changes the current user's password. * * @param passwordChangeDto current and new password. * @throws InvalidPasswordException {@code 400 (Bad Request)} if the new password is incorrect. */ @PostMapping(path = "/account/change-password") public void changePassword(@RequestBody PasswordChangeDTO passwordChangeDto) { if (isPasswordLengthInvalid(passwordChangeDto.getNewPassword())) { throw new InvalidPasswordException(); } userService.changePassword(passwordChangeDto.getCurrentPassword(), passwordChangeDto.getNewPassword()); } /** * {@code POST /account/reset-password/init} : Send an email to reset the password of the user. * * @param mail the mail of the user. */ @PostMapping(path = "/account/reset-password/init") public void requestPasswordReset(@RequestBody String mail) { Optional<User> user = userService.requestPasswordReset(mail); if (user.isPresent()) { mailService.sendPasswordResetMail(user.orElseThrow()); } else { // Pretend the request has been successful to prevent checking which emails really exist // but log that an invalid attempt has been made log.warn("Password reset requested for non existing mail"); } } /** * {@code POST /account/reset-password/finish} : Finish to reset the password of the user. * * @param keyAndPassword the generated key and the new password. * @throws InvalidPasswordException {@code 400 (Bad Request)} if the password is incorrect. * @throws RuntimeException {@code 500 (Internal Server Error)} if the password could not be reset. */ @PostMapping(path = "/account/reset-password/finish") public void finishPasswordReset(@RequestBody KeyAndPasswordVM keyAndPassword) { if (isPasswordLengthInvalid(keyAndPassword.getNewPassword())) { throw new InvalidPasswordException(); } Optional<User> user = userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey()); if (!user.isPresent()) { throw new AccountResourceException("No user was found for this reset key"); } } private static boolean isPasswordLengthInvalid(String password) { return ( StringUtils.isEmpty(password) || password.length() < ManagedUserVM.PASSWORD_MIN_LENGTH || password.length() > ManagedUserVM.PASSWORD_MAX_LENGTH ); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/AuthenticateController.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/AuthenticateController.java
package com.baeldung.jhipster8.web.rest; import static com.baeldung.jhipster8.security.SecurityUtils.AUTHORITIES_KEY; import static com.baeldung.jhipster8.security.SecurityUtils.JWT_ALGORITHM; import com.baeldung.jhipster8.web.rest.vm.LoginVM; import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.jwt.JwsHeader; import org.springframework.security.oauth2.jwt.JwtClaimsSet; import org.springframework.security.oauth2.jwt.JwtEncoder; import org.springframework.security.oauth2.jwt.JwtEncoderParameters; import org.springframework.web.bind.annotation.*; /** * Controller to authenticate users. */ @RestController @RequestMapping("/api") public class AuthenticateController { private final Logger log = LoggerFactory.getLogger(AuthenticateController.class); private final JwtEncoder jwtEncoder; @Value("${jhipster.security.authentication.jwt.token-validity-in-seconds:0}") private long tokenValidityInSeconds; @Value("${jhipster.security.authentication.jwt.token-validity-in-seconds-for-remember-me:0}") private long tokenValidityInSecondsForRememberMe; private final AuthenticationManagerBuilder authenticationManagerBuilder; public AuthenticateController(JwtEncoder jwtEncoder, AuthenticationManagerBuilder authenticationManagerBuilder) { this.jwtEncoder = jwtEncoder; this.authenticationManagerBuilder = authenticationManagerBuilder; } @PostMapping("/authenticate") public ResponseEntity<JWTToken> authorize(@Valid @RequestBody LoginVM loginVM) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( loginVM.getUsername(), loginVM.getPassword() ); Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = this.createToken(authentication, loginVM.isRememberMe()); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setBearerAuth(jwt); return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK); } /** * {@code 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. */ @GetMapping("/authenticate") public String isAuthenticated(HttpServletRequest request) { log.debug("REST request to check if the current user is authenticated"); return request.getRemoteUser(); } public String createToken(Authentication authentication, boolean rememberMe) { String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(" ")); Instant now = Instant.now(); Instant validity; if (rememberMe) { validity = now.plus(this.tokenValidityInSecondsForRememberMe, ChronoUnit.SECONDS); } else { validity = now.plus(this.tokenValidityInSeconds, ChronoUnit.SECONDS); } // @formatter:off JwtClaimsSet claims = JwtClaimsSet.builder() .issuedAt(now) .expiresAt(validity) .subject(authentication.getName()) .claim(AUTHORITIES_KEY, authorities) .build(); JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build(); return this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue(); } /** * Object to return as body in JWT Authentication. */ static class JWTToken { private String idToken; JWTToken(String idToken) { this.idToken = idToken; } @JsonProperty("id_token") String getIdToken() { return idToken; } void setIdToken(String idToken) { this.idToken = idToken; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/package-info.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/package-info.java
/** * Rest layer. */ package com.baeldung.jhipster8.web.rest;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/PublicUserResource.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/PublicUserResource.java
package com.baeldung.jhipster8.web.rest; import com.baeldung.jhipster8.service.UserService; import com.baeldung.jhipster8.service.dto.UserDTO; import java.util.*; import java.util.Collections; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import tech.jhipster.web.util.PaginationUtil; @RestController @RequestMapping("/api") public class PublicUserResource { private static final List<String> ALLOWED_ORDERED_PROPERTIES = Collections.unmodifiableList( Arrays.asList("id", "login", "firstName", "lastName", "email", "activated", "langKey") ); private final Logger log = LoggerFactory.getLogger(PublicUserResource.class); private final UserService userService; public PublicUserResource(UserService userService) { this.userService = userService; } /** * {@code GET /users} : get all users with only public information - calling this method is allowed for anyone. * * @param pageable the pagination information. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users. */ @GetMapping("/users") public ResponseEntity<List<UserDTO>> getAllPublicUsers(@org.springdoc.core.annotations.ParameterObject Pageable pageable) { log.debug("REST request to get all public User names"); if (!onlyContainsAllowedProperties(pageable)) { return ResponseEntity.badRequest().build(); } final Page<UserDTO> page = userService.getAllPublicUsers(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } private boolean onlyContainsAllowedProperties(Pageable pageable) { return pageable.getSort().stream().map(Sort.Order::getProperty).allMatch(ALLOWED_ORDERED_PROPERTIES::contains); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/UserResource.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/UserResource.java
package com.baeldung.jhipster8.web.rest; import com.baeldung.jhipster8.config.Constants; import com.baeldung.jhipster8.domain.User; import com.baeldung.jhipster8.repository.UserRepository; import com.baeldung.jhipster8.security.AuthoritiesConstants; import com.baeldung.jhipster8.service.MailService; import com.baeldung.jhipster8.service.UserService; import com.baeldung.jhipster8.service.dto.AdminUserDTO; import com.baeldung.jhipster8.web.rest.errors.BadRequestAlertException; import com.baeldung.jhipster8.web.rest.errors.EmailAlreadyUsedException; import com.baeldung.jhipster8.web.rest.errors.LoginAlreadyUsedException; import jakarta.validation.Valid; import jakarta.validation.constraints.Pattern; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import java.util.Collections; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import tech.jhipster.web.util.HeaderUtil; import tech.jhipster.web.util.PaginationUtil; import tech.jhipster.web.util.ResponseUtil; /** * REST controller for managing users. * <p> * This class accesses the {@link com.baeldung.jhipster8.domain.User} entity, and needs to fetch its collection of authorities. * <p> * For a normal use-case, it would be better to have an eager relationship between User and Authority, * and send everything to the client side: there would be no View Model and DTO, a lot less code, and an outer-join * which would be good for performance. * <p> * We use a View Model and a DTO for 3 reasons: * <ul> * <li>We want to keep a lazy association between the user and the authorities, because people will * 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.</li> * <li> 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).</li> * <li> As this manages users, for security reasons, we'd rather have a DTO layer.</li> * </ul> * <p> * Another option would be to have a specific JPA entity graph to handle this case. */ @RestController @RequestMapping("/api/admin") public class UserResource { private static final List<String> ALLOWED_ORDERED_PROPERTIES = Collections.unmodifiableList( Arrays.asList( "id", "login", "firstName", "lastName", "email", "activated", "langKey", "createdBy", "createdDate", "lastModifiedBy", "lastModifiedDate" ) ); private final Logger log = LoggerFactory.getLogger(UserResource.class); @Value("${jhipster.clientApp.name}") private String applicationName; private final UserService userService; private final UserRepository userRepository; private final MailService mailService; public UserResource(UserService userService, UserRepository userRepository, MailService mailService) { this.userService = userService; this.userRepository = userRepository; this.mailService = mailService; } /** * {@code POST /admin/users} : Creates a new user. * <p> * 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 {@link ResponseEntity} with status {@code 201 (Created)} and with body the new user, or with status {@code 400 (Bad Request)} if the login or email is already in use. * @throws URISyntaxException if the Location URI syntax is incorrect. * @throws BadRequestAlertException {@code 400 (Bad Request)} if the login or email is already in use. */ @PostMapping("/users") @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") public ResponseEntity<User> createUser(@Valid @RequestBody AdminUserDTO userDTO) throws URISyntaxException { log.debug("REST request to save User : {}", userDTO); if (userDTO.getId() != null) { throw new BadRequestAlertException("A new user cannot already have an ID", "userManagement", "idexists"); // Lowercase the user login before comparing with database } else if (userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).isPresent()) { throw new LoginAlreadyUsedException(); } else if (userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).isPresent()) { throw new EmailAlreadyUsedException(); } else { User newUser = userService.createUser(userDTO); mailService.sendCreationEmail(newUser); return ResponseEntity.created(new URI("/api/admin/users/" + newUser.getLogin())) .headers( HeaderUtil.createAlert(applicationName, "A user is created with identifier " + newUser.getLogin(), newUser.getLogin()) ) .body(newUser); } } /** * {@code PUT /admin/users} : Updates an existing User. * * @param userDTO the user to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated user. * @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already in use. * @throws LoginAlreadyUsedException {@code 400 (Bad Request)} if the login is already in use. */ @PutMapping({ "/users", "/users/{login}" }) @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") public ResponseEntity<AdminUserDTO> updateUser( @PathVariable(name = "login", required = false) @Pattern(regexp = Constants.LOGIN_REGEX) String login, @Valid @RequestBody AdminUserDTO userDTO ) { log.debug("REST request to update User : {}", userDTO); Optional<User> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); if (existingUser.isPresent() && (!existingUser.orElseThrow().getId().equals(userDTO.getId()))) { throw new EmailAlreadyUsedException(); } existingUser = userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()); if (existingUser.isPresent() && (!existingUser.orElseThrow().getId().equals(userDTO.getId()))) { throw new LoginAlreadyUsedException(); } Optional<AdminUserDTO> updatedUser = userService.updateUser(userDTO); return ResponseUtil.wrapOrNotFound( updatedUser, HeaderUtil.createAlert(applicationName, "A user is updated with identifier " + userDTO.getLogin(), userDTO.getLogin()) ); } /** * {@code GET /admin/users} : get all users with all the details - calling this are only allowed for the administrators. * * @param pageable the pagination information. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users. */ @GetMapping("/users") @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") public ResponseEntity<List<AdminUserDTO>> getAllUsers(@org.springdoc.core.annotations.ParameterObject Pageable pageable) { log.debug("REST request to get all User for an admin"); if (!onlyContainsAllowedProperties(pageable)) { return ResponseEntity.badRequest().build(); } final Page<AdminUserDTO> page = userService.getAllManagedUsers(pageable); HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page); return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK); } private boolean onlyContainsAllowedProperties(Pageable pageable) { return pageable.getSort().stream().map(Sort.Order::getProperty).allMatch(ALLOWED_ORDERED_PROPERTIES::contains); } /** * {@code GET /admin/users/:login} : get the "login" user. * * @param login the login of the user to find. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the "login" user, or with status {@code 404 (Not Found)}. */ @GetMapping("/users/{login}") @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") public ResponseEntity<AdminUserDTO> getUser(@PathVariable("login") @Pattern(regexp = Constants.LOGIN_REGEX) String login) { log.debug("REST request to get User : {}", login); return ResponseUtil.wrapOrNotFound(userService.getUserWithAuthoritiesByLogin(login).map(AdminUserDTO::new)); } /** * {@code DELETE /admin/users/:login} : delete the "login" User. * * @param login the login of the user to delete. * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/users/{login}") @PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")") public ResponseEntity<Void> deleteUser(@PathVariable("login") @Pattern(regexp = Constants.LOGIN_REGEX) String login) { log.debug("REST request to delete User: {}", login); userService.deleteUser(login); return ResponseEntity.noContent() .headers(HeaderUtil.createAlert(applicationName, "A user is deleted with identifier " + login, login)) .build(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/AuthorityResource.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/AuthorityResource.java
package com.baeldung.jhipster8.web.rest; import com.baeldung.jhipster8.domain.Authority; import com.baeldung.jhipster8.repository.AuthorityRepository; import com.baeldung.jhipster8.web.rest.errors.BadRequestAlertException; import jakarta.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import tech.jhipster.web.util.HeaderUtil; import tech.jhipster.web.util.ResponseUtil; /** * REST controller for managing {@link com.baeldung.jhipster8.domain.Authority}. */ @RestController @RequestMapping("/api/authorities") @Transactional public class AuthorityResource { private final Logger log = LoggerFactory.getLogger(AuthorityResource.class); private static final String ENTITY_NAME = "adminAuthority"; @Value("${jhipster.clientApp.name}") private String applicationName; private final AuthorityRepository authorityRepository; public AuthorityResource(AuthorityRepository authorityRepository) { this.authorityRepository = authorityRepository; } /** * {@code POST /authorities} : Create a new authority. * * @param authority the authority to create. * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new authority, or with status {@code 400 (Bad Request)} if the authority has already an ID. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PostMapping("") @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')") public ResponseEntity<Authority> createAuthority(@Valid @RequestBody Authority authority) throws URISyntaxException { log.debug("REST request to save Authority : {}", authority); if (authorityRepository.existsById(authority.getName())) { throw new BadRequestAlertException("authority already exists", ENTITY_NAME, "idexists"); } authority = authorityRepository.save(authority); return ResponseEntity.created(new URI("/api/authorities/" + authority.getName())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, authority.getName())) .body(authority); } /** * {@code GET /authorities} : get all the authorities. * * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of authorities in body. */ @GetMapping("") @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')") public List<Authority> getAllAuthorities() { log.debug("REST request to get all Authorities"); return authorityRepository.findAll(); } /** * {@code GET /authorities/:id} : get the "id" authority. * * @param id the id of the authority to retrieve. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the authority, or with status {@code 404 (Not Found)}. */ @GetMapping("/{id}") @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')") public ResponseEntity<Authority> getAuthority(@PathVariable("id") String id) { log.debug("REST request to get Authority : {}", id); Optional<Authority> authority = authorityRepository.findById(id); return ResponseUtil.wrapOrNotFound(authority); } /** * {@code DELETE /authorities/:id} : delete the "id" authority. * * @param id the id of the authority to delete. * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/{id}") @PreAuthorize("hasAnyAuthority('ROLE_ADMIN')") public ResponseEntity<Void> deleteAuthority(@PathVariable("id") String id) { log.debug("REST request to delete Authority : {}", id); authorityRepository.deleteById(id); return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id)).build(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/errors/InvalidPasswordException.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/errors/InvalidPasswordException.java
package com.baeldung.jhipster8.web.rest.errors; import org.springframework.http.HttpStatus; import org.springframework.web.ErrorResponseException; import tech.jhipster.web.rest.errors.ProblemDetailWithCause.ProblemDetailWithCauseBuilder; @SuppressWarnings("java:S110") // Inheritance tree of classes should not be too deep public class InvalidPasswordException extends ErrorResponseException { private static final long serialVersionUID = 1L; public InvalidPasswordException() { super( HttpStatus.BAD_REQUEST, ProblemDetailWithCauseBuilder.instance() .withStatus(HttpStatus.BAD_REQUEST.value()) .withType(ErrorConstants.INVALID_PASSWORD_TYPE) .withTitle("Incorrect password") .build(), null ); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/errors/package-info.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/errors/package-info.java
/** * Rest layer error handling. */ package com.baeldung.jhipster8.web.rest.errors;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/errors/LoginAlreadyUsedException.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/errors/LoginAlreadyUsedException.java
package com.baeldung.jhipster8.web.rest.errors; @SuppressWarnings("java:S110") // Inheritance tree of classes should not be too deep public class LoginAlreadyUsedException extends BadRequestAlertException { private static final long serialVersionUID = 1L; public LoginAlreadyUsedException() { super(ErrorConstants.LOGIN_ALREADY_USED_TYPE, "Login name already used!", "userManagement", "userexists"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/errors/ErrorConstants.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/errors/ErrorConstants.java
package com.baeldung.jhipster8.web.rest.errors; import java.net.URI; public final class ErrorConstants { public static final String ERR_CONCURRENCY_FAILURE = "error.concurrencyFailure"; public static final String ERR_VALIDATION = "error.validation"; public static final String PROBLEM_BASE_URL = "https://www.jhipster.tech/problem"; public static final URI DEFAULT_TYPE = URI.create(PROBLEM_BASE_URL + "/problem-with-message"); public static final URI CONSTRAINT_VIOLATION_TYPE = URI.create(PROBLEM_BASE_URL + "/constraint-violation"); public static final URI INVALID_PASSWORD_TYPE = URI.create(PROBLEM_BASE_URL + "/invalid-password"); public static final URI EMAIL_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/email-already-used"); public static final URI LOGIN_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/login-already-used"); private ErrorConstants() {} }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/errors/FieldErrorVM.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/errors/FieldErrorVM.java
package com.baeldung.jhipster8.web.rest.errors; import java.io.Serializable; public class FieldErrorVM implements Serializable { private static final long serialVersionUID = 1L; private final String objectName; private final String field; private final String message; public FieldErrorVM(String dto, String field, String message) { this.objectName = dto; this.field = field; this.message = message; } public String getObjectName() { return objectName; } public String getField() { return field; } public String getMessage() { return message; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/errors/EmailAlreadyUsedException.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/errors/EmailAlreadyUsedException.java
package com.baeldung.jhipster8.web.rest.errors; @SuppressWarnings("java:S110") // Inheritance tree of classes should not be too deep public class EmailAlreadyUsedException extends BadRequestAlertException { private static final long serialVersionUID = 1L; public EmailAlreadyUsedException() { super(ErrorConstants.EMAIL_ALREADY_USED_TYPE, "Email is already in use!", "userManagement", "emailexists"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/errors/BadRequestAlertException.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/errors/BadRequestAlertException.java
package com.baeldung.jhipster8.web.rest.errors; import java.net.URI; import org.springframework.http.HttpStatus; import org.springframework.web.ErrorResponseException; import tech.jhipster.web.rest.errors.ProblemDetailWithCause; import tech.jhipster.web.rest.errors.ProblemDetailWithCause.ProblemDetailWithCauseBuilder; @SuppressWarnings("java:S110") // Inheritance tree of classes should not be too deep public class BadRequestAlertException extends ErrorResponseException { private static final long serialVersionUID = 1L; private final String entityName; private final String errorKey; public BadRequestAlertException(String defaultMessage, String entityName, String errorKey) { this(ErrorConstants.DEFAULT_TYPE, defaultMessage, entityName, errorKey); } public BadRequestAlertException(URI type, String defaultMessage, String entityName, String errorKey) { super( HttpStatus.BAD_REQUEST, ProblemDetailWithCauseBuilder.instance() .withStatus(HttpStatus.BAD_REQUEST.value()) .withType(type) .withTitle(defaultMessage) .withProperty("message", "error." + errorKey) .withProperty("params", entityName) .build(), null ); this.entityName = entityName; this.errorKey = errorKey; } public String getEntityName() { return entityName; } public String getErrorKey() { return errorKey; } public ProblemDetailWithCause getProblemDetailWithCause() { return (ProblemDetailWithCause) this.getBody(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/errors/ExceptionTranslator.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/errors/ExceptionTranslator.java
package com.baeldung.jhipster8.web.rest.errors; import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation; import jakarta.servlet.http.HttpServletRequest; import java.net.URI; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.dao.DataAccessException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageConversionException; import org.springframework.lang.Nullable; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.web.ErrorResponse; import org.springframework.web.ErrorResponseException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import tech.jhipster.config.JHipsterConstants; import tech.jhipster.web.rest.errors.ProblemDetailWithCause; import tech.jhipster.web.rest.errors.ProblemDetailWithCause.ProblemDetailWithCauseBuilder; import tech.jhipster.web.util.HeaderUtil; /** * Controller advice to translate the server side exceptions to client-friendly json structures. * The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807). */ @ControllerAdvice public class ExceptionTranslator extends ResponseEntityExceptionHandler { private static final String FIELD_ERRORS_KEY = "fieldErrors"; private static final String MESSAGE_KEY = "message"; private static final String PATH_KEY = "path"; private static final boolean CASUAL_CHAIN_ENABLED = false; @Value("${jhipster.clientApp.name}") private String applicationName; private final Environment env; public ExceptionTranslator(Environment env) { this.env = env; } @ExceptionHandler public ResponseEntity<Object> handleAnyException(Throwable ex, NativeWebRequest request) { ProblemDetailWithCause pdCause = wrapAndCustomizeProblem(ex, request); return handleExceptionInternal((Exception) ex, pdCause, buildHeaders(ex), HttpStatusCode.valueOf(pdCause.getStatus()), request); } @Nullable @Override protected ResponseEntity<Object> handleExceptionInternal( Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatusCode statusCode, WebRequest request ) { body = body == null ? wrapAndCustomizeProblem((Throwable) ex, (NativeWebRequest) request) : body; return super.handleExceptionInternal(ex, body, headers, statusCode, request); } protected ProblemDetailWithCause wrapAndCustomizeProblem(Throwable ex, NativeWebRequest request) { return customizeProblem(getProblemDetailWithCause(ex), ex, request); } private ProblemDetailWithCause getProblemDetailWithCause(Throwable ex) { if ( ex instanceof com.baeldung.jhipster8.service.UsernameAlreadyUsedException ) return (ProblemDetailWithCause) new LoginAlreadyUsedException().getBody(); if ( ex instanceof com.baeldung.jhipster8.service.EmailAlreadyUsedException ) return (ProblemDetailWithCause) new EmailAlreadyUsedException().getBody(); if ( ex instanceof com.baeldung.jhipster8.service.InvalidPasswordException ) return (ProblemDetailWithCause) new InvalidPasswordException().getBody(); if ( ex instanceof ErrorResponseException exp && exp.getBody() instanceof ProblemDetailWithCause problemDetailWithCause ) return problemDetailWithCause; return ProblemDetailWithCauseBuilder.instance().withStatus(toStatus(ex).value()).build(); } protected ProblemDetailWithCause customizeProblem(ProblemDetailWithCause problem, Throwable err, NativeWebRequest request) { if (problem.getStatus() <= 0) problem.setStatus(toStatus(err)); if (problem.getType() == null || problem.getType().equals(URI.create("about:blank"))) problem.setType(getMappedType(err)); // higher precedence to Custom/ResponseStatus types String title = extractTitle(err, problem.getStatus()); String problemTitle = problem.getTitle(); if (problemTitle == null || !problemTitle.equals(title)) { problem.setTitle(title); } if (problem.getDetail() == null) { // higher precedence to cause problem.setDetail(getCustomizedErrorDetails(err)); } Map<String, Object> problemProperties = problem.getProperties(); if (problemProperties == null || !problemProperties.containsKey(MESSAGE_KEY)) problem.setProperty( MESSAGE_KEY, getMappedMessageKey(err) != null ? getMappedMessageKey(err) : "error.http." + problem.getStatus() ); if (problemProperties == null || !problemProperties.containsKey(PATH_KEY)) problem.setProperty(PATH_KEY, getPathValue(request)); if ( (err instanceof MethodArgumentNotValidException fieldException) && (problemProperties == null || !problemProperties.containsKey(FIELD_ERRORS_KEY)) ) problem.setProperty(FIELD_ERRORS_KEY, getFieldErrors(fieldException)); problem.setCause(buildCause(err.getCause(), request).orElse(null)); return problem; } private String extractTitle(Throwable err, int statusCode) { return getCustomizedTitle(err) != null ? getCustomizedTitle(err) : extractTitleForResponseStatus(err, statusCode); } private List<FieldErrorVM> getFieldErrors(MethodArgumentNotValidException ex) { return ex .getBindingResult() .getFieldErrors() .stream() .map( f -> new FieldErrorVM( f.getObjectName().replaceFirst("DTO$", ""), f.getField(), StringUtils.isNotBlank(f.getDefaultMessage()) ? f.getDefaultMessage() : f.getCode() ) ) .toList(); } private String extractTitleForResponseStatus(Throwable err, int statusCode) { ResponseStatus specialStatus = extractResponseStatus(err); return specialStatus == null ? HttpStatus.valueOf(statusCode).getReasonPhrase() : specialStatus.reason(); } private String extractURI(NativeWebRequest request) { HttpServletRequest nativeRequest = request.getNativeRequest(HttpServletRequest.class); return nativeRequest != null ? nativeRequest.getRequestURI() : StringUtils.EMPTY; } private HttpStatus toStatus(final Throwable throwable) { // Let the ErrorResponse take this responsibility if (throwable instanceof ErrorResponse err) return HttpStatus.valueOf(err.getBody().getStatus()); return Optional.ofNullable(getMappedStatus(throwable)).orElse( Optional.ofNullable(resolveResponseStatus(throwable)).map(ResponseStatus::value).orElse(HttpStatus.INTERNAL_SERVER_ERROR) ); } private ResponseStatus extractResponseStatus(final Throwable throwable) { return Optional.ofNullable(resolveResponseStatus(throwable)).orElse(null); } private ResponseStatus resolveResponseStatus(final Throwable type) { final ResponseStatus candidate = findMergedAnnotation(type.getClass(), ResponseStatus.class); return candidate == null && type.getCause() != null ? resolveResponseStatus(type.getCause()) : candidate; } private URI getMappedType(Throwable err) { if (err instanceof MethodArgumentNotValidException) return ErrorConstants.CONSTRAINT_VIOLATION_TYPE; return ErrorConstants.DEFAULT_TYPE; } private String getMappedMessageKey(Throwable err) { if (err instanceof MethodArgumentNotValidException) { return ErrorConstants.ERR_VALIDATION; } else if (err instanceof ConcurrencyFailureException || err.getCause() instanceof ConcurrencyFailureException) { return ErrorConstants.ERR_CONCURRENCY_FAILURE; } return null; } private String getCustomizedTitle(Throwable err) { if (err instanceof MethodArgumentNotValidException) return "Method argument not valid"; return null; } private String getCustomizedErrorDetails(Throwable err) { Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles()); if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { if (err instanceof HttpMessageConversionException) return "Unable to convert http message"; if (err instanceof DataAccessException) return "Failure during data access"; if (containsPackageName(err.getMessage())) return "Unexpected runtime exception"; } return err.getCause() != null ? err.getCause().getMessage() : err.getMessage(); } private HttpStatus getMappedStatus(Throwable err) { // Where we disagree with Spring defaults if (err instanceof AccessDeniedException) return HttpStatus.FORBIDDEN; if (err instanceof ConcurrencyFailureException) return HttpStatus.CONFLICT; if (err instanceof BadCredentialsException) return HttpStatus.UNAUTHORIZED; return null; } private URI getPathValue(NativeWebRequest request) { if (request == null) return URI.create("about:blank"); return URI.create(extractURI(request)); } private HttpHeaders buildHeaders(Throwable err) { return err instanceof BadRequestAlertException badRequestAlertException ? HeaderUtil.createFailureAlert( applicationName, true, badRequestAlertException.getEntityName(), badRequestAlertException.getErrorKey(), badRequestAlertException.getMessage() ) : null; } public Optional<ProblemDetailWithCause> buildCause(final Throwable throwable, NativeWebRequest request) { if (throwable != null && isCasualChainEnabled()) { return Optional.of(customizeProblem(getProblemDetailWithCause(throwable), throwable, request)); } return Optional.ofNullable(null); } private boolean isCasualChainEnabled() { // Customize as per the needs return CASUAL_CHAIN_ENABLED; } private boolean containsPackageName(String message) { // This list is for sure not complete return StringUtils.containsAny( message, "org.", "java.", "net.", "jakarta.", "javax.", "com.", "io.", "de.", "com.baeldung.jhipster8" ); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/vm/package-info.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/vm/package-info.java
/** * Rest layer visual models. */ package com.baeldung.jhipster8.web.rest.vm;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/vm/KeyAndPasswordVM.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/vm/KeyAndPasswordVM.java
package com.baeldung.jhipster8.web.rest.vm; /** * View Model object for storing the user's key and password. */ public class KeyAndPasswordVM { private String key; private String newPassword; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getNewPassword() { return newPassword; } public void setNewPassword(String newPassword) { this.newPassword = newPassword; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/vm/ManagedUserVM.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/vm/ManagedUserVM.java
package com.baeldung.jhipster8.web.rest.vm; import com.baeldung.jhipster8.service.dto.AdminUserDTO; import jakarta.validation.constraints.Size; /** * View Model extending the AdminUserDTO, which is meant to be used in the user management UI. */ public class ManagedUserVM extends AdminUserDTO { public static final int PASSWORD_MIN_LENGTH = 4; public static final int PASSWORD_MAX_LENGTH = 100; @Size(min = PASSWORD_MIN_LENGTH, max = PASSWORD_MAX_LENGTH) private String password; public ManagedUserVM() { // Empty constructor needed for Jackson. } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } // prettier-ignore @Override public String toString() { return "ManagedUserVM{" + super.toString() + "} "; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/vm/LoginVM.java
jhipster-8-modules/jhipster-8-monolithic/src/main/java/com/baeldung/jhipster8/web/rest/vm/LoginVM.java
package com.baeldung.jhipster8.web.rest.vm; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; /** * View Model object for storing a user's credentials. */ public class LoginVM { @NotNull @Size(min = 1, max = 50) private String username; @NotNull @Size(min = 4, max = 100) private String password; private boolean rememberMe; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isRememberMe() { return rememberMe; } public void setRememberMe(boolean rememberMe) { this.rememberMe = rememberMe; } // prettier-ignore @Override public String toString() { return "LoginVM{" + "username='" + username + '\'' + ", rememberMe=" + rememberMe + '}'; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/IntegrationTest.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/IntegrationTest.java
package com.cars.app; import com.cars.app.config.AsyncSyncConfiguration; import com.cars.app.config.EmbeddedSQL; import com.cars.app.config.JacksonConfiguration; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.boot.test.context.SpringBootTest; /** * Base composite annotation for integration tests. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @SpringBootTest(classes = { CarsappApp.class, JacksonConfiguration.class, AsyncSyncConfiguration.class }) @EmbeddedSQL public @interface IntegrationTest { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/TechnicalStructureTest.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/TechnicalStructureTest.java
package com.cars.app; import static com.tngtech.archunit.base.DescribedPredicate.alwaysTrue; import static com.tngtech.archunit.core.domain.JavaClass.Predicates.belongToAnyOf; import static com.tngtech.archunit.library.Architectures.layeredArchitecture; import com.tngtech.archunit.core.importer.ImportOption.DoNotIncludeTests; import com.tngtech.archunit.junit.AnalyzeClasses; import com.tngtech.archunit.junit.ArchTest; import com.tngtech.archunit.lang.ArchRule; @AnalyzeClasses(packagesOf = CarsappApp.class, importOptions = DoNotIncludeTests.class) class TechnicalStructureTest { // prettier-ignore @ArchTest static final ArchRule respectsTechnicalArchitectureLayers = layeredArchitecture() .consideringAllDependencies() .layer("Config").definedBy("..config..") .layer("Web").definedBy("..web..") .optionalLayer("Service").definedBy("..service..") .layer("Security").definedBy("..security..") .optionalLayer("Persistence").definedBy("..repository..") .layer("Domain").definedBy("..domain..") .whereLayer("Config").mayNotBeAccessedByAnyLayer() .whereLayer("Web").mayOnlyBeAccessedByLayers("Config") .whereLayer("Service").mayOnlyBeAccessedByLayers("Web", "Config") .whereLayer("Security").mayOnlyBeAccessedByLayers("Config", "Service", "Web") .whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service", "Security", "Web", "Config") .whereLayer("Domain").mayOnlyBeAccessedByLayers("Persistence", "Service", "Security", "Web", "Config") .ignoreDependency(belongToAnyOf(CarsappApp.class), alwaysTrue()) .ignoreDependency(alwaysTrue(), belongToAnyOf( com.cars.app.config.Constants.class, com.cars.app.config.ApplicationProperties.class )); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/management/SecurityMetersServiceTests.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/management/SecurityMetersServiceTests.java
package com.cars.app.management; import static org.assertj.core.api.Assertions.assertThat; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.Collection; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class SecurityMetersServiceTests { private static final String INVALID_TOKENS_METER_EXPECTED_NAME = "security.authentication.invalid-tokens"; private MeterRegistry meterRegistry; private SecurityMetersService securityMetersService; @BeforeEach public void setup() { meterRegistry = new SimpleMeterRegistry(); securityMetersService = new SecurityMetersService(meterRegistry); } @Test void testInvalidTokensCountersByCauseAreCreated() { meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).counter(); meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter(); meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "unsupported").counter(); meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter(); meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter(); Collection<Counter> counters = meterRegistry.find(INVALID_TOKENS_METER_EXPECTED_NAME).counters(); assertThat(counters).hasSize(4); } @Test void testCountMethodsShouldBeBoundToCorrectCounters() { assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count()).isZero(); securityMetersService.trackTokenExpired(); assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count()).isEqualTo(1); assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "unsupported").counter().count()).isZero(); securityMetersService.trackTokenUnsupported(); assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "unsupported").counter().count()).isEqualTo(1); assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count()).isZero(); securityMetersService.trackTokenInvalidSignature(); assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count()).isEqualTo(1); assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isZero(); securityMetersService.trackTokenMalformed(); assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isEqualTo(1); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/domain/CarAsserts.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/domain/CarAsserts.java
package com.cars.app.domain; import static org.assertj.core.api.Assertions.assertThat; public class CarAsserts { /** * Asserts that the entity has all properties (fields/relationships) set. * * @param expected the expected entity * @param actual the actual entity */ public static void assertCarAllPropertiesEquals(Car expected, Car actual) { assertCarAutoGeneratedPropertiesEquals(expected, actual); assertCarAllUpdatablePropertiesEquals(expected, actual); } /** * Asserts that the entity has all updatable properties (fields/relationships) set. * * @param expected the expected entity * @param actual the actual entity */ public static void assertCarAllUpdatablePropertiesEquals(Car expected, Car actual) { assertCarUpdatableFieldsEquals(expected, actual); assertCarUpdatableRelationshipsEquals(expected, actual); } /** * Asserts that the entity has all the auto generated properties (fields/relationships) set. * * @param expected the expected entity * @param actual the actual entity */ public static void assertCarAutoGeneratedPropertiesEquals(Car expected, Car actual) { assertThat(expected) .as("Verify Car auto generated properties") .satisfies(e -> assertThat(e.getId()).as("check id").isEqualTo(actual.getId())); } /** * Asserts that the entity has all the updatable fields set. * * @param expected the expected entity * @param actual the actual entity */ public static void assertCarUpdatableFieldsEquals(Car expected, Car actual) { assertThat(expected) .as("Verify Car relevant properties") .satisfies(e -> assertThat(e.getPrice()).as("check price").isEqualTo(actual.getPrice())); } /** * Asserts that the entity has all the updatable relationships set. * * @param expected the expected entity * @param actual the actual entity */ public static void assertCarUpdatableRelationshipsEquals(Car expected, Car actual) {} }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/domain/AssertUtils.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/domain/AssertUtils.java
package com.cars.app.domain; import java.math.BigDecimal; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.Comparator; public class AssertUtils { public static Comparator<ZonedDateTime> zonedDataTimeSameInstant = Comparator.nullsFirst( (e1, a2) -> e1.withZoneSameInstant(ZoneOffset.UTC).compareTo(a2.withZoneSameInstant(ZoneOffset.UTC)) ); public static Comparator<BigDecimal> bigDecimalCompareTo = Comparator.nullsFirst((e1, a2) -> e1.compareTo(a2)); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/domain/CarTest.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/domain/CarTest.java
package com.cars.app.domain; import static com.cars.app.domain.CarTestSamples.*; import static org.assertj.core.api.Assertions.assertThat; import com.cars.app.web.rest.TestUtil; import org.junit.jupiter.api.Test; class CarTest { @Test void equalsVerifier() throws Exception { TestUtil.equalsVerifier(Car.class); Car car1 = getCarSample1(); Car car2 = new Car(); assertThat(car1).isNotEqualTo(car2); car2.setId(car1.getId()); assertThat(car1).isEqualTo(car2); car2 = getCarSample2(); assertThat(car1).isNotEqualTo(car2); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/domain/CarTestSamples.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/domain/CarTestSamples.java
package com.cars.app.domain; import java.util.Random; import java.util.concurrent.atomic.AtomicLong; public class CarTestSamples { private static final Random random = new Random(); private static final AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); public static Car getCarSample1() { return new Car().id(1L); } public static Car getCarSample2() { return new Car().id(2L); } public static Car getCarRandomSampleGenerator() { return new Car().id(longCount.incrementAndGet()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/repository/timezone/DateTimeWrapper.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/repository/timezone/DateTimeWrapper.java
package com.cars.app.repository.timezone; import jakarta.persistence.*; import java.io.Serializable; import java.time.*; import java.util.Objects; @Entity @Table(name = "jhi_date_time_wrapper") public class DateTimeWrapper implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") @SequenceGenerator(name = "sequenceGenerator") private Long id; @Column(name = "instant") private Instant instant; @Column(name = "local_date_time") private LocalDateTime localDateTime; @Column(name = "offset_date_time") private OffsetDateTime offsetDateTime; @Column(name = "zoned_date_time") private ZonedDateTime zonedDateTime; @Column(name = "local_time") private LocalTime localTime; @Column(name = "offset_time") private OffsetTime offsetTime; @Column(name = "local_date") private LocalDate localDate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Instant getInstant() { return instant; } public void setInstant(Instant instant) { this.instant = instant; } public LocalDateTime getLocalDateTime() { return localDateTime; } public void setLocalDateTime(LocalDateTime localDateTime) { this.localDateTime = localDateTime; } public OffsetDateTime getOffsetDateTime() { return offsetDateTime; } public void setOffsetDateTime(OffsetDateTime offsetDateTime) { this.offsetDateTime = offsetDateTime; } public ZonedDateTime getZonedDateTime() { return zonedDateTime; } public void setZonedDateTime(ZonedDateTime zonedDateTime) { this.zonedDateTime = zonedDateTime; } public LocalTime getLocalTime() { return localTime; } public void setLocalTime(LocalTime localTime) { this.localTime = localTime; } public OffsetTime getOffsetTime() { return offsetTime; } public void setOffsetTime(OffsetTime offsetTime) { this.offsetTime = offsetTime; } public LocalDate getLocalDate() { return localDate; } public void setLocalDate(LocalDate localDate) { this.localDate = localDate; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DateTimeWrapper dateTimeWrapper = (DateTimeWrapper) o; return !(dateTimeWrapper.getId() == null || getId() == null) && Objects.equals(getId(), dateTimeWrapper.getId()); } @Override public int hashCode() { return Objects.hashCode(getId()); } // prettier-ignore @Override public String toString() { return "TimeZoneTest{" + "id=" + id + ", instant=" + instant + ", localDateTime=" + localDateTime + ", offsetDateTime=" + offsetDateTime + ", zonedDateTime=" + zonedDateTime + '}'; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/repository/timezone/DateTimeWrapperRepository.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/repository/timezone/DateTimeWrapperRepository.java
package com.cars.app.repository.timezone; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * Spring Data JPA repository for the {@link DateTimeWrapper} entity. */ @Repository public interface DateTimeWrapperRepository extends JpaRepository<DateTimeWrapper, Long> {}
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/security/SecurityUtilsUnitTest.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/security/SecurityUtilsUnitTest.java
package com.cars.app.security; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Collection; import java.util.Optional; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; /** * Test class for the {@link SecurityUtils} utility class. */ class SecurityUtilsUnitTest { @BeforeEach @AfterEach void cleanup() { SecurityContextHolder.clearContext(); } @Test void testGetCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); SecurityContextHolder.setContext(securityContext); Optional<String> login = SecurityUtils.getCurrentUserLogin(); assertThat(login).contains("admin"); } @Test void testGetCurrentUserJWT() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "token")); SecurityContextHolder.setContext(securityContext); Optional<String> jwt = SecurityUtils.getCurrentUserJWT(); assertThat(jwt).contains("token"); } @Test void testIsAuthenticated() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); SecurityContextHolder.setContext(securityContext); boolean isAuthenticated = SecurityUtils.isAuthenticated(); assertThat(isAuthenticated).isTrue(); } @Test void testAnonymousIsNotAuthenticated() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities)); SecurityContextHolder.setContext(securityContext); boolean isAuthenticated = SecurityUtils.isAuthenticated(); assertThat(isAuthenticated).isFalse(); } @Test void testHasCurrentUserThisAuthority() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("user", "user", authorities)); SecurityContextHolder.setContext(securityContext); assertThat(SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.USER)).isTrue(); assertThat(SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN)).isFalse(); } @Test void testHasCurrentUserAnyOfAuthorities() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("user", "user", authorities)); SecurityContextHolder.setContext(securityContext); assertThat(SecurityUtils.hasCurrentUserAnyOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN)).isTrue(); assertThat(SecurityUtils.hasCurrentUserAnyOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN)).isFalse(); } @Test void testHasCurrentUserNoneOfAuthorities() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER)); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("user", "user", authorities)); SecurityContextHolder.setContext(securityContext); assertThat(SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN)).isFalse(); assertThat(SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN)).isTrue(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/security/jwt/TestAuthenticationResource.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/security/jwt/TestAuthenticationResource.java
package com.cars.app.security.jwt; import org.springframework.web.bind.annotation.*; /** * REST controller for managing testing authentication token. */ @RestController @RequestMapping("/api") public class TestAuthenticationResource { /** * {@code GET /authenticate} : check if the authentication token correctly validates * * @return ok. */ @GetMapping("/authenticate") public String isAuthenticated() { return "ok"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/security/jwt/AuthenticationIntegrationTest.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/security/jwt/AuthenticationIntegrationTest.java
package com.cars.app.security.jwt; import com.cars.app.config.SecurityConfiguration; import com.cars.app.config.SecurityJwtConfiguration; import com.cars.app.config.WebConfigurer; import com.cars.app.management.SecurityMetersService; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.boot.test.context.SpringBootTest; import tech.jhipster.config.JHipsterProperties; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @SpringBootTest( classes = { JHipsterProperties.class, WebConfigurer.class, SecurityConfiguration.class, SecurityJwtConfiguration.class, SecurityMetersService.class, JwtAuthenticationTestUtils.class, } ) public @interface AuthenticationIntegrationTest { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/security/jwt/TokenAuthenticationSecurityMetersIT.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/security/jwt/TokenAuthenticationSecurityMetersIT.java
package com.cars.app.security.jwt; import static com.cars.app.security.jwt.JwtAuthenticationTestUtils.*; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.http.HttpHeaders.AUTHORIZATION; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import java.util.Collection; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @AutoConfigureMockMvc @AuthenticationIntegrationTest class TokenAuthenticationSecurityMetersIT { private static final String INVALID_TOKENS_METER_EXPECTED_NAME = "security.authentication.invalid-tokens"; @Autowired private MockMvc mvc; @Value("${jhipster.security.authentication.jwt.base64-secret}") private String jwtKey; @Autowired private MeterRegistry meterRegistry; @Test void testValidTokenShouldNotCountAnything() throws Exception { Collection<Counter> counters = meterRegistry.find(INVALID_TOKENS_METER_EXPECTED_NAME).counters(); var count = aggregate(counters); tryToAuthenticate(createValidToken(jwtKey)); assertThat(aggregate(counters)).isEqualTo(count); } @Test void testTokenExpiredCount() throws Exception { var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count(); tryToAuthenticate(createExpiredToken(jwtKey)); assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count()).isEqualTo(count + 1); } @Test void testTokenSignatureInvalidCount() throws Exception { var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count(); tryToAuthenticate(createTokenWithDifferentSignature()); assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count()).isEqualTo( count + 1 ); } @Test void testTokenMalformedCount() throws Exception { var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count(); tryToAuthenticate(createSignedInvalidJwt(jwtKey)); assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isEqualTo(count + 1); } @Test void testTokenInvalidCount() throws Exception { var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count(); tryToAuthenticate(createInvalidToken(jwtKey)); assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isEqualTo(count + 1); } private void tryToAuthenticate(String token) throws Exception { mvc.perform(MockMvcRequestBuilders.get("/api/authenticate").header(AUTHORIZATION, BEARER + token)); } private double aggregate(Collection<Counter> counters) { return counters.stream().mapToDouble(Counter::count).sum(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/security/jwt/TokenAuthenticationIT.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/security/jwt/TokenAuthenticationIT.java
package com.cars.app.security.jwt; import static com.cars.app.security.jwt.JwtAuthenticationTestUtils.*; import static org.springframework.http.HttpHeaders.AUTHORIZATION; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @AutoConfigureMockMvc @AuthenticationIntegrationTest class TokenAuthenticationIT { @Autowired private MockMvc mvc; @Value("${jhipster.security.authentication.jwt.base64-secret}") private String jwtKey; @Test void testLoginWithValidToken() throws Exception { expectOk(createValidToken(jwtKey)); } @Test void testReturnFalseWhenJWThasInvalidSignature() throws Exception { expectUnauthorized(createTokenWithDifferentSignature()); } @Test void testReturnFalseWhenJWTisMalformed() throws Exception { expectUnauthorized(createSignedInvalidJwt(jwtKey)); } @Test void testReturnFalseWhenJWTisExpired() throws Exception { expectUnauthorized(createExpiredToken(jwtKey)); } private void expectOk(String token) throws Exception { mvc.perform(MockMvcRequestBuilders.get("/api/authenticate").header(AUTHORIZATION, BEARER + token)).andExpect(status().isOk()); } private void expectUnauthorized(String token) throws Exception { mvc .perform(MockMvcRequestBuilders.get("/api/authenticate").header(AUTHORIZATION, BEARER + token)) .andExpect(status().isUnauthorized()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/security/jwt/JwtAuthenticationTestUtils.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/security/jwt/JwtAuthenticationTestUtils.java
package com.cars.app.security.jwt; import static com.cars.app.security.SecurityUtils.AUTHORITIES_KEY; import static com.cars.app.security.SecurityUtils.JWT_ALGORITHM; import com.nimbusds.jose.jwk.source.ImmutableSecret; import com.nimbusds.jose.util.Base64; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.Instant; import java.util.Collections; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.springframework.context.annotation.Bean; import org.springframework.security.crypto.codec.Hex; import org.springframework.security.oauth2.jwt.JwsHeader; import org.springframework.security.oauth2.jwt.JwtClaimsSet; import org.springframework.security.oauth2.jwt.JwtEncoder; import org.springframework.security.oauth2.jwt.JwtEncoderParameters; import org.springframework.security.oauth2.jwt.NimbusJwtEncoder; import org.springframework.web.servlet.handler.HandlerMappingIntrospector; public class JwtAuthenticationTestUtils { public static final String BEARER = "Bearer "; @Bean private HandlerMappingIntrospector mvcHandlerMappingIntrospector() { return new HandlerMappingIntrospector(); } @Bean private TestAuthenticationResource authenticationResource() { return new TestAuthenticationResource(); } @Bean private MeterRegistry meterRegistry() { return new SimpleMeterRegistry(); } public static String createValidToken(String jwtKey) { return createValidTokenForUser(jwtKey, "anonymous"); } public static String createValidTokenForUser(String jwtKey, String user) { JwtEncoder encoder = jwtEncoder(jwtKey); var now = Instant.now(); JwtClaimsSet claims = JwtClaimsSet.builder() .issuedAt(now) .expiresAt(now.plusSeconds(60)) .subject(user) .claims(customClaim -> customClaim.put(AUTHORITIES_KEY, Collections.singletonList("ROLE_ADMIN"))) .build(); JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build(); return encoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue(); } public static String createTokenWithDifferentSignature() { JwtEncoder encoder = jwtEncoder("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"); var now = Instant.now(); var past = now.plusSeconds(60); JwtClaimsSet claims = JwtClaimsSet.builder().issuedAt(now).expiresAt(past).subject("anonymous").build(); JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build(); return encoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue(); } public static String createExpiredToken(String jwtKey) { JwtEncoder encoder = jwtEncoder(jwtKey); var now = Instant.now(); var past = now.minusSeconds(600); JwtClaimsSet claims = JwtClaimsSet.builder().issuedAt(past).expiresAt(past.plusSeconds(1)).subject("anonymous").build(); JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build(); return encoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue(); } public static String createInvalidToken(String jwtKey) { return createValidToken(jwtKey).substring(1); } public static String createSignedInvalidJwt(String jwtKey) throws Exception { return calculateHMAC("foo", jwtKey); } private static JwtEncoder jwtEncoder(String jwtKey) { return new NimbusJwtEncoder(new ImmutableSecret<>(getSecretKey(jwtKey))); } private static SecretKey getSecretKey(String jwtKey) { byte[] keyBytes = Base64.from(jwtKey).decode(); return new SecretKeySpec(keyBytes, 0, keyBytes.length, JWT_ALGORITHM.getName()); } private static String calculateHMAC(String data, String key) throws Exception { SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.from(key).decode(), "HmacSHA512"); Mac mac = Mac.getInstance("HmacSHA512"); mac.init(secretKeySpec); return String.copyValueOf(Hex.encode(mac.doFinal(data.getBytes()))); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/PostgreSqlTestContainer.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/PostgreSqlTestContainer.java
package com.cars.app.config; import java.util.Collections; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.JdbcDatabaseContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.containers.output.Slf4jLogConsumer; public class PostgreSqlTestContainer implements SqlTestContainer { private static final Logger log = LoggerFactory.getLogger(PostgreSqlTestContainer.class); private PostgreSQLContainer<?> postgreSQLContainer; @Override public void destroy() { if (null != postgreSQLContainer && postgreSQLContainer.isRunning()) { postgreSQLContainer.stop(); } } @Override public void afterPropertiesSet() { if (null == postgreSQLContainer) { postgreSQLContainer = new PostgreSQLContainer<>("postgres:16.2") .withDatabaseName("carsapp") .withTmpFs(Collections.singletonMap("/testtmpfs", "rw")) .withLogConsumer(new Slf4jLogConsumer(log)) .withReuse(true); } if (!postgreSQLContainer.isRunning()) { postgreSQLContainer.start(); } } @Override public JdbcDatabaseContainer<?> getTestContainer() { return postgreSQLContainer; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/SqlTestContainer.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/SqlTestContainer.java
package com.cars.app.config; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.testcontainers.containers.JdbcDatabaseContainer; public interface SqlTestContainer extends InitializingBean, DisposableBean { JdbcDatabaseContainer<?> getTestContainer(); }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/CRLFLogConverterTest.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/CRLFLogConverterTest.java
package com.cars.app.config; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import ch.qos.logback.classic.spi.ILoggingEvent; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import org.slf4j.Marker; import org.slf4j.MarkerFactory; import org.springframework.boot.ansi.AnsiColor; import org.springframework.boot.ansi.AnsiElement; class CRLFLogConverterTest { @Test void transformShouldReturnInputStringWhenMarkerListIsEmpty() { ILoggingEvent event = mock(ILoggingEvent.class); when(event.getMarkerList()).thenReturn(null); when(event.getLoggerName()).thenReturn("org.hibernate.example.Logger"); String input = "Test input string"; CRLFLogConverter converter = new CRLFLogConverter(); String result = converter.transform(event, input); assertEquals(input, result); } @Test void transformShouldReturnInputStringWhenMarkersContainCRLFSafeMarker() { ILoggingEvent event = mock(ILoggingEvent.class); Marker marker = MarkerFactory.getMarker("CRLF_SAFE"); List<Marker> markers = Collections.singletonList(marker); when(event.getMarkerList()).thenReturn(markers); String input = "Test input string"; CRLFLogConverter converter = new CRLFLogConverter(); String result = converter.transform(event, input); assertEquals(input, result); } @Test void transformShouldReturnInputStringWhenMarkersNotContainCRLFSafeMarker() { ILoggingEvent event = mock(ILoggingEvent.class); Marker marker = MarkerFactory.getMarker("CRLF_NOT_SAFE"); List<Marker> markers = Collections.singletonList(marker); when(event.getMarkerList()).thenReturn(markers); when(event.getLoggerName()).thenReturn("org.hibernate.example.Logger"); String input = "Test input string"; CRLFLogConverter converter = new CRLFLogConverter(); String result = converter.transform(event, input); assertEquals(input, result); } @Test void transformShouldReturnInputStringWhenLoggerIsSafe() { ILoggingEvent event = mock(ILoggingEvent.class); when(event.getLoggerName()).thenReturn("org.hibernate.example.Logger"); String input = "Test input string"; CRLFLogConverter converter = new CRLFLogConverter(); String result = converter.transform(event, input); assertEquals(input, result); } @Test void transformShouldReplaceNewlinesAndCarriageReturnsWithUnderscoreWhenMarkersDoNotContainCRLFSafeMarkerAndLoggerIsNotSafe() { ILoggingEvent event = mock(ILoggingEvent.class); List<Marker> markers = Collections.emptyList(); when(event.getMarkerList()).thenReturn(markers); when(event.getLoggerName()).thenReturn("com.mycompany.myapp.example.Logger"); String input = "Test\ninput\rstring"; CRLFLogConverter converter = new CRLFLogConverter(); String result = converter.transform(event, input); assertEquals("Test_input_string", result); } @Test void transformShouldReplaceNewlinesAndCarriageReturnsWithAnsiStringWhenMarkersDoNotContainCRLFSafeMarkerAndLoggerIsNotSafeAndAnsiElementIsNotNull() { ILoggingEvent event = mock(ILoggingEvent.class); List<Marker> markers = Collections.emptyList(); when(event.getMarkerList()).thenReturn(markers); when(event.getLoggerName()).thenReturn("com.mycompany.myapp.example.Logger"); String input = "Test\ninput\rstring"; CRLFLogConverter converter = new CRLFLogConverter(); converter.setOptionList(List.of("red")); String result = converter.transform(event, input); assertEquals("Test_input_string", result); } @Test void isLoggerSafeShouldReturnTrueWhenLoggerNameStartsWithSafeLogger() { ILoggingEvent event = mock(ILoggingEvent.class); when(event.getLoggerName()).thenReturn("org.springframework.boot.autoconfigure.example.Logger"); CRLFLogConverter converter = new CRLFLogConverter(); boolean result = converter.isLoggerSafe(event); assertTrue(result); } @Test void isLoggerSafeShouldReturnFalseWhenLoggerNameDoesNotStartWithSafeLogger() { ILoggingEvent event = mock(ILoggingEvent.class); when(event.getLoggerName()).thenReturn("com.mycompany.myapp.example.Logger"); CRLFLogConverter converter = new CRLFLogConverter(); boolean result = converter.isLoggerSafe(event); assertFalse(result); } @Test void testToAnsiString() { CRLFLogConverter cut = new CRLFLogConverter(); AnsiElement ansiElement = AnsiColor.RED; String result = cut.toAnsiString("input", ansiElement); assertThat(result).isEqualTo("input"); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/EmbeddedSQL.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/EmbeddedSQL.java
package com.cars.app.config; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface EmbeddedSQL { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/SqlTestContainersSpringContextCustomizerFactory.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/SqlTestContainersSpringContextCustomizerFactory.java
package com.cars.app.config; import java.util.Arrays; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.test.context.ContextConfigurationAttributes; import org.springframework.test.context.ContextCustomizer; import org.springframework.test.context.ContextCustomizerFactory; import org.springframework.test.context.MergedContextConfiguration; import tech.jhipster.config.JHipsterConstants; public class SqlTestContainersSpringContextCustomizerFactory implements ContextCustomizerFactory { private Logger log = LoggerFactory.getLogger(SqlTestContainersSpringContextCustomizerFactory.class); private static SqlTestContainer prodTestContainer; @Override public ContextCustomizer createContextCustomizer(Class<?> testClass, List<ContextConfigurationAttributes> configAttributes) { return new ContextCustomizer() { @Override public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) { ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); TestPropertyValues testValues = TestPropertyValues.empty(); EmbeddedSQL sqlAnnotation = AnnotatedElementUtils.findMergedAnnotation(testClass, EmbeddedSQL.class); boolean usingTestProdProfile = Arrays.asList(context.getEnvironment().getActiveProfiles()).contains( "test" + JHipsterConstants.SPRING_PROFILE_PRODUCTION ); if (null != sqlAnnotation && usingTestProdProfile) { log.debug("detected the EmbeddedSQL annotation on class {}", testClass.getName()); log.info("Warming up the sql database"); if (null == prodTestContainer) { try { Class<? extends SqlTestContainer> containerClass = (Class<? extends SqlTestContainer>) Class.forName( this.getClass().getPackageName() + ".PostgreSqlTestContainer" ); prodTestContainer = beanFactory.createBean(containerClass); beanFactory.registerSingleton(containerClass.getName(), prodTestContainer); // ((DefaultListableBeanFactory)beanFactory).registerDisposableBean(containerClass.getName(), prodTestContainer); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } testValues = testValues.and("spring.datasource.url=" + prodTestContainer.getTestContainer().getJdbcUrl() + ""); testValues = testValues.and("spring.datasource.username=" + prodTestContainer.getTestContainer().getUsername()); testValues = testValues.and("spring.datasource.password=" + prodTestContainer.getTestContainer().getPassword()); } testValues.applyTo(context); } @Override public int hashCode() { return SqlTestContainer.class.getName().hashCode(); } @Override public boolean equals(Object obj) { return this.hashCode() == obj.hashCode(); } }; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/StaticResourcesWebConfigurerTest.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/StaticResourcesWebConfigurerTest.java
package com.cars.app.config; import static com.cars.app.config.StaticResourcesWebConfiguration.*; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.CacheControl; import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import tech.jhipster.config.JHipsterDefaults; import tech.jhipster.config.JHipsterProperties; class StaticResourcesWebConfigurerTest { public static final int MAX_AGE_TEST = 5; public StaticResourcesWebConfiguration staticResourcesWebConfiguration; private ResourceHandlerRegistry resourceHandlerRegistry; private MockServletContext servletContext; private WebApplicationContext applicationContext; private JHipsterProperties props; @BeforeEach void setUp() { servletContext = spy(new MockServletContext()); applicationContext = mock(WebApplicationContext.class); resourceHandlerRegistry = spy(new ResourceHandlerRegistry(applicationContext, servletContext)); props = new JHipsterProperties(); staticResourcesWebConfiguration = spy(new StaticResourcesWebConfiguration(props)); } @Test void shouldAppendResourceHandlerAndInitializeIt() { staticResourcesWebConfiguration.addResourceHandlers(resourceHandlerRegistry); verify(resourceHandlerRegistry, times(1)).addResourceHandler(RESOURCE_PATHS); verify(staticResourcesWebConfiguration, times(1)).initializeResourceHandler(any(ResourceHandlerRegistration.class)); for (String testingPath : RESOURCE_PATHS) { assertThat(resourceHandlerRegistry.hasMappingForPattern(testingPath)).isTrue(); } } @Test void shouldInitializeResourceHandlerWithCacheControlAndLocations() { CacheControl ccExpected = CacheControl.maxAge(5, TimeUnit.DAYS).cachePublic(); when(staticResourcesWebConfiguration.getCacheControl()).thenReturn(ccExpected); ResourceHandlerRegistration resourceHandlerRegistration = spy(new ResourceHandlerRegistration(RESOURCE_PATHS)); staticResourcesWebConfiguration.initializeResourceHandler(resourceHandlerRegistration); verify(staticResourcesWebConfiguration, times(1)).getCacheControl(); verify(resourceHandlerRegistration, times(1)).setCacheControl(ccExpected); verify(resourceHandlerRegistration, times(1)).addResourceLocations(RESOURCE_LOCATIONS); } @Test void shouldCreateCacheControlBasedOnJhipsterDefaultProperties() { CacheControl cacheExpected = CacheControl.maxAge(JHipsterDefaults.Http.Cache.timeToLiveInDays, TimeUnit.DAYS).cachePublic(); assertThat(staticResourcesWebConfiguration.getCacheControl()) .extracting(CacheControl::getHeaderValue) .isEqualTo(cacheExpected.getHeaderValue()); } @Test void shouldCreateCacheControlWithSpecificConfigurationInProperties() { props.getHttp().getCache().setTimeToLiveInDays(MAX_AGE_TEST); CacheControl cacheExpected = CacheControl.maxAge(MAX_AGE_TEST, TimeUnit.DAYS).cachePublic(); assertThat(staticResourcesWebConfiguration.getCacheControl()) .extracting(CacheControl::getHeaderValue) .isEqualTo(cacheExpected.getHeaderValue()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/AsyncSyncConfiguration.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/AsyncSyncConfiguration.java
package com.cars.app.config; import java.util.concurrent.Executor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.task.SyncTaskExecutor; @Configuration public class AsyncSyncConfiguration { @Bean(name = "taskExecutor") public Executor taskExecutor() { return new SyncTaskExecutor(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/WebConfigurerTestController.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/WebConfigurerTestController.java
package com.cars.app.config; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class WebConfigurerTestController { @GetMapping("/api/test-cors") public void testCorsOnApiPath() {} @GetMapping("/test/test-cors") public void testCorsOnOtherPath() {} }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/WebConfigurerTest.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/WebConfigurerTest.java
package com.cars.app.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 jakarta.servlet.*; import java.io.File; import java.util.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; import org.springframework.http.HttpHeaders; import org.springframework.mock.env.MockEnvironment; import org.springframework.mock.web.MockServletContext; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import tech.jhipster.config.JHipsterConstants; import tech.jhipster.config.JHipsterProperties; /** * Unit tests for the {@link WebConfigurer} class. */ class WebConfigurerTest { private WebConfigurer webConfigurer; private MockServletContext servletContext; private MockEnvironment env; private JHipsterProperties props; @BeforeEach public void setup() { servletContext = spy(new MockServletContext()); doReturn(mock(FilterRegistration.Dynamic.class)).when(servletContext).addFilter(anyString(), any(Filter.class)); doReturn(mock(ServletRegistration.Dynamic.class)).when(servletContext).addServlet(anyString(), any(Servlet.class)); env = new MockEnvironment(); props = new JHipsterProperties(); webConfigurer = new WebConfigurer(env, props); } @Test void shouldCustomizeServletContainer() { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); webConfigurer.customize(container); assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html"); assertThat(container.getMimeMappings().get("json")).isEqualTo("application/json"); if (container.getDocumentRoot() != null) { assertThat(container.getDocumentRoot()).isEqualTo(new File("target/classes/static/")); } } @Test void shouldCorsFilterOnApiPath() throws Exception { props.getCors().setAllowedOrigins(Collections.singletonList("other.domain.com")); props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); props.getCors().setAllowedHeaders(Collections.singletonList("*")); props.getCors().setMaxAge(1800L); props.getCors().setAllowCredentials(true); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).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")); 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")); } @Test void shouldCorsFilterOnOtherPath() throws Exception { props.getCors().setAllowedOrigins(Collections.singletonList("*")); props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); props.getCors().setAllowedHeaders(Collections.singletonList("*")); props.getCors().setMaxAge(1800L); props.getCors().setAllowCredentials(true); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).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)); } @Test void shouldCorsFilterDeactivatedForNullAllowedOrigins() throws Exception { props.getCors().setAllowedOrigins(null); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).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)); } @Test void shouldCorsFilterDeactivatedForEmptyAllowedOrigins() throws Exception { props.getCors().setAllowedOrigins(new ArrayList<>()); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).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)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/SpringBootTestClassOrderer.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/SpringBootTestClassOrderer.java
package com.cars.app.config; import com.cars.app.IntegrationTest; import java.util.Comparator; import org.junit.jupiter.api.ClassDescriptor; import org.junit.jupiter.api.ClassOrderer; import org.junit.jupiter.api.ClassOrdererContext; public class SpringBootTestClassOrderer implements ClassOrderer { @Override public void orderClasses(ClassOrdererContext context) { context.getClassDescriptors().sort(Comparator.comparingInt(SpringBootTestClassOrderer::getOrder)); } private static int getOrder(ClassDescriptor classDescriptor) { if (classDescriptor.findAnnotation(IntegrationTest.class).isPresent()) { return 2; } return 1; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/timezone/HibernateTimeZoneIT.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/config/timezone/HibernateTimeZoneIT.java
package com.cars.app.config.timezone; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import com.cars.app.IntegrationTest; import com.cars.app.repository.timezone.DateTimeWrapper; import com.cars.app.repository.timezone.DateTimeWrapperRepository; import java.time.*; import java.time.format.DateTimeFormatter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; import org.springframework.transaction.annotation.Transactional; /** * Integration tests for verifying the behavior of Hibernate in the context of storing various date and time types across different databases. * The tests focus on ensuring that the stored values are correctly transformed and stored according to the configured timezone. * Timezone is environment specific, and can be adjusted according to your needs. * * For more context, refer to: * - GitHub Issue: https://github.com/jhipster/generator-jhipster/issues/22579 * - Pull Request: https://github.com/jhipster/generator-jhipster/pull/22946 */ @IntegrationTest class HibernateTimeZoneIT { @Autowired private DateTimeWrapperRepository dateTimeWrapperRepository; @Autowired private JdbcTemplate jdbcTemplate; @Value("${spring.jpa.properties.hibernate.jdbc.time_zone:UTC}") private String zoneId; private DateTimeWrapper dateTimeWrapper; private DateTimeFormatter dateTimeFormatter; private DateTimeFormatter timeFormatter; private DateTimeFormatter offsetTimeFormatter; private DateTimeFormatter dateFormatter; @BeforeEach public void setup() { dateTimeWrapper = new DateTimeWrapper(); dateTimeWrapper.setInstant(Instant.parse("2014-11-12T05:10:00.0Z")); dateTimeWrapper.setLocalDateTime(LocalDateTime.parse("2014-11-12T07:20:00.0")); dateTimeWrapper.setOffsetDateTime(OffsetDateTime.parse("2011-12-14T08:30:00.0Z")); dateTimeWrapper.setZonedDateTime(ZonedDateTime.parse("2011-12-14T08:40:00.0Z")); dateTimeWrapper.setLocalTime(LocalTime.parse("14:50:00")); dateTimeWrapper.setOffsetTime(OffsetTime.parse("14:00:00+02:00")); dateTimeWrapper.setLocalDate(LocalDate.parse("2016-09-10")); dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S").withZone(ZoneId.of(zoneId)); timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss").withZone(ZoneId.of(zoneId)); offsetTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss"); dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); } @Test @Transactional void storeInstantWithZoneIdConfigShouldBeStoredOnConfiguredTimeZone() { dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); String request = generateSqlRequest("instant", dateTimeWrapper.getId()); SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); String expectedValue = dateTimeFormatter.format(dateTimeWrapper.getInstant()); assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue); } @Test @Transactional void storeLocalDateTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZone() { dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); String request = generateSqlRequest("local_date_time", dateTimeWrapper.getId()); SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); String expectedValue = dateTimeWrapper.getLocalDateTime().atZone(ZoneId.systemDefault()).format(dateTimeFormatter); assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue); } @Test @Transactional void storeOffsetDateTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZone() { dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); String request = generateSqlRequest("offset_date_time", dateTimeWrapper.getId()); SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); String expectedValue = dateTimeWrapper.getOffsetDateTime().format(dateTimeFormatter); assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue); } @Test @Transactional void storeZoneDateTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZone() { dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); String request = generateSqlRequest("zoned_date_time", dateTimeWrapper.getId()); SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); String expectedValue = dateTimeWrapper.getZonedDateTime().format(dateTimeFormatter); assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue); } @Test @Transactional void storeLocalTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZoneAccordingToHis1stJan1970Value() { dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); 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); assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue); } @Test @Transactional void storeOffsetTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZoneAccordingToHis1stJan1970Value() { dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); String request = generateSqlRequest("offset_time", dateTimeWrapper.getId()); SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); String expectedValue = dateTimeWrapper .getOffsetTime() // Convert to configured timezone .withOffsetSameInstant(ZoneId.of(zoneId).getRules().getOffset(Instant.now())) // Normalize to System TimeZone. // TODO this behavior looks a bug, refer to https://github.com/jhipster/generator-jhipster/issues/22579. .withOffsetSameLocal(OffsetDateTime.ofInstant(Instant.EPOCH, ZoneId.systemDefault()).getOffset()) // Convert the normalized value to configured timezone .withOffsetSameInstant(ZoneId.of(zoneId).getRules().getOffset(Instant.EPOCH)) .format(offsetTimeFormatter); assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue); } @Test @Transactional void storeLocalDateWithZoneIdConfigShouldBeStoredWithoutTransformation() { dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper); String request = generateSqlRequest("local_date", dateTimeWrapper.getId()); SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request); String expectedValue = dateTimeWrapper.getLocalDate().format(dateFormatter); assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue); } private String generateSqlRequest(String fieldName, long id) { return format("SELECT %s FROM jhi_date_time_wrapper where id=%d", fieldName, id); } private void assertThatValueFromSqlRowSetIsEqualToExpectedValue(SqlRowSet sqlRowSet, String expectedValue) { while (sqlRowSet.next()) { String dbValue = sqlRowSet.getString(1); assertThat(dbValue).isNotNull(); assertThat(dbValue).isEqualTo(expectedValue); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/web/filter/SpaWebFilterIT.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/web/filter/SpaWebFilterIT.java
package com.cars.app.web.filter; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.cars.app.IntegrationTest; import com.cars.app.security.AuthoritiesConstants; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; @AutoConfigureMockMvc @WithMockUser @IntegrationTest class SpaWebFilterIT { @Autowired private MockMvc mockMvc; @Test void testFilterForwardsToIndex() throws Exception { mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html")); } @Test @WithMockUser(authorities = AuthoritiesConstants.ADMIN) void testFilterDoesNotForwardToIndexForV3ApiDocs() throws Exception { mockMvc.perform(get("/v3/api-docs")).andExpect(status().isOk()).andExpect(forwardedUrl(null)); } @Test void testFilterDoesNotForwardToIndexForDotFile() throws Exception { mockMvc.perform(get("/file.js")).andExpect(status().isNotFound()); } @Test void getBackendEndpoint() throws Exception { mockMvc.perform(get("/test")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html")); } @Test void forwardUnmappedFirstLevelMapping() throws Exception { mockMvc.perform(get("/first-level")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html")); } @Test void forwardUnmappedSecondLevelMapping() throws Exception { mockMvc.perform(get("/first-level/second-level")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html")); } @Test void forwardUnmappedThirdLevelMapping() throws Exception { mockMvc.perform(get("/first-level/second-level/third-level")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html")); } @Test void forwardUnmappedDeepMapping() throws Exception { mockMvc.perform(get("/1/2/3/4/5/6/7/8/9/10")).andExpect(forwardedUrl("/index.html")); } @Test void getUnmappedFirstLevelFile() throws Exception { mockMvc.perform(get("/foo.js")).andExpect(status().isNotFound()); } /** * This test verifies that any files that aren't permitted by Spring Security will be forbidden. * If you want to change this to return isNotFound(), you need to add a request mapping that * allows this file in SecurityConfiguration. */ @Test void getUnmappedSecondLevelFile() throws Exception { mockMvc.perform(get("/foo/bar.js")).andExpect(status().isForbidden()); } @Test void getUnmappedThirdLevelFile() throws Exception { mockMvc.perform(get("/foo/another/bar.js")).andExpect(status().isForbidden()); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/web/rest/CarResourceIT.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/web/rest/CarResourceIT.java
package com.cars.app.web.rest; import static com.cars.app.domain.CarAsserts.*; import static com.cars.app.web.rest.TestUtil.createUpdateProxyForBean; import static org.assertj.core.api.Assertions.assertThat; 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 com.cars.app.IntegrationTest; import com.cars.app.domain.Car; import com.cars.app.repository.CarRepository; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.persistence.EntityManager; import java.util.Random; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; /** * Integration tests for the {@link CarResource} REST controller. */ @IntegrationTest @AutoConfigureMockMvc @WithMockUser class CarResourceIT { private static final Double DEFAULT_PRICE = 1D; private static final Double UPDATED_PRICE = 2D; private static final String ENTITY_API_URL = "/api/cars"; private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}"; private static Random random = new Random(); private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE)); @Autowired private ObjectMapper om; @Autowired private CarRepository carRepository; @Autowired private EntityManager em; @Autowired private MockMvc restCarMockMvc; private Car car; /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Car createEntity(EntityManager em) { Car car = new Car().price(DEFAULT_PRICE); return car; } /** * Create an updated entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Car createUpdatedEntity(EntityManager em) { Car car = new Car().price(UPDATED_PRICE); return car; } @BeforeEach public void initTest() { car = createEntity(em); } @Test @Transactional void createCar() throws Exception { long databaseSizeBeforeCreate = getRepositoryCount(); // Create the Car var returnedCar = om.readValue( restCarMockMvc .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(car))) .andExpect(status().isCreated()) .andReturn() .getResponse() .getContentAsString(), Car.class ); // Validate the Car in the database assertIncrementedRepositoryCount(databaseSizeBeforeCreate); assertCarUpdatableFieldsEquals(returnedCar, getPersistedCar(returnedCar)); } @Test @Transactional void createCarWithExistingId() throws Exception { // Create the Car with an existing ID car.setId(1L); long databaseSizeBeforeCreate = getRepositoryCount(); // An entity with an existing ID cannot be created, so this API call must fail restCarMockMvc .perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(car))) .andExpect(status().isBadRequest()); // Validate the Car in the database assertSameRepositoryCount(databaseSizeBeforeCreate); } @Test @Transactional void getAllCars() throws Exception { // Initialize the database carRepository.saveAndFlush(car); // Get all the carList restCarMockMvc .perform(get(ENTITY_API_URL + "?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(car.getId().intValue()))) .andExpect(jsonPath("$.[*].price").value(hasItem(DEFAULT_PRICE.doubleValue()))); } @Test @Transactional void getCar() throws Exception { // Initialize the database carRepository.saveAndFlush(car); // Get the car restCarMockMvc .perform(get(ENTITY_API_URL_ID, car.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.id").value(car.getId().intValue())) .andExpect(jsonPath("$.price").value(DEFAULT_PRICE.doubleValue())); } @Test @Transactional void getNonExistingCar() throws Exception { // Get the car restCarMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound()); } @Test @Transactional void putExistingCar() throws Exception { // Initialize the database carRepository.saveAndFlush(car); long databaseSizeBeforeUpdate = getRepositoryCount(); // Update the car Car updatedCar = carRepository.findById(car.getId()).orElseThrow(); // Disconnect from session so that the updates on updatedCar are not directly saved in db em.detach(updatedCar); updatedCar.price(UPDATED_PRICE); restCarMockMvc .perform( put(ENTITY_API_URL_ID, updatedCar.getId()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(updatedCar)) ) .andExpect(status().isOk()); // Validate the Car in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); assertPersistedCarToMatchAllProperties(updatedCar); } @Test @Transactional void putNonExistingCar() throws Exception { long databaseSizeBeforeUpdate = getRepositoryCount(); car.setId(longCount.incrementAndGet()); // If the entity doesn't have an ID, it will throw BadRequestAlertException restCarMockMvc .perform(put(ENTITY_API_URL_ID, car.getId()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(car))) .andExpect(status().isBadRequest()); // Validate the Car in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); } @Test @Transactional void putWithIdMismatchCar() throws Exception { long databaseSizeBeforeUpdate = getRepositoryCount(); car.setId(longCount.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restCarMockMvc .perform( put(ENTITY_API_URL_ID, longCount.incrementAndGet()) .contentType(MediaType.APPLICATION_JSON) .content(om.writeValueAsBytes(car)) ) .andExpect(status().isBadRequest()); // Validate the Car in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); } @Test @Transactional void putWithMissingIdPathParamCar() throws Exception { long databaseSizeBeforeUpdate = getRepositoryCount(); car.setId(longCount.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restCarMockMvc .perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(car))) .andExpect(status().isMethodNotAllowed()); // Validate the Car in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); } @Test @Transactional void partialUpdateCarWithPatch() throws Exception { // Initialize the database carRepository.saveAndFlush(car); long databaseSizeBeforeUpdate = getRepositoryCount(); // Update the car using partial update Car partialUpdatedCar = new Car(); partialUpdatedCar.setId(car.getId()); restCarMockMvc .perform( patch(ENTITY_API_URL_ID, partialUpdatedCar.getId()) .contentType("application/merge-patch+json") .content(om.writeValueAsBytes(partialUpdatedCar)) ) .andExpect(status().isOk()); // Validate the Car in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); assertCarUpdatableFieldsEquals(createUpdateProxyForBean(partialUpdatedCar, car), getPersistedCar(car)); } @Test @Transactional void fullUpdateCarWithPatch() throws Exception { // Initialize the database carRepository.saveAndFlush(car); long databaseSizeBeforeUpdate = getRepositoryCount(); // Update the car using partial update Car partialUpdatedCar = new Car(); partialUpdatedCar.setId(car.getId()); partialUpdatedCar.price(UPDATED_PRICE); restCarMockMvc .perform( patch(ENTITY_API_URL_ID, partialUpdatedCar.getId()) .contentType("application/merge-patch+json") .content(om.writeValueAsBytes(partialUpdatedCar)) ) .andExpect(status().isOk()); // Validate the Car in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); assertCarUpdatableFieldsEquals(partialUpdatedCar, getPersistedCar(partialUpdatedCar)); } @Test @Transactional void patchNonExistingCar() throws Exception { long databaseSizeBeforeUpdate = getRepositoryCount(); car.setId(longCount.incrementAndGet()); // If the entity doesn't have an ID, it will throw BadRequestAlertException restCarMockMvc .perform(patch(ENTITY_API_URL_ID, car.getId()).contentType("application/merge-patch+json").content(om.writeValueAsBytes(car))) .andExpect(status().isBadRequest()); // Validate the Car in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); } @Test @Transactional void patchWithIdMismatchCar() throws Exception { long databaseSizeBeforeUpdate = getRepositoryCount(); car.setId(longCount.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restCarMockMvc .perform( patch(ENTITY_API_URL_ID, longCount.incrementAndGet()) .contentType("application/merge-patch+json") .content(om.writeValueAsBytes(car)) ) .andExpect(status().isBadRequest()); // Validate the Car in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); } @Test @Transactional void patchWithMissingIdPathParamCar() throws Exception { long databaseSizeBeforeUpdate = getRepositoryCount(); car.setId(longCount.incrementAndGet()); // If url ID doesn't match entity ID, it will throw BadRequestAlertException restCarMockMvc .perform(patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(om.writeValueAsBytes(car))) .andExpect(status().isMethodNotAllowed()); // Validate the Car in the database assertSameRepositoryCount(databaseSizeBeforeUpdate); } @Test @Transactional void deleteCar() throws Exception { // Initialize the database carRepository.saveAndFlush(car); long databaseSizeBeforeDelete = getRepositoryCount(); // Delete the car restCarMockMvc.perform(delete(ENTITY_API_URL_ID, car.getId()).accept(MediaType.APPLICATION_JSON)).andExpect(status().isNoContent()); // Validate the database contains one less item assertDecrementedRepositoryCount(databaseSizeBeforeDelete); } protected long getRepositoryCount() { return carRepository.count(); } protected void assertIncrementedRepositoryCount(long countBefore) { assertThat(countBefore + 1).isEqualTo(getRepositoryCount()); } protected void assertDecrementedRepositoryCount(long countBefore) { assertThat(countBefore - 1).isEqualTo(getRepositoryCount()); } protected void assertSameRepositoryCount(long countBefore) { assertThat(countBefore).isEqualTo(getRepositoryCount()); } protected Car getPersistedCar(Car car) { return carRepository.findById(car.getId()).orElseThrow(); } protected void assertPersistedCarToMatchAllProperties(Car expectedCar) { assertCarAllPropertiesEquals(expectedCar, getPersistedCar(expectedCar)); } protected void assertPersistedCarToMatchUpdatableProperties(Car expectedCar) { assertCarAllUpdatablePropertiesEquals(expectedCar, getPersistedCar(expectedCar)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/web/rest/TestUtil.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/web/rest/TestUtil.java
package com.cars.app.web.rest; import static org.assertj.core.api.Assertions.assertThat; import jakarta.persistence.EntityManager; import jakarta.persistence.TypedQuery; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; import java.lang.reflect.Method; import java.math.BigDecimal; import java.time.ZonedDateTime; import java.time.format.DateTimeParseException; import java.util.List; import org.hamcrest.Description; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.hamcrest.TypeSafeMatcher; import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.cglib.proxy.MethodProxy; import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; import org.springframework.format.support.DefaultFormattingConversionService; import org.springframework.format.support.FormattingConversionService; /** * Utility class for testing REST controllers. */ public final class TestUtil { /** * Create a byte array with a specific size filled with specified data. * * @param size the size of the byte array. * @param data the data to put in the byte array. * @return the JSON byte array. */ public static byte[] createByteArray(int size, String data) { byte[] byteArray = new byte[size]; for (int i = 0; i < size; i++) { byteArray[i] = Byte.parseByte(data, 2); } return byteArray; } /** * A matcher that tests that the examined string represents the same instant as the reference datetime. */ public static class ZonedDateTimeMatcher extends TypeSafeDiagnosingMatcher<String> { private final ZonedDateTime date; public ZonedDateTimeMatcher(ZonedDateTime date) { this.date = date; } @Override protected boolean matchesSafely(String item, Description mismatchDescription) { try { if (!date.isEqual(ZonedDateTime.parse(item))) { mismatchDescription.appendText("was ").appendValue(item); return false; } return true; } catch (DateTimeParseException e) { mismatchDescription.appendText("was ").appendValue(item).appendText(", which could not be parsed as a ZonedDateTime"); return false; } } @Override public void describeTo(Description description) { description.appendText("a String representing the same Instant as ").appendValue(date); } } /** * Creates a matcher that matches when the examined string represents 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) { return new ZonedDateTimeMatcher(date); } /** * A matcher that tests that the examined number represents the same value - it can be Long, Double, etc - as the reference BigDecimal. */ public static class NumberMatcher extends TypeSafeMatcher<Number> { final BigDecimal value; public NumberMatcher(BigDecimal value) { this.value = value; } @Override public void describeTo(Description description) { description.appendText("a numeric value is ").appendValue(value); } @Override protected boolean matchesSafely(Number item) { BigDecimal bigDecimal = asDecimal(item); return bigDecimal != null && value.compareTo(bigDecimal) == 0; } private static BigDecimal asDecimal(Number item) { if (item == null) { return null; } if (item instanceof BigDecimal) { return (BigDecimal) item; } else if (item instanceof Long) { return BigDecimal.valueOf((Long) item); } else if (item instanceof Integer) { return BigDecimal.valueOf((Integer) item); } else if (item instanceof Double) { return BigDecimal.valueOf((Double) item); } else if (item instanceof Float) { return BigDecimal.valueOf((Float) item); } else { return BigDecimal.valueOf(item.doubleValue()); } } } /** * Creates a matcher that matches when the examined number represents the same value as the reference BigDecimal. * * @param number the reference BigDecimal against which the examined number is checked. */ public static NumberMatcher sameNumber(BigDecimal number) { return new NumberMatcher(number); } /** * Verifies the equals/hashcode contract on the domain object. */ public static <T> void equalsVerifier(Class<T> clazz) throws Exception { T domainObject1 = clazz.getConstructor().newInstance(); assertThat(domainObject1.toString()).isNotNull(); assertThat(domainObject1).isEqualTo(domainObject1); assertThat(domainObject1).hasSameHashCodeAs(domainObject1); // Test with an instance of another class Object testOtherObject = new Object(); assertThat(domainObject1).isNotEqualTo(testOtherObject); assertThat(domainObject1).isNotEqualTo(null); // Test with an instance of the same class T domainObject2 = clazz.getConstructor().newInstance(); assertThat(domainObject1).isNotEqualTo(domainObject2); // HashCodes are equals because the objects are not persisted yet assertThat(domainObject1).hasSameHashCodeAs(domainObject2); } /** * Create a {@link FormattingConversionService} which use ISO date format, instead of the localized one. * @return the {@link FormattingConversionService}. */ public static FormattingConversionService createFormattingConversionService() { DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService(); DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); registrar.setUseIsoFormat(true); registrar.registerFormatters(dfcs); return dfcs; } /** * Executes a query on the EntityManager finding all stored objects. * @param <T> The type of objects to be searched * @param em The instance of the EntityManager * @param clazz The class type to be searched * @return A list of all found objects */ public static <T> List<T> findAll(EntityManager em, Class<T> clazz) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<T> cq = cb.createQuery(clazz); Root<T> rootEntry = cq.from(clazz); CriteriaQuery<T> all = cq.select(rootEntry); TypedQuery<T> allQuery = em.createQuery(all); return allQuery.getResultList(); } @SuppressWarnings("unchecked") public static <T> T createUpdateProxyForBean(T update, T original) { Enhancer e = new Enhancer(); e.setSuperclass(original.getClass()); e.setCallback( new MethodInterceptor() { public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { Object val = update.getClass().getMethod(method.getName(), method.getParameterTypes()).invoke(update, args); if (val == null) { return original.getClass().getMethod(method.getName(), method.getParameterTypes()).invoke(original, args); } return val; } } ); return (T) e.create(); } private TestUtil() {} }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/web/rest/WithUnauthenticatedMockUser.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/web/rest/WithUnauthenticatedMockUser.java
package com.cars.app.web.rest; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.test.context.support.WithSecurityContext; import org.springframework.security.test.context.support.WithSecurityContextFactory; @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @WithSecurityContext(factory = WithUnauthenticatedMockUser.Factory.class) public @interface WithUnauthenticatedMockUser { class Factory implements WithSecurityContextFactory<WithUnauthenticatedMockUser> { @Override public SecurityContext createSecurityContext(WithUnauthenticatedMockUser annotation) { return SecurityContextHolder.createEmptyContext(); } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/web/rest/errors/ExceptionTranslatorTestController.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/web/rest/errors/ExceptionTranslatorTestController.java
package com.cars.app.web.rest.errors; import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/exception-translator-test") public class ExceptionTranslatorTestController { @GetMapping("/concurrency-failure") public void concurrencyFailure() { throw new ConcurrencyFailureException("test concurrency failure"); } @PostMapping("/method-argument") public void methodArgument(@Valid @RequestBody TestDTO testDTO) {} @GetMapping("/missing-servlet-request-part") public void missingServletRequestPartException(@RequestPart("part") String part) {} @GetMapping("/missing-servlet-request-parameter") public void missingServletRequestParameterException(@RequestParam("param") String param) {} @GetMapping("/access-denied") public void accessdenied() { throw new AccessDeniedException("test access denied!"); } @GetMapping("/unauthorized") public void unauthorized() { throw new BadCredentialsException("test authentication failed!"); } @GetMapping("/response-status") public void exceptionWithResponseStatus() { throw new TestResponseStatusException(); } @GetMapping("/internal-server-error") public void internalServerError() { throw new RuntimeException(); } public static class TestDTO { @NotNull private String test; public String getTest() { return test; } public void setTest(String test) { this.test = test; } } @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "test response status") @SuppressWarnings("serial") public static class TestResponseStatusException extends RuntimeException {} }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/web/rest/errors/ExceptionTranslatorIT.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/test/java/com/cars/app/web/rest/errors/ExceptionTranslatorIT.java
package com.cars.app.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 com.cars.app.IntegrationTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; /** * Integration tests {@link ExceptionTranslator} controller advice. */ @WithMockUser @AutoConfigureMockMvc @IntegrationTest class ExceptionTranslatorIT { @Autowired private MockMvc mockMvc; @Test void testConcurrencyFailure() throws Exception { mockMvc .perform(get("/api/exception-translator-test/concurrency-failure")) .andExpect(status().isConflict()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE)); } @Test void testMethodArgumentNotValid() throws Exception { mockMvc .perform(post("/api/exception-translator-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("test")) .andExpect(jsonPath("$.fieldErrors.[0].field").value("test")) .andExpect(jsonPath("$.fieldErrors.[0].message").value("must not be null")); } @Test void testMissingServletRequestPartException() throws Exception { mockMvc .perform(get("/api/exception-translator-test/missing-servlet-request-part")) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.400")); } @Test void testMissingServletRequestParameterException() throws Exception { mockMvc .perform(get("/api/exception-translator-test/missing-servlet-request-parameter")) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.400")); } @Test void testAccessDenied() throws Exception { mockMvc .perform(get("/api/exception-translator-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 void testUnauthorized() throws Exception { mockMvc .perform(get("/api/exception-translator-test/unauthorized")) .andExpect(status().isUnauthorized()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.401")) .andExpect(jsonPath("$.path").value("/api/exception-translator-test/unauthorized")) .andExpect(jsonPath("$.detail").value("test authentication failed!")); } @Test void testMethodNotSupported() throws Exception { mockMvc .perform(post("/api/exception-translator-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' is not supported")); } @Test void testExceptionWithResponseStatus() throws Exception { mockMvc .perform(get("/api/exception-translator-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 void testInternalServerError() throws Exception { mockMvc .perform(get("/api/exception-translator-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")); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/ApplicationWebXml.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/ApplicationWebXml.java
package com.cars.app; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import tech.jhipster.config.DefaultProfileUtil; /** * This is a helper Java class that provides an alternative to creating a {@code web.xml}. * This will be invoked only when the application is deployed to a Servlet container like Tomcat, JBoss etc. */ public class ApplicationWebXml extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { // set a default to use when no profile is configured. DefaultProfileUtil.addDefaultProfile(application.application()); return application.sources(CarsappApp.class); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/CarsappApp.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/CarsappApp.java
package com.cars.app; import com.cars.app.config.ApplicationProperties; import com.cars.app.config.CRLFLogConverter; import jakarta.annotation.PostConstruct; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Collection; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.core.env.Environment; import tech.jhipster.config.DefaultProfileUtil; import tech.jhipster.config.JHipsterConstants; @SpringBootApplication @EnableConfigurationProperties({ LiquibaseProperties.class, ApplicationProperties.class }) public class CarsappApp { private static final Logger log = LoggerFactory.getLogger(CarsappApp.class); private final Environment env; public CarsappApp(Environment env) { this.env = env; } /** * Initializes carsapp. * <p> * Spring profiles can be configured with a program argument --spring.profiles.active=your-active-profile * <p> * You can find more information on how profiles work with JHipster on <a href="https://www.jhipster.tech/profiles/">https://www.jhipster.tech/profiles/</a>. */ @PostConstruct public void initApplication() { Collection<String> 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_CLOUD) ) { log.error( "You have misconfigured your application! It should not " + "run with both the 'dev' and 'cloud' profiles at the same time." ); } } /** * Main method, used to run the application. * * @param args the command line arguments. */ public static void main(String[] args) { SpringApplication app = new SpringApplication(CarsappApp.class); DefaultProfileUtil.addDefaultProfile(app); Environment env = app.run(args).getEnvironment(); logApplicationStartup(env); } private static void logApplicationStartup(Environment env) { String protocol = Optional.ofNullable(env.getProperty("server.ssl.key-store")).map(key -> "https").orElse("http"); String applicationName = env.getProperty("spring.application.name"); String serverPort = env.getProperty("server.port"); String contextPath = Optional.ofNullable(env.getProperty("server.servlet.context-path")) .filter(StringUtils::isNotBlank) .orElse("/"); String hostAddress = "localhost"; try { hostAddress = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { log.warn("The host name could not be determined, using `localhost` as fallback"); } log.info( CRLFLogConverter.CRLF_SAFE_MARKER, """ ---------------------------------------------------------- \tApplication '{}' is running! Access URLs: \tLocal: \t\t{}://localhost:{}{} \tExternal: \t{}://{}:{}{} \tProfile(s): \t{} ----------------------------------------------------------""", applicationName, protocol, serverPort, contextPath, protocol, hostAddress, serverPort, contextPath, env.getActiveProfiles().length == 0 ? env.getDefaultProfiles() : env.getActiveProfiles() ); String configServerStatus = env.getProperty("configserver.status"); if (configServerStatus == null) { configServerStatus = "Not found or not setup for this application"; } log.info( CRLFLogConverter.CRLF_SAFE_MARKER, "\n----------------------------------------------------------\n\t" + "Config Server: \t{}\n----------------------------------------------------------", configServerStatus ); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/package-info.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/package-info.java
/** * Application root. */ package com.cars.app;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/GeneratedByJHipster.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/GeneratedByJHipster.java
package com.cars.app; import jakarta.annotation.Generated; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Generated(value = "JHipster", comments = "Generated by JHipster 8.4.0") @Retention(RetentionPolicy.SOURCE) @Target({ ElementType.TYPE }) public @interface GeneratedByJHipster { }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/management/package-info.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/management/package-info.java
/** * Application management. */ package com.cars.app.management;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/management/SecurityMetersService.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/management/SecurityMetersService.java
package com.cars.app.management; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import org.springframework.stereotype.Service; @Service public class SecurityMetersService { public static final String INVALID_TOKENS_METER_NAME = "security.authentication.invalid-tokens"; public static final String INVALID_TOKENS_METER_DESCRIPTION = "Indicates validation error count of the tokens presented by the clients."; public static final String INVALID_TOKENS_METER_BASE_UNIT = "errors"; public static final String INVALID_TOKENS_METER_CAUSE_DIMENSION = "cause"; private final Counter tokenInvalidSignatureCounter; private final Counter tokenExpiredCounter; private final Counter tokenUnsupportedCounter; private final Counter tokenMalformedCounter; public SecurityMetersService(MeterRegistry registry) { this.tokenInvalidSignatureCounter = invalidTokensCounterForCauseBuilder("invalid-signature").register(registry); this.tokenExpiredCounter = invalidTokensCounterForCauseBuilder("expired").register(registry); this.tokenUnsupportedCounter = invalidTokensCounterForCauseBuilder("unsupported").register(registry); this.tokenMalformedCounter = invalidTokensCounterForCauseBuilder("malformed").register(registry); } private Counter.Builder invalidTokensCounterForCauseBuilder(String cause) { return Counter.builder(INVALID_TOKENS_METER_NAME) .baseUnit(INVALID_TOKENS_METER_BASE_UNIT) .description(INVALID_TOKENS_METER_DESCRIPTION) .tag(INVALID_TOKENS_METER_CAUSE_DIMENSION, cause); } public void trackTokenInvalidSignature() { this.tokenInvalidSignatureCounter.increment(); } public void trackTokenExpired() { this.tokenExpiredCounter.increment(); } public void trackTokenUnsupported() { this.tokenUnsupportedCounter.increment(); } public void trackTokenMalformed() { this.tokenMalformedCounter.increment(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/aop/logging/package-info.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/aop/logging/package-info.java
/** * Logging aspect. */ package com.cars.app.aop.logging;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/aop/logging/LoggingAspect.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/aop/logging/LoggingAspect.java
package com.cars.app.aop.logging; import java.util.Arrays; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; import org.springframework.core.env.Profiles; import tech.jhipster.config.JHipsterConstants; /** * Aspect for logging execution of service and repository Spring components. * * By default, it only runs with the "dev" profile. */ @Aspect public class LoggingAspect { private final Environment env; public LoggingAspect(Environment env) { this.env = env; } /** * 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 *)" ) public void springBeanPointcut() { // Method is empty as this is just a Pointcut, the implementations are in the advices. } /** * Pointcut that matches all Spring beans in the application's main packages. */ @Pointcut("within(com.cars.app.repository..*)" + " || within(com.cars.app.service..*)" + " || within(com.cars.app.web.rest..*)") public void applicationPackagePointcut() { // Method is empty as this is just a Pointcut, the implementations are in the advices. } /** * Retrieves the {@link Logger} associated to the given {@link JoinPoint}. * * @param joinPoint join point we want the logger for. * @return {@link Logger} associated to the given {@link JoinPoint}. */ private Logger logger(JoinPoint joinPoint) { return LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringTypeName()); } /** * Advice that logs methods throwing exceptions. * * @param joinPoint join point for advice. * @param e exception. */ @AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) { logger(joinPoint).error( "Exception in {}() with cause = '{}' and exception = '{}'", joinPoint.getSignature().getName(), e.getCause() != null ? e.getCause() : "NULL", e.getMessage(), e ); } else { logger(joinPoint).error( "Exception in {}() with cause = {}", joinPoint.getSignature().getName(), e.getCause() != null ? String.valueOf(e.getCause()) : "NULL" ); } } /** * Advice that logs when a method is entered and exited. * * @param joinPoint join point for advice. * @return result. * @throws Throwable throws {@link IllegalArgumentException}. */ @Around("applicationPackagePointcut() && springBeanPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { Logger log = logger(joinPoint); if (log.isDebugEnabled()) { log.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); } try { Object result = joinPoint.proceed(); if (log.isDebugEnabled()) { log.debug("Exit: {}() with result = {}", joinPoint.getSignature().getName(), result); } return result; } catch (IllegalArgumentException e) { log.error("Illegal argument: {} in {}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getName()); throw e; } } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/domain/package-info.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/domain/package-info.java
/** * Domain objects. */ package com.cars.app.domain;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/domain/Car.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/domain/Car.java
package com.cars.app.domain; import jakarta.persistence.*; import java.io.Serializable; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; /** * A Car. */ @Entity @Table(name = "car") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @SuppressWarnings("common-java:DuplicatedBlocks") public class Car implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") @SequenceGenerator(name = "sequenceGenerator") @Column(name = "id") private Long id; @Column(name = "price") private Double price; // jhipster-needle-entity-add-field - JHipster will add fields here public Long getId() { return this.id; } public Car id(Long id) { this.setId(id); return this; } public void setId(Long id) { this.id = id; } public Double getPrice() { return this.price; } public Car price(Double price) { this.setPrice(price); return this; } public void setPrice(Double price) { this.price = price; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Car)) { return false; } return getId() != null && getId().equals(((Car) o).getId()); } @Override public int hashCode() { // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ return getClass().hashCode(); } // prettier-ignore @Override public String toString() { return "Car{" + "id=" + getId() + ", price=" + getPrice() + "}"; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/domain/AbstractAuditingEntity.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/domain/AbstractAuditingEntity.java
package com.cars.app.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import jakarta.persistence.Column; import jakarta.persistence.EntityListeners; import jakarta.persistence.MappedSuperclass; import java.io.Serializable; import java.time.Instant; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; /** * Base abstract class for entities which will hold definitions for created, last modified, created by, * last modified by attributes. */ @MappedSuperclass @EntityListeners(AuditingEntityListener.class) @JsonIgnoreProperties(value = { "createdBy", "createdDate", "lastModifiedBy", "lastModifiedDate" }, allowGetters = true) public abstract class AbstractAuditingEntity<T> implements Serializable { private static final long serialVersionUID = 1L; public abstract T getId(); @CreatedBy @Column(name = "created_by", nullable = false, length = 50, updatable = false) private String createdBy; @CreatedDate @Column(name = "created_date", updatable = false) private Instant createdDate = Instant.now(); @LastModifiedBy @Column(name = "last_modified_by", length = 50) private String lastModifiedBy; @LastModifiedDate @Column(name = "last_modified_date") private Instant lastModifiedDate = Instant.now(); public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Instant getCreatedDate() { return createdDate; } public void setCreatedDate(Instant createdDate) { this.createdDate = createdDate; } public String getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public Instant getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(Instant lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/repository/package-info.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/repository/package-info.java
/** * Repository layer. */ package com.cars.app.repository;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/repository/CarRepository.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/repository/CarRepository.java
package com.cars.app.repository; import com.cars.app.domain.Car; import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; /** * Spring Data JPA repository for the Car entity. */ @SuppressWarnings("unused") @Repository public interface CarRepository extends JpaRepository<Car, Long> {}
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/security/package-info.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/security/package-info.java
/** * Application security utilities. */ package com.cars.app.security;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/security/SpringSecurityAuditorAware.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/security/SpringSecurityAuditorAware.java
package com.cars.app.security; import com.cars.app.config.Constants; import java.util.Optional; import org.springframework.data.domain.AuditorAware; import org.springframework.stereotype.Component; /** * Implementation of {@link AuditorAware} based on Spring Security. */ @Component public class SpringSecurityAuditorAware implements AuditorAware<String> { @Override public Optional<String> getCurrentAuditor() { return Optional.of(SecurityUtils.getCurrentUserLogin().orElse(Constants.SYSTEM)); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/security/SecurityUtils.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/security/SecurityUtils.java
package com.cars.app.security; import java.util.Arrays; import java.util.Optional; import java.util.stream.Stream; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.oauth2.jose.jws.MacAlgorithm; import org.springframework.security.oauth2.jwt.Jwt; /** * Utility class for Spring Security. */ public final class SecurityUtils { public static final MacAlgorithm JWT_ALGORITHM = MacAlgorithm.HS512; public static final String AUTHORITIES_KEY = "auth"; private SecurityUtils() {} /** * Get the login of the current user. * * @return the login of the current user. */ public static Optional<String> getCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(extractPrincipal(securityContext.getAuthentication())); } private static String extractPrincipal(Authentication authentication) { if (authentication == null) { return null; } else if (authentication.getPrincipal() instanceof UserDetails springSecurityUser) { return springSecurityUser.getUsername(); } else if (authentication.getPrincipal() instanceof Jwt jwt) { return jwt.getSubject(); } else if (authentication.getPrincipal() instanceof String s) { return s; } return null; } /** * Get the JWT of the current user. * * @return the JWT of the current user. */ public static Optional<String> getCurrentUserJWT() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .filter(authentication -> authentication.getCredentials() instanceof String) .map(authentication -> (String) authentication.getCredentials()); } /** * Check if a user is authenticated. * * @return true if the user is authenticated, false otherwise. */ public static boolean isAuthenticated() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return authentication != null && getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals); } /** * Checks if the current user has any of the authorities. * * @param authorities the authorities to check. * @return true if the current user has any of the authorities, false otherwise. */ public static boolean hasCurrentUserAnyOfAuthorities(String... authorities) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return ( authentication != null && getAuthorities(authentication).anyMatch(authority -> Arrays.asList(authorities).contains(authority)) ); } /** * Checks if the current user has none of the authorities. * * @param authorities the authorities to check. * @return true if the current user has none of the authorities, false otherwise. */ public static boolean hasCurrentUserNoneOfAuthorities(String... authorities) { return !hasCurrentUserAnyOfAuthorities(authorities); } /** * Checks if the current user has a specific authority. * * @param authority the authority to check. * @return true if the current user has the authority, false otherwise. */ public static boolean hasCurrentUserThisAuthority(String authority) { return hasCurrentUserAnyOfAuthorities(authority); } private static Stream<String> getAuthorities(Authentication authentication) { return authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/security/AuthoritiesConstants.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/security/AuthoritiesConstants.java
package com.cars.app.security; /** * Constants for Spring Security authorities. */ public final class AuthoritiesConstants { public static final String ADMIN = "ROLE_ADMIN"; public static final String USER = "ROLE_USER"; public static final String ANONYMOUS = "ROLE_ANONYMOUS"; private AuthoritiesConstants() {} }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/SecurityConfiguration.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/SecurityConfiguration.java
package com.cars.app.config; import static org.springframework.security.config.Customizer.withDefaults; import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; import com.cars.app.security.*; import com.cars.app.web.filter.SpaWebFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.env.Profiles; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer.FrameOptionsConfig; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint; import org.springframework.security.oauth2.server.resource.web.access.BearerTokenAccessDeniedHandler; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter; import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher; import org.springframework.web.servlet.handler.HandlerMappingIntrospector; import tech.jhipster.config.JHipsterConstants; import tech.jhipster.config.JHipsterProperties; @Configuration @EnableMethodSecurity(securedEnabled = true) public class SecurityConfiguration { private final Environment env; private final JHipsterProperties jHipsterProperties; public SecurityConfiguration(Environment env, JHipsterProperties jHipsterProperties) { this.env = env; this.jHipsterProperties = jHipsterProperties; } @Bean public SecurityFilterChain filterChain(HttpSecurity http, MvcRequestMatcher.Builder mvc) throws Exception { http .csrf(csrf -> csrf.disable()) .addFilterAfter(new SpaWebFilter(), BasicAuthenticationFilter.class) .headers( headers -> headers .contentSecurityPolicy(csp -> csp.policyDirectives(jHipsterProperties.getSecurity().getContentSecurityPolicy())) .frameOptions(FrameOptionsConfig::sameOrigin) .referrerPolicy( referrer -> referrer.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN) ) .permissionsPolicy( permissions -> permissions.policy( "camera=(), fullscreen=(self), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), sync-xhr=()" ) ) ) .authorizeHttpRequests( authz -> // prettier-ignore authz .requestMatchers(mvc.pattern("/index.html"), mvc.pattern("/*.js"), mvc.pattern("/*.txt"), mvc.pattern("/*.json"), mvc.pattern("/*.map"), mvc.pattern("/*.css")).permitAll() .requestMatchers(mvc.pattern("/*.ico"), mvc.pattern("/*.png"), mvc.pattern("/*.svg"), mvc.pattern("/*.webapp")).permitAll() .requestMatchers(mvc.pattern("/app/**")).permitAll() .requestMatchers(mvc.pattern("/i18n/**")).permitAll() .requestMatchers(mvc.pattern("/content/**")).permitAll() .requestMatchers(mvc.pattern("/swagger-ui/**")).permitAll() .requestMatchers(mvc.pattern(HttpMethod.POST, "/api/authenticate")).permitAll() .requestMatchers(mvc.pattern(HttpMethod.GET, "/api/authenticate")).permitAll() .requestMatchers(mvc.pattern("/api/admin/**")).hasAuthority(AuthoritiesConstants.ADMIN) .requestMatchers(mvc.pattern("/api/**")).authenticated() .requestMatchers(mvc.pattern("/v3/api-docs/**")).hasAuthority(AuthoritiesConstants.ADMIN) .requestMatchers(mvc.pattern("/management/health")).permitAll() .requestMatchers(mvc.pattern("/management/health/**")).permitAll() .requestMatchers(mvc.pattern("/management/info")).permitAll() .requestMatchers(mvc.pattern("/management/prometheus")).permitAll() .requestMatchers(mvc.pattern("/management/**")).hasAuthority(AuthoritiesConstants.ADMIN) ) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .exceptionHandling( exceptions -> exceptions .authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint()) .accessDeniedHandler(new BearerTokenAccessDeniedHandler()) ) .oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults())); if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) { http.authorizeHttpRequests(authz -> authz.requestMatchers(antMatcher("/h2-console/**")).permitAll()); } return http.build(); } @Bean MvcRequestMatcher.Builder mvc(HandlerMappingIntrospector introspector) { return new MvcRequestMatcher.Builder(introspector); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/ApplicationProperties.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/ApplicationProperties.java
package com.cars.app.config; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Properties specific to Carsapp. * <p> * Properties are configured in the {@code application.yml} file. * See {@link tech.jhipster.config.JHipsterProperties} for a good example. */ @ConfigurationProperties(prefix = "application", ignoreUnknownFields = false) public class ApplicationProperties { private final Liquibase liquibase = new Liquibase(); // jhipster-needle-application-properties-property public Liquibase getLiquibase() { return liquibase; } // jhipster-needle-application-properties-property-getter public static class Liquibase { private Boolean asyncStart; public Boolean getAsyncStart() { return asyncStart; } public void setAsyncStart(Boolean asyncStart) { this.asyncStart = asyncStart; } } // jhipster-needle-application-properties-property-class }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/DatabaseConfiguration.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/DatabaseConfiguration.java
package com.cars.app.config; import java.sql.SQLException; 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; import org.springframework.transaction.annotation.EnableTransactionManagement; import tech.jhipster.config.JHipsterConstants; import tech.jhipster.config.h2.H2ConfigurationHelper; @Configuration @EnableJpaRepositories({ "com.cars.app.repository" }) @EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware") @EnableTransactionManagement public class DatabaseConfiguration { private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class); private final Environment env; public DatabaseConfiguration(Environment env) { this.env = env; } /** * Open the TCP port for the H2 database, so it is available remotely. * * @return the H2 database TCP server. * @throws SQLException if the server failed to start. */ @Bean(initMethod = "start", destroyMethod = "stop") @Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) public Object h2TCPServer() throws SQLException { String port = getValidPortForH2(); 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) { port = 10000 + port; } else { if (port < 63536) { port = port + 2000; } else { port = port - 2000; } } return String.valueOf(port); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/CacheConfiguration.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/CacheConfiguration.java
package com.cars.app.config; import com.hazelcast.config.*; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import jakarta.annotation.PreDestroy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.info.BuildProperties; import org.springframework.boot.info.GitProperties; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.context.annotation.*; import org.springframework.core.env.Environment; import org.springframework.core.env.Profiles; import tech.jhipster.config.JHipsterConstants; import tech.jhipster.config.JHipsterProperties; import tech.jhipster.config.cache.PrefixedKeyGenerator; @Configuration @EnableCaching public class CacheConfiguration { private GitProperties gitProperties; private BuildProperties buildProperties; private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class); private final Environment env; private final ServerProperties serverProperties; private final DiscoveryClient discoveryClient; private Registration registration; public CacheConfiguration(Environment env, ServerProperties serverProperties, DiscoveryClient discoveryClient) { this.env = env; this.serverProperties = serverProperties; this.discoveryClient = discoveryClient; } @Autowired(required = false) public void setRegistration(Registration registration) { this.registration = registration; } @PreDestroy public void destroy() { log.info("Closing Cache Manager"); Hazelcast.shutdownAll(); } @Bean public CacheManager cacheManager(HazelcastInstance hazelcastInstance) { log.debug("Starting HazelcastCacheManager"); return new com.hazelcast.spring.cache.HazelcastCacheManager(hazelcastInstance); } @Bean public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) { log.debug("Configuring Hazelcast"); HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("carsapp"); if (hazelCastInstance != null) { log.debug("Hazelcast already initialized"); return hazelCastInstance; } Config config = new Config(); config.setInstanceName("carsapp"); config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); if (this.registration == null) { log.warn("No discovery service is set up, Hazelcast cannot create a cluster."); } else { // The serviceId is by default the application's name, // see the "spring.application.name" standard Spring property String serviceId = registration.getServiceId(); log.debug("Configuring Hazelcast clustering for instanceId: {}", serviceId); // In development, everything goes through 127.0.0.1, with a different port if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) { log.debug( "Application is running with the \"dev\" profile, Hazelcast " + "cluster will only work with localhost instances" ); config.getNetworkConfig().setPort(serverProperties.getPort() + 5701); config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true); for (ServiceInstance instance : discoveryClient.getInstances(serviceId)) { String clusterMember = "127.0.0.1:" + (instance.getPort() + 5701); log.debug("Adding Hazelcast (dev) cluster member {}", clusterMember); config.getNetworkConfig().getJoin().getTcpIpConfig().addMember(clusterMember); } } else { // Production configuration, one host per instance all using port 5701 config.getNetworkConfig().setPort(5701); config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true); for (ServiceInstance instance : discoveryClient.getInstances(serviceId)) { String clusterMember = instance.getHost() + ":5701"; log.debug("Adding Hazelcast (prod) cluster member {}", clusterMember); config.getNetworkConfig().getJoin().getTcpIpConfig().addMember(clusterMember); } } } config.setManagementCenterConfig(new ManagementCenterConfig()); config.addMapConfig(initializeDefaultMapConfig(jHipsterProperties)); config.addMapConfig(initializeDomainMapConfig(jHipsterProperties)); return Hazelcast.newHazelcastInstance(config); } private MapConfig initializeDefaultMapConfig(JHipsterProperties jHipsterProperties) { MapConfig mapConfig = new MapConfig("default"); /* Number of backups. If 1 is set as the backup-count for example, then all entries of the map will be copied to another JVM for fail-safety. Valid numbers are 0 (no backup), 1, 2, 3. */ mapConfig.setBackupCount(jHipsterProperties.getCache().getHazelcast().getBackupCount()); /* Valid values are: NONE (no eviction), LRU (Least Recently Used), LFU (Least Frequently Used). NONE is the default. */ mapConfig.getEvictionConfig().setEvictionPolicy(EvictionPolicy.LRU); /* Maximum size of the map. When max size is reached, map is evicted based on the policy defined. Any integer between 0 and Integer.MAX_VALUE. 0 means Integer.MAX_VALUE. Default is 0. */ mapConfig.getEvictionConfig().setMaxSizePolicy(MaxSizePolicy.USED_HEAP_SIZE); return mapConfig; } private MapConfig initializeDomainMapConfig(JHipsterProperties jHipsterProperties) { MapConfig mapConfig = new MapConfig("com.cars.app.domain.*"); mapConfig.setTimeToLiveSeconds(jHipsterProperties.getCache().getHazelcast().getTimeToLiveSeconds()); return mapConfig; } @Autowired(required = false) public void setGitProperties(GitProperties gitProperties) { this.gitProperties = gitProperties; } @Autowired(required = false) public void setBuildProperties(BuildProperties buildProperties) { this.buildProperties = buildProperties; } @Bean public KeyGenerator keyGenerator() { return new PrefixedKeyGenerator(this.gitProperties, this.buildProperties); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/package-info.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/package-info.java
/** * Application configuration. */ package com.cars.app.config;
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/DateTimeFormatConfiguration.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/DateTimeFormatConfiguration.java
package com.cars.app.config; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * Configure the converters to use the ISO format for dates by default. */ @Configuration public class DateTimeFormatConfiguration implements WebMvcConfigurer { @Override public void addFormatters(FormatterRegistry registry) { DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); registrar.setUseIsoFormat(true); registrar.registerFormatters(registry); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/CRLFLogConverter.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/CRLFLogConverter.java
package com.cars.app.config; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.pattern.CompositeConverter; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Marker; import org.slf4j.MarkerFactory; import org.springframework.boot.ansi.AnsiColor; import org.springframework.boot.ansi.AnsiElement; import org.springframework.boot.ansi.AnsiOutput; import org.springframework.boot.ansi.AnsiStyle; /** * Log filter to prevent attackers from forging log entries by submitting input containing CRLF characters. * CRLF characters are replaced with a red colored _ character. * * @see <a href="https://owasp.org/www-community/attacks/Log_Injection">Log Forging Description</a> * @see <a href="https://github.com/jhipster/generator-jhipster/issues/14949">JHipster issue</a> */ public class CRLFLogConverter extends CompositeConverter<ILoggingEvent> { public static final Marker CRLF_SAFE_MARKER = MarkerFactory.getMarker("CRLF_SAFE"); private static final String[] SAFE_LOGGERS = { "org.hibernate", "org.springframework.boot.autoconfigure", "org.springframework.boot.diagnostics", }; private static final Map<String, AnsiElement> ELEMENTS; static { Map<String, AnsiElement> ansiElements = new HashMap<>(); ansiElements.put("faint", AnsiStyle.FAINT); ansiElements.put("red", AnsiColor.RED); ansiElements.put("green", AnsiColor.GREEN); ansiElements.put("yellow", AnsiColor.YELLOW); ansiElements.put("blue", AnsiColor.BLUE); ansiElements.put("magenta", AnsiColor.MAGENTA); ansiElements.put("cyan", AnsiColor.CYAN); ELEMENTS = Collections.unmodifiableMap(ansiElements); } @Override protected String transform(ILoggingEvent event, String in) { AnsiElement element = ELEMENTS.get(getFirstOption()); List<Marker> markers = event.getMarkerList(); if ((markers != null && !markers.isEmpty() && markers.get(0).contains(CRLF_SAFE_MARKER)) || isLoggerSafe(event)) { return in; } String replacement = element == null ? "_" : toAnsiString("_", element); return in.replaceAll("[\n\r\t]", replacement); } protected boolean isLoggerSafe(ILoggingEvent event) { for (String safeLogger : SAFE_LOGGERS) { if (event.getLoggerName().startsWith(safeLogger)) { return true; } } return false; } protected String toAnsiString(String in, AnsiElement element) { return AnsiOutput.toString(element, in); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/AsyncConfiguration.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/AsyncConfiguration.java
package com.cars.app.config; import java.util.concurrent.Executor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; import org.springframework.boot.autoconfigure.task.TaskExecutionProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import tech.jhipster.async.ExceptionHandlingAsyncTaskExecutor; @Configuration @EnableAsync @EnableScheduling @Profile("!testdev & !testprod") public class AsyncConfiguration implements AsyncConfigurer { private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class); private final TaskExecutionProperties taskExecutionProperties; public AsyncConfiguration(TaskExecutionProperties taskExecutionProperties) { this.taskExecutionProperties = taskExecutionProperties; } @Override @Bean(name = "taskExecutor") public Executor getAsyncExecutor() { log.debug("Creating Async Task Executor"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(taskExecutionProperties.getPool().getCoreSize()); executor.setMaxPoolSize(taskExecutionProperties.getPool().getMaxSize()); executor.setQueueCapacity(taskExecutionProperties.getPool().getQueueCapacity()); executor.setThreadNamePrefix(taskExecutionProperties.getThreadNamePrefix()); return new ExceptionHandlingAsyncTaskExecutor(executor); } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new SimpleAsyncUncaughtExceptionHandler(); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/WebConfigurer.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/WebConfigurer.java
package com.cars.app.config; import static java.net.URLDecoder.decode; import jakarta.servlet.*; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.web.server.*; import org.springframework.boot.web.servlet.ServletContextInitializer; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.env.Profiles; import org.springframework.util.CollectionUtils; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import tech.jhipster.config.JHipsterConstants; import tech.jhipster.config.JHipsterProperties; import tech.jhipster.config.h2.H2ConfigurationHelper; /** * Configuration of web application with Servlet 3.0 APIs. */ @Configuration public class WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { private final Logger log = LoggerFactory.getLogger(WebConfigurer.class); private final Environment env; private final JHipsterProperties jHipsterProperties; public WebConfigurer(Environment env, JHipsterProperties jHipsterProperties) { this.env = env; this.jHipsterProperties = jHipsterProperties; } @Override public void onStartup(ServletContext servletContext) { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) { initH2Console(servletContext); } log.info("Web application fully configured"); } /** * Customize the Servlet engine: Mime types, the document root, the cache. */ @Override public void customize(WebServerFactory server) { // When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets. setLocationForStaticAssets(server); } private void setLocationForStaticAssets(WebServerFactory server) { if (server instanceof ConfigurableServletWebServerFactory servletWebServer) { File root; String prefixPath = resolvePathPrefix(); root = new File(prefixPath + "target/classes/static/"); if (root.exists() && root.isDirectory()) { servletWebServer.setDocumentRoot(root); } } } /** * Resolve path prefix to static resources. */ private String resolvePathPrefix() { String fullExecutablePath = decode(this.getClass().getResource("").getPath(), StandardCharsets.UTF_8); String rootPath = Paths.get(".").toUri().normalize().getPath(); String extractedPath = fullExecutablePath.replace(rootPath, ""); int extractionEndIndex = extractedPath.indexOf("target/"); if (extractionEndIndex <= 0) { return ""; } return extractedPath.substring(0, extractionEndIndex); } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = jHipsterProperties.getCors(); if (!CollectionUtils.isEmpty(config.getAllowedOrigins()) || !CollectionUtils.isEmpty(config.getAllowedOriginPatterns())) { log.debug("Registering CORS filter"); source.registerCorsConfiguration("/api/**", config); source.registerCorsConfiguration("/management/**", config); source.registerCorsConfiguration("/v3/api-docs", config); source.registerCorsConfiguration("/swagger-ui/**", config); } return new CorsFilter(source); } /** * Initializes H2 console. */ private void initH2Console(ServletContext servletContext) { log.debug("Initialize H2 console"); H2ConfigurationHelper.initH2Console(servletContext); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false
eugenp/tutorials
https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/JacksonConfiguration.java
jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/JacksonConfiguration.java
package com.cars.app.config; import com.fasterxml.jackson.datatype.hibernate6.Hibernate6Module; import com.fasterxml.jackson.datatype.hibernate6.Hibernate6Module.Feature; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class JacksonConfiguration { /** * Support for Java date and time API. * @return the corresponding Jackson module. */ @Bean public JavaTimeModule javaTimeModule() { return new JavaTimeModule(); } @Bean public Jdk8Module jdk8TimeModule() { return new Jdk8Module(); } /* * Support for Hibernate types in Jackson. */ @Bean public Hibernate6Module hibernate6Module() { return new Hibernate6Module().configure(Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS, true); } }
java
MIT
4463e58ffb73fe599bac2479abd84598c6e70a1a
2026-01-04T14:45:57.069771Z
false