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-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/SecurityConfiguration.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/SecurityConfiguration.java | package com.baeldung.jhipster.gateway.config;
import com.baeldung.jhipster.gateway.config.oauth2.OAuth2JwtAccessTokenConverter;
import com.baeldung.jhipster.gateway.config.oauth2.OAuth2Properties;
import com.baeldung.jhipster.gateway.security.oauth2.OAuth2SignatureVerifierClient;
import com.baeldung.jhipster.gateway.security.AuthoritiesConstants;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.loadbalancer.RestTemplateCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.client.RestTemplate;
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends ResourceServerConfigurerAdapter {
private final OAuth2Properties oAuth2Properties;
private final CorsFilter corsFilter;
public SecurityConfiguration(OAuth2Properties oAuth2Properties, CorsFilter corsFilter) {
this.oAuth2Properties = oAuth2Properties;
this.corsFilter = corsFilter;
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf()
.ignoringAntMatchers("/h2-console/**")
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.addFilterBefore(corsFilter, CsrfFilter.class)
.headers()
.frameOptions()
.disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll()
.antMatchers("/management/info").permitAll()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN);
}
@Bean
public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
return new JwtTokenStore(jwtAccessTokenConverter);
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter(OAuth2SignatureVerifierClient signatureVerifierClient) {
return new OAuth2JwtAccessTokenConverter(oAuth2Properties, signatureVerifierClient);
}
@Bean
@Qualifier("loadBalancedRestTemplate")
public RestTemplate loadBalancedRestTemplate(RestTemplateCustomizer customizer) {
RestTemplate restTemplate = new RestTemplate();
customizer.customize(restTemplate);
return restTemplate;
}
@Bean
@Qualifier("vanillaRestTemplate")
public RestTemplate vanillaRestTemplate() {
return new RestTemplate();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/GatewayConfiguration.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/GatewayConfiguration.java | package com.baeldung.jhipster.gateway.config;
import io.github.jhipster.config.JHipsterProperties;
import com.baeldung.jhipster.gateway.gateway.ratelimiting.RateLimitingFilter;
import com.baeldung.jhipster.gateway.gateway.accesscontrol.AccessControlFilter;
import com.baeldung.jhipster.gateway.gateway.responserewriting.SwaggerBasePathRewritingFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GatewayConfiguration {
@Configuration
public static class SwaggerBasePathRewritingConfiguration {
@Bean
public SwaggerBasePathRewritingFilter swaggerBasePathRewritingFilter(){
return new SwaggerBasePathRewritingFilter();
}
}
@Configuration
public static class AccessControlFilterConfiguration {
@Bean
public AccessControlFilter accessControlFilter(RouteLocator routeLocator, JHipsterProperties jHipsterProperties){
return new AccessControlFilter(routeLocator, jHipsterProperties);
}
}
/**
* Configures the Zuul filter that limits the number of API calls per user.
* <p>
* This uses Bucket4J to limit the API calls, see {@link com.baeldung.jhipster.gateway.gateway.ratelimiting.RateLimitingFilter}.
*/
@Configuration
@ConditionalOnProperty("jhipster.gateway.rate-limiting.enabled")
public static class RateLimitingConfiguration {
private final JHipsterProperties jHipsterProperties;
public RateLimitingConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@Bean
public RateLimitingFilter rateLimitingFilter() {
return new RateLimitingFilter(jHipsterProperties);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/ApplicationProperties.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/ApplicationProperties.java | package com.baeldung.jhipster.gateway.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Properties specific to Gateway.
* <p>
* Properties are configured in the application.yml file.
* See {@link io.github.jhipster.config.JHipsterProperties} for a good example.
*/
@ConfigurationProperties(prefix = "application", ignoreUnknownFields = false)
public class ApplicationProperties {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/CloudDatabaseConfiguration.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/CloudDatabaseConfiguration.java | package com.baeldung.jhipster.gateway.config;
import io.github.jhipster.config.JHipsterConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cloud.config.java.AbstractCloudConfig;
import org.springframework.context.annotation.*;
import javax.sql.DataSource;
@Configuration
@Profile(JHipsterConstants.SPRING_PROFILE_CLOUD)
public class CloudDatabaseConfiguration extends AbstractCloudConfig {
private final Logger log = LoggerFactory.getLogger(CloudDatabaseConfiguration.class);
@Bean
public DataSource dataSource(CacheManager cacheManager) {
log.info("Configuring JDBC datasource from a cloud provider");
return connectionFactory().dataSource();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/DefaultProfileUtil.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/DefaultProfileUtil.java | package com.baeldung.jhipster.gateway.config;
import io.github.jhipster.config.JHipsterConstants;
import org.springframework.boot.SpringApplication;
import org.springframework.core.env.Environment;
import java.util.*;
/**
* Utility class to load a Spring profile to be used as default
* when there is no <code>spring.profiles.active</code> set in the environment or as command line argument.
* If the value is not available in <code>application.yml</code> then <code>dev</code> profile will be used as default.
*/
public final class DefaultProfileUtil {
private static final String SPRING_PROFILE_DEFAULT = "spring.profiles.default";
private DefaultProfileUtil() {
}
/**
* Set a default to use when no profile is configured.
*
* @param app the Spring application
*/
public static void addDefaultProfile(SpringApplication app) {
Map<String, Object> defProperties = new HashMap<>();
/*
* The default profile to use when no other profiles are defined
* This cannot be set in the <code>application.yml</code> file.
* See https://github.com/spring-projects/spring-boot/issues/1219
*/
defProperties.put(SPRING_PROFILE_DEFAULT, JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
app.setDefaultProperties(defProperties);
}
/**
* Get the profiles that are applied else get default profiles.
*
* @param env spring environment
* @return profiles
*/
public static String[] getActiveProfiles(Environment env) {
String[] profiles = env.getActiveProfiles();
if (profiles.length == 0) {
return env.getDefaultProfiles();
}
return profiles;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/DatabaseConfiguration.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/DatabaseConfiguration.java | package com.baeldung.jhipster.gateway.config;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.h2.H2ConfigurationHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.sql.SQLException;
@Configuration
@EnableJpaRepositories("com.baeldung.jhipster.gateway.repository")
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement
public class DatabaseConfiguration {
private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);
/**
* 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 {
log.debug("Starting H2 database");
return H2ConfigurationHelper.createServer();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/CacheConfiguration.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/CacheConfiguration.java | package com.baeldung.jhipster.gateway.config;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.JHipsterProperties;
import com.hazelcast.config.*;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.Hazelcast;
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.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
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 javax.annotation.PreDestroy;
@Configuration
@EnableCaching
public class CacheConfiguration {
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");
CacheManager cacheManager = new com.hazelcast.spring.cache.HazelcastCacheManager(hazelcastInstance);
return cacheManager;
}
@Bean
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
log.debug("Configuring Hazelcast");
HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("gateway");
if (hazelCastInstance != null) {
log.debug("Hazelcast already initialized");
return hazelCastInstance;
}
Config config = new Config();
config.setInstanceName("gateway");
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(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
log.debug("Application is running with the \"dev\" profile, Hazelcast " +
"cluster will only work with localhost instances");
System.setProperty("hazelcast.local.localAddress", "127.0.0.1");
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.getMapConfigs().put("default", initializeDefaultMapConfig(jHipsterProperties));
// Full reference is available at: http://docs.hazelcast.org/docs/management-center/3.9/manual/html/Deploying_and_Starting.html
config.setManagementCenterConfig(initializeDefaultManagementCenterConfig(jHipsterProperties));
config.getMapConfigs().put("com.baeldung.jhipster.gateway.domain.*", initializeDomainMapConfig(jHipsterProperties));
return Hazelcast.newHazelcastInstance(config);
}
private ManagementCenterConfig initializeDefaultManagementCenterConfig(JHipsterProperties jHipsterProperties) {
ManagementCenterConfig managementCenterConfig = new ManagementCenterConfig();
managementCenterConfig.setEnabled(jHipsterProperties.getCache().getHazelcast().getManagementCenter().isEnabled());
managementCenterConfig.setUrl(jHipsterProperties.getCache().getHazelcast().getManagementCenter().getUrl());
managementCenterConfig.setUpdateInterval(jHipsterProperties.getCache().getHazelcast().getManagementCenter().getUpdateInterval());
return managementCenterConfig;
}
private MapConfig initializeDefaultMapConfig(JHipsterProperties jHipsterProperties) {
MapConfig mapConfig = new MapConfig();
/*
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.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.setMaxSizeConfig(new MaxSizeConfig(0, MaxSizeConfig.MaxSizePolicy.USED_HEAP_SIZE));
return mapConfig;
}
private MapConfig initializeDomainMapConfig(JHipsterProperties jHipsterProperties) {
MapConfig mapConfig = new MapConfig();
mapConfig.setTimeToLiveSeconds(jHipsterProperties.getCache().getHazelcast().getTimeToLiveSeconds());
return mapConfig;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/package-info.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/package-info.java | /**
* Spring Framework configuration files.
*/
package com.baeldung.jhipster.gateway.config;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/DateTimeFormatConfiguration.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/DateTimeFormatConfiguration.java | package com.baeldung.jhipster.gateway.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-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/AsyncConfiguration.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/AsyncConfiguration.java | package com.baeldung.jhipster.gateway.config;
import io.github.jhipster.async.ExceptionHandlingAsyncTaskExecutor;
import io.github.jhipster.config.JHipsterProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.*;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer, SchedulingConfigurer {
private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);
private final JHipsterProperties jHipsterProperties;
public AsyncConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
log.debug("Creating Async Task Executor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(jHipsterProperties.getAsync().getCorePoolSize());
executor.setMaxPoolSize(jHipsterProperties.getAsync().getMaxPoolSize());
executor.setQueueCapacity(jHipsterProperties.getAsync().getQueueCapacity());
executor.setThreadNamePrefix("gateway-Executor-");
return new ExceptionHandlingAsyncTaskExecutor(executor);
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(scheduledTaskExecutor());
}
@Bean
public Executor scheduledTaskExecutor() {
return Executors.newScheduledThreadPool(jHipsterProperties.getAsync().getCorePoolSize());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/WebConfigurer.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/WebConfigurer.java | package com.baeldung.jhipster.gateway.config;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.servlet.InstrumentedFilter;
import com.codahale.metrics.servlets.MetricsServlet;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.JHipsterProperties;
import io.github.jhipster.config.h2.H2ConfigurationHelper;
import io.github.jhipster.web.filter.CachingHttpHeadersFilter;
import io.undertow.UndertowOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.*;
import org.springframework.boot.web.servlet.ServletContextInitializer;
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.http.MediaType;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import javax.servlet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.*;
import static java.net.URLDecoder.decode;
/**
* 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;
private MetricRegistry metricRegistry;
public WebConfigurer(Environment env, JHipsterProperties jHipsterProperties) {
this.env = env;
this.jHipsterProperties = jHipsterProperties;
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
if (env.getActiveProfiles().length != 0) {
log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles());
}
EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
initMetrics(servletContext, disps);
if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) {
initCachingHttpHeadersFilter(servletContext, disps);
}
if (env.acceptsProfiles(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) {
setMimeMappings(server);
// When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets.
setLocationForStaticAssets(server);
/*
* Enable HTTP/2 for Undertow - https://twitter.com/ankinson/status/829256167700492288
* HTTP/2 requires HTTPS, so HTTP requests will fallback to HTTP/1.1.
* See the JHipsterProperties class and your application-*.yml configuration files
* for more information.
*/
if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) &&
server instanceof UndertowServletWebServerFactory) {
((UndertowServletWebServerFactory) server)
.addBuilderCustomizers(builder ->
builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true));
}
}
private void setMimeMappings(WebServerFactory server) {
if (server instanceof ConfigurableServletWebServerFactory) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
// IE issue, see https://github.com/jhipster/generator-jhipster/pull/711
mappings.add("html", MediaType.TEXT_HTML_VALUE + ";charset=" + StandardCharsets.UTF_8.name().toLowerCase());
// CloudFoundry issue, see https://github.com/cloudfoundry/gorouter/issues/64
mappings.add("json", MediaType.TEXT_HTML_VALUE + ";charset=" + StandardCharsets.UTF_8.name().toLowerCase());
ConfigurableServletWebServerFactory servletWebServer = (ConfigurableServletWebServerFactory) server;
servletWebServer.setMimeMappings(mappings);
}
}
private void setLocationForStaticAssets(WebServerFactory server) {
if (server instanceof ConfigurableServletWebServerFactory) {
ConfigurableServletWebServerFactory servletWebServer = (ConfigurableServletWebServerFactory) server;
File root;
String prefixPath = resolvePathPrefix();
root = new File(prefixPath + "target/www/");
if (root.exists() && root.isDirectory()) {
servletWebServer.setDocumentRoot(root);
}
}
}
/**
* Resolve path prefix to static resources.
*/
private String resolvePathPrefix() {
String fullExecutablePath;
try {
fullExecutablePath = decode(this.getClass().getResource("").getPath(), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
/* try without decoding if this ever happens */
fullExecutablePath = this.getClass().getResource("").getPath();
}
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);
}
/**
* Initializes the caching HTTP Headers Filter.
*/
private void initCachingHttpHeadersFilter(ServletContext servletContext,
EnumSet<DispatcherType> disps) {
log.debug("Registering Caching HTTP Headers Filter");
FilterRegistration.Dynamic cachingHttpHeadersFilter =
servletContext.addFilter("cachingHttpHeadersFilter",
new CachingHttpHeadersFilter(jHipsterProperties));
cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/i18n/*");
cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/content/*");
cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/app/*");
cachingHttpHeadersFilter.setAsyncSupported(true);
}
/**
* Initializes Metrics.
*/
private void initMetrics(ServletContext servletContext, EnumSet<DispatcherType> disps) {
log.debug("Initializing Metrics registries");
servletContext.setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE,
metricRegistry);
servletContext.setAttribute(MetricsServlet.METRICS_REGISTRY,
metricRegistry);
log.debug("Registering Metrics Filter");
FilterRegistration.Dynamic metricsFilter = servletContext.addFilter("webappMetricsFilter",
new InstrumentedFilter());
metricsFilter.addMappingForUrlPatterns(disps, true, "/*");
metricsFilter.setAsyncSupported(true);
log.debug("Registering Metrics Servlet");
ServletRegistration.Dynamic metricsAdminServlet =
servletContext.addServlet("metricsServlet", new MetricsServlet());
metricsAdminServlet.addMapping("/management/metrics/*");
metricsAdminServlet.setAsyncSupported(true);
metricsAdminServlet.setLoadOnStartup(2);
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = jHipsterProperties.getCors();
if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
log.debug("Registering CORS filter");
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/management/**", config);
source.registerCorsConfiguration("/v2/api-docs", config);
source.registerCorsConfiguration("/auth/**", config);
source.registerCorsConfiguration("/*/api/**", config);
source.registerCorsConfiguration("/*/management/**", config);
source.registerCorsConfiguration("/*/oauth/**", config);
}
return new CorsFilter(source);
}
/**
* Initializes H2 console.
*/
private void initH2Console(ServletContext servletContext) {
log.debug("Initialize H2 console");
H2ConfigurationHelper.initH2Console(servletContext);
}
@Autowired(required = false)
public void setMetricRegistry(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/JacksonConfiguration.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/JacksonConfiguration.java | package com.baeldung.jhipster.gateway.config;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zalando.problem.ProblemModule;
import org.zalando.problem.violations.ConstraintViolationProblemModule;
@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 Hibernate5Module hibernate5Module() {
return new Hibernate5Module();
}
/*
* Jackson Afterburner module to speed up serialization/deserialization.
*/
@Bean
public AfterburnerModule afterburnerModule() {
return new AfterburnerModule();
}
/*
* Module for serialization/deserialization of RFC7807 Problem.
*/
@Bean
ProblemModule problemModule() {
return new ProblemModule();
}
/*
* Module for serialization/deserialization of ConstraintViolationProblem.
*/
@Bean
ConstraintViolationProblemModule constraintViolationProblemModule() {
return new ConstraintViolationProblemModule();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/LoggingConfiguration.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/LoggingConfiguration.java | package com.baeldung.jhipster.gateway.config;
import java.net.InetSocketAddress;
import java.util.Iterator;
import io.github.jhipster.config.JHipsterProperties;
import ch.qos.logback.classic.AsyncAppender;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.boolex.OnMarkerEvaluator;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.filter.EvaluatorFilter;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.spi.FilterReply;
import net.logstash.logback.appender.LogstashTcpSocketAppender;
import net.logstash.logback.encoder.LogstashEncoder;
import net.logstash.logback.stacktrace.ShortenedThrowableConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
@Configuration
@RefreshScope
public class LoggingConfiguration {
private static final String LOGSTASH_APPENDER_NAME = "LOGSTASH";
private static final String ASYNC_LOGSTASH_APPENDER_NAME = "ASYNC_LOGSTASH";
private final Logger log = LoggerFactory.getLogger(LoggingConfiguration.class);
private LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
private final String appName;
private final String serverPort;
private final String version;
private final JHipsterProperties jHipsterProperties;
public LoggingConfiguration(@Value("${spring.application.name}") String appName, @Value("${server.port}") String serverPort,
@Value("${info.project.version:}") String version, JHipsterProperties jHipsterProperties) {
this.appName = appName;
this.serverPort = serverPort;
this.version = version;
this.jHipsterProperties = jHipsterProperties;
if (jHipsterProperties.getLogging().getLogstash().isEnabled()) {
addLogstashAppender(context);
addContextListener(context);
}
if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
setMetricsMarkerLogbackFilter(context);
}
}
private void addContextListener(LoggerContext context) {
LogbackLoggerContextListener loggerContextListener = new LogbackLoggerContextListener();
loggerContextListener.setContext(context);
context.addListener(loggerContextListener);
}
private void addLogstashAppender(LoggerContext context) {
log.info("Initializing Logstash logging");
LogstashTcpSocketAppender logstashAppender = new LogstashTcpSocketAppender();
logstashAppender.setName(LOGSTASH_APPENDER_NAME);
logstashAppender.setContext(context);
String optionalFields = "";
String customFields = "{\"app_name\":\"" + appName + "\",\"app_port\":\"" + serverPort + "\"," +
optionalFields + "\"version\":\"" + version + "\"}";
// More documentation is available at: https://github.com/logstash/logstash-logback-encoder
LogstashEncoder logstashEncoder = new LogstashEncoder();
// Set the Logstash appender config from JHipster properties
logstashEncoder.setCustomFields(customFields);
// Set the Logstash appender config from JHipster properties
logstashAppender.addDestinations(new InetSocketAddress(jHipsterProperties.getLogging().getLogstash().getHost(), jHipsterProperties.getLogging().getLogstash().getPort()));
ShortenedThrowableConverter throwableConverter = new ShortenedThrowableConverter();
throwableConverter.setRootCauseFirst(true);
logstashEncoder.setThrowableConverter(throwableConverter);
logstashEncoder.setCustomFields(customFields);
logstashAppender.setEncoder(logstashEncoder);
logstashAppender.start();
// Wrap the appender in an Async appender for performance
AsyncAppender asyncLogstashAppender = new AsyncAppender();
asyncLogstashAppender.setContext(context);
asyncLogstashAppender.setName(ASYNC_LOGSTASH_APPENDER_NAME);
asyncLogstashAppender.setQueueSize(jHipsterProperties.getLogging().getLogstash().getQueueSize());
asyncLogstashAppender.addAppender(logstashAppender);
asyncLogstashAppender.start();
context.getLogger("ROOT").addAppender(asyncLogstashAppender);
}
// Configure a log filter to remove "metrics" logs from all appenders except the "LOGSTASH" appender
private void setMetricsMarkerLogbackFilter(LoggerContext context) {
log.info("Filtering metrics logs from all appenders except the {} appender", LOGSTASH_APPENDER_NAME);
OnMarkerEvaluator onMarkerMetricsEvaluator = new OnMarkerEvaluator();
onMarkerMetricsEvaluator.setContext(context);
onMarkerMetricsEvaluator.addMarker("metrics");
onMarkerMetricsEvaluator.start();
EvaluatorFilter<ILoggingEvent> metricsFilter = new EvaluatorFilter<>();
metricsFilter.setContext(context);
metricsFilter.setEvaluator(onMarkerMetricsEvaluator);
metricsFilter.setOnMatch(FilterReply.DENY);
metricsFilter.start();
for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) {
for (Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders(); it.hasNext();) {
Appender<ILoggingEvent> appender = it.next();
if (!appender.getName().equals(ASYNC_LOGSTASH_APPENDER_NAME)) {
log.debug("Filter metrics logs from the {} appender", appender.getName());
appender.setContext(context);
appender.addFilter(metricsFilter);
appender.start();
}
}
}
}
/**
* Logback configuration is achieved by configuration file and API.
* When configuration file change is detected, the configuration is reset.
* This listener ensures that the programmatic configuration is also re-applied after reset.
*/
class LogbackLoggerContextListener extends ContextAwareBase implements LoggerContextListener {
@Override
public boolean isResetResistant() {
return true;
}
@Override
public void onStart(LoggerContext context) {
addLogstashAppender(context);
}
@Override
public void onReset(LoggerContext context) {
addLogstashAppender(context);
}
@Override
public void onStop(LoggerContext context) {
// Nothing to do.
}
@Override
public void onLevelChange(ch.qos.logback.classic.Logger logger, Level level) {
// Nothing to do.
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/MetricsConfiguration.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/MetricsConfiguration.java | package com.baeldung.jhipster.gateway.config;
import io.github.jhipster.config.JHipsterProperties;
import com.codahale.metrics.JmxReporter;
import com.codahale.metrics.JvmAttributeGaugeSet;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Slf4jReporter;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.codahale.metrics.jvm.*;
import com.ryantenney.metrics.spring.config.annotation.EnableMetrics;
import com.ryantenney.metrics.spring.config.annotation.MetricsConfigurerAdapter;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import javax.annotation.PostConstruct;
import java.lang.management.ManagementFactory;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableMetrics(proxyTargetClass = true)
public class MetricsConfiguration extends MetricsConfigurerAdapter {
private static final String PROP_METRIC_REG_JVM_MEMORY = "jvm.memory";
private static final String PROP_METRIC_REG_JVM_GARBAGE = "jvm.garbage";
private static final String PROP_METRIC_REG_JVM_THREADS = "jvm.threads";
private static final String PROP_METRIC_REG_JVM_FILES = "jvm.files";
private static final String PROP_METRIC_REG_JVM_BUFFERS = "jvm.buffers";
private static final String PROP_METRIC_REG_JVM_ATTRIBUTE_SET = "jvm.attributes";
private final Logger log = LoggerFactory.getLogger(MetricsConfiguration.class);
private MetricRegistry metricRegistry = new MetricRegistry();
private HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();
private final JHipsterProperties jHipsterProperties;
private HikariDataSource hikariDataSource;
public MetricsConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@Autowired(required = false)
public void setHikariDataSource(HikariDataSource hikariDataSource) {
this.hikariDataSource = hikariDataSource;
}
@Override
@Bean
public MetricRegistry getMetricRegistry() {
return metricRegistry;
}
@Override
@Bean
public HealthCheckRegistry getHealthCheckRegistry() {
return healthCheckRegistry;
}
@PostConstruct
public void init() {
log.debug("Registering JVM gauges");
metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet());
metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet());
metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet());
metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge());
metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
metricRegistry.register(PROP_METRIC_REG_JVM_ATTRIBUTE_SET, new JvmAttributeGaugeSet());
if (hikariDataSource != null) {
log.debug("Monitoring the datasource");
// remove the factory created by HikariDataSourceMetricsPostProcessor until JHipster migrate to Micrometer
hikariDataSource.setMetricsTrackerFactory(null);
hikariDataSource.setMetricRegistry(metricRegistry);
}
if (jHipsterProperties.getMetrics().getJmx().isEnabled()) {
log.debug("Initializing Metrics JMX reporting");
JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
jmxReporter.start();
}
if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
log.info("Initializing Metrics Log reporting");
Marker metricsMarker = MarkerFactory.getMarker("metrics");
final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
.outputTo(LoggerFactory.getLogger("metrics"))
.markWith(metricsMarker)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.build();
reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/LiquibaseConfiguration.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/LiquibaseConfiguration.java | package com.baeldung.jhipster.gateway.config;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.task.TaskExecutor;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.liquibase.AsyncSpringLiquibase;
import liquibase.integration.spring.SpringLiquibase;
@Configuration
public class LiquibaseConfiguration {
private final Logger log = LoggerFactory.getLogger(LiquibaseConfiguration.class);
private final Environment env;
private final CacheManager cacheManager;
public LiquibaseConfiguration(Environment env, CacheManager cacheManager) {
this.env = env;
this.cacheManager = cacheManager;
}
@Bean
public SpringLiquibase liquibase(@Qualifier("taskExecutor") TaskExecutor taskExecutor,
DataSource dataSource, LiquibaseProperties liquibaseProperties) {
// Use liquibase.integration.spring.SpringLiquibase if you don't want Liquibase to start asynchronously
SpringLiquibase liquibase = new AsyncSpringLiquibase(taskExecutor, env);
liquibase.setDataSource(dataSource);
liquibase.setChangeLog("classpath:config/liquibase/master.xml");
liquibase.setContexts(liquibaseProperties.getContexts());
liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
liquibase.setDropFirst(liquibaseProperties.isDropFirst());
liquibase.setChangeLogParameters(liquibaseProperties.getParameters());
if (env.acceptsProfiles(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-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/Constants.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/Constants.java | package com.baeldung.jhipster.gateway.config;
/**
* Application constants.
*/
public final class Constants {
// Regex for acceptable logins
public static final String LOGIN_REGEX = "^[_.@A-Za-z0-9-]*$";
public static final String SYSTEM_ACCOUNT = "system";
public static final String ANONYMOUS_USER = "anonymoususer";
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-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/LoggingAspectConfiguration.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/LoggingAspectConfiguration.java | package com.baeldung.jhipster.gateway.config;
import com.baeldung.jhipster.gateway.aop.logging.LoggingAspect;
import io.github.jhipster.config.JHipsterConstants;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
@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-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/LocaleConfiguration.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/LocaleConfiguration.java | package com.baeldung.jhipster.gateway.config;
import io.github.jhipster.config.locale.AngularCookieLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
@Configuration
public class LocaleConfiguration implements WebMvcConfigurer {
@Bean(name = "localeResolver")
public LocaleResolver localeResolver() {
AngularCookieLocaleResolver cookieLocaleResolver = new AngularCookieLocaleResolver();
cookieLocaleResolver.setCookieName("NG_TRANSLATE_LANG_KEY");
return cookieLocaleResolver;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("language");
registry.addInterceptor(localeChangeInterceptor);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/oauth2/OAuth2AuthenticationConfiguration.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/oauth2/OAuth2AuthenticationConfiguration.java | package com.baeldung.jhipster.gateway.config.oauth2;
import com.baeldung.jhipster.gateway.security.oauth2.CookieTokenExtractor;
import com.baeldung.jhipster.gateway.security.oauth2.OAuth2AuthenticationService;
import com.baeldung.jhipster.gateway.security.oauth2.OAuth2CookieHelper;
import com.baeldung.jhipster.gateway.security.oauth2.OAuth2TokenEndpointClient;
import com.baeldung.jhipster.gateway.web.filter.RefreshTokenFilterConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.authentication.TokenExtractor;
import org.springframework.security.oauth2.provider.token.TokenStore;
/**
* Configures the RefreshFilter refreshing expired OAuth2 token Cookies.
*/
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class OAuth2AuthenticationConfiguration extends ResourceServerConfigurerAdapter {
private final OAuth2Properties oAuth2Properties;
private final OAuth2TokenEndpointClient tokenEndpointClient;
private final TokenStore tokenStore;
public OAuth2AuthenticationConfiguration(OAuth2Properties oAuth2Properties, OAuth2TokenEndpointClient tokenEndpointClient, TokenStore tokenStore) {
this.oAuth2Properties = oAuth2Properties;
this.tokenEndpointClient = tokenEndpointClient;
this.tokenStore = tokenStore;
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/auth/login").permitAll()
.antMatchers("/auth/logout").authenticated()
.and()
.apply(refreshTokenSecurityConfigurerAdapter());
}
/**
* A SecurityConfigurerAdapter to install a servlet filter that refreshes OAuth2 tokens.
*/
private RefreshTokenFilterConfigurer refreshTokenSecurityConfigurerAdapter() {
return new RefreshTokenFilterConfigurer(uaaAuthenticationService(), tokenStore);
}
@Bean
public OAuth2CookieHelper cookieHelper() {
return new OAuth2CookieHelper(oAuth2Properties);
}
@Bean
public OAuth2AuthenticationService uaaAuthenticationService() {
return new OAuth2AuthenticationService(tokenEndpointClient, cookieHelper());
}
/**
* Configure the ResourceServer security by installing a new TokenExtractor.
*/
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenExtractor(tokenExtractor());
}
/**
* The new TokenExtractor can extract tokens from Cookies and Authorization headers.
*
* @return the CookieTokenExtractor bean.
*/
@Bean
public TokenExtractor tokenExtractor() {
return new CookieTokenExtractor();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/oauth2/OAuth2Properties.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/oauth2/OAuth2Properties.java | package com.baeldung.jhipster.gateway.config.oauth2;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* OAuth2 properties define properties for OAuth2-based microservices.
*/
@Component
@ConfigurationProperties(prefix = "oauth2", ignoreUnknownFields = false)
public class OAuth2Properties {
private WebClientConfiguration webClientConfiguration = new WebClientConfiguration();
private SignatureVerification signatureVerification = new SignatureVerification();
public WebClientConfiguration getWebClientConfiguration() {
return webClientConfiguration;
}
public SignatureVerification getSignatureVerification() {
return signatureVerification;
}
public static class WebClientConfiguration {
private String clientId = "web_app";
private String secret = "changeit";
/**
* Holds the session timeout in seconds for non-remember-me sessions.
* After so many seconds of inactivity, the session will be terminated.
* Only checked during token refresh, so long access token validity may
* delay the session timeout accordingly.
*/
private int sessionTimeoutInSeconds = 1800;
/**
* Defines the cookie domain. If specified, cookies will be set on this domain.
* If not configured, then cookies will be set on the top-level domain of the
* request you sent, i.e. if you send a request to <code>app1.your-domain.com</code>,
* then cookies will be set <code>on .your-domain.com</code>, such that they
* are also valid for <code>app2.your-domain.com</code>.
*/
private String cookieDomain;
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public int getSessionTimeoutInSeconds() {
return sessionTimeoutInSeconds;
}
public void setSessionTimeoutInSeconds(int sessionTimeoutInSeconds) {
this.sessionTimeoutInSeconds = sessionTimeoutInSeconds;
}
public String getCookieDomain() {
return cookieDomain;
}
public void setCookieDomain(String cookieDomain) {
this.cookieDomain = cookieDomain;
}
}
public static class SignatureVerification {
/**
* Maximum refresh rate for public keys in ms.
* We won't fetch new public keys any faster than that to avoid spamming UAA in case
* we receive a lot of "illegal" tokens.
*/
private long publicKeyRefreshRateLimit = 10 * 1000L;
/**
* Maximum TTL for the public key in ms.
* The public key will be fetched again from UAA if it gets older than that.
* That way, we make sure that we get the newest keys always in case they are updated there.
*/
private long ttl = 24 * 60 * 60 * 1000L;
/**
* Endpoint where to retrieve the public key used to verify token signatures.
*/
private String publicKeyEndpointUri = "http://uaa/oauth/token_key";
public long getPublicKeyRefreshRateLimit() {
return publicKeyRefreshRateLimit;
}
public void setPublicKeyRefreshRateLimit(long publicKeyRefreshRateLimit) {
this.publicKeyRefreshRateLimit = publicKeyRefreshRateLimit;
}
public long getTtl() {
return ttl;
}
public void setTtl(long ttl) {
this.ttl = ttl;
}
public String getPublicKeyEndpointUri() {
return publicKeyEndpointUri;
}
public void setPublicKeyEndpointUri(String publicKeyEndpointUri) {
this.publicKeyEndpointUri = publicKeyEndpointUri;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/oauth2/OAuth2JwtAccessTokenConverter.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/oauth2/OAuth2JwtAccessTokenConverter.java | package com.baeldung.jhipster.gateway.config.oauth2;
import com.baeldung.jhipster.gateway.security.oauth2.OAuth2SignatureVerifierClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.jwt.crypto.sign.SignatureVerifier;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import java.util.Map;
/**
* Improved JwtAccessTokenConverter that can handle lazy fetching of public verifier keys.
*/
public class OAuth2JwtAccessTokenConverter extends JwtAccessTokenConverter {
private final Logger log = LoggerFactory.getLogger(OAuth2JwtAccessTokenConverter.class);
private final OAuth2Properties oAuth2Properties;
private final OAuth2SignatureVerifierClient signatureVerifierClient;
/**
* When did we last fetch the public key?
*/
private long lastKeyFetchTimestamp;
public OAuth2JwtAccessTokenConverter(OAuth2Properties oAuth2Properties, OAuth2SignatureVerifierClient signatureVerifierClient) {
this.oAuth2Properties = oAuth2Properties;
this.signatureVerifierClient = signatureVerifierClient;
tryCreateSignatureVerifier();
}
/**
* Try to decode the token with the current public key.
* If it fails, contact the OAuth2 server to get a new public key, then try again.
* We might not have fetched it in the first place or it might have changed.
*
* @param token the JWT token to decode.
* @return the resulting claims.
* @throws InvalidTokenException if we cannot decode the token.
*/
@Override
protected Map<String, Object> decode(String token) {
try {
//check if our public key and thus SignatureVerifier have expired
long ttl = oAuth2Properties.getSignatureVerification().getTtl();
if (ttl > 0 && System.currentTimeMillis() - lastKeyFetchTimestamp > ttl) {
throw new InvalidTokenException("public key expired");
}
return super.decode(token);
} catch (InvalidTokenException ex) {
if (tryCreateSignatureVerifier()) {
return super.decode(token);
}
throw ex;
}
}
/**
* Fetch a new public key from the AuthorizationServer.
*
* @return true, if we could fetch it; false, if we could not.
*/
private boolean tryCreateSignatureVerifier() {
long t = System.currentTimeMillis();
if (t - lastKeyFetchTimestamp < oAuth2Properties.getSignatureVerification().getPublicKeyRefreshRateLimit()) {
return false;
}
try {
SignatureVerifier verifier = signatureVerifierClient.getSignatureVerifier();
if (verifier != null) {
setVerifier(verifier);
lastKeyFetchTimestamp = t;
log.debug("Public key retrieved from OAuth2 server to create SignatureVerifier");
return true;
}
} catch (Throwable ex) {
log.error("could not get public key from OAuth2 server to create SignatureVerifier", ex);
}
return false;
}
/**
* Extract JWT claims and set it to OAuth2Authentication decoded details.
* Here is how to get details:
*
* <pre>
* <code>
* SecurityContext securityContext = SecurityContextHolder.getContext();
* Authentication authentication = securityContext.getAuthentication();
* if (authentication != null) {
* Object details = authentication.getDetails();
* if(details instanceof OAuth2AuthenticationDetails) {
* Object decodedDetails = ((OAuth2AuthenticationDetails) details).getDecodedDetails();
* if(decodedDetails != null && decodedDetails instanceof Map) {
* String detailFoo = ((Map) decodedDetails).get("foo");
* }
* }
* }
* </code>
* </pre>
* @param claims OAuth2JWTToken claims
* @return OAuth2Authentication
*/
@Override
public OAuth2Authentication extractAuthentication(Map<String, ?> claims) {
OAuth2Authentication authentication = super.extractAuthentication(claims);
authentication.setDetails(claims);
return authentication;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/apidoc/GatewaySwaggerResourcesProvider.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/apidoc/GatewaySwaggerResourcesProvider.java | package com.baeldung.jhipster.gateway.config.apidoc;
import java.util.ArrayList;
import java.util.List;
import io.github.jhipster.config.JHipsterConstants;
import org.springframework.context.annotation.*;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
/**
* Retrieves all registered microservices Swagger resources.
*/
@Component
@Primary
@Profile(JHipsterConstants.SPRING_PROFILE_SWAGGER)
public class GatewaySwaggerResourcesProvider implements SwaggerResourcesProvider {
private final RouteLocator routeLocator;
public GatewaySwaggerResourcesProvider(RouteLocator routeLocator) {
this.routeLocator = routeLocator;
}
@Override
public List<SwaggerResource> get() {
List<SwaggerResource> resources = new ArrayList<>();
//Add the default swagger resource that correspond to the gateway's own swagger doc
resources.add(swaggerResource("default", "/v2/api-docs"));
//Add the registered microservices swagger docs as additional swagger resources
List<Route> routes = routeLocator.getRoutes();
routes.forEach(route -> {
resources.add(swaggerResource(route.getId(), route.getFullPath().replace("**", "v2/api-docs")));
});
return resources;
}
private SwaggerResource swaggerResource(String name, String location) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion("2.0");
return swaggerResource;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/audit/AuditEventConverter.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/audit/AuditEventConverter.java | package com.baeldung.jhipster.gateway.config.audit;
import com.baeldung.jhipster.gateway.domain.PersistentAuditEvent;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import java.util.*;
@Component
public class AuditEventConverter {
/**
* Convert a list of PersistentAuditEvent to a list of AuditEvent
*
* @param persistentAuditEvents the list to convert
* @return the converted list.
*/
public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
if (persistentAuditEvents == null) {
return Collections.emptyList();
}
List<AuditEvent> auditEvents = new ArrayList<>();
for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
auditEvents.add(convertToAuditEvent(persistentAuditEvent));
}
return auditEvents;
}
/**
* Convert a PersistentAuditEvent to an AuditEvent
*
* @param persistentAuditEvent the event to convert
* @return the converted list.
*/
public AuditEvent convertToAuditEvent(PersistentAuditEvent persistentAuditEvent) {
if (persistentAuditEvent == null) {
return null;
}
return new AuditEvent(persistentAuditEvent.getAuditEventDate(), persistentAuditEvent.getPrincipal(),
persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
}
/**
* Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface
*
* @param data the data to convert
* @return a map of String, Object
*/
public Map<String, Object> convertDataToObjects(Map<String, String> data) {
Map<String, Object> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, String> entry : data.entrySet()) {
results.put(entry.getKey(), entry.getValue());
}
}
return results;
}
/**
* Internal conversion. This method will allow to save additional data.
* By default, it will save the object as string
*
* @param data the data to convert
* @return a map of String, String
*/
public Map<String, String> convertDataToStrings(Map<String, Object> data) {
Map<String, String> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, Object> entry : data.entrySet()) {
// Extract the data that will be saved.
if (entry.getValue() instanceof WebAuthenticationDetails) {
WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) entry.getValue();
results.put("remoteAddress", authenticationDetails.getRemoteAddress());
results.put("sessionId", authenticationDetails.getSessionId());
} else {
results.put(entry.getKey(), Objects.toString(entry.getValue()));
}
}
}
return results;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/audit/package-info.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/config/audit/package-info.java | /**
* Audit specific code.
*/
package com.baeldung.jhipster.gateway.config.audit;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/filter/RefreshTokenFilterConfigurer.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/filter/RefreshTokenFilterConfigurer.java | package com.baeldung.jhipster.gateway.web.filter;
import com.baeldung.jhipster.gateway.security.oauth2.OAuth2AuthenticationService;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.DefaultSecurityFilterChain;
/**
* Configures a RefreshTokenFilter to refresh access tokens if they are about to expire.
*
* @see RefreshTokenFilter
*/
public class RefreshTokenFilterConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
/**
* RefreshTokenFilter needs the OAuth2AuthenticationService to refresh cookies using the refresh token.
*/
private OAuth2AuthenticationService authenticationService;
private final TokenStore tokenStore;
public RefreshTokenFilterConfigurer(OAuth2AuthenticationService authenticationService, TokenStore tokenStore) {
this.authenticationService = authenticationService;
this.tokenStore = tokenStore;
}
/**
* Install RefreshTokenFilter as a servlet Filter.
*/
@Override
public void configure(HttpSecurity http) throws Exception {
RefreshTokenFilter customFilter = new RefreshTokenFilter(authenticationService, tokenStore);
http.addFilterBefore(customFilter, OAuth2AuthenticationProcessingFilter.class);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/filter/RefreshTokenFilter.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/filter/RefreshTokenFilter.java | package com.baeldung.jhipster.gateway.web.filter;
import com.baeldung.jhipster.gateway.security.oauth2.OAuth2AuthenticationService;
import com.baeldung.jhipster.gateway.security.oauth2.OAuth2CookieHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.ClientAuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.UnauthorizedClientException;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Filters incoming requests and refreshes the access token before it expires.
*/
public class RefreshTokenFilter extends GenericFilterBean {
/**
* Number of seconds before expiry to start refreshing access tokens so we don't run into race conditions when forwarding
* requests downstream. Otherwise, access tokens may still be valid when we check here but may then be expired
* when relayed to another microservice a wee bit later.
*/
private static final int REFRESH_WINDOW_SECS = 30;
private final Logger log = LoggerFactory.getLogger(RefreshTokenFilter.class);
/**
* The OAuth2AuthenticationService is doing the actual work. We are just a simple filter after all.
*/
private final OAuth2AuthenticationService authenticationService;
private final TokenStore tokenStore;
public RefreshTokenFilter(OAuth2AuthenticationService authenticationService, TokenStore tokenStore) {
this.authenticationService = authenticationService;
this.tokenStore = tokenStore;
}
/**
* Check access token cookie and refresh it, if it is either not present, expired or about to expire.
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
try {
httpServletRequest = refreshTokensIfExpiring(httpServletRequest, httpServletResponse);
} catch (ClientAuthenticationException ex) {
log.warn("Security exception: could not refresh tokens", ex);
httpServletRequest = authenticationService.stripTokens(httpServletRequest);
}
filterChain.doFilter(httpServletRequest, servletResponse);
}
/**
* Refresh the access and refresh tokens if they are about to expire.
*
* @param httpServletRequest the servlet request holding the current cookies. If no refresh cookie is present,
* then we are out of luck.
* @param httpServletResponse the servlet response that gets the new set-cookie headers, if they had to be
* refreshed.
* @return a new request to use downstream that contains the new cookies, if they had to be refreshed.
* @throws InvalidTokenException if the tokens could not be refreshed.
*/
public HttpServletRequest refreshTokensIfExpiring(HttpServletRequest httpServletRequest, HttpServletResponse
httpServletResponse) {
HttpServletRequest newHttpServletRequest = httpServletRequest;
//get access token from cookie
Cookie accessTokenCookie = OAuth2CookieHelper.getAccessTokenCookie(httpServletRequest);
if (mustRefreshToken(accessTokenCookie)) { //we either have no access token, or it is expired, or it is about to expire
//get the refresh token cookie and, if present, request new tokens
Cookie refreshCookie = OAuth2CookieHelper.getRefreshTokenCookie(httpServletRequest);
if (refreshCookie != null) {
try {
newHttpServletRequest = authenticationService.refreshToken(httpServletRequest, httpServletResponse, refreshCookie);
} catch (HttpClientErrorException ex) {
throw new UnauthorizedClientException("could not refresh OAuth2 token", ex);
}
} else if (accessTokenCookie != null) {
log.warn("access token found, but no refresh token, stripping them all");
OAuth2AccessToken token = tokenStore.readAccessToken(accessTokenCookie.getValue());
if (token.isExpired()) {
throw new InvalidTokenException("access token has expired, but there's no refresh token");
}
}
}
return newHttpServletRequest;
}
/**
* Check if we must refresh the access token.
* We must refresh it, if we either have no access token, or it is expired, or it is about to expire.
*
* @param accessTokenCookie the current access token.
* @return true, if it must be refreshed; false, otherwise.
*/
private boolean mustRefreshToken(Cookie accessTokenCookie) {
if (accessTokenCookie == null) {
return true;
}
OAuth2AccessToken token = tokenStore.readAccessToken(accessTokenCookie.getValue());
//check if token is expired or about to expire
if (token.isExpired() || token.getExpiresIn() < REFRESH_WINDOW_SECS) {
return true;
}
return false; //access token is still fine
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/GatewayResource.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/GatewayResource.java | package com.baeldung.jhipster.gateway.web.rest;
import com.baeldung.jhipster.gateway.web.rest.vm.RouteVM;
import java.util.ArrayList;
import java.util.List;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.http.*;
import org.springframework.security.access.annotation.Secured;
import com.baeldung.jhipster.gateway.security.AuthoritiesConstants;
import org.springframework.web.bind.annotation.*;
import com.codahale.metrics.annotation.Timed;
/**
* REST controller for managing Gateway configuration.
*/
@RestController
@RequestMapping("/api/gateway")
public class GatewayResource {
private final RouteLocator routeLocator;
private final DiscoveryClient discoveryClient;
public GatewayResource(RouteLocator routeLocator, DiscoveryClient discoveryClient) {
this.routeLocator = routeLocator;
this.discoveryClient = discoveryClient;
}
/**
* GET /routes : get the active routes.
*
* @return the ResponseEntity with status 200 (OK) and with body the list of routes
*/
@GetMapping("/routes")
@Timed
@Secured(AuthoritiesConstants.ADMIN)
public ResponseEntity<List<RouteVM>> activeRoutes() {
List<Route> routes = routeLocator.getRoutes();
List<RouteVM> routeVMs = new ArrayList<>();
routes.forEach(route -> {
RouteVM routeVM = new RouteVM();
routeVM.setPath(route.getFullPath());
routeVM.setServiceId(route.getId());
routeVM.setServiceInstances(discoveryClient.getInstances(route.getLocation()));
routeVMs.add(routeVM);
});
return new ResponseEntity<>(routeVMs, HttpStatus.OK);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/AuthResource.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/AuthResource.java | package com.baeldung.jhipster.gateway.web.rest;
import com.codahale.metrics.annotation.Timed;
import com.baeldung.jhipster.gateway.security.oauth2.OAuth2AuthenticationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/**
* Authentication endpoint for web client.
* Used to authenticate a user using OAuth2 access tokens or log him out.
*
* @author markus.oellinger
*/
@RestController
@RequestMapping("/auth")
public class AuthResource {
private final Logger log = LoggerFactory.getLogger(AuthResource.class);
private OAuth2AuthenticationService authenticationService;
public AuthResource(OAuth2AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
/**
* Authenticates a user setting the access and refresh token cookies.
*
* @param request the HttpServletRequest holding - among others - the headers passed from the client.
* @param response the HttpServletResponse getting the cookies set upon successful authentication.
* @param params the login params (username, password, rememberMe).
* @return the access token of the authenticated user. Will return an error code if it fails to authenticate the user.
*/
@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = MediaType
.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<OAuth2AccessToken> authenticate(HttpServletRequest request, HttpServletResponse response, @RequestBody
Map<String, String> params) {
return authenticationService.authenticate(request, response, params);
}
/**
* Logout current user deleting his cookies.
*
* @param request the HttpServletRequest holding - among others - the headers passed from the client.
* @param response the HttpServletResponse getting the cookies set upon successful authentication.
* @return an empty response entity.
*/
@RequestMapping(value = "/logout", method = RequestMethod.POST)
@Timed
public ResponseEntity<?> logout(HttpServletRequest request, HttpServletResponse response) {
log.info("logging out user {}", SecurityContextHolder.getContext().getAuthentication().getName());
authenticationService.logout(request, response);
return ResponseEntity.noContent().build();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/package-info.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/package-info.java | /**
* Spring MVC REST controllers.
*/
package com.baeldung.jhipster.gateway.web.rest;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/LogsResource.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/LogsResource.java | package com.baeldung.jhipster.gateway.web.rest;
import com.baeldung.jhipster.gateway.web.rest.vm.LoggerVM;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.codahale.metrics.annotation.Timed;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
/**
* Controller for view and managing Log Level at runtime.
*/
@RestController
@RequestMapping("/management")
public class LogsResource {
@GetMapping("/logs")
@Timed
public List<LoggerVM> getList() {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
return context.getLoggerList()
.stream()
.map(LoggerVM::new)
.collect(Collectors.toList());
}
@PutMapping("/logs")
@ResponseStatus(HttpStatus.NO_CONTENT)
@Timed
public void changeLevel(@RequestBody LoggerVM jsonLogger) {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel()));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/util/HeaderUtil.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/util/HeaderUtil.java | package com.baeldung.jhipster.gateway.web.rest.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
/**
* Utility class for HTTP headers creation.
*/
public final class HeaderUtil {
private static final Logger log = LoggerFactory.getLogger(HeaderUtil.class);
private static final String APPLICATION_NAME = "gatewayApp";
private HeaderUtil() {
}
public static HttpHeaders createAlert(String message, String param) {
HttpHeaders headers = new HttpHeaders();
headers.add("X-" + APPLICATION_NAME + "-alert", message);
headers.add("X-" + APPLICATION_NAME + "-params", param);
return headers;
}
public static HttpHeaders createEntityCreationAlert(String entityName, String param) {
return createAlert(APPLICATION_NAME + "." + entityName + ".created", param);
}
public static HttpHeaders createEntityUpdateAlert(String entityName, String param) {
return createAlert(APPLICATION_NAME + "." + entityName + ".updated", param);
}
public static HttpHeaders createEntityDeletionAlert(String entityName, String param) {
return createAlert(APPLICATION_NAME + "." + entityName + ".deleted", param);
}
public static HttpHeaders createFailureAlert(String entityName, String errorKey, String defaultMessage) {
log.error("Entity processing failed, {}", defaultMessage);
HttpHeaders headers = new HttpHeaders();
headers.add("X-" + APPLICATION_NAME + "-error", "error." + errorKey);
headers.add("X-" + APPLICATION_NAME + "-params", entityName);
return headers;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/util/PaginationUtil.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/util/PaginationUtil.java | package com.baeldung.jhipster.gateway.web.rest.util;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.web.util.UriComponentsBuilder;
/**
* Utility class for handling pagination.
*
* <p>
* Pagination uses the same principles as the <a href="https://developer.github.com/v3/#pagination">GitHub API</a>,
* and follow <a href="http://tools.ietf.org/html/rfc5988">RFC 5988 (Link header)</a>.
*/
public final class PaginationUtil {
private PaginationUtil() {
}
public static <T> HttpHeaders generatePaginationHttpHeaders(Page<T> page, String baseUrl) {
HttpHeaders headers = new HttpHeaders();
headers.add("X-Total-Count", Long.toString(page.getTotalElements()));
String link = "";
if ((page.getNumber() + 1) < page.getTotalPages()) {
link = "<" + generateUri(baseUrl, page.getNumber() + 1, page.getSize()) + ">; rel=\"next\",";
}
// prev link
if ((page.getNumber()) > 0) {
link += "<" + generateUri(baseUrl, page.getNumber() - 1, page.getSize()) + ">; rel=\"prev\",";
}
// last and first link
int lastPage = 0;
if (page.getTotalPages() > 0) {
lastPage = page.getTotalPages() - 1;
}
link += "<" + generateUri(baseUrl, lastPage, page.getSize()) + ">; rel=\"last\",";
link += "<" + generateUri(baseUrl, 0, page.getSize()) + ">; rel=\"first\"";
headers.add(HttpHeaders.LINK, link);
return headers;
}
private static String generateUri(String baseUrl, int page, int size) {
return UriComponentsBuilder.fromUriString(baseUrl).queryParam("page", page).queryParam("size", size).toUriString();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/InvalidPasswordException.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/InvalidPasswordException.java | package com.baeldung.jhipster.gateway.web.rest.errors;
import org.zalando.problem.AbstractThrowableProblem;
import org.zalando.problem.Status;
public class InvalidPasswordException extends AbstractThrowableProblem {
private static final long serialVersionUID = 1L;
public InvalidPasswordException() {
super(ErrorConstants.INVALID_PASSWORD_TYPE, "Incorrect password", Status.BAD_REQUEST);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/CustomParameterizedException.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/CustomParameterizedException.java | package com.baeldung.jhipster.gateway.web.rest.errors;
import org.zalando.problem.AbstractThrowableProblem;
import java.util.HashMap;
import java.util.Map;
import static org.zalando.problem.Status.BAD_REQUEST;
/**
* Custom, parameterized exception, which can be translated on the client side.
* For example:
*
* <pre>
* throw new CustomParameterizedException("myCustomError", "hello", "world");
* </pre>
*
* Can be translated with:
*
* <pre>
* "error.myCustomError" : "The server says {{param0}} to {{param1}}"
* </pre>
*/
public class CustomParameterizedException extends AbstractThrowableProblem {
private static final long serialVersionUID = 1L;
private static final String PARAM = "param";
public CustomParameterizedException(String message, String... params) {
this(message, toParamMap(params));
}
public CustomParameterizedException(String message, Map<String, Object> paramMap) {
super(ErrorConstants.PARAMETERIZED_TYPE, "Parameterized Exception", BAD_REQUEST, null, null, null, toProblemParameters(message, paramMap));
}
public static Map<String, Object> toParamMap(String... params) {
Map<String, Object> paramMap = new HashMap<>();
if (params != null && params.length > 0) {
for (int i = 0; i < params.length; i++) {
paramMap.put(PARAM + i, params[i]);
}
}
return paramMap;
}
public static Map<String, Object> toProblemParameters(String message, Map<String, Object> paramMap) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("message", message);
parameters.put("params", paramMap);
return parameters;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/package-info.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/package-info.java | /**
* Specific errors used with Zalando's "problem-spring-web" library.
*
* More information on https://github.com/zalando/problem-spring-web
*/
package com.baeldung.jhipster.gateway.web.rest.errors;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/LoginAlreadyUsedException.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/LoginAlreadyUsedException.java | package com.baeldung.jhipster.gateway.web.rest.errors;
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-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/EmailNotFoundException.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/EmailNotFoundException.java | package com.baeldung.jhipster.gateway.web.rest.errors;
import org.zalando.problem.AbstractThrowableProblem;
import org.zalando.problem.Status;
public class EmailNotFoundException extends AbstractThrowableProblem {
private static final long serialVersionUID = 1L;
public EmailNotFoundException() {
super(ErrorConstants.EMAIL_NOT_FOUND_TYPE, "Email address not registered", Status.BAD_REQUEST);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/InternalServerErrorException.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/InternalServerErrorException.java | package com.baeldung.jhipster.gateway.web.rest.errors;
import org.zalando.problem.AbstractThrowableProblem;
import org.zalando.problem.Status;
/**
* Simple exception with a message, that returns an Internal Server Error code.
*/
public class InternalServerErrorException extends AbstractThrowableProblem {
private static final long serialVersionUID = 1L;
public InternalServerErrorException(String message) {
super(ErrorConstants.DEFAULT_TYPE, message, Status.INTERNAL_SERVER_ERROR);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/ErrorConstants.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/ErrorConstants.java | package com.baeldung.jhipster.gateway.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 PARAMETERIZED_TYPE = URI.create(PROBLEM_BASE_URL + "/parameterized");
public static final URI ENTITY_NOT_FOUND_TYPE = URI.create(PROBLEM_BASE_URL + "/entity-not-found");
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");
public static final URI EMAIL_NOT_FOUND_TYPE = URI.create(PROBLEM_BASE_URL + "/email-not-found");
private ErrorConstants() {
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/FieldErrorVM.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/FieldErrorVM.java | package com.baeldung.jhipster.gateway.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-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/EmailAlreadyUsedException.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/EmailAlreadyUsedException.java | package com.baeldung.jhipster.gateway.web.rest.errors;
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-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/BadRequestAlertException.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/BadRequestAlertException.java | package com.baeldung.jhipster.gateway.web.rest.errors;
import org.zalando.problem.AbstractThrowableProblem;
import org.zalando.problem.Status;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
public class BadRequestAlertException extends AbstractThrowableProblem {
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(type, defaultMessage, Status.BAD_REQUEST, null, null, null, getAlertParameters(entityName, errorKey));
this.entityName = entityName;
this.errorKey = errorKey;
}
public String getEntityName() {
return entityName;
}
public String getErrorKey() {
return errorKey;
}
private static Map<String, Object> getAlertParameters(String entityName, String errorKey) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("message", "error." + errorKey);
parameters.put("params", entityName);
return parameters;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/ExceptionTranslator.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/errors/ExceptionTranslator.java | package com.baeldung.jhipster.gateway.web.rest.errors;
import com.baeldung.jhipster.gateway.web.rest.util.HeaderUtil;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.NativeWebRequest;
import org.zalando.problem.DefaultProblem;
import org.zalando.problem.Problem;
import org.zalando.problem.ProblemBuilder;
import org.zalando.problem.Status;
import org.zalando.problem.spring.web.advice.ProblemHandling;
import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait;
import org.zalando.problem.violations.ConstraintViolationProblem;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;
/**
* 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 implements ProblemHandling, SecurityAdviceTrait {
/**
* Post-process the Problem payload to add the message key for the front-end if needed
*/
@Override
public ResponseEntity<Problem> process(@Nullable ResponseEntity<Problem> entity, NativeWebRequest request) {
if (entity == null) {
return entity;
}
Problem problem = entity.getBody();
if (!(problem instanceof ConstraintViolationProblem || problem instanceof DefaultProblem)) {
return entity;
}
ProblemBuilder builder = Problem.builder()
.withType(Problem.DEFAULT_TYPE.equals(problem.getType()) ? ErrorConstants.DEFAULT_TYPE : problem.getType())
.withStatus(problem.getStatus())
.withTitle(problem.getTitle())
.with("path", request.getNativeRequest(HttpServletRequest.class).getRequestURI());
if (problem instanceof ConstraintViolationProblem) {
builder
.with("violations", ((ConstraintViolationProblem) problem).getViolations())
.with("message", ErrorConstants.ERR_VALIDATION);
} else {
builder
.withCause(((DefaultProblem) problem).getCause())
.withDetail(problem.getDetail())
.withInstance(problem.getInstance());
problem.getParameters().forEach(builder::with);
if (!problem.getParameters().containsKey("message") && problem.getStatus() != null) {
builder.with("message", "error.http." + problem.getStatus().getStatusCode());
}
}
return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode());
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with("message", ErrorConstants.ERR_VALIDATION)
.with("fieldErrors", fieldErrors)
.build();
return create(ex, problem, request);
}
@ExceptionHandler
public ResponseEntity<Problem> handleNoSuchElementException(NoSuchElementException ex, NativeWebRequest request) {
Problem problem = Problem.builder()
.withStatus(Status.NOT_FOUND)
.with("message", ErrorConstants.ENTITY_NOT_FOUND_TYPE)
.build();
return create(ex, problem, request);
}
@ExceptionHandler
public ResponseEntity<Problem> handleBadRequestAlertException(BadRequestAlertException ex, NativeWebRequest request) {
return create(ex, request, HeaderUtil.createFailureAlert(ex.getEntityName(), ex.getErrorKey(), ex.getMessage()));
}
@ExceptionHandler
public ResponseEntity<Problem> handleConcurrencyFailure(ConcurrencyFailureException ex, NativeWebRequest request) {
Problem problem = Problem.builder()
.withStatus(Status.CONFLICT)
.with("message", ErrorConstants.ERR_CONCURRENCY_FAILURE)
.build();
return create(ex, problem, request);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/vm/package-info.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/vm/package-info.java | /**
* View Models used by Spring MVC REST controllers.
*/
package com.baeldung.jhipster.gateway.web.rest.vm;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/vm/LoggerVM.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/vm/LoggerVM.java | package com.baeldung.jhipster.gateway.web.rest.vm;
import ch.qos.logback.classic.Logger;
/**
* View Model object for storing a Logback logger.
*/
public class LoggerVM {
private String name;
private String level;
public LoggerVM(Logger logger) {
this.name = logger.getName();
this.level = logger.getEffectiveLevel().toString();
}
public LoggerVM() {
// Empty public constructor used by Jackson.
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
@Override
public String toString() {
return "LoggerVM{" +
"name='" + name + '\'' +
", level='" + level + '\'' +
'}';
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/vm/RouteVM.java | jhipster-modules/jhipster-uaa/gateway/src/main/java/com/baeldung/jhipster/gateway/web/rest/vm/RouteVM.java | package com.baeldung.jhipster.gateway.web.rest.vm;
import java.util.List;
import org.springframework.cloud.client.ServiceInstance;
/**
* View Model that stores a route managed by the Gateway.
*/
public class RouteVM {
private String path;
private String serviceId;
private List<ServiceInstance> serviceInstances;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getServiceId() {
return serviceId;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public List<ServiceInstance> getServiceInstances() {
return serviceInstances;
}
public void setServiceInstances(List<ServiceInstance> serviceInstances) {
this.serviceInstances = serviceInstances;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/security/OAuth2TokenMockUtil.java | jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/security/OAuth2TokenMockUtil.java | package com.baeldung.jhipster.quotes.security;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.stereotype.Component;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import static org.mockito.BDDMockito.given;
/**
* A bean providing simple mocking of OAuth2 access tokens for security integration tests.
*/
@Component
public class OAuth2TokenMockUtil {
@MockBean
private ResourceServerTokenServices tokenServices;
private OAuth2Authentication createAuthentication(String username, Set<String> scopes, Set<String> roles) {
List<GrantedAuthority> authorities = roles.stream()
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
User principal = new User(username, "test", true, true, true, true, authorities);
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
principal.getAuthorities());
// Create the authorization request and OAuth2Authentication object
OAuth2Request authRequest = new OAuth2Request(null, "testClient", null, true, scopes, null, null, null,
null);
return new OAuth2Authentication(authRequest, authentication);
}
public RequestPostProcessor oauth2Authentication(String username, Set<String> scopes, Set<String> roles) {
String uuid = String.valueOf(UUID.randomUUID());
given(tokenServices.loadAuthentication(uuid))
.willReturn(createAuthentication(username, scopes, roles));
given(tokenServices.readAccessToken(uuid)).willReturn(new DefaultOAuth2AccessToken(uuid));
return new OAuth2PostProcessor(uuid);
}
public RequestPostProcessor oauth2Authentication(String username, Set<String> scopes) {
return oauth2Authentication(username, scopes, Collections.emptySet());
}
public RequestPostProcessor oauth2Authentication(String username) {
return oauth2Authentication(username, Collections.emptySet());
}
public static class OAuth2PostProcessor implements RequestPostProcessor {
private String token;
public OAuth2PostProcessor(String token) {
this.token = token;
}
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest mockHttpServletRequest) {
mockHttpServletRequest.addHeader("Authorization", "Bearer " + token);
return mockHttpServletRequest;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/config/WebConfigurerUnitTest.java | jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/config/WebConfigurerUnitTest.java | package com.baeldung.jhipster.quotes.config;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.servlet.InstrumentedFilter;
import com.codahale.metrics.servlets.MetricsServlet;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.JHipsterProperties;
import io.undertow.Undertow;
import io.undertow.Undertow.Builder;
import io.undertow.UndertowOptions;
import org.h2.server.web.WebServlet;
import org.junit.Before;
import org.junit.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.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.xnio.OptionMap;
import javax.servlet.*;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Unit tests for the WebConfigurer class.
*
* @see WebConfigurer
*/
public class WebConfigurerUnitTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private MetricRegistry metricRegistry;
@Before
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);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class));
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class));
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class));
}
@Test
public void testCustomizeServletContainer() {
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;charset=utf-8");
assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() 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(
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
public void testCorsFilterOnOtherPath() 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
public void testCorsFilterDeactivated() 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
public void testCorsFilterDeactivated2() 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-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/config/SecurityBeanOverrideConfiguration.java | jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/config/SecurityBeanOverrideConfiguration.java | package com.baeldung.jhipster.quotes.config;
import org.springframework.cloud.client.loadbalancer.RestTemplateCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.web.client.RestTemplate;
/**
* Overrides UAA specific beans, so they do not interfere the testing
* This configuration must be included in @SpringBootTest in order to take effect.
*/
@Configuration
public class SecurityBeanOverrideConfiguration {
@Bean
@Primary
public TokenStore tokenStore() {
return null;
}
@Bean
@Primary
public JwtAccessTokenConverter jwtAccessTokenConverter() {
return null;
}
@Bean
@Primary
public RestTemplate loadBalancedRestTemplate(RestTemplateCustomizer customizer) {
return null;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/config/WebConfigurerTestController.java | jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/config/WebConfigurerTestController.java | package com.baeldung.jhipster.quotes.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-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/web/rest/QuoteResourceIntTest.java | jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/web/rest/QuoteResourceIntTest.java | package com.baeldung.jhipster.quotes.web.rest;
import com.baeldung.jhipster.quotes.QuotesApp;
import com.baeldung.jhipster.quotes.config.SecurityBeanOverrideConfiguration;
import com.baeldung.jhipster.quotes.domain.Quote;
import com.baeldung.jhipster.quotes.repository.QuoteRepository;
import com.baeldung.jhipster.quotes.service.QuoteService;
import com.baeldung.jhipster.quotes.service.dto.QuoteDTO;
import com.baeldung.jhipster.quotes.service.mapper.QuoteMapper;
import com.baeldung.jhipster.quotes.web.rest.errors.ExceptionTranslator;
import com.baeldung.jhipster.quotes.service.dto.QuoteCriteria;
import com.baeldung.jhipster.quotes.service.QuoteQueryService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.time.ZoneOffset;
import java.time.ZoneId;
import java.util.List;
import static com.baeldung.jhipster.quotes.web.rest.TestUtil.sameInstant;
import static com.baeldung.jhipster.quotes.web.rest.TestUtil.createFormattingConversionService;
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.*;
/**
* Test class for the QuoteResource REST controller.
*
* @see QuoteResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SecurityBeanOverrideConfiguration.class, QuotesApp.class})
public class QuoteResourceIntTest {
private static final String DEFAULT_SYMBOL = "AAAAAAAAAA";
private static final String UPDATED_SYMBOL = "BBBBBBBBBB";
private static final BigDecimal DEFAULT_PRICE = new BigDecimal(1);
private static final BigDecimal UPDATED_PRICE = new BigDecimal(2);
private static final ZonedDateTime DEFAULT_LAST_TRADE = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
private static final ZonedDateTime UPDATED_LAST_TRADE = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);
@Autowired
private QuoteRepository quoteRepository;
@Autowired
private QuoteMapper quoteMapper;
@Autowired
private QuoteService quoteService;
@Autowired
private QuoteQueryService quoteQueryService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restQuoteMockMvc;
private Quote quote;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final QuoteResource quoteResource = new QuoteResource(quoteService, quoteQueryService);
this.restQuoteMockMvc = MockMvcBuilders.standaloneSetup(quoteResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* 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 Quote createEntity(EntityManager em) {
Quote quote = new Quote()
.symbol(DEFAULT_SYMBOL)
.price(DEFAULT_PRICE)
.lastTrade(DEFAULT_LAST_TRADE);
return quote;
}
@Before
public void initTest() {
quote = createEntity(em);
}
@Test
@Transactional
public void createQuote() throws Exception {
int databaseSizeBeforeCreate = quoteRepository.findAll().size();
// Create the Quote
QuoteDTO quoteDTO = quoteMapper.toDto(quote);
restQuoteMockMvc.perform(post("/api/quotes")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(quoteDTO)))
.andExpect(status().isCreated());
// Validate the Quote in the database
List<Quote> quoteList = quoteRepository.findAll();
assertThat(quoteList).hasSize(databaseSizeBeforeCreate + 1);
Quote testQuote = quoteList.get(quoteList.size() - 1);
assertThat(testQuote.getSymbol()).isEqualTo(DEFAULT_SYMBOL);
assertThat(testQuote.getPrice()).isEqualTo(DEFAULT_PRICE);
assertThat(testQuote.getLastTrade()).isEqualTo(DEFAULT_LAST_TRADE);
}
@Test
@Transactional
public void createQuoteWithExistingId() throws Exception {
int databaseSizeBeforeCreate = quoteRepository.findAll().size();
// Create the Quote with an existing ID
quote.setId(1L);
QuoteDTO quoteDTO = quoteMapper.toDto(quote);
// An entity with an existing ID cannot be created, so this API call must fail
restQuoteMockMvc.perform(post("/api/quotes")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(quoteDTO)))
.andExpect(status().isBadRequest());
// Validate the Quote in the database
List<Quote> quoteList = quoteRepository.findAll();
assertThat(quoteList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void checkSymbolIsRequired() throws Exception {
int databaseSizeBeforeTest = quoteRepository.findAll().size();
// set the field null
quote.setSymbol(null);
// Create the Quote, which fails.
QuoteDTO quoteDTO = quoteMapper.toDto(quote);
restQuoteMockMvc.perform(post("/api/quotes")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(quoteDTO)))
.andExpect(status().isBadRequest());
List<Quote> quoteList = quoteRepository.findAll();
assertThat(quoteList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkPriceIsRequired() throws Exception {
int databaseSizeBeforeTest = quoteRepository.findAll().size();
// set the field null
quote.setPrice(null);
// Create the Quote, which fails.
QuoteDTO quoteDTO = quoteMapper.toDto(quote);
restQuoteMockMvc.perform(post("/api/quotes")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(quoteDTO)))
.andExpect(status().isBadRequest());
List<Quote> quoteList = quoteRepository.findAll();
assertThat(quoteList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void checkLastTradeIsRequired() throws Exception {
int databaseSizeBeforeTest = quoteRepository.findAll().size();
// set the field null
quote.setLastTrade(null);
// Create the Quote, which fails.
QuoteDTO quoteDTO = quoteMapper.toDto(quote);
restQuoteMockMvc.perform(post("/api/quotes")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(quoteDTO)))
.andExpect(status().isBadRequest());
List<Quote> quoteList = quoteRepository.findAll();
assertThat(quoteList).hasSize(databaseSizeBeforeTest);
}
@Test
@Transactional
public void getAllQuotes() throws Exception {
// Initialize the database
quoteRepository.saveAndFlush(quote);
// Get all the quoteList
restQuoteMockMvc.perform(get("/api/quotes?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(quote.getId().intValue())))
.andExpect(jsonPath("$.[*].symbol").value(hasItem(DEFAULT_SYMBOL.toString())))
.andExpect(jsonPath("$.[*].price").value(hasItem(DEFAULT_PRICE.intValue())))
.andExpect(jsonPath("$.[*].lastTrade").value(hasItem(sameInstant(DEFAULT_LAST_TRADE))));
}
@Test
@Transactional
public void getQuote() throws Exception {
// Initialize the database
quoteRepository.saveAndFlush(quote);
// Get the quote
restQuoteMockMvc.perform(get("/api/quotes/{id}", quote.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(quote.getId().intValue()))
.andExpect(jsonPath("$.symbol").value(DEFAULT_SYMBOL.toString()))
.andExpect(jsonPath("$.price").value(DEFAULT_PRICE.intValue()))
.andExpect(jsonPath("$.lastTrade").value(sameInstant(DEFAULT_LAST_TRADE)));
}
@Test
@Transactional
public void getAllQuotesBySymbolIsEqualToSomething() throws Exception {
// Initialize the database
quoteRepository.saveAndFlush(quote);
// Get all the quoteList where symbol equals to DEFAULT_SYMBOL
defaultQuoteShouldBeFound("symbol.equals=" + DEFAULT_SYMBOL);
// Get all the quoteList where symbol equals to UPDATED_SYMBOL
defaultQuoteShouldNotBeFound("symbol.equals=" + UPDATED_SYMBOL);
}
@Test
@Transactional
public void getAllQuotesBySymbolIsInShouldWork() throws Exception {
// Initialize the database
quoteRepository.saveAndFlush(quote);
// Get all the quoteList where symbol in DEFAULT_SYMBOL or UPDATED_SYMBOL
defaultQuoteShouldBeFound("symbol.in=" + DEFAULT_SYMBOL + "," + UPDATED_SYMBOL);
// Get all the quoteList where symbol equals to UPDATED_SYMBOL
defaultQuoteShouldNotBeFound("symbol.in=" + UPDATED_SYMBOL);
}
@Test
@Transactional
public void getAllQuotesBySymbolIsNullOrNotNull() throws Exception {
// Initialize the database
quoteRepository.saveAndFlush(quote);
// Get all the quoteList where symbol is not null
defaultQuoteShouldBeFound("symbol.specified=true");
// Get all the quoteList where symbol is null
defaultQuoteShouldNotBeFound("symbol.specified=false");
}
@Test
@Transactional
public void getAllQuotesByPriceIsEqualToSomething() throws Exception {
// Initialize the database
quoteRepository.saveAndFlush(quote);
// Get all the quoteList where price equals to DEFAULT_PRICE
defaultQuoteShouldBeFound("price.equals=" + DEFAULT_PRICE);
// Get all the quoteList where price equals to UPDATED_PRICE
defaultQuoteShouldNotBeFound("price.equals=" + UPDATED_PRICE);
}
@Test
@Transactional
public void getAllQuotesByPriceIsInShouldWork() throws Exception {
// Initialize the database
quoteRepository.saveAndFlush(quote);
// Get all the quoteList where price in DEFAULT_PRICE or UPDATED_PRICE
defaultQuoteShouldBeFound("price.in=" + DEFAULT_PRICE + "," + UPDATED_PRICE);
// Get all the quoteList where price equals to UPDATED_PRICE
defaultQuoteShouldNotBeFound("price.in=" + UPDATED_PRICE);
}
@Test
@Transactional
public void getAllQuotesByPriceIsNullOrNotNull() throws Exception {
// Initialize the database
quoteRepository.saveAndFlush(quote);
// Get all the quoteList where price is not null
defaultQuoteShouldBeFound("price.specified=true");
// Get all the quoteList where price is null
defaultQuoteShouldNotBeFound("price.specified=false");
}
@Test
@Transactional
public void getAllQuotesByLastTradeIsEqualToSomething() throws Exception {
// Initialize the database
quoteRepository.saveAndFlush(quote);
// Get all the quoteList where lastTrade equals to DEFAULT_LAST_TRADE
defaultQuoteShouldBeFound("lastTrade.equals=" + DEFAULT_LAST_TRADE);
// Get all the quoteList where lastTrade equals to UPDATED_LAST_TRADE
defaultQuoteShouldNotBeFound("lastTrade.equals=" + UPDATED_LAST_TRADE);
}
@Test
@Transactional
public void getAllQuotesByLastTradeIsInShouldWork() throws Exception {
// Initialize the database
quoteRepository.saveAndFlush(quote);
// Get all the quoteList where lastTrade in DEFAULT_LAST_TRADE or UPDATED_LAST_TRADE
defaultQuoteShouldBeFound("lastTrade.in=" + DEFAULT_LAST_TRADE + "," + UPDATED_LAST_TRADE);
// Get all the quoteList where lastTrade equals to UPDATED_LAST_TRADE
defaultQuoteShouldNotBeFound("lastTrade.in=" + UPDATED_LAST_TRADE);
}
@Test
@Transactional
public void getAllQuotesByLastTradeIsNullOrNotNull() throws Exception {
// Initialize the database
quoteRepository.saveAndFlush(quote);
// Get all the quoteList where lastTrade is not null
defaultQuoteShouldBeFound("lastTrade.specified=true");
// Get all the quoteList where lastTrade is null
defaultQuoteShouldNotBeFound("lastTrade.specified=false");
}
@Test
@Transactional
public void getAllQuotesByLastTradeIsGreaterThanOrEqualToSomething() throws Exception {
// Initialize the database
quoteRepository.saveAndFlush(quote);
// Get all the quoteList where lastTrade greater than or equals to DEFAULT_LAST_TRADE
defaultQuoteShouldBeFound("lastTrade.greaterOrEqualThan=" + DEFAULT_LAST_TRADE);
// Get all the quoteList where lastTrade greater than or equals to UPDATED_LAST_TRADE
defaultQuoteShouldNotBeFound("lastTrade.greaterOrEqualThan=" + UPDATED_LAST_TRADE);
}
@Test
@Transactional
public void getAllQuotesByLastTradeIsLessThanSomething() throws Exception {
// Initialize the database
quoteRepository.saveAndFlush(quote);
// Get all the quoteList where lastTrade less than or equals to DEFAULT_LAST_TRADE
defaultQuoteShouldNotBeFound("lastTrade.lessThan=" + DEFAULT_LAST_TRADE);
// Get all the quoteList where lastTrade less than or equals to UPDATED_LAST_TRADE
defaultQuoteShouldBeFound("lastTrade.lessThan=" + UPDATED_LAST_TRADE);
}
/**
* Executes the search, and checks that the default entity is returned
*/
private void defaultQuoteShouldBeFound(String filter) throws Exception {
restQuoteMockMvc.perform(get("/api/quotes?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(quote.getId().intValue())))
.andExpect(jsonPath("$.[*].symbol").value(hasItem(DEFAULT_SYMBOL.toString())))
.andExpect(jsonPath("$.[*].price").value(hasItem(DEFAULT_PRICE.intValue())))
.andExpect(jsonPath("$.[*].lastTrade").value(hasItem(sameInstant(DEFAULT_LAST_TRADE))));
// Check, that the count call also returns 1
restQuoteMockMvc.perform(get("/api/quotes/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("1"));
}
/**
* Executes the search, and checks that the default entity is not returned
*/
private void defaultQuoteShouldNotBeFound(String filter) throws Exception {
restQuoteMockMvc.perform(get("/api/quotes?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
// Check, that the count call also returns 0
restQuoteMockMvc.perform(get("/api/quotes/count?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(content().string("0"));
}
@Test
@Transactional
public void getNonExistingQuote() throws Exception {
// Get the quote
restQuoteMockMvc.perform(get("/api/quotes/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateQuote() throws Exception {
// Initialize the database
quoteRepository.saveAndFlush(quote);
int databaseSizeBeforeUpdate = quoteRepository.findAll().size();
// Update the quote
Quote updatedQuote = quoteRepository.findById(quote.getId()).get();
// Disconnect from session so that the updates on updatedQuote are not directly saved in db
em.detach(updatedQuote);
updatedQuote
.symbol(UPDATED_SYMBOL)
.price(UPDATED_PRICE)
.lastTrade(UPDATED_LAST_TRADE);
QuoteDTO quoteDTO = quoteMapper.toDto(updatedQuote);
restQuoteMockMvc.perform(put("/api/quotes")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(quoteDTO)))
.andExpect(status().isOk());
// Validate the Quote in the database
List<Quote> quoteList = quoteRepository.findAll();
assertThat(quoteList).hasSize(databaseSizeBeforeUpdate);
Quote testQuote = quoteList.get(quoteList.size() - 1);
assertThat(testQuote.getSymbol()).isEqualTo(UPDATED_SYMBOL);
assertThat(testQuote.getPrice()).isEqualTo(UPDATED_PRICE);
assertThat(testQuote.getLastTrade()).isEqualTo(UPDATED_LAST_TRADE);
}
@Test
@Transactional
public void updateNonExistingQuote() throws Exception {
int databaseSizeBeforeUpdate = quoteRepository.findAll().size();
// Create the Quote
QuoteDTO quoteDTO = quoteMapper.toDto(quote);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restQuoteMockMvc.perform(put("/api/quotes")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(quoteDTO)))
.andExpect(status().isBadRequest());
// Validate the Quote in the database
List<Quote> quoteList = quoteRepository.findAll();
assertThat(quoteList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteQuote() throws Exception {
// Initialize the database
quoteRepository.saveAndFlush(quote);
int databaseSizeBeforeDelete = quoteRepository.findAll().size();
// Get the quote
restQuoteMockMvc.perform(delete("/api/quotes/{id}", quote.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Quote> quoteList = quoteRepository.findAll();
assertThat(quoteList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Quote.class);
Quote quote1 = new Quote();
quote1.setId(1L);
Quote quote2 = new Quote();
quote2.setId(quote1.getId());
assertThat(quote1).isEqualTo(quote2);
quote2.setId(2L);
assertThat(quote1).isNotEqualTo(quote2);
quote1.setId(null);
assertThat(quote1).isNotEqualTo(quote2);
}
@Test
@Transactional
public void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(QuoteDTO.class);
QuoteDTO quoteDTO1 = new QuoteDTO();
quoteDTO1.setId(1L);
QuoteDTO quoteDTO2 = new QuoteDTO();
assertThat(quoteDTO1).isNotEqualTo(quoteDTO2);
quoteDTO2.setId(quoteDTO1.getId());
assertThat(quoteDTO1).isEqualTo(quoteDTO2);
quoteDTO2.setId(2L);
assertThat(quoteDTO1).isNotEqualTo(quoteDTO2);
quoteDTO1.setId(null);
assertThat(quoteDTO1).isNotEqualTo(quoteDTO2);
}
@Test
@Transactional
public void testEntityFromId() {
assertThat(quoteMapper.fromId(42L).getId()).isEqualTo(42);
assertThat(quoteMapper.fromId(null)).isNull();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/web/rest/TestUtil.java | jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/web/rest/TestUtil.java | package com.baeldung.jhipster.quotes.web.rest;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.http.MediaType;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Utility class for testing REST controllers.
*/
public class TestUtil {
/** MediaType for JSON UTF8 */
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(
MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), StandardCharsets.UTF_8);
/**
* Convert an object to JSON byte array.
*
* @param object
* the object to convert
* @return the JSON byte array
* @throws IOException
*/
public static byte[] convertObjectToJsonBytes(Object object)
throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
JavaTimeModule module = new JavaTimeModule();
mapper.registerModule(module);
return mapper.writeValueAsBytes(object);
}
/**
* 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 reprensents the same instant as the reference datetime
* @param date the reference datetime against which the examined string is checked
*/
public static ZonedDateTimeMatcher sameInstant(ZonedDateTime date) {
return new ZonedDateTimeMatcher(date);
}
/**
* 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.hashCode()).isEqualTo(domainObject1.hashCode());
// 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.hashCode()).isEqualTo(domainObject2.hashCode());
}
/**
* Create a FormattingConversionService which use ISO date format, instead of the localized one.
* @return the FormattingConversionService
*/
public static FormattingConversionService createFormattingConversionService() {
DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService ();
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setUseIsoFormat(true);
registrar.registerFormatters(dfcs);
return dfcs;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/web/rest/LogsResourceIntTest.java | jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/web/rest/LogsResourceIntTest.java | package com.baeldung.jhipster.quotes.web.rest;
import com.baeldung.jhipster.quotes.QuotesApp;
import com.baeldung.jhipster.quotes.config.SecurityBeanOverrideConfiguration;
import com.baeldung.jhipster.quotes.web.rest.vm.LoggerVM;
import ch.qos.logback.classic.AsyncAppender;
import ch.qos.logback.classic.LoggerContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Test class for the LogsResource REST controller.
*
* @see LogsResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SecurityBeanOverrideConfiguration.class, QuotesApp.class})
public class LogsResourceIntTest {
private MockMvc restLogsMockMvc;
@Before
public void setup() {
LogsResource logsResource = new LogsResource();
this.restLogsMockMvc = MockMvcBuilders
.standaloneSetup(logsResource)
.build();
}
@Test
public void getAllLogs() throws Exception {
restLogsMockMvc.perform(get("/management/logs"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
}
@Test
public void changeLogs() throws Exception {
LoggerVM logger = new LoggerVM();
logger.setLevel("INFO");
logger.setName("some.test.logger");
restLogsMockMvc.perform(put("/management/logs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(logger)))
.andExpect(status().isNoContent());
}
@Test
public void testLogstashAppender() {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
assertThat(context.getLogger("ROOT").getAppender("ASYNC_LOGSTASH")).isInstanceOf(AsyncAppender.class);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/web/rest/util/PaginationUtilUnitTest.java | jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/web/rest/util/PaginationUtilUnitTest.java | package com.baeldung.jhipster.quotes.web.rest.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
/**
* Tests based on parsing algorithm in app/components/util/pagination-util.service.js
*
* @see PaginationUtil
*/
public class PaginationUtilUnitTest {
@Test
public void generatePaginationHttpHeadersTest() {
String baseUrl = "/api/_search/example";
List<String> content = new ArrayList<>();
Page<String> page = new PageImpl<>(content, PageRequest.of(6, 50), 400L);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
List<String> strHeaders = headers.get(HttpHeaders.LINK);
assertNotNull(strHeaders);
assertTrue(strHeaders.size() == 1);
String headerData = strHeaders.get(0);
assertTrue(headerData.split(",").length == 4);
String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
+ "</api/_search/example?page=5&size=50>; rel=\"prev\","
+ "</api/_search/example?page=7&size=50>; rel=\"last\","
+ "</api/_search/example?page=0&size=50>; rel=\"first\"";
assertEquals(expectedData, headerData);
List<String> xTotalCountHeaders = headers.get("X-Total-Count");
assertTrue(xTotalCountHeaders.size() == 1);
assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/web/rest/errors/ExceptionTranslatorTestController.java | jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/web/rest/errors/ExceptionTranslatorTestController.java | package com.baeldung.jhipster.quotes.web.rest.errors;
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.*;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
@RestController
public class ExceptionTranslatorTestController {
@GetMapping("/test/concurrency-failure")
public void concurrencyFailure() {
throw new ConcurrencyFailureException("test concurrency failure");
}
@PostMapping("/test/method-argument")
public void methodArgument(@Valid @RequestBody TestDTO testDTO) {
}
@GetMapping("/test/parameterized-error")
public void parameterizedError() {
throw new CustomParameterizedException("test parameterized error", "param0_value", "param1_value");
}
@GetMapping("/test/parameterized-error2")
public void parameterizedError2() {
Map<String, Object> params = new HashMap<>();
params.put("foo", "foo_value");
params.put("bar", "bar_value");
throw new CustomParameterizedException("test parameterized error", params);
}
@GetMapping("/test/missing-servlet-request-part")
public void missingServletRequestPartException(@RequestPart String part) {
}
@GetMapping("/test/missing-servlet-request-parameter")
public void missingServletRequestParameterException(@RequestParam String param) {
}
@GetMapping("/test/access-denied")
public void accessdenied() {
throw new AccessDeniedException("test access denied!");
}
@GetMapping("/test/unauthorized")
public void unauthorized() {
throw new BadCredentialsException("test authentication failed!");
}
@GetMapping("/test/response-status")
public void exceptionWithReponseStatus() {
throw new TestResponseStatusException();
}
@GetMapping("/test/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-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/web/rest/errors/ExceptionTranslatorIntTest.java | jhipster-modules/jhipster-uaa/quotes/src/test/java/com/baeldung/jhipster/quotes/web/rest/errors/ExceptionTranslatorIntTest.java | package com.baeldung.jhipster.quotes.web.rest.errors;
import com.baeldung.jhipster.quotes.QuotesApp;
import com.baeldung.jhipster.quotes.config.SecurityBeanOverrideConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Test class for the ExceptionTranslator controller advice.
*
* @see ExceptionTranslator
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SecurityBeanOverrideConfiguration.class, QuotesApp.class})
public class ExceptionTranslatorIntTest {
@Autowired
private ExceptionTranslatorTestController controller;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter)
.build();
}
@Test
public void testConcurrencyFailure() throws Exception {
mockMvc.perform(get("/test/concurrency-failure"))
.andExpect(status().isConflict())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE));
}
@Test
public void testMethodArgumentNotValid() throws Exception {
mockMvc.perform(post("/test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION))
.andExpect(jsonPath("$.fieldErrors.[0].objectName").value("testDTO"))
.andExpect(jsonPath("$.fieldErrors.[0].field").value("test"))
.andExpect(jsonPath("$.fieldErrors.[0].message").value("NotNull"));
}
@Test
public void testParameterizedError() throws Exception {
mockMvc.perform(get("/test/parameterized-error"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("test parameterized error"))
.andExpect(jsonPath("$.params.param0").value("param0_value"))
.andExpect(jsonPath("$.params.param1").value("param1_value"));
}
@Test
public void testParameterizedError2() throws Exception {
mockMvc.perform(get("/test/parameterized-error2"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("test parameterized error"))
.andExpect(jsonPath("$.params.foo").value("foo_value"))
.andExpect(jsonPath("$.params.bar").value("bar_value"));
}
@Test
public void testMissingServletRequestPartException() throws Exception {
mockMvc.perform(get("/test/missing-servlet-request-part"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.400"));
}
@Test
public void testMissingServletRequestParameterException() throws Exception {
mockMvc.perform(get("/test/missing-servlet-request-parameter"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.400"));
}
@Test
public void testAccessDenied() throws Exception {
mockMvc.perform(get("/test/access-denied"))
.andExpect(status().isForbidden())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.403"))
.andExpect(jsonPath("$.detail").value("test access denied!"));
}
@Test
public void testUnauthorized() throws Exception {
mockMvc.perform(get("/test/unauthorized"))
.andExpect(status().isUnauthorized())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.401"))
.andExpect(jsonPath("$.path").value("/test/unauthorized"))
.andExpect(jsonPath("$.detail").value("test authentication failed!"));
}
@Test
public void testMethodNotSupported() throws Exception {
mockMvc.perform(post("/test/access-denied"))
.andExpect(status().isMethodNotAllowed())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.405"))
.andExpect(jsonPath("$.detail").value("Request method 'POST' not supported"));
}
@Test
public void testExceptionWithResponseStatus() throws Exception {
mockMvc.perform(get("/test/response-status"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.400"))
.andExpect(jsonPath("$.title").value("test response status"));
}
@Test
public void testInternalServerError() throws Exception {
mockMvc.perform(get("/test/internal-server-error"))
.andExpect(status().isInternalServerError())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.500"))
.andExpect(jsonPath("$.title").value("Internal Server Error"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/ApplicationWebXml.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/ApplicationWebXml.java | package com.baeldung.jhipster.quotes;
import com.baeldung.jhipster.quotes.config.DefaultProfileUtil;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
* This is a helper Java class that provides an alternative to creating a 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(QuotesApp.class);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/QuotesApp.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/QuotesApp.java | package com.baeldung.jhipster.quotes;
import com.baeldung.jhipster.quotes.client.OAuth2InterceptedFeignConfiguration;
import com.baeldung.jhipster.quotes.config.ApplicationProperties;
import com.baeldung.jhipster.quotes.config.DefaultProfileUtil;
import io.github.jhipster.config.JHipsterConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.env.Environment;
import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
@ComponentScan(
excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = OAuth2InterceptedFeignConfiguration.class)
)
@SpringBootApplication
@EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class})
@EnableDiscoveryClient
public class QuotesApp {
private static final Logger log = LoggerFactory.getLogger(QuotesApp.class);
private final Environment env;
public QuotesApp(Environment env) {
this.env = env;
}
/**
* Initializes quotes.
* <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(QuotesApp.class);
DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
logApplicationStartup(env);
}
private static void logApplicationStartup(Environment env) {
String protocol = "http";
if (env.getProperty("server.ssl.key-store") != null) {
protocol = "https";
}
String serverPort = env.getProperty("server.port");
String contextPath = env.getProperty("server.servlet.context-path");
if (StringUtils.isBlank(contextPath)) {
contextPath = "/";
}
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("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\t{}://localhost:{}{}\n\t" +
"External: \t{}://{}:{}{}\n\t" +
"Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name"),
protocol,
serverPort,
contextPath,
protocol,
hostAddress,
serverPort,
contextPath,
env.getActiveProfiles());
String configServerStatus = env.getProperty("configserver.status");
if (configServerStatus == null) {
configServerStatus = "Not found or not setup for this application";
}
log.info("\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-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/service/QuoteQueryService.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/service/QuoteQueryService.java | package com.baeldung.jhipster.quotes.service;
import java.util.List;
import javax.persistence.criteria.JoinType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import io.github.jhipster.service.QueryService;
import com.baeldung.jhipster.quotes.domain.Quote;
import com.baeldung.jhipster.quotes.domain.*; // for static metamodels
import com.baeldung.jhipster.quotes.repository.QuoteRepository;
import com.baeldung.jhipster.quotes.service.dto.QuoteCriteria;
import com.baeldung.jhipster.quotes.service.dto.QuoteDTO;
import com.baeldung.jhipster.quotes.service.mapper.QuoteMapper;
/**
* Service for executing complex queries for Quote entities in the database.
* The main input is a {@link QuoteCriteria} which gets converted to {@link Specification},
* in a way that all the filters must apply.
* It returns a {@link List} of {@link QuoteDTO} or a {@link Page} of {@link QuoteDTO} which fulfills the criteria.
*/
@Service
@Transactional(readOnly = true)
public class QuoteQueryService extends QueryService<Quote> {
private final Logger log = LoggerFactory.getLogger(QuoteQueryService.class);
private final QuoteRepository quoteRepository;
private final QuoteMapper quoteMapper;
public QuoteQueryService(QuoteRepository quoteRepository, QuoteMapper quoteMapper) {
this.quoteRepository = quoteRepository;
this.quoteMapper = quoteMapper;
}
/**
* Return a {@link List} of {@link QuoteDTO} which matches the criteria from the database
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public List<QuoteDTO> findByCriteria(QuoteCriteria criteria) {
log.debug("find by criteria : {}", criteria);
final Specification<Quote> specification = createSpecification(criteria);
return quoteMapper.toDto(quoteRepository.findAll(specification));
}
/**
* Return a {@link Page} of {@link QuoteDTO} which matches the criteria from the database
* @param criteria The object which holds all the filters, which the entities should match.
* @param page The page, which should be returned.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public Page<QuoteDTO> findByCriteria(QuoteCriteria criteria, Pageable page) {
log.debug("find by criteria : {}, page: {}", criteria, page);
final Specification<Quote> specification = createSpecification(criteria);
return quoteRepository.findAll(specification, page)
.map(quoteMapper::toDto);
}
/**
* Return the number of matching entities in the database
* @param criteria The object which holds all the filters, which the entities should match.
* @return the number of matching entities.
*/
@Transactional(readOnly = true)
public long countByCriteria(QuoteCriteria criteria) {
log.debug("count by criteria : {}", criteria);
final Specification<Quote> specification = createSpecification(criteria);
return quoteRepository.count(specification);
}
/**
* Function to convert QuoteCriteria to a {@link Specification}
*/
private Specification<Quote> createSpecification(QuoteCriteria criteria) {
Specification<Quote> specification = Specification.where(null);
if (criteria != null) {
if (criteria.getId() != null) {
specification = specification.and(buildSpecification(criteria.getId(), Quote_.id));
}
if (criteria.getSymbol() != null) {
specification = specification.and(buildStringSpecification(criteria.getSymbol(), Quote_.symbol));
}
if (criteria.getPrice() != null) {
specification = specification.and(buildRangeSpecification(criteria.getPrice(), Quote_.price));
}
if (criteria.getLastTrade() != null) {
specification = specification.and(buildRangeSpecification(criteria.getLastTrade(), Quote_.lastTrade));
}
}
return specification;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/service/package-info.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/service/package-info.java | /**
* Service layer beans.
*/
package com.baeldung.jhipster.quotes.service;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/service/QuoteService.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/service/QuoteService.java | package com.baeldung.jhipster.quotes.service;
import com.baeldung.jhipster.quotes.service.dto.QuoteDTO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.Optional;
/**
* Service Interface for managing Quote.
*/
public interface QuoteService {
/**
* Save a quote.
*
* @param quoteDTO the entity to save
* @return the persisted entity
*/
QuoteDTO save(QuoteDTO quoteDTO);
/**
* Get all the quotes.
*
* @param pageable the pagination information
* @return the list of entities
*/
Page<QuoteDTO> findAll(Pageable pageable);
/**
* Get the "id" quote.
*
* @param id the id of the entity
* @return the entity
*/
Optional<QuoteDTO> findOne(Long id);
/**
* Delete the "id" quote.
*
* @param id the id of the entity
*/
void delete(Long id);
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/service/dto/QuoteDTO.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/service/dto/QuoteDTO.java | package com.baeldung.jhipster.quotes.service.dto;
import java.time.ZonedDateTime;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Objects;
/**
* A DTO for the Quote entity.
*/
public class QuoteDTO implements Serializable {
private Long id;
@NotNull
private String symbol;
@NotNull
private BigDecimal price;
@NotNull
private ZonedDateTime lastTrade;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public ZonedDateTime getLastTrade() {
return lastTrade;
}
public void setLastTrade(ZonedDateTime lastTrade) {
this.lastTrade = lastTrade;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
QuoteDTO quoteDTO = (QuoteDTO) o;
if (quoteDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), quoteDTO.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "QuoteDTO{" +
"id=" + getId() +
", symbol='" + getSymbol() + "'" +
", price=" + getPrice() +
", lastTrade='" + getLastTrade() + "'" +
"}";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/service/dto/QuoteCriteria.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/service/dto/QuoteCriteria.java | package com.baeldung.jhipster.quotes.service.dto;
import java.io.Serializable;
import java.util.Objects;
import io.github.jhipster.service.filter.BooleanFilter;
import io.github.jhipster.service.filter.DoubleFilter;
import io.github.jhipster.service.filter.Filter;
import io.github.jhipster.service.filter.FloatFilter;
import io.github.jhipster.service.filter.IntegerFilter;
import io.github.jhipster.service.filter.LongFilter;
import io.github.jhipster.service.filter.StringFilter;
import io.github.jhipster.service.filter.BigDecimalFilter;
import io.github.jhipster.service.filter.ZonedDateTimeFilter;
/**
* Criteria class for the Quote entity. This class is used in QuoteResource to
* receive all the possible filtering options from the Http GET request parameters.
* For example the following could be a valid requests:
* <code> /quotes?id.greaterThan=5&attr1.contains=something&attr2.specified=false</code>
* As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use
* fix type specific filters.
*/
public class QuoteCriteria implements Serializable {
private static final long serialVersionUID = 1L;
private LongFilter id;
private StringFilter symbol;
private BigDecimalFilter price;
private ZonedDateTimeFilter lastTrade;
public QuoteCriteria() {
}
public LongFilter getId() {
return id;
}
public void setId(LongFilter id) {
this.id = id;
}
public StringFilter getSymbol() {
return symbol;
}
public void setSymbol(StringFilter symbol) {
this.symbol = symbol;
}
public BigDecimalFilter getPrice() {
return price;
}
public void setPrice(BigDecimalFilter price) {
this.price = price;
}
public ZonedDateTimeFilter getLastTrade() {
return lastTrade;
}
public void setLastTrade(ZonedDateTimeFilter lastTrade) {
this.lastTrade = lastTrade;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final QuoteCriteria that = (QuoteCriteria) o;
return
Objects.equals(id, that.id) &&
Objects.equals(symbol, that.symbol) &&
Objects.equals(price, that.price) &&
Objects.equals(lastTrade, that.lastTrade);
}
@Override
public int hashCode() {
return Objects.hash(
id,
symbol,
price,
lastTrade
);
}
@Override
public String toString() {
return "QuoteCriteria{" +
(id != null ? "id=" + id + ", " : "") +
(symbol != null ? "symbol=" + symbol + ", " : "") +
(price != null ? "price=" + price + ", " : "") +
(lastTrade != null ? "lastTrade=" + lastTrade + ", " : "") +
"}";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/service/impl/QuoteServiceImpl.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/service/impl/QuoteServiceImpl.java | package com.baeldung.jhipster.quotes.service.impl;
import com.baeldung.jhipster.quotes.service.QuoteService;
import com.baeldung.jhipster.quotes.domain.Quote;
import com.baeldung.jhipster.quotes.repository.QuoteRepository;
import com.baeldung.jhipster.quotes.service.dto.QuoteDTO;
import com.baeldung.jhipster.quotes.service.mapper.QuoteMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* Service Implementation for managing Quote.
*/
@Service
@Transactional
public class QuoteServiceImpl implements QuoteService {
private final Logger log = LoggerFactory.getLogger(QuoteServiceImpl.class);
private final QuoteRepository quoteRepository;
private final QuoteMapper quoteMapper;
public QuoteServiceImpl(QuoteRepository quoteRepository, QuoteMapper quoteMapper) {
this.quoteRepository = quoteRepository;
this.quoteMapper = quoteMapper;
}
/**
* Save a quote.
*
* @param quoteDTO the entity to save
* @return the persisted entity
*/
@Override
public QuoteDTO save(QuoteDTO quoteDTO) {
log.debug("Request to save Quote : {}", quoteDTO);
Quote quote = quoteMapper.toEntity(quoteDTO);
quote = quoteRepository.save(quote);
return quoteMapper.toDto(quote);
}
/**
* Get all the quotes.
*
* @param pageable the pagination information
* @return the list of entities
*/
@Override
@Transactional(readOnly = true)
public Page<QuoteDTO> findAll(Pageable pageable) {
log.debug("Request to get all Quotes");
return quoteRepository.findAll(pageable)
.map(quoteMapper::toDto);
}
/**
* Get one quote by id.
*
* @param id the id of the entity
* @return the entity
*/
@Override
@Transactional(readOnly = true)
public Optional<QuoteDTO> findOne(Long id) {
log.debug("Request to get Quote : {}", id);
return quoteRepository.findById(id)
.map(quoteMapper::toDto);
}
/**
* Delete the quote by id.
*
* @param id the id of the entity
*/
@Override
public void delete(Long id) {
log.debug("Request to delete Quote : {}", id);
quoteRepository.deleteById(id);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/service/mapper/QuoteMapper.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/service/mapper/QuoteMapper.java | package com.baeldung.jhipster.quotes.service.mapper;
import com.baeldung.jhipster.quotes.domain.*;
import com.baeldung.jhipster.quotes.service.dto.QuoteDTO;
import org.mapstruct.*;
/**
* Mapper for the entity Quote and its DTO QuoteDTO.
*/
@Mapper(componentModel = "spring", uses = {})
public interface QuoteMapper extends EntityMapper<QuoteDTO, Quote> {
default Quote fromId(Long id) {
if (id == null) {
return null;
}
Quote quote = new Quote();
quote.setId(id);
return quote;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/service/mapper/EntityMapper.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/service/mapper/EntityMapper.java | package com.baeldung.jhipster.quotes.service.mapper;
import java.util.List;
/**
* Contract for a generic dto to entity mapper.
*
* @param <D> - DTO type parameter.
* @param <E> - Entity type parameter.
*/
public interface EntityMapper <D, E> {
E toEntity(D dto);
D toDto(E entity);
List <E> toEntity(List<D> dtoList);
List <D> toDto(List<E> entityList);
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/aop/logging/LoggingAspect.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/aop/logging/LoggingAspect.java | package com.baeldung.jhipster.quotes.aop.logging;
import io.github.jhipster.config.JHipsterConstants;
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 java.util.Arrays;
/**
* 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 Logger log = LoggerFactory.getLogger(this.getClass());
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.baeldung.jhipster.quotes.repository..*)"+
" || within(com.baeldung.jhipster.quotes.service..*)"+
" || within(com.baeldung.jhipster.quotes.web.rest..*)")
public void applicationPackagePointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
/**
* 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(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e);
} else {
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL");
}
}
/**
* Advice that logs when a method is entered and exited.
*
* @param joinPoint join point for advice
* @return result
* @throws Throwable throws IllegalArgumentException
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
if (log.isDebugEnabled()) {
log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
throw e;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/domain/Quote.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/domain/Quote.java | package com.baeldung.jhipster.quotes.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.ZonedDateTime;
import java.util.Objects;
/**
* A Quote.
*/
@Entity
@Table(name = "quote")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Quote implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "symbol", nullable = false)
private String symbol;
@NotNull
@Column(name = "price", precision = 10, scale = 2, nullable = false)
private BigDecimal price;
@NotNull
@Column(name = "last_trade", nullable = false)
private ZonedDateTime lastTrade;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSymbol() {
return symbol;
}
public Quote symbol(String symbol) {
this.symbol = symbol;
return this;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public BigDecimal getPrice() {
return price;
}
public Quote price(BigDecimal price) {
this.price = price;
return this;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public ZonedDateTime getLastTrade() {
return lastTrade;
}
public Quote lastTrade(ZonedDateTime lastTrade) {
this.lastTrade = lastTrade;
return this;
}
public void setLastTrade(ZonedDateTime lastTrade) {
this.lastTrade = lastTrade;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Quote quote = (Quote) o;
if (quote.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), quote.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "Quote{" +
"id=" + getId() +
", symbol='" + getSymbol() + "'" +
", price=" + getPrice() +
", lastTrade='" + getLastTrade() + "'" +
"}";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/domain/package-info.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/domain/package-info.java | /**
* JPA domain objects.
*/
package com.baeldung.jhipster.quotes.domain;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/domain/PersistentAuditEvent.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/domain/PersistentAuditEvent.java | package com.baeldung.jhipster.quotes.domain;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
/**
* Persist AuditEvent managed by the Spring Boot actuator.
*
* @see org.springframework.boot.actuate.audit.AuditEvent
*/
@Entity
@Table(name = "jhi_persistent_audit_event")
public class PersistentAuditEvent implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "event_id")
private Long id;
@NotNull
@Column(nullable = false)
private String principal;
@Column(name = "event_date")
private Instant auditEventDate;
@Column(name = "event_type")
private String auditEventType;
@ElementCollection
@MapKeyColumn(name = "name")
@Column(name = "value")
@CollectionTable(name = "jhi_persistent_audit_evt_data", joinColumns=@JoinColumn(name="event_id"))
private Map<String, String> data = new HashMap<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPrincipal() {
return principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public Instant getAuditEventDate() {
return auditEventDate;
}
public void setAuditEventDate(Instant auditEventDate) {
this.auditEventDate = auditEventDate;
}
public String getAuditEventType() {
return auditEventType;
}
public void setAuditEventType(String auditEventType) {
this.auditEventType = auditEventType;
}
public Map<String, String> getData() {
return data;
}
public void setData(Map<String, String> data) {
this.data = data;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/domain/AbstractAuditingEntity.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/domain/AbstractAuditingEntity.java | package com.baeldung.jhipster.quotes.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.envers.Audited;
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;
import java.io.Serializable;
import java.time.Instant;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
/**
* Base abstract class for entities which will hold definitions for created, last modified by and created,
* last modified by date.
*/
@MappedSuperclass
@Audited
@EntityListeners(AuditingEntityListener.class)
public abstract class AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@CreatedBy
@Column(name = "created_by", nullable = false, length = 50, updatable = false)
@JsonIgnore
private String createdBy;
@CreatedDate
@Column(name = "created_date", nullable = false, updatable = false)
@JsonIgnore
private Instant createdDate = Instant.now();
@LastModifiedBy
@Column(name = "last_modified_by", length = 50)
@JsonIgnore
private String lastModifiedBy;
@LastModifiedDate
@Column(name = "last_modified_date")
@JsonIgnore
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-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/repository/QuoteRepository.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/repository/QuoteRepository.java | package com.baeldung.jhipster.quotes.repository;
import com.baeldung.jhipster.quotes.domain.Quote;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data repository for the Quote entity.
*/
@SuppressWarnings("unused")
@Repository
public interface QuoteRepository extends JpaRepository<Quote, Long>, JpaSpecificationExecutor<Quote> {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/repository/package-info.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/repository/package-info.java | /**
* Spring Data JPA repositories.
*/
package com.baeldung.jhipster.quotes.repository;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/security/package-info.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/security/package-info.java | /**
* Spring Security configuration.
*/
package com.baeldung.jhipster.quotes.security;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/security/SpringSecurityAuditorAware.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/security/SpringSecurityAuditorAware.java | package com.baeldung.jhipster.quotes.security;
import com.baeldung.jhipster.quotes.config.Constants;
import java.util.Optional;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
/**
* Implementation of 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_ACCOUNT));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/security/SecurityUtils.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/security/SecurityUtils.java | package com.baeldung.jhipster.quotes.security;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Optional;
/**
* Utility class for Spring Security.
*/
public final class SecurityUtils {
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(securityContext.getAuthentication())
.map(authentication -> {
if (authentication.getPrincipal() instanceof UserDetails) {
UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
return springSecurityUser.getUsername();
} else if (authentication.getPrincipal() instanceof String) {
return (String) authentication.getPrincipal();
}
return null;
});
}
/**
* Check if a user is authenticated.
*
* @return true if the user is authenticated, false otherwise
*/
public static boolean isAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.map(authentication -> authentication.getAuthorities().stream()
.noneMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS)))
.orElse(false);
}
/**
* If the current user has a specific authority (security role).
* <p>
* The name of this method comes from the isUserInRole() method in the Servlet API
*
* @param authority the authority to check
* @return true if the current user has the authority, false otherwise
*/
public static boolean isCurrentUserInRole(String authority) {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.map(authentication -> authentication.getAuthorities().stream()
.anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(authority)))
.orElse(false);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/security/AuthoritiesConstants.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/security/AuthoritiesConstants.java | package com.baeldung.jhipster.quotes.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-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/security/oauth2/UaaSignatureVerifierClient.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/security/oauth2/UaaSignatureVerifierClient.java | package com.baeldung.jhipster.quotes.security.oauth2;
import com.baeldung.jhipster.quotes.config.oauth2.OAuth2Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.jwt.crypto.sign.SignatureVerifier;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
/**
* Client fetching the public key from UAA to create a SignatureVerifier.
*/
@Component
public class UaaSignatureVerifierClient implements OAuth2SignatureVerifierClient {
private final Logger log = LoggerFactory.getLogger(UaaSignatureVerifierClient.class);
private final RestTemplate restTemplate;
protected final OAuth2Properties oAuth2Properties;
public UaaSignatureVerifierClient(DiscoveryClient discoveryClient, @Qualifier("loadBalancedRestTemplate") RestTemplate restTemplate,
OAuth2Properties oAuth2Properties) {
this.restTemplate = restTemplate;
this.oAuth2Properties = oAuth2Properties;
// Load available UAA servers
discoveryClient.getServices();
}
/**
* Fetches the public key from the UAA.
*
* @return the public key used to verify JWT tokens; or null.
*/
@Override
public SignatureVerifier getSignatureVerifier() throws Exception {
try {
HttpEntity<Void> request = new HttpEntity<Void>(new HttpHeaders());
String key = (String) restTemplate
.exchange(getPublicKeyEndpoint(), HttpMethod.GET, request, Map.class).getBody()
.get("value");
return new RsaVerifier(key);
} catch (IllegalStateException ex) {
log.warn("could not contact UAA to get public key");
return null;
}
}
/** Returns the configured endpoint URI to retrieve the public key. */
private String getPublicKeyEndpoint() {
String tokenEndpointUrl = oAuth2Properties.getSignatureVerification().getPublicKeyEndpointUri();
if (tokenEndpointUrl == null) {
throw new InvalidClientException("no token endpoint configured in application properties");
}
return tokenEndpointUrl;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/security/oauth2/OAuth2SignatureVerifierClient.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/security/oauth2/OAuth2SignatureVerifierClient.java | package com.baeldung.jhipster.quotes.security.oauth2;
import org.springframework.security.jwt.crypto.sign.SignatureVerifier;
/**
* Abstracts how to create a SignatureVerifier to verify JWT tokens with a public key.
* Implementations will have to contact the OAuth2 authorization server to fetch the public key
* and use it to build a SignatureVerifier in a server specific way.
*
* @see UaaSignatureVerifierClient
*/
public interface OAuth2SignatureVerifierClient {
/**
* Returns the SignatureVerifier used to verify JWT tokens.
* Fetches the public key from the Authorization server to create
* this verifier.
*
* @return the new verifier used to verify JWT signatures.
* Will be null if we cannot contact the token endpoint.
* @throws Exception if we could not create a SignatureVerifier or contact the token endpoint.
*/
SignatureVerifier getSignatureVerifier() throws Exception;
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/SecurityConfiguration.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/SecurityConfiguration.java | package com.baeldung.jhipster.quotes.config;
import com.baeldung.jhipster.quotes.config.oauth2.OAuth2JwtAccessTokenConverter;
import com.baeldung.jhipster.quotes.config.oauth2.OAuth2Properties;
import com.baeldung.jhipster.quotes.security.oauth2.OAuth2SignatureVerifierClient;
import com.baeldung.jhipster.quotes.security.AuthoritiesConstants;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.loadbalancer.RestTemplateCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.web.client.RestTemplate;
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends ResourceServerConfigurerAdapter {
private final OAuth2Properties oAuth2Properties;
public SecurityConfiguration(OAuth2Properties oAuth2Properties) {
this.oAuth2Properties = oAuth2Properties;
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.headers()
.frameOptions()
.disable()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll()
.antMatchers("/management/info").permitAll()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN);
}
@Bean
public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
return new JwtTokenStore(jwtAccessTokenConverter);
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter(OAuth2SignatureVerifierClient signatureVerifierClient) {
return new OAuth2JwtAccessTokenConverter(oAuth2Properties, signatureVerifierClient);
}
@Bean
@Qualifier("loadBalancedRestTemplate")
public RestTemplate loadBalancedRestTemplate(RestTemplateCustomizer customizer) {
RestTemplate restTemplate = new RestTemplate();
customizer.customize(restTemplate);
return restTemplate;
}
@Bean
@Qualifier("vanillaRestTemplate")
public RestTemplate vanillaRestTemplate() {
return new RestTemplate();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/FeignConfiguration.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/FeignConfiguration.java | package com.baeldung.jhipster.quotes.config;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableFeignClients(basePackages = "com.baeldung.jhipster.quotes")
public class FeignConfiguration {
/**
* Set the Feign specific log level to log client REST requests
*/
@Bean
feign.Logger.Level feignLoggerLevel() {
return feign.Logger.Level.BASIC;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/ApplicationProperties.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/ApplicationProperties.java | package com.baeldung.jhipster.quotes.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Properties specific to Quotes.
* <p>
* Properties are configured in the application.yml file.
* See {@link io.github.jhipster.config.JHipsterProperties} for a good example.
*/
@ConfigurationProperties(prefix = "application", ignoreUnknownFields = false)
public class ApplicationProperties {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/CloudDatabaseConfiguration.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/CloudDatabaseConfiguration.java | package com.baeldung.jhipster.quotes.config;
import io.github.jhipster.config.JHipsterConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cloud.config.java.AbstractCloudConfig;
import org.springframework.context.annotation.*;
import javax.sql.DataSource;
@Configuration
@Profile(JHipsterConstants.SPRING_PROFILE_CLOUD)
public class CloudDatabaseConfiguration extends AbstractCloudConfig {
private final Logger log = LoggerFactory.getLogger(CloudDatabaseConfiguration.class);
@Bean
public DataSource dataSource(CacheManager cacheManager) {
log.info("Configuring JDBC datasource from a cloud provider");
return connectionFactory().dataSource();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/DefaultProfileUtil.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/DefaultProfileUtil.java | package com.baeldung.jhipster.quotes.config;
import io.github.jhipster.config.JHipsterConstants;
import org.springframework.boot.SpringApplication;
import org.springframework.core.env.Environment;
import java.util.*;
/**
* Utility class to load a Spring profile to be used as default
* when there is no <code>spring.profiles.active</code> set in the environment or as command line argument.
* If the value is not available in <code>application.yml</code> then <code>dev</code> profile will be used as default.
*/
public final class DefaultProfileUtil {
private static final String SPRING_PROFILE_DEFAULT = "spring.profiles.default";
private DefaultProfileUtil() {
}
/**
* Set a default to use when no profile is configured.
*
* @param app the Spring application
*/
public static void addDefaultProfile(SpringApplication app) {
Map<String, Object> defProperties = new HashMap<>();
/*
* The default profile to use when no other profiles are defined
* This cannot be set in the <code>application.yml</code> file.
* See https://github.com/spring-projects/spring-boot/issues/1219
*/
defProperties.put(SPRING_PROFILE_DEFAULT, JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
app.setDefaultProperties(defProperties);
}
/**
* Get the profiles that are applied else get default profiles.
*
* @param env spring environment
* @return profiles
*/
public static String[] getActiveProfiles(Environment env) {
String[] profiles = env.getActiveProfiles();
if (profiles.length == 0) {
return env.getDefaultProfiles();
}
return profiles;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/DatabaseConfiguration.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/DatabaseConfiguration.java | package com.baeldung.jhipster.quotes.config;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.h2.H2ConfigurationHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.sql.SQLException;
@Configuration
@EnableJpaRepositories("com.baeldung.jhipster.quotes.repository")
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement
public class DatabaseConfiguration {
private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);
/**
* 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 {
log.debug("Starting H2 database");
return H2ConfigurationHelper.createServer();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/CacheConfiguration.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/CacheConfiguration.java | package com.baeldung.jhipster.quotes.config;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.JHipsterProperties;
import com.hazelcast.config.*;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.Hazelcast;
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.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
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 javax.annotation.PreDestroy;
@Configuration
@EnableCaching
public class CacheConfiguration {
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");
CacheManager cacheManager = new com.hazelcast.spring.cache.HazelcastCacheManager(hazelcastInstance);
return cacheManager;
}
@Bean
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
log.debug("Configuring Hazelcast");
HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("quotes");
if (hazelCastInstance != null) {
log.debug("Hazelcast already initialized");
return hazelCastInstance;
}
Config config = new Config();
config.setInstanceName("quotes");
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(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
log.debug("Application is running with the \"dev\" profile, Hazelcast " +
"cluster will only work with localhost instances");
System.setProperty("hazelcast.local.localAddress", "127.0.0.1");
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.getMapConfigs().put("default", initializeDefaultMapConfig(jHipsterProperties));
// Full reference is available at: http://docs.hazelcast.org/docs/management-center/3.9/manual/html/Deploying_and_Starting.html
config.setManagementCenterConfig(initializeDefaultManagementCenterConfig(jHipsterProperties));
config.getMapConfigs().put("com.baeldung.jhipster.quotes.domain.*", initializeDomainMapConfig(jHipsterProperties));
return Hazelcast.newHazelcastInstance(config);
}
private ManagementCenterConfig initializeDefaultManagementCenterConfig(JHipsterProperties jHipsterProperties) {
ManagementCenterConfig managementCenterConfig = new ManagementCenterConfig();
managementCenterConfig.setEnabled(jHipsterProperties.getCache().getHazelcast().getManagementCenter().isEnabled());
managementCenterConfig.setUrl(jHipsterProperties.getCache().getHazelcast().getManagementCenter().getUrl());
managementCenterConfig.setUpdateInterval(jHipsterProperties.getCache().getHazelcast().getManagementCenter().getUpdateInterval());
return managementCenterConfig;
}
private MapConfig initializeDefaultMapConfig(JHipsterProperties jHipsterProperties) {
MapConfig mapConfig = new MapConfig();
/*
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.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.setMaxSizeConfig(new MaxSizeConfig(0, MaxSizeConfig.MaxSizePolicy.USED_HEAP_SIZE));
return mapConfig;
}
private MapConfig initializeDomainMapConfig(JHipsterProperties jHipsterProperties) {
MapConfig mapConfig = new MapConfig();
mapConfig.setTimeToLiveSeconds(jHipsterProperties.getCache().getHazelcast().getTimeToLiveSeconds());
return mapConfig;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/package-info.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/package-info.java | /**
* Spring Framework configuration files.
*/
package com.baeldung.jhipster.quotes.config;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/DateTimeFormatConfiguration.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/DateTimeFormatConfiguration.java | package com.baeldung.jhipster.quotes.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-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/AsyncConfiguration.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/AsyncConfiguration.java | package com.baeldung.jhipster.quotes.config;
import io.github.jhipster.async.ExceptionHandlingAsyncTaskExecutor;
import io.github.jhipster.config.JHipsterProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.*;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer, SchedulingConfigurer {
private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);
private final JHipsterProperties jHipsterProperties;
public AsyncConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
log.debug("Creating Async Task Executor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(jHipsterProperties.getAsync().getCorePoolSize());
executor.setMaxPoolSize(jHipsterProperties.getAsync().getMaxPoolSize());
executor.setQueueCapacity(jHipsterProperties.getAsync().getQueueCapacity());
executor.setThreadNamePrefix("quotes-Executor-");
return new ExceptionHandlingAsyncTaskExecutor(executor);
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(scheduledTaskExecutor());
}
@Bean
public Executor scheduledTaskExecutor() {
return Executors.newScheduledThreadPool(jHipsterProperties.getAsync().getCorePoolSize());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/WebConfigurer.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/WebConfigurer.java | package com.baeldung.jhipster.quotes.config;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.servlet.InstrumentedFilter;
import com.codahale.metrics.servlets.MetricsServlet;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.JHipsterProperties;
import io.github.jhipster.config.h2.H2ConfigurationHelper;
import io.undertow.UndertowOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.*;
import org.springframework.boot.web.servlet.ServletContextInitializer;
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.http.MediaType;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import javax.servlet.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
/**
* 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;
private MetricRegistry metricRegistry;
public WebConfigurer(Environment env, JHipsterProperties jHipsterProperties) {
this.env = env;
this.jHipsterProperties = jHipsterProperties;
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
if (env.getActiveProfiles().length != 0) {
log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles());
}
EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
initMetrics(servletContext, disps);
if (env.acceptsProfiles(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) {
setMimeMappings(server);
/*
* Enable HTTP/2 for Undertow - https://twitter.com/ankinson/status/829256167700492288
* HTTP/2 requires HTTPS, so HTTP requests will fallback to HTTP/1.1.
* See the JHipsterProperties class and your application-*.yml configuration files
* for more information.
*/
if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) &&
server instanceof UndertowServletWebServerFactory) {
((UndertowServletWebServerFactory) server)
.addBuilderCustomizers(builder ->
builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true));
}
}
private void setMimeMappings(WebServerFactory server) {
if (server instanceof ConfigurableServletWebServerFactory) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
// IE issue, see https://github.com/jhipster/generator-jhipster/pull/711
mappings.add("html", MediaType.TEXT_HTML_VALUE + ";charset=" + StandardCharsets.UTF_8.name().toLowerCase());
// CloudFoundry issue, see https://github.com/cloudfoundry/gorouter/issues/64
mappings.add("json", MediaType.TEXT_HTML_VALUE + ";charset=" + StandardCharsets.UTF_8.name().toLowerCase());
ConfigurableServletWebServerFactory servletWebServer = (ConfigurableServletWebServerFactory) server;
servletWebServer.setMimeMappings(mappings);
}
}
/**
* Initializes Metrics.
*/
private void initMetrics(ServletContext servletContext, EnumSet<DispatcherType> disps) {
log.debug("Initializing Metrics registries");
servletContext.setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE,
metricRegistry);
servletContext.setAttribute(MetricsServlet.METRICS_REGISTRY,
metricRegistry);
log.debug("Registering Metrics Filter");
FilterRegistration.Dynamic metricsFilter = servletContext.addFilter("webappMetricsFilter",
new InstrumentedFilter());
metricsFilter.addMappingForUrlPatterns(disps, true, "/*");
metricsFilter.setAsyncSupported(true);
log.debug("Registering Metrics Servlet");
ServletRegistration.Dynamic metricsAdminServlet =
servletContext.addServlet("metricsServlet", new MetricsServlet());
metricsAdminServlet.addMapping("/management/metrics/*");
metricsAdminServlet.setAsyncSupported(true);
metricsAdminServlet.setLoadOnStartup(2);
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = jHipsterProperties.getCors();
if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
log.debug("Registering CORS filter");
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/management/**", config);
source.registerCorsConfiguration("/v2/api-docs", config);
}
return new CorsFilter(source);
}
/**
* Initializes H2 console.
*/
private void initH2Console(ServletContext servletContext) {
log.debug("Initialize H2 console");
H2ConfigurationHelper.initH2Console(servletContext);
}
@Autowired(required = false)
public void setMetricRegistry(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/JacksonConfiguration.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/JacksonConfiguration.java | package com.baeldung.jhipster.quotes.config;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zalando.problem.ProblemModule;
import org.zalando.problem.violations.ConstraintViolationProblemModule;
@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 Hibernate5Module hibernate5Module() {
return new Hibernate5Module();
}
/*
* Jackson Afterburner module to speed up serialization/deserialization.
*/
@Bean
public AfterburnerModule afterburnerModule() {
return new AfterburnerModule();
}
/*
* Module for serialization/deserialization of RFC7807 Problem.
*/
@Bean
ProblemModule problemModule() {
return new ProblemModule();
}
/*
* Module for serialization/deserialization of ConstraintViolationProblem.
*/
@Bean
ConstraintViolationProblemModule constraintViolationProblemModule() {
return new ConstraintViolationProblemModule();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/LoggingConfiguration.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/LoggingConfiguration.java | package com.baeldung.jhipster.quotes.config;
import java.net.InetSocketAddress;
import java.util.Iterator;
import io.github.jhipster.config.JHipsterProperties;
import ch.qos.logback.classic.AsyncAppender;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.boolex.OnMarkerEvaluator;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.filter.EvaluatorFilter;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.spi.FilterReply;
import net.logstash.logback.appender.LogstashTcpSocketAppender;
import net.logstash.logback.encoder.LogstashEncoder;
import net.logstash.logback.stacktrace.ShortenedThrowableConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
@Configuration
@RefreshScope
public class LoggingConfiguration {
private static final String LOGSTASH_APPENDER_NAME = "LOGSTASH";
private static final String ASYNC_LOGSTASH_APPENDER_NAME = "ASYNC_LOGSTASH";
private final Logger log = LoggerFactory.getLogger(LoggingConfiguration.class);
private LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
private final String appName;
private final String serverPort;
private final String version;
private final JHipsterProperties jHipsterProperties;
public LoggingConfiguration(@Value("${spring.application.name}") String appName, @Value("${server.port}") String serverPort,
@Value("${info.project.version:}") String version, JHipsterProperties jHipsterProperties) {
this.appName = appName;
this.serverPort = serverPort;
this.version = version;
this.jHipsterProperties = jHipsterProperties;
if (jHipsterProperties.getLogging().getLogstash().isEnabled()) {
addLogstashAppender(context);
addContextListener(context);
}
if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
setMetricsMarkerLogbackFilter(context);
}
}
private void addContextListener(LoggerContext context) {
LogbackLoggerContextListener loggerContextListener = new LogbackLoggerContextListener();
loggerContextListener.setContext(context);
context.addListener(loggerContextListener);
}
private void addLogstashAppender(LoggerContext context) {
log.info("Initializing Logstash logging");
LogstashTcpSocketAppender logstashAppender = new LogstashTcpSocketAppender();
logstashAppender.setName(LOGSTASH_APPENDER_NAME);
logstashAppender.setContext(context);
String optionalFields = "";
String customFields = "{\"app_name\":\"" + appName + "\",\"app_port\":\"" + serverPort + "\"," +
optionalFields + "\"version\":\"" + version + "\"}";
// More documentation is available at: https://github.com/logstash/logstash-logback-encoder
LogstashEncoder logstashEncoder = new LogstashEncoder();
// Set the Logstash appender config from JHipster properties
logstashEncoder.setCustomFields(customFields);
// Set the Logstash appender config from JHipster properties
logstashAppender.addDestinations(new InetSocketAddress(jHipsterProperties.getLogging().getLogstash().getHost(), jHipsterProperties.getLogging().getLogstash().getPort()));
ShortenedThrowableConverter throwableConverter = new ShortenedThrowableConverter();
throwableConverter.setRootCauseFirst(true);
logstashEncoder.setThrowableConverter(throwableConverter);
logstashEncoder.setCustomFields(customFields);
logstashAppender.setEncoder(logstashEncoder);
logstashAppender.start();
// Wrap the appender in an Async appender for performance
AsyncAppender asyncLogstashAppender = new AsyncAppender();
asyncLogstashAppender.setContext(context);
asyncLogstashAppender.setName(ASYNC_LOGSTASH_APPENDER_NAME);
asyncLogstashAppender.setQueueSize(jHipsterProperties.getLogging().getLogstash().getQueueSize());
asyncLogstashAppender.addAppender(logstashAppender);
asyncLogstashAppender.start();
context.getLogger("ROOT").addAppender(asyncLogstashAppender);
}
// Configure a log filter to remove "metrics" logs from all appenders except the "LOGSTASH" appender
private void setMetricsMarkerLogbackFilter(LoggerContext context) {
log.info("Filtering metrics logs from all appenders except the {} appender", LOGSTASH_APPENDER_NAME);
OnMarkerEvaluator onMarkerMetricsEvaluator = new OnMarkerEvaluator();
onMarkerMetricsEvaluator.setContext(context);
onMarkerMetricsEvaluator.addMarker("metrics");
onMarkerMetricsEvaluator.start();
EvaluatorFilter<ILoggingEvent> metricsFilter = new EvaluatorFilter<>();
metricsFilter.setContext(context);
metricsFilter.setEvaluator(onMarkerMetricsEvaluator);
metricsFilter.setOnMatch(FilterReply.DENY);
metricsFilter.start();
for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) {
for (Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders(); it.hasNext();) {
Appender<ILoggingEvent> appender = it.next();
if (!appender.getName().equals(ASYNC_LOGSTASH_APPENDER_NAME)) {
log.debug("Filter metrics logs from the {} appender", appender.getName());
appender.setContext(context);
appender.addFilter(metricsFilter);
appender.start();
}
}
}
}
/**
* Logback configuration is achieved by configuration file and API.
* When configuration file change is detected, the configuration is reset.
* This listener ensures that the programmatic configuration is also re-applied after reset.
*/
class LogbackLoggerContextListener extends ContextAwareBase implements LoggerContextListener {
@Override
public boolean isResetResistant() {
return true;
}
@Override
public void onStart(LoggerContext context) {
addLogstashAppender(context);
}
@Override
public void onReset(LoggerContext context) {
addLogstashAppender(context);
}
@Override
public void onStop(LoggerContext context) {
// Nothing to do.
}
@Override
public void onLevelChange(ch.qos.logback.classic.Logger logger, Level level) {
// Nothing to do.
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/MetricsConfiguration.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/MetricsConfiguration.java | package com.baeldung.jhipster.quotes.config;
import io.github.jhipster.config.JHipsterProperties;
import com.codahale.metrics.JmxReporter;
import com.codahale.metrics.JvmAttributeGaugeSet;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Slf4jReporter;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.codahale.metrics.jvm.*;
import com.ryantenney.metrics.spring.config.annotation.EnableMetrics;
import com.ryantenney.metrics.spring.config.annotation.MetricsConfigurerAdapter;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import javax.annotation.PostConstruct;
import java.lang.management.ManagementFactory;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableMetrics(proxyTargetClass = true)
public class MetricsConfiguration extends MetricsConfigurerAdapter {
private static final String PROP_METRIC_REG_JVM_MEMORY = "jvm.memory";
private static final String PROP_METRIC_REG_JVM_GARBAGE = "jvm.garbage";
private static final String PROP_METRIC_REG_JVM_THREADS = "jvm.threads";
private static final String PROP_METRIC_REG_JVM_FILES = "jvm.files";
private static final String PROP_METRIC_REG_JVM_BUFFERS = "jvm.buffers";
private static final String PROP_METRIC_REG_JVM_ATTRIBUTE_SET = "jvm.attributes";
private final Logger log = LoggerFactory.getLogger(MetricsConfiguration.class);
private MetricRegistry metricRegistry = new MetricRegistry();
private HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();
private final JHipsterProperties jHipsterProperties;
private HikariDataSource hikariDataSource;
public MetricsConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@Autowired(required = false)
public void setHikariDataSource(HikariDataSource hikariDataSource) {
this.hikariDataSource = hikariDataSource;
}
@Override
@Bean
public MetricRegistry getMetricRegistry() {
return metricRegistry;
}
@Override
@Bean
public HealthCheckRegistry getHealthCheckRegistry() {
return healthCheckRegistry;
}
@PostConstruct
public void init() {
log.debug("Registering JVM gauges");
metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet());
metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet());
metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet());
metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge());
metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
metricRegistry.register(PROP_METRIC_REG_JVM_ATTRIBUTE_SET, new JvmAttributeGaugeSet());
if (hikariDataSource != null) {
log.debug("Monitoring the datasource");
// remove the factory created by HikariDataSourceMetricsPostProcessor until JHipster migrate to Micrometer
hikariDataSource.setMetricsTrackerFactory(null);
hikariDataSource.setMetricRegistry(metricRegistry);
}
if (jHipsterProperties.getMetrics().getJmx().isEnabled()) {
log.debug("Initializing Metrics JMX reporting");
JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
jmxReporter.start();
}
if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
log.info("Initializing Metrics Log reporting");
Marker metricsMarker = MarkerFactory.getMarker("metrics");
final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
.outputTo(LoggerFactory.getLogger("metrics"))
.markWith(metricsMarker)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.build();
reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/LiquibaseConfiguration.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/LiquibaseConfiguration.java | package com.baeldung.jhipster.quotes.config;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.task.TaskExecutor;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.liquibase.AsyncSpringLiquibase;
import liquibase.integration.spring.SpringLiquibase;
@Configuration
public class LiquibaseConfiguration {
private final Logger log = LoggerFactory.getLogger(LiquibaseConfiguration.class);
private final Environment env;
private final CacheManager cacheManager;
public LiquibaseConfiguration(Environment env, CacheManager cacheManager) {
this.env = env;
this.cacheManager = cacheManager;
}
@Bean
public SpringLiquibase liquibase(@Qualifier("taskExecutor") TaskExecutor taskExecutor,
DataSource dataSource, LiquibaseProperties liquibaseProperties) {
// Use liquibase.integration.spring.SpringLiquibase if you don't want Liquibase to start asynchronously
SpringLiquibase liquibase = new AsyncSpringLiquibase(taskExecutor, env);
liquibase.setDataSource(dataSource);
liquibase.setChangeLog("classpath:config/liquibase/master.xml");
liquibase.setContexts(liquibaseProperties.getContexts());
liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
liquibase.setDropFirst(liquibaseProperties.isDropFirst());
liquibase.setChangeLogParameters(liquibaseProperties.getParameters());
if (env.acceptsProfiles(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-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/Constants.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/Constants.java | package com.baeldung.jhipster.quotes.config;
/**
* Application constants.
*/
public final class Constants {
// Regex for acceptable logins
public static final String LOGIN_REGEX = "^[_.@A-Za-z0-9-]*$";
public static final String SYSTEM_ACCOUNT = "system";
public static final String ANONYMOUS_USER = "anonymoususer";
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-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/LoggingAspectConfiguration.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/LoggingAspectConfiguration.java | package com.baeldung.jhipster.quotes.config;
import com.baeldung.jhipster.quotes.aop.logging.LoggingAspect;
import io.github.jhipster.config.JHipsterConstants;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
@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-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/LocaleConfiguration.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/LocaleConfiguration.java | package com.baeldung.jhipster.quotes.config;
import io.github.jhipster.config.locale.AngularCookieLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
@Configuration
public class LocaleConfiguration implements WebMvcConfigurer {
@Bean(name = "localeResolver")
public LocaleResolver localeResolver() {
AngularCookieLocaleResolver cookieLocaleResolver = new AngularCookieLocaleResolver();
cookieLocaleResolver.setCookieName("NG_TRANSLATE_LANG_KEY");
return cookieLocaleResolver;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("language");
registry.addInterceptor(localeChangeInterceptor);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/oauth2/OAuth2Properties.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/oauth2/OAuth2Properties.java | package com.baeldung.jhipster.quotes.config.oauth2;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* OAuth2 properties define properties for OAuth2-based microservices.
*/
@Component
@ConfigurationProperties(prefix = "oauth2", ignoreUnknownFields = false)
public class OAuth2Properties {
private WebClientConfiguration webClientConfiguration = new WebClientConfiguration();
private SignatureVerification signatureVerification = new SignatureVerification();
public WebClientConfiguration getWebClientConfiguration() {
return webClientConfiguration;
}
public SignatureVerification getSignatureVerification() {
return signatureVerification;
}
public static class WebClientConfiguration {
private String clientId = "web_app";
private String secret = "changeit";
/**
* Holds the session timeout in seconds for non-remember-me sessions.
* After so many seconds of inactivity, the session will be terminated.
* Only checked during token refresh, so long access token validity may
* delay the session timeout accordingly.
*/
private int sessionTimeoutInSeconds = 1800;
/**
* Defines the cookie domain. If specified, cookies will be set on this domain.
* If not configured, then cookies will be set on the top-level domain of the
* request you sent, i.e. if you send a request to <code>app1.your-domain.com</code>,
* then cookies will be set <code>on .your-domain.com</code>, such that they
* are also valid for <code>app2.your-domain.com</code>.
*/
private String cookieDomain;
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public int getSessionTimeoutInSeconds() {
return sessionTimeoutInSeconds;
}
public void setSessionTimeoutInSeconds(int sessionTimeoutInSeconds) {
this.sessionTimeoutInSeconds = sessionTimeoutInSeconds;
}
public String getCookieDomain() {
return cookieDomain;
}
public void setCookieDomain(String cookieDomain) {
this.cookieDomain = cookieDomain;
}
}
public static class SignatureVerification {
/**
* Maximum refresh rate for public keys in ms.
* We won't fetch new public keys any faster than that to avoid spamming UAA in case
* we receive a lot of "illegal" tokens.
*/
private long publicKeyRefreshRateLimit = 10 * 1000L;
/**
* Maximum TTL for the public key in ms.
* The public key will be fetched again from UAA if it gets older than that.
* That way, we make sure that we get the newest keys always in case they are updated there.
*/
private long ttl = 24 * 60 * 60 * 1000L;
/**
* Endpoint where to retrieve the public key used to verify token signatures.
*/
private String publicKeyEndpointUri = "http://uaa/oauth/token_key";
public long getPublicKeyRefreshRateLimit() {
return publicKeyRefreshRateLimit;
}
public void setPublicKeyRefreshRateLimit(long publicKeyRefreshRateLimit) {
this.publicKeyRefreshRateLimit = publicKeyRefreshRateLimit;
}
public long getTtl() {
return ttl;
}
public void setTtl(long ttl) {
this.ttl = ttl;
}
public String getPublicKeyEndpointUri() {
return publicKeyEndpointUri;
}
public void setPublicKeyEndpointUri(String publicKeyEndpointUri) {
this.publicKeyEndpointUri = publicKeyEndpointUri;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/oauth2/OAuth2JwtAccessTokenConverter.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/oauth2/OAuth2JwtAccessTokenConverter.java | package com.baeldung.jhipster.quotes.config.oauth2;
import com.baeldung.jhipster.quotes.security.oauth2.OAuth2SignatureVerifierClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.jwt.crypto.sign.SignatureVerifier;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import java.util.Map;
/**
* Improved JwtAccessTokenConverter that can handle lazy fetching of public verifier keys.
*/
public class OAuth2JwtAccessTokenConverter extends JwtAccessTokenConverter {
private final Logger log = LoggerFactory.getLogger(OAuth2JwtAccessTokenConverter.class);
private final OAuth2Properties oAuth2Properties;
private final OAuth2SignatureVerifierClient signatureVerifierClient;
/**
* When did we last fetch the public key?
*/
private long lastKeyFetchTimestamp;
public OAuth2JwtAccessTokenConverter(OAuth2Properties oAuth2Properties, OAuth2SignatureVerifierClient signatureVerifierClient) {
this.oAuth2Properties = oAuth2Properties;
this.signatureVerifierClient = signatureVerifierClient;
tryCreateSignatureVerifier();
}
/**
* Try to decode the token with the current public key.
* If it fails, contact the OAuth2 server to get a new public key, then try again.
* We might not have fetched it in the first place or it might have changed.
*
* @param token the JWT token to decode.
* @return the resulting claims.
* @throws InvalidTokenException if we cannot decode the token.
*/
@Override
protected Map<String, Object> decode(String token) {
try {
//check if our public key and thus SignatureVerifier have expired
long ttl = oAuth2Properties.getSignatureVerification().getTtl();
if (ttl > 0 && System.currentTimeMillis() - lastKeyFetchTimestamp > ttl) {
throw new InvalidTokenException("public key expired");
}
return super.decode(token);
} catch (InvalidTokenException ex) {
if (tryCreateSignatureVerifier()) {
return super.decode(token);
}
throw ex;
}
}
/**
* Fetch a new public key from the AuthorizationServer.
*
* @return true, if we could fetch it; false, if we could not.
*/
private boolean tryCreateSignatureVerifier() {
long t = System.currentTimeMillis();
if (t - lastKeyFetchTimestamp < oAuth2Properties.getSignatureVerification().getPublicKeyRefreshRateLimit()) {
return false;
}
try {
SignatureVerifier verifier = signatureVerifierClient.getSignatureVerifier();
if (verifier != null) {
setVerifier(verifier);
lastKeyFetchTimestamp = t;
log.debug("Public key retrieved from OAuth2 server to create SignatureVerifier");
return true;
}
} catch (Throwable ex) {
log.error("could not get public key from OAuth2 server to create SignatureVerifier", ex);
}
return false;
}
/**
* Extract JWT claims and set it to OAuth2Authentication decoded details.
* Here is how to get details:
*
* <pre>
* <code>
* SecurityContext securityContext = SecurityContextHolder.getContext();
* Authentication authentication = securityContext.getAuthentication();
* if (authentication != null) {
* Object details = authentication.getDetails();
* if(details instanceof OAuth2AuthenticationDetails) {
* Object decodedDetails = ((OAuth2AuthenticationDetails) details).getDecodedDetails();
* if(decodedDetails != null && decodedDetails instanceof Map) {
* String detailFoo = ((Map) decodedDetails).get("foo");
* }
* }
* }
* </code>
* </pre>
* @param claims OAuth2JWTToken claims
* @return OAuth2Authentication
*/
@Override
public OAuth2Authentication extractAuthentication(Map<String, ?> claims) {
OAuth2Authentication authentication = super.extractAuthentication(claims);
authentication.setDetails(claims);
return authentication;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/audit/AuditEventConverter.java | jhipster-modules/jhipster-uaa/quotes/src/main/java/com/baeldung/jhipster/quotes/config/audit/AuditEventConverter.java | package com.baeldung.jhipster.quotes.config.audit;
import com.baeldung.jhipster.quotes.domain.PersistentAuditEvent;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import java.util.*;
@Component
public class AuditEventConverter {
/**
* Convert a list of PersistentAuditEvent to a list of AuditEvent
*
* @param persistentAuditEvents the list to convert
* @return the converted list.
*/
public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
if (persistentAuditEvents == null) {
return Collections.emptyList();
}
List<AuditEvent> auditEvents = new ArrayList<>();
for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
auditEvents.add(convertToAuditEvent(persistentAuditEvent));
}
return auditEvents;
}
/**
* Convert a PersistentAuditEvent to an AuditEvent
*
* @param persistentAuditEvent the event to convert
* @return the converted list.
*/
public AuditEvent convertToAuditEvent(PersistentAuditEvent persistentAuditEvent) {
if (persistentAuditEvent == null) {
return null;
}
return new AuditEvent(persistentAuditEvent.getAuditEventDate(), persistentAuditEvent.getPrincipal(),
persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
}
/**
* Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface
*
* @param data the data to convert
* @return a map of String, Object
*/
public Map<String, Object> convertDataToObjects(Map<String, String> data) {
Map<String, Object> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, String> entry : data.entrySet()) {
results.put(entry.getKey(), entry.getValue());
}
}
return results;
}
/**
* Internal conversion. This method will allow to save additional data.
* By default, it will save the object as string
*
* @param data the data to convert
* @return a map of String, String
*/
public Map<String, String> convertDataToStrings(Map<String, Object> data) {
Map<String, String> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, Object> entry : data.entrySet()) {
// Extract the data that will be saved.
if (entry.getValue() instanceof WebAuthenticationDetails) {
WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) entry.getValue();
results.put("remoteAddress", authenticationDetails.getRemoteAddress());
results.put("sessionId", authenticationDetails.getSessionId());
} else {
results.put(entry.getKey(), Objects.toString(entry.getValue()));
}
}
}
return results;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.