repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/LoggingConfiguration.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/LoggingConfiguration.java | package com.cars.app.config;
import static tech.jhipster.config.logging.LoggingUtils.*;
import ch.qos.logback.classic.LoggerContext;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.info.BuildProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import tech.jhipster.config.JHipsterProperties;
/*
* Configures the console and Logstash log appenders from the app properties
*/
@Configuration
@RefreshScope
public class LoggingConfiguration {
public LoggingConfiguration(
@Value("${spring.application.name}") String appName,
@Value("${server.port}") String serverPort,
JHipsterProperties jHipsterProperties,
ObjectProvider<BuildProperties> buildProperties,
ObjectMapper mapper
) throws JsonProcessingException {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
Map<String, String> map = new HashMap<>();
map.put("app_name", appName);
map.put("app_port", serverPort);
buildProperties.ifAvailable(it -> map.put("version", it.getVersion()));
String customFields = mapper.writeValueAsString(map);
JHipsterProperties.Logging loggingProperties = jHipsterProperties.getLogging();
JHipsterProperties.Logging.Logstash logstashProperties = loggingProperties.getLogstash();
if (loggingProperties.isUseJsonFormat()) {
addJsonConsoleAppender(context, customFields);
}
if (logstashProperties.isEnabled()) {
addLogstashTcpSocketAppender(context, customFields, logstashProperties);
}
if (loggingProperties.isUseJsonFormat() || logstashProperties.isEnabled()) {
addContextListener(context, customFields, loggingProperties);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/SecurityJwtConfiguration.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/SecurityJwtConfiguration.java | package com.cars.app.config;
import static com.cars.app.security.SecurityUtils.AUTHORITIES_KEY;
import static com.cars.app.security.SecurityUtils.JWT_ALGORITHM;
import com.cars.app.management.SecurityMetersService;
import com.nimbusds.jose.jwk.source.ImmutableSecret;
import com.nimbusds.jose.util.Base64;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
@Configuration
public class SecurityJwtConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityJwtConfiguration.class);
@Value("${jhipster.security.authentication.jwt.base64-secret}")
private String jwtKey;
@Bean
public JwtDecoder jwtDecoder(SecurityMetersService metersService) {
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withSecretKey(getSecretKey()).macAlgorithm(JWT_ALGORITHM).build();
return token -> {
try {
return jwtDecoder.decode(token);
} catch (Exception e) {
if (e.getMessage().contains("Invalid signature")) {
metersService.trackTokenInvalidSignature();
} else if (e.getMessage().contains("Jwt expired at")) {
metersService.trackTokenExpired();
} else if (
e.getMessage().contains("Invalid JWT serialization") ||
e.getMessage().contains("Malformed token") ||
e.getMessage().contains("Invalid unsecured/JWS/JWE")
) {
metersService.trackTokenMalformed();
} else {
log.error("Unknown JWT error {}", e.getMessage());
}
throw e;
}
};
}
@Bean
public JwtEncoder jwtEncoder() {
return new NimbusJwtEncoder(new ImmutableSecret<>(getSecretKey()));
}
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
grantedAuthoritiesConverter.setAuthorityPrefix("");
grantedAuthoritiesConverter.setAuthoritiesClaimName(AUTHORITIES_KEY);
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}
private SecretKey getSecretKey() {
byte[] keyBytes = Base64.from(jwtKey).decode();
return new SecretKeySpec(keyBytes, 0, keyBytes.length, JWT_ALGORITHM.getName());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/LiquibaseConfiguration.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/LiquibaseConfiguration.java | package com.cars.app.config;
import java.util.concurrent.Executor;
import javax.sql.DataSource;
import liquibase.integration.spring.SpringLiquibase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseDataSource;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.liquibase.SpringLiquibaseUtil;
@Configuration
public class LiquibaseConfiguration {
private final Logger log = LoggerFactory.getLogger(LiquibaseConfiguration.class);
private final Environment env;
public LiquibaseConfiguration(Environment env) {
this.env = env;
}
@Value("${application.liquibase.async-start:true}")
private Boolean asyncStart;
@Bean
public SpringLiquibase liquibase(
@Qualifier("taskExecutor") Executor executor,
LiquibaseProperties liquibaseProperties,
@LiquibaseDataSource ObjectProvider<DataSource> liquibaseDataSource,
ObjectProvider<DataSource> dataSource,
DataSourceProperties dataSourceProperties
) {
SpringLiquibase liquibase;
if (Boolean.TRUE.equals(asyncStart)) {
liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase(
this.env,
executor,
liquibaseDataSource.getIfAvailable(),
liquibaseProperties,
dataSource.getIfUnique(),
dataSourceProperties
);
} else {
liquibase = SpringLiquibaseUtil.createSpringLiquibase(
liquibaseDataSource.getIfAvailable(),
liquibaseProperties,
dataSource.getIfUnique(),
dataSourceProperties
);
}
liquibase.setChangeLog("classpath:config/liquibase/master.xml");
liquibase.setContexts(liquibaseProperties.getContexts());
liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
liquibase.setLiquibaseSchema(liquibaseProperties.getLiquibaseSchema());
liquibase.setLiquibaseTablespace(liquibaseProperties.getLiquibaseTablespace());
liquibase.setDatabaseChangeLogLockTable(liquibaseProperties.getDatabaseChangeLogLockTable());
liquibase.setDatabaseChangeLogTable(liquibaseProperties.getDatabaseChangeLogTable());
liquibase.setDropFirst(liquibaseProperties.isDropFirst());
liquibase.setLabelFilter(liquibaseProperties.getLabelFilter());
liquibase.setChangeLogParameters(liquibaseProperties.getParameters());
liquibase.setRollbackFile(liquibaseProperties.getRollbackFile());
liquibase.setTestRollbackOnUpdate(liquibaseProperties.isTestRollbackOnUpdate());
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE))) {
liquibase.setShouldRun(false);
} else {
liquibase.setShouldRun(liquibaseProperties.isEnabled());
log.debug("Configuring Liquibase");
}
return liquibase;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/OpenApiConfiguration.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/OpenApiConfiguration.java | package com.cars.app.config;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.JHipsterProperties;
import tech.jhipster.config.apidoc.customizer.JHipsterOpenApiCustomizer;
@Configuration
@Profile(JHipsterConstants.SPRING_PROFILE_API_DOCS)
public class OpenApiConfiguration {
public static final String API_FIRST_PACKAGE = "com.cars.app.web.api";
@Bean
@ConditionalOnMissingBean(name = "apiFirstGroupedOpenAPI")
public GroupedOpenApi apiFirstGroupedOpenAPI(
JHipsterOpenApiCustomizer jhipsterOpenApiCustomizer,
JHipsterProperties jHipsterProperties
) {
JHipsterProperties.ApiDocs properties = jHipsterProperties.getApiDocs();
return GroupedOpenApi.builder()
.group("openapi")
.addOpenApiCustomizer(jhipsterOpenApiCustomizer)
.packagesToScan(API_FIRST_PACKAGE)
.pathsToMatch(properties.getDefaultIncludePattern())
.build();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/EurekaWorkaroundConfiguration.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/EurekaWorkaroundConfiguration.java | // This is a workaround for
// https://github.com/jhipster/jhipster-registry/issues/537
// https://github.com/jhipster/generator-jhipster/issues/18533
// The original issue will be fixed with spring cloud 2021.0.4
// https://github.com/spring-cloud/spring-cloud-netflix/issues/3941
package com.cars.app.config;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class EurekaWorkaroundConfiguration implements HealthIndicator {
private boolean applicationIsUp = false;
@EventListener(ApplicationReadyEvent.class)
public void onStartup() {
this.applicationIsUp = true;
}
@Override
public Health health() {
if (!applicationIsUp) {
return Health.down().build();
}
return Health.up().build();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/StaticResourcesWebConfiguration.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/StaticResourcesWebConfiguration.java | package com.cars.app.config;
import java.util.concurrent.TimeUnit;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.JHipsterProperties;
@Configuration
@Profile({ JHipsterConstants.SPRING_PROFILE_PRODUCTION })
public class StaticResourcesWebConfiguration implements WebMvcConfigurer {
protected static final String[] RESOURCE_LOCATIONS = { "classpath:/static/", "classpath:/static/content/", "classpath:/static/i18n/" };
protected static final String[] RESOURCE_PATHS = { "/*.js", "/*.css", "/*.svg", "/*.png", "*.ico", "/content/**", "/i18n/*" };
private final JHipsterProperties jhipsterProperties;
public StaticResourcesWebConfiguration(JHipsterProperties jHipsterProperties) {
this.jhipsterProperties = jHipsterProperties;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
ResourceHandlerRegistration resourceHandlerRegistration = appendResourceHandler(registry);
initializeResourceHandler(resourceHandlerRegistration);
}
protected ResourceHandlerRegistration appendResourceHandler(ResourceHandlerRegistry registry) {
return registry.addResourceHandler(RESOURCE_PATHS);
}
protected void initializeResourceHandler(ResourceHandlerRegistration resourceHandlerRegistration) {
resourceHandlerRegistration.addResourceLocations(RESOURCE_LOCATIONS).setCacheControl(getCacheControl());
}
protected CacheControl getCacheControl() {
return CacheControl.maxAge(getJHipsterHttpCacheProperty(), TimeUnit.DAYS).cachePublic();
}
private int getJHipsterHttpCacheProperty() {
return jhipsterProperties.getHttp().getCache().getTimeToLiveInDays();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/Constants.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/Constants.java | package com.cars.app.config;
/**
* Application constants.
*/
public final class Constants {
public static final String SYSTEM = "system";
private Constants() {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/LoggingAspectConfiguration.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/config/LoggingAspectConfiguration.java | package com.cars.app.config;
import com.cars.app.aop.logging.LoggingAspect;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import tech.jhipster.config.JHipsterConstants;
@Configuration
@EnableAspectJAutoProxy
public class LoggingAspectConfiguration {
@Bean
@Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)
public LoggingAspect loggingAspect(Environment env) {
return new LoggingAspect(env);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/filter/SpaWebFilter.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/filter/SpaWebFilter.java | package com.cars.app.web.filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.web.filter.OncePerRequestFilter;
public class SpaWebFilter extends OncePerRequestFilter {
/**
* Forwards any unmapped paths (except those containing a period) to the client {@code index.html}.
*/
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// Request URI includes the contextPath if any, removed it.
String path = request.getRequestURI().substring(request.getContextPath().length());
if (
!path.startsWith("/api") &&
!path.startsWith("/management") &&
!path.startsWith("/v3/api-docs") &&
!path.startsWith("/h2-console") &&
!path.contains(".") &&
path.matches("/(.*)")
) {
request.getRequestDispatcher("/index.html").forward(request, response);
return;
}
filterChain.doFilter(request, response);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/filter/package-info.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/filter/package-info.java | /**
* Request chain filters.
*/
package com.cars.app.web.filter;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/rest/package-info.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/rest/package-info.java | /**
* Rest layer.
*/
package com.cars.app.web.rest;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/rest/CarResource.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/rest/CarResource.java | package com.cars.app.web.rest;
import com.cars.app.domain.Car;
import com.cars.app.repository.CarRepository;
import com.cars.app.web.rest.errors.BadRequestAlertException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.ResponseUtil;
/**
* REST controller for managing {@link com.cars.app.domain.Car}.
*/
@RestController
@RequestMapping("/api/cars")
@Transactional
public class CarResource {
private final Logger log = LoggerFactory.getLogger(CarResource.class);
private static final String ENTITY_NAME = "carsappCar";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final CarRepository carRepository;
public CarResource(CarRepository carRepository) {
this.carRepository = carRepository;
}
/**
* {@code POST /cars} : Create a new car.
*
* @param car the car to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new car, or with status {@code 400 (Bad Request)} if the car has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("")
public ResponseEntity<Car> createCar(@RequestBody Car car) throws URISyntaxException {
log.debug("REST request to save Car : {}", car);
if (car.getId() != null) {
throw new BadRequestAlertException("A new car cannot already have an ID", ENTITY_NAME, "idexists");
}
car = carRepository.save(car);
return ResponseEntity.created(new URI("/api/cars/" + car.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, car.getId().toString()))
.body(car);
}
/**
* {@code PUT /cars/:id} : Updates an existing car.
*
* @param id the id of the car to save.
* @param car the car to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated car,
* or with status {@code 400 (Bad Request)} if the car is not valid,
* or with status {@code 500 (Internal Server Error)} if the car couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/{id}")
public ResponseEntity<Car> updateCar(@PathVariable(value = "id", required = false) final Long id, @RequestBody Car car)
throws URISyntaxException {
log.debug("REST request to update Car : {}, {}", id, car);
if (car.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
if (!Objects.equals(id, car.getId())) {
throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
}
if (!carRepository.existsById(id)) {
throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
}
car = carRepository.save(car);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, car.getId().toString()))
.body(car);
}
/**
* {@code PATCH /cars/:id} : Partial updates given fields of an existing car, field will ignore if it is null
*
* @param id the id of the car to save.
* @param car the car to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated car,
* or with status {@code 400 (Bad Request)} if the car is not valid,
* or with status {@code 404 (Not Found)} if the car is not found,
* or with status {@code 500 (Internal Server Error)} if the car couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PatchMapping(value = "/{id}", consumes = { "application/json", "application/merge-patch+json" })
public ResponseEntity<Car> partialUpdateCar(@PathVariable(value = "id", required = false) final Long id, @RequestBody Car car)
throws URISyntaxException {
log.debug("REST request to partial update Car partially : {}, {}", id, car);
if (car.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
if (!Objects.equals(id, car.getId())) {
throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
}
if (!carRepository.existsById(id)) {
throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
}
Optional<Car> result = carRepository
.findById(car.getId())
.map(existingCar -> {
if (car.getPrice() != null) {
existingCar.setPrice(car.getPrice());
}
return existingCar;
})
.map(carRepository::save);
return ResponseUtil.wrapOrNotFound(
result,
HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, car.getId().toString())
);
}
/**
* {@code GET /cars} : get all the cars.
*
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of cars in body.
*/
@GetMapping("")
public List<Car> getAllCars() {
log.debug("REST request to get all Cars");
return carRepository.findAll();
}
/**
* {@code GET /cars/:id} : get the "id" car.
*
* @param id the id of the car to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the car, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/{id}")
public ResponseEntity<Car> getCar(@PathVariable("id") Long id) {
log.debug("REST request to get Car : {}", id);
Optional<Car> car = carRepository.findById(id);
return ResponseUtil.wrapOrNotFound(car);
}
/**
* {@code DELETE /cars/:id} : delete the "id" car.
*
* @param id the id of the car to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteCar(@PathVariable("id") Long id) {
log.debug("REST request to delete Car : {}", id);
carRepository.deleteById(id);
return ResponseEntity.noContent()
.headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString()))
.build();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/rest/errors/package-info.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/rest/errors/package-info.java | /**
* Rest layer error handling.
*/
package com.cars.app.web.rest.errors;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/rest/errors/ErrorConstants.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/rest/errors/ErrorConstants.java | package com.cars.app.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");
private ErrorConstants() {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/rest/errors/FieldErrorVM.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/rest/errors/FieldErrorVM.java | package com.cars.app.web.rest.errors;
import java.io.Serializable;
public class FieldErrorVM implements Serializable {
private static final long serialVersionUID = 1L;
private final String objectName;
private final String field;
private final String message;
public FieldErrorVM(String dto, String field, String message) {
this.objectName = dto;
this.field = field;
this.message = message;
}
public String getObjectName() {
return objectName;
}
public String getField() {
return field;
}
public String getMessage() {
return message;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/rest/errors/BadRequestAlertException.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/rest/errors/BadRequestAlertException.java | package com.cars.app.web.rest.errors;
import java.net.URI;
import org.springframework.http.HttpStatus;
import org.springframework.web.ErrorResponseException;
import tech.jhipster.web.rest.errors.ProblemDetailWithCause;
import tech.jhipster.web.rest.errors.ProblemDetailWithCause.ProblemDetailWithCauseBuilder;
@SuppressWarnings("java:S110") // Inheritance tree of classes should not be too deep
public class BadRequestAlertException extends ErrorResponseException {
private static final long serialVersionUID = 1L;
private final String entityName;
private final String errorKey;
public BadRequestAlertException(String defaultMessage, String entityName, String errorKey) {
this(ErrorConstants.DEFAULT_TYPE, defaultMessage, entityName, errorKey);
}
public BadRequestAlertException(URI type, String defaultMessage, String entityName, String errorKey) {
super(
HttpStatus.BAD_REQUEST,
ProblemDetailWithCauseBuilder.instance()
.withStatus(HttpStatus.BAD_REQUEST.value())
.withType(type)
.withTitle(defaultMessage)
.withProperty("message", "error." + errorKey)
.withProperty("params", entityName)
.build(),
null
);
this.entityName = entityName;
this.errorKey = errorKey;
}
public String getEntityName() {
return entityName;
}
public String getErrorKey() {
return errorKey;
}
public ProblemDetailWithCause getProblemDetailWithCause() {
return (ProblemDetailWithCause) this.getBody();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/rest/errors/ExceptionTranslator.java | jhipster-8-modules/jhipster-8-microservice/car-app/src/main/java/com/cars/app/web/rest/errors/ExceptionTranslator.java | package com.cars.app.web.rest.errors;
import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation;
import jakarta.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.lang.Nullable;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.ErrorResponse;
import org.springframework.web.ErrorResponseException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.web.rest.errors.ProblemDetailWithCause;
import tech.jhipster.web.rest.errors.ProblemDetailWithCause.ProblemDetailWithCauseBuilder;
import tech.jhipster.web.util.HeaderUtil;
/**
* Controller advice to translate the server side exceptions to client-friendly json structures.
* The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807).
*/
@ControllerAdvice
public class ExceptionTranslator extends ResponseEntityExceptionHandler {
private static final String FIELD_ERRORS_KEY = "fieldErrors";
private static final String MESSAGE_KEY = "message";
private static final String PATH_KEY = "path";
private static final boolean CASUAL_CHAIN_ENABLED = false;
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final Environment env;
public ExceptionTranslator(Environment env) {
this.env = env;
}
@ExceptionHandler
public ResponseEntity<Object> handleAnyException(Throwable ex, NativeWebRequest request) {
ProblemDetailWithCause pdCause = wrapAndCustomizeProblem(ex, request);
return handleExceptionInternal((Exception) ex, pdCause, buildHeaders(ex), HttpStatusCode.valueOf(pdCause.getStatus()), request);
}
@Nullable
@Override
protected ResponseEntity<Object> handleExceptionInternal(
Exception ex,
@Nullable Object body,
HttpHeaders headers,
HttpStatusCode statusCode,
WebRequest request
) {
body = body == null ? wrapAndCustomizeProblem((Throwable) ex, (NativeWebRequest) request) : body;
return super.handleExceptionInternal(ex, body, headers, statusCode, request);
}
protected ProblemDetailWithCause wrapAndCustomizeProblem(Throwable ex, NativeWebRequest request) {
return customizeProblem(getProblemDetailWithCause(ex), ex, request);
}
private ProblemDetailWithCause getProblemDetailWithCause(Throwable ex) {
if (
ex instanceof ErrorResponseException exp && exp.getBody() instanceof ProblemDetailWithCause problemDetailWithCause
) return problemDetailWithCause;
return ProblemDetailWithCauseBuilder.instance().withStatus(toStatus(ex).value()).build();
}
protected ProblemDetailWithCause customizeProblem(ProblemDetailWithCause problem, Throwable err, NativeWebRequest request) {
if (problem.getStatus() <= 0) problem.setStatus(toStatus(err));
if (problem.getType() == null || problem.getType().equals(URI.create("about:blank"))) problem.setType(getMappedType(err));
// higher precedence to Custom/ResponseStatus types
String title = extractTitle(err, problem.getStatus());
String problemTitle = problem.getTitle();
if (problemTitle == null || !problemTitle.equals(title)) {
problem.setTitle(title);
}
if (problem.getDetail() == null) {
// higher precedence to cause
problem.setDetail(getCustomizedErrorDetails(err));
}
Map<String, Object> problemProperties = problem.getProperties();
if (problemProperties == null || !problemProperties.containsKey(MESSAGE_KEY)) problem.setProperty(
MESSAGE_KEY,
getMappedMessageKey(err) != null ? getMappedMessageKey(err) : "error.http." + problem.getStatus()
);
if (problemProperties == null || !problemProperties.containsKey(PATH_KEY)) problem.setProperty(PATH_KEY, getPathValue(request));
if (
(err instanceof MethodArgumentNotValidException fieldException) &&
(problemProperties == null || !problemProperties.containsKey(FIELD_ERRORS_KEY))
) problem.setProperty(FIELD_ERRORS_KEY, getFieldErrors(fieldException));
problem.setCause(buildCause(err.getCause(), request).orElse(null));
return problem;
}
private String extractTitle(Throwable err, int statusCode) {
return getCustomizedTitle(err) != null ? getCustomizedTitle(err) : extractTitleForResponseStatus(err, statusCode);
}
private List<FieldErrorVM> getFieldErrors(MethodArgumentNotValidException ex) {
return ex
.getBindingResult()
.getFieldErrors()
.stream()
.map(
f ->
new FieldErrorVM(
f.getObjectName().replaceFirst("DTO$", ""),
f.getField(),
StringUtils.isNotBlank(f.getDefaultMessage()) ? f.getDefaultMessage() : f.getCode()
)
)
.toList();
}
private String extractTitleForResponseStatus(Throwable err, int statusCode) {
ResponseStatus specialStatus = extractResponseStatus(err);
return specialStatus == null ? HttpStatus.valueOf(statusCode).getReasonPhrase() : specialStatus.reason();
}
private String extractURI(NativeWebRequest request) {
HttpServletRequest nativeRequest = request.getNativeRequest(HttpServletRequest.class);
return nativeRequest != null ? nativeRequest.getRequestURI() : StringUtils.EMPTY;
}
private HttpStatus toStatus(final Throwable throwable) {
// Let the ErrorResponse take this responsibility
if (throwable instanceof ErrorResponse err) return HttpStatus.valueOf(err.getBody().getStatus());
return Optional.ofNullable(getMappedStatus(throwable)).orElse(
Optional.ofNullable(resolveResponseStatus(throwable)).map(ResponseStatus::value).orElse(HttpStatus.INTERNAL_SERVER_ERROR)
);
}
private ResponseStatus extractResponseStatus(final Throwable throwable) {
return Optional.ofNullable(resolveResponseStatus(throwable)).orElse(null);
}
private ResponseStatus resolveResponseStatus(final Throwable type) {
final ResponseStatus candidate = findMergedAnnotation(type.getClass(), ResponseStatus.class);
return candidate == null && type.getCause() != null ? resolveResponseStatus(type.getCause()) : candidate;
}
private URI getMappedType(Throwable err) {
if (err instanceof MethodArgumentNotValidException) return ErrorConstants.CONSTRAINT_VIOLATION_TYPE;
return ErrorConstants.DEFAULT_TYPE;
}
private String getMappedMessageKey(Throwable err) {
if (err instanceof MethodArgumentNotValidException) {
return ErrorConstants.ERR_VALIDATION;
} else if (err instanceof ConcurrencyFailureException || err.getCause() instanceof ConcurrencyFailureException) {
return ErrorConstants.ERR_CONCURRENCY_FAILURE;
}
return null;
}
private String getCustomizedTitle(Throwable err) {
if (err instanceof MethodArgumentNotValidException) return "Method argument not valid";
return null;
}
private String getCustomizedErrorDetails(Throwable err) {
Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) {
if (err instanceof HttpMessageConversionException) return "Unable to convert http message";
if (err instanceof DataAccessException) return "Failure during data access";
if (containsPackageName(err.getMessage())) return "Unexpected runtime exception";
}
return err.getCause() != null ? err.getCause().getMessage() : err.getMessage();
}
private HttpStatus getMappedStatus(Throwable err) {
// Where we disagree with Spring defaults
if (err instanceof AccessDeniedException) return HttpStatus.FORBIDDEN;
if (err instanceof ConcurrencyFailureException) return HttpStatus.CONFLICT;
if (err instanceof BadCredentialsException) return HttpStatus.UNAUTHORIZED;
return null;
}
private URI getPathValue(NativeWebRequest request) {
if (request == null) return URI.create("about:blank");
return URI.create(extractURI(request));
}
private HttpHeaders buildHeaders(Throwable err) {
return err instanceof BadRequestAlertException badRequestAlertException
? HeaderUtil.createFailureAlert(
applicationName,
true,
badRequestAlertException.getEntityName(),
badRequestAlertException.getErrorKey(),
badRequestAlertException.getMessage()
)
: null;
}
public Optional<ProblemDetailWithCause> buildCause(final Throwable throwable, NativeWebRequest request) {
if (throwable != null && isCasualChainEnabled()) {
return Optional.of(customizeProblem(getProblemDetailWithCause(throwable), throwable, request));
}
return Optional.ofNullable(null);
}
private boolean isCasualChainEnabled() {
// Customize as per the needs
return CASUAL_CHAIN_ENABLED;
}
private boolean containsPackageName(String message) {
// This list is for sure not complete
return StringUtils.containsAny(message, "org.", "java.", "net.", "jakarta.", "javax.", "com.", "io.", "de.", "com.cars.app");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/IntegrationTest.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/IntegrationTest.java | package com.dealers.app;
import com.dealers.app.config.AsyncSyncConfiguration;
import com.dealers.app.config.EmbeddedSQL;
import com.dealers.app.config.JacksonConfiguration;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.test.context.SpringBootTest;
/**
* Base composite annotation for integration tests.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SpringBootTest(classes = { DealerApp.class, JacksonConfiguration.class, AsyncSyncConfiguration.class })
@EmbeddedSQL
public @interface IntegrationTest {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/TechnicalStructureTest.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/TechnicalStructureTest.java | package com.dealers.app;
import static com.tngtech.archunit.base.DescribedPredicate.alwaysTrue;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.belongToAnyOf;
import static com.tngtech.archunit.library.Architectures.layeredArchitecture;
import com.tngtech.archunit.core.importer.ImportOption.DoNotIncludeTests;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
@AnalyzeClasses(packagesOf = DealerApp.class, importOptions = DoNotIncludeTests.class)
class TechnicalStructureTest {
// prettier-ignore
@ArchTest
static final ArchRule respectsTechnicalArchitectureLayers = layeredArchitecture()
.consideringAllDependencies()
.layer("Config").definedBy("..config..")
.layer("Web").definedBy("..web..")
.optionalLayer("Service").definedBy("..service..")
.layer("Security").definedBy("..security..")
.optionalLayer("Persistence").definedBy("..repository..")
.layer("Domain").definedBy("..domain..")
.whereLayer("Config").mayNotBeAccessedByAnyLayer()
.whereLayer("Web").mayOnlyBeAccessedByLayers("Config")
.whereLayer("Service").mayOnlyBeAccessedByLayers("Web", "Config")
.whereLayer("Security").mayOnlyBeAccessedByLayers("Config", "Service", "Web")
.whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service", "Security", "Web", "Config")
.whereLayer("Domain").mayOnlyBeAccessedByLayers("Persistence", "Service", "Security", "Web", "Config")
.ignoreDependency(belongToAnyOf(DealerApp.class), alwaysTrue())
.ignoreDependency(alwaysTrue(), belongToAnyOf(
com.dealers.app.config.Constants.class,
com.dealers.app.config.ApplicationProperties.class
));
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/management/SecurityMetersServiceTests.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/management/SecurityMetersServiceTests.java | package com.dealers.app.management;
import static org.assertj.core.api.Assertions.assertThat;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.util.Collection;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class SecurityMetersServiceTests {
private static final String INVALID_TOKENS_METER_EXPECTED_NAME = "security.authentication.invalid-tokens";
private MeterRegistry meterRegistry;
private SecurityMetersService securityMetersService;
@BeforeEach
public void setup() {
meterRegistry = new SimpleMeterRegistry();
securityMetersService = new SecurityMetersService(meterRegistry);
}
@Test
void testInvalidTokensCountersByCauseAreCreated() {
meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).counter();
meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter();
meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "unsupported").counter();
meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter();
meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter();
Collection<Counter> counters = meterRegistry.find(INVALID_TOKENS_METER_EXPECTED_NAME).counters();
assertThat(counters).hasSize(4);
}
@Test
void testCountMethodsShouldBeBoundToCorrectCounters() {
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count()).isZero();
securityMetersService.trackTokenExpired();
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count()).isEqualTo(1);
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "unsupported").counter().count()).isZero();
securityMetersService.trackTokenUnsupported();
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "unsupported").counter().count()).isEqualTo(1);
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count()).isZero();
securityMetersService.trackTokenInvalidSignature();
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count()).isEqualTo(1);
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isZero();
securityMetersService.trackTokenMalformed();
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isEqualTo(1);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/domain/AssertUtils.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/domain/AssertUtils.java | package com.dealers.app.domain;
import java.math.BigDecimal;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Comparator;
public class AssertUtils {
public static Comparator<ZonedDateTime> zonedDataTimeSameInstant = Comparator.nullsFirst(
(e1, a2) -> e1.withZoneSameInstant(ZoneOffset.UTC).compareTo(a2.withZoneSameInstant(ZoneOffset.UTC))
);
public static Comparator<BigDecimal> bigDecimalCompareTo = Comparator.nullsFirst((e1, a2) -> e1.compareTo(a2));
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/repository/timezone/DateTimeWrapper.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/repository/timezone/DateTimeWrapper.java | package com.dealers.app.repository.timezone;
import jakarta.persistence.*;
import java.io.Serializable;
import java.time.*;
import java.util.Objects;
@Entity
@Table(name = "jhi_date_time_wrapper")
public class DateTimeWrapper implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@Column(name = "instant")
private Instant instant;
@Column(name = "local_date_time")
private LocalDateTime localDateTime;
@Column(name = "offset_date_time")
private OffsetDateTime offsetDateTime;
@Column(name = "zoned_date_time")
private ZonedDateTime zonedDateTime;
@Column(name = "local_time")
private LocalTime localTime;
@Column(name = "offset_time")
private OffsetTime offsetTime;
@Column(name = "local_date")
private LocalDate localDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Instant getInstant() {
return instant;
}
public void setInstant(Instant instant) {
this.instant = instant;
}
public LocalDateTime getLocalDateTime() {
return localDateTime;
}
public void setLocalDateTime(LocalDateTime localDateTime) {
this.localDateTime = localDateTime;
}
public OffsetDateTime getOffsetDateTime() {
return offsetDateTime;
}
public void setOffsetDateTime(OffsetDateTime offsetDateTime) {
this.offsetDateTime = offsetDateTime;
}
public ZonedDateTime getZonedDateTime() {
return zonedDateTime;
}
public void setZonedDateTime(ZonedDateTime zonedDateTime) {
this.zonedDateTime = zonedDateTime;
}
public LocalTime getLocalTime() {
return localTime;
}
public void setLocalTime(LocalTime localTime) {
this.localTime = localTime;
}
public OffsetTime getOffsetTime() {
return offsetTime;
}
public void setOffsetTime(OffsetTime offsetTime) {
this.offsetTime = offsetTime;
}
public LocalDate getLocalDate() {
return localDate;
}
public void setLocalDate(LocalDate localDate) {
this.localDate = localDate;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DateTimeWrapper dateTimeWrapper = (DateTimeWrapper) o;
return !(dateTimeWrapper.getId() == null || getId() == null) && Objects.equals(getId(), dateTimeWrapper.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
// prettier-ignore
@Override
public String toString() {
return "TimeZoneTest{" +
"id=" + id +
", instant=" + instant +
", localDateTime=" + localDateTime +
", offsetDateTime=" + offsetDateTime +
", zonedDateTime=" + zonedDateTime +
'}';
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/repository/timezone/DateTimeWrapperRepository.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/repository/timezone/DateTimeWrapperRepository.java | package com.dealers.app.repository.timezone;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* Spring Data JPA repository for the {@link DateTimeWrapper} entity.
*/
@Repository
public interface DateTimeWrapperRepository extends JpaRepository<DateTimeWrapper, Long> {}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/security/SecurityUtilsUnitTest.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/security/SecurityUtilsUnitTest.java | package com.dealers.app.security;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* Test class for the {@link SecurityUtils} utility class.
*/
class SecurityUtilsUnitTest {
@BeforeEach
@AfterEach
void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
void testGetCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
SecurityContextHolder.setContext(securityContext);
Optional<String> login = SecurityUtils.getCurrentUserLogin();
assertThat(login).contains("admin");
}
@Test
void testGetCurrentUserJWT() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "token"));
SecurityContextHolder.setContext(securityContext);
Optional<String> jwt = SecurityUtils.getCurrentUserJWT();
assertThat(jwt).contains("token");
}
@Test
void testIsAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
SecurityContextHolder.setContext(securityContext);
boolean isAuthenticated = SecurityUtils.isAuthenticated();
assertThat(isAuthenticated).isTrue();
}
@Test
void testAnonymousIsNotAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities));
SecurityContextHolder.setContext(securityContext);
boolean isAuthenticated = SecurityUtils.isAuthenticated();
assertThat(isAuthenticated).isFalse();
}
@Test
void testHasCurrentUserThisAuthority() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("user", "user", authorities));
SecurityContextHolder.setContext(securityContext);
assertThat(SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.USER)).isTrue();
assertThat(SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN)).isFalse();
}
@Test
void testHasCurrentUserAnyOfAuthorities() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("user", "user", authorities));
SecurityContextHolder.setContext(securityContext);
assertThat(SecurityUtils.hasCurrentUserAnyOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN)).isTrue();
assertThat(SecurityUtils.hasCurrentUserAnyOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN)).isFalse();
}
@Test
void testHasCurrentUserNoneOfAuthorities() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("user", "user", authorities));
SecurityContextHolder.setContext(securityContext);
assertThat(SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN)).isFalse();
assertThat(SecurityUtils.hasCurrentUserNoneOfAuthorities(AuthoritiesConstants.ANONYMOUS, AuthoritiesConstants.ADMIN)).isTrue();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/security/jwt/TestAuthenticationResource.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/security/jwt/TestAuthenticationResource.java | package com.dealers.app.security.jwt;
import org.springframework.web.bind.annotation.*;
/**
* REST controller for managing testing authentication token.
*/
@RestController
@RequestMapping("/api")
public class TestAuthenticationResource {
/**
* {@code GET /authenticate} : check if the authentication token correctly validates
*
* @return ok.
*/
@GetMapping("/authenticate")
public String isAuthenticated() {
return "ok";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/security/jwt/AuthenticationIntegrationTest.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/security/jwt/AuthenticationIntegrationTest.java | package com.dealers.app.security.jwt;
import com.dealers.app.config.SecurityConfiguration;
import com.dealers.app.config.SecurityJwtConfiguration;
import com.dealers.app.config.WebConfigurer;
import com.dealers.app.management.SecurityMetersService;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.test.context.SpringBootTest;
import tech.jhipster.config.JHipsterProperties;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SpringBootTest(
classes = {
JHipsterProperties.class,
WebConfigurer.class,
SecurityConfiguration.class,
SecurityJwtConfiguration.class,
SecurityMetersService.class,
JwtAuthenticationTestUtils.class,
}
)
public @interface AuthenticationIntegrationTest {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/security/jwt/TokenAuthenticationSecurityMetersIT.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/security/jwt/TokenAuthenticationSecurityMetersIT.java | package com.dealers.app.security.jwt;
import static com.dealers.app.security.jwt.JwtAuthenticationTestUtils.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.http.HttpHeaders.AUTHORIZATION;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import java.util.Collection;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@AutoConfigureMockMvc
@AuthenticationIntegrationTest
class TokenAuthenticationSecurityMetersIT {
private static final String INVALID_TOKENS_METER_EXPECTED_NAME = "security.authentication.invalid-tokens";
@Autowired
private MockMvc mvc;
@Value("${jhipster.security.authentication.jwt.base64-secret}")
private String jwtKey;
@Autowired
private MeterRegistry meterRegistry;
@Test
void testValidTokenShouldNotCountAnything() throws Exception {
Collection<Counter> counters = meterRegistry.find(INVALID_TOKENS_METER_EXPECTED_NAME).counters();
var count = aggregate(counters);
tryToAuthenticate(createValidToken(jwtKey));
assertThat(aggregate(counters)).isEqualTo(count);
}
@Test
void testTokenExpiredCount() throws Exception {
var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count();
tryToAuthenticate(createExpiredToken(jwtKey));
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count()).isEqualTo(count + 1);
}
@Test
void testTokenSignatureInvalidCount() throws Exception {
var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count();
tryToAuthenticate(createTokenWithDifferentSignature());
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count()).isEqualTo(
count + 1
);
}
@Test
void testTokenMalformedCount() throws Exception {
var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count();
tryToAuthenticate(createSignedInvalidJwt(jwtKey));
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isEqualTo(count + 1);
}
@Test
void testTokenInvalidCount() throws Exception {
var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count();
tryToAuthenticate(createInvalidToken(jwtKey));
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isEqualTo(count + 1);
}
private void tryToAuthenticate(String token) throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/api/authenticate").header(AUTHORIZATION, BEARER + token));
}
private double aggregate(Collection<Counter> counters) {
return counters.stream().mapToDouble(Counter::count).sum();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/security/jwt/TokenAuthenticationIT.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/security/jwt/TokenAuthenticationIT.java | package com.dealers.app.security.jwt;
import static com.dealers.app.security.jwt.JwtAuthenticationTestUtils.*;
import static org.springframework.http.HttpHeaders.AUTHORIZATION;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@AutoConfigureMockMvc
@AuthenticationIntegrationTest
class TokenAuthenticationIT {
@Autowired
private MockMvc mvc;
@Value("${jhipster.security.authentication.jwt.base64-secret}")
private String jwtKey;
@Test
void testLoginWithValidToken() throws Exception {
expectOk(createValidToken(jwtKey));
}
@Test
void testReturnFalseWhenJWThasInvalidSignature() throws Exception {
expectUnauthorized(createTokenWithDifferentSignature());
}
@Test
void testReturnFalseWhenJWTisMalformed() throws Exception {
expectUnauthorized(createSignedInvalidJwt(jwtKey));
}
@Test
void testReturnFalseWhenJWTisExpired() throws Exception {
expectUnauthorized(createExpiredToken(jwtKey));
}
private void expectOk(String token) throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/api/authenticate").header(AUTHORIZATION, BEARER + token)).andExpect(status().isOk());
}
private void expectUnauthorized(String token) throws Exception {
mvc
.perform(MockMvcRequestBuilders.get("/api/authenticate").header(AUTHORIZATION, BEARER + token))
.andExpect(status().isUnauthorized());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/security/jwt/JwtAuthenticationTestUtils.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/security/jwt/JwtAuthenticationTestUtils.java | package com.dealers.app.security.jwt;
import static com.dealers.app.security.SecurityUtils.AUTHORITIES_KEY;
import static com.dealers.app.security.SecurityUtils.JWT_ALGORITHM;
import com.nimbusds.jose.jwk.source.ImmutableSecret;
import com.nimbusds.jose.util.Base64;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.time.Instant;
import java.util.Collections;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
public class JwtAuthenticationTestUtils {
public static final String BEARER = "Bearer ";
@Bean
private HandlerMappingIntrospector mvcHandlerMappingIntrospector() {
return new HandlerMappingIntrospector();
}
@Bean
private TestAuthenticationResource authenticationResource() {
return new TestAuthenticationResource();
}
@Bean
private MeterRegistry meterRegistry() {
return new SimpleMeterRegistry();
}
public static String createValidToken(String jwtKey) {
return createValidTokenForUser(jwtKey, "anonymous");
}
public static String createValidTokenForUser(String jwtKey, String user) {
JwtEncoder encoder = jwtEncoder(jwtKey);
var now = Instant.now();
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuedAt(now)
.expiresAt(now.plusSeconds(60))
.subject(user)
.claims(customClaim -> customClaim.put(AUTHORITIES_KEY, Collections.singletonList("ROLE_ADMIN")))
.build();
JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build();
return encoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue();
}
public static String createTokenWithDifferentSignature() {
JwtEncoder encoder = jwtEncoder("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8");
var now = Instant.now();
var past = now.plusSeconds(60);
JwtClaimsSet claims = JwtClaimsSet.builder().issuedAt(now).expiresAt(past).subject("anonymous").build();
JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build();
return encoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue();
}
public static String createExpiredToken(String jwtKey) {
JwtEncoder encoder = jwtEncoder(jwtKey);
var now = Instant.now();
var past = now.minusSeconds(600);
JwtClaimsSet claims = JwtClaimsSet.builder().issuedAt(past).expiresAt(past.plusSeconds(1)).subject("anonymous").build();
JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build();
return encoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue();
}
public static String createInvalidToken(String jwtKey) {
return createValidToken(jwtKey).substring(1);
}
public static String createSignedInvalidJwt(String jwtKey) throws Exception {
return calculateHMAC("foo", jwtKey);
}
private static JwtEncoder jwtEncoder(String jwtKey) {
return new NimbusJwtEncoder(new ImmutableSecret<>(getSecretKey(jwtKey)));
}
private static SecretKey getSecretKey(String jwtKey) {
byte[] keyBytes = Base64.from(jwtKey).decode();
return new SecretKeySpec(keyBytes, 0, keyBytes.length, JWT_ALGORITHM.getName());
}
private static String calculateHMAC(String data, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.from(key).decode(), "HmacSHA512");
Mac mac = Mac.getInstance("HmacSHA512");
mac.init(secretKeySpec);
return String.copyValueOf(Hex.encode(mac.doFinal(data.getBytes())));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/PostgreSqlTestContainer.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/PostgreSqlTestContainer.java | package com.dealers.app.config;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.JdbcDatabaseContainer;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.containers.output.Slf4jLogConsumer;
public class PostgreSqlTestContainer implements SqlTestContainer {
private static final Logger log = LoggerFactory.getLogger(PostgreSqlTestContainer.class);
private PostgreSQLContainer<?> postgreSQLContainer;
@Override
public void destroy() {
if (null != postgreSQLContainer && postgreSQLContainer.isRunning()) {
postgreSQLContainer.stop();
}
}
@Override
public void afterPropertiesSet() {
if (null == postgreSQLContainer) {
postgreSQLContainer = new PostgreSQLContainer<>("postgres:16.2")
.withDatabaseName("dealerApp")
.withTmpFs(Collections.singletonMap("/testtmpfs", "rw"))
.withLogConsumer(new Slf4jLogConsumer(log))
.withReuse(true);
}
if (!postgreSQLContainer.isRunning()) {
postgreSQLContainer.start();
}
}
@Override
public JdbcDatabaseContainer<?> getTestContainer() {
return postgreSQLContainer;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/SqlTestContainer.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/SqlTestContainer.java | package com.dealers.app.config;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.testcontainers.containers.JdbcDatabaseContainer;
public interface SqlTestContainer extends InitializingBean, DisposableBean {
JdbcDatabaseContainer<?> getTestContainer();
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/CRLFLogConverterTest.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/CRLFLogConverterTest.java | package com.dealers.app.config;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import ch.qos.logback.classic.spi.ILoggingEvent;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.boot.ansi.AnsiColor;
import org.springframework.boot.ansi.AnsiElement;
class CRLFLogConverterTest {
@Test
void transformShouldReturnInputStringWhenMarkerListIsEmpty() {
ILoggingEvent event = mock(ILoggingEvent.class);
when(event.getMarkerList()).thenReturn(null);
when(event.getLoggerName()).thenReturn("org.hibernate.example.Logger");
String input = "Test input string";
CRLFLogConverter converter = new CRLFLogConverter();
String result = converter.transform(event, input);
assertEquals(input, result);
}
@Test
void transformShouldReturnInputStringWhenMarkersContainCRLFSafeMarker() {
ILoggingEvent event = mock(ILoggingEvent.class);
Marker marker = MarkerFactory.getMarker("CRLF_SAFE");
List<Marker> markers = Collections.singletonList(marker);
when(event.getMarkerList()).thenReturn(markers);
String input = "Test input string";
CRLFLogConverter converter = new CRLFLogConverter();
String result = converter.transform(event, input);
assertEquals(input, result);
}
@Test
void transformShouldReturnInputStringWhenMarkersNotContainCRLFSafeMarker() {
ILoggingEvent event = mock(ILoggingEvent.class);
Marker marker = MarkerFactory.getMarker("CRLF_NOT_SAFE");
List<Marker> markers = Collections.singletonList(marker);
when(event.getMarkerList()).thenReturn(markers);
when(event.getLoggerName()).thenReturn("org.hibernate.example.Logger");
String input = "Test input string";
CRLFLogConverter converter = new CRLFLogConverter();
String result = converter.transform(event, input);
assertEquals(input, result);
}
@Test
void transformShouldReturnInputStringWhenLoggerIsSafe() {
ILoggingEvent event = mock(ILoggingEvent.class);
when(event.getLoggerName()).thenReturn("org.hibernate.example.Logger");
String input = "Test input string";
CRLFLogConverter converter = new CRLFLogConverter();
String result = converter.transform(event, input);
assertEquals(input, result);
}
@Test
void transformShouldReplaceNewlinesAndCarriageReturnsWithUnderscoreWhenMarkersDoNotContainCRLFSafeMarkerAndLoggerIsNotSafe() {
ILoggingEvent event = mock(ILoggingEvent.class);
List<Marker> markers = Collections.emptyList();
when(event.getMarkerList()).thenReturn(markers);
when(event.getLoggerName()).thenReturn("com.mycompany.myapp.example.Logger");
String input = "Test\ninput\rstring";
CRLFLogConverter converter = new CRLFLogConverter();
String result = converter.transform(event, input);
assertEquals("Test_input_string", result);
}
@Test
void transformShouldReplaceNewlinesAndCarriageReturnsWithAnsiStringWhenMarkersDoNotContainCRLFSafeMarkerAndLoggerIsNotSafeAndAnsiElementIsNotNull() {
ILoggingEvent event = mock(ILoggingEvent.class);
List<Marker> markers = Collections.emptyList();
when(event.getMarkerList()).thenReturn(markers);
when(event.getLoggerName()).thenReturn("com.mycompany.myapp.example.Logger");
String input = "Test\ninput\rstring";
CRLFLogConverter converter = new CRLFLogConverter();
converter.setOptionList(List.of("red"));
String result = converter.transform(event, input);
assertEquals("Test_input_string", result);
}
@Test
void isLoggerSafeShouldReturnTrueWhenLoggerNameStartsWithSafeLogger() {
ILoggingEvent event = mock(ILoggingEvent.class);
when(event.getLoggerName()).thenReturn("org.springframework.boot.autoconfigure.example.Logger");
CRLFLogConverter converter = new CRLFLogConverter();
boolean result = converter.isLoggerSafe(event);
assertTrue(result);
}
@Test
void isLoggerSafeShouldReturnFalseWhenLoggerNameDoesNotStartWithSafeLogger() {
ILoggingEvent event = mock(ILoggingEvent.class);
when(event.getLoggerName()).thenReturn("com.mycompany.myapp.example.Logger");
CRLFLogConverter converter = new CRLFLogConverter();
boolean result = converter.isLoggerSafe(event);
assertFalse(result);
}
@Test
void testToAnsiString() {
CRLFLogConverter cut = new CRLFLogConverter();
AnsiElement ansiElement = AnsiColor.RED;
String result = cut.toAnsiString("input", ansiElement);
assertThat(result).isEqualTo("input");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/EmbeddedSQL.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/EmbeddedSQL.java | package com.dealers.app.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EmbeddedSQL {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/SqlTestContainersSpringContextCustomizerFactory.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/SqlTestContainersSpringContextCustomizerFactory.java | package com.dealers.app.config;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.test.context.ContextConfigurationAttributes;
import org.springframework.test.context.ContextCustomizer;
import org.springframework.test.context.ContextCustomizerFactory;
import org.springframework.test.context.MergedContextConfiguration;
import tech.jhipster.config.JHipsterConstants;
public class SqlTestContainersSpringContextCustomizerFactory implements ContextCustomizerFactory {
private Logger log = LoggerFactory.getLogger(SqlTestContainersSpringContextCustomizerFactory.class);
private static SqlTestContainer prodTestContainer;
@Override
public ContextCustomizer createContextCustomizer(Class<?> testClass, List<ContextConfigurationAttributes> configAttributes) {
return new ContextCustomizer() {
@Override
public void customizeContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
TestPropertyValues testValues = TestPropertyValues.empty();
EmbeddedSQL sqlAnnotation = AnnotatedElementUtils.findMergedAnnotation(testClass, EmbeddedSQL.class);
boolean usingTestProdProfile = Arrays.asList(context.getEnvironment().getActiveProfiles()).contains(
"test" + JHipsterConstants.SPRING_PROFILE_PRODUCTION
);
if (null != sqlAnnotation && usingTestProdProfile) {
log.debug("detected the EmbeddedSQL annotation on class {}", testClass.getName());
log.info("Warming up the sql database");
if (null == prodTestContainer) {
try {
Class<? extends SqlTestContainer> containerClass = (Class<? extends SqlTestContainer>) Class.forName(
this.getClass().getPackageName() + ".PostgreSqlTestContainer"
);
prodTestContainer = beanFactory.createBean(containerClass);
beanFactory.registerSingleton(containerClass.getName(), prodTestContainer);
// ((DefaultListableBeanFactory)beanFactory).registerDisposableBean(containerClass.getName(), prodTestContainer);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
testValues = testValues.and("spring.datasource.url=" + prodTestContainer.getTestContainer().getJdbcUrl() + "");
testValues = testValues.and("spring.datasource.username=" + prodTestContainer.getTestContainer().getUsername());
testValues = testValues.and("spring.datasource.password=" + prodTestContainer.getTestContainer().getPassword());
}
testValues.applyTo(context);
}
@Override
public int hashCode() {
return SqlTestContainer.class.getName().hashCode();
}
@Override
public boolean equals(Object obj) {
return this.hashCode() == obj.hashCode();
}
};
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/StaticResourcesWebConfigurerTest.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/StaticResourcesWebConfigurerTest.java | package com.dealers.app.config;
import static com.dealers.app.config.StaticResourcesWebConfiguration.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.CacheControl;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import tech.jhipster.config.JHipsterDefaults;
import tech.jhipster.config.JHipsterProperties;
class StaticResourcesWebConfigurerTest {
public static final int MAX_AGE_TEST = 5;
public StaticResourcesWebConfiguration staticResourcesWebConfiguration;
private ResourceHandlerRegistry resourceHandlerRegistry;
private MockServletContext servletContext;
private WebApplicationContext applicationContext;
private JHipsterProperties props;
@BeforeEach
void setUp() {
servletContext = spy(new MockServletContext());
applicationContext = mock(WebApplicationContext.class);
resourceHandlerRegistry = spy(new ResourceHandlerRegistry(applicationContext, servletContext));
props = new JHipsterProperties();
staticResourcesWebConfiguration = spy(new StaticResourcesWebConfiguration(props));
}
@Test
void shouldAppendResourceHandlerAndInitializeIt() {
staticResourcesWebConfiguration.addResourceHandlers(resourceHandlerRegistry);
verify(resourceHandlerRegistry, times(1)).addResourceHandler(RESOURCE_PATHS);
verify(staticResourcesWebConfiguration, times(1)).initializeResourceHandler(any(ResourceHandlerRegistration.class));
for (String testingPath : RESOURCE_PATHS) {
assertThat(resourceHandlerRegistry.hasMappingForPattern(testingPath)).isTrue();
}
}
@Test
void shouldInitializeResourceHandlerWithCacheControlAndLocations() {
CacheControl ccExpected = CacheControl.maxAge(5, TimeUnit.DAYS).cachePublic();
when(staticResourcesWebConfiguration.getCacheControl()).thenReturn(ccExpected);
ResourceHandlerRegistration resourceHandlerRegistration = spy(new ResourceHandlerRegistration(RESOURCE_PATHS));
staticResourcesWebConfiguration.initializeResourceHandler(resourceHandlerRegistration);
verify(staticResourcesWebConfiguration, times(1)).getCacheControl();
verify(resourceHandlerRegistration, times(1)).setCacheControl(ccExpected);
verify(resourceHandlerRegistration, times(1)).addResourceLocations(RESOURCE_LOCATIONS);
}
@Test
void shouldCreateCacheControlBasedOnJhipsterDefaultProperties() {
CacheControl cacheExpected = CacheControl.maxAge(JHipsterDefaults.Http.Cache.timeToLiveInDays, TimeUnit.DAYS).cachePublic();
assertThat(staticResourcesWebConfiguration.getCacheControl())
.extracting(CacheControl::getHeaderValue)
.isEqualTo(cacheExpected.getHeaderValue());
}
@Test
void shouldCreateCacheControlWithSpecificConfigurationInProperties() {
props.getHttp().getCache().setTimeToLiveInDays(MAX_AGE_TEST);
CacheControl cacheExpected = CacheControl.maxAge(MAX_AGE_TEST, TimeUnit.DAYS).cachePublic();
assertThat(staticResourcesWebConfiguration.getCacheControl())
.extracting(CacheControl::getHeaderValue)
.isEqualTo(cacheExpected.getHeaderValue());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/AsyncSyncConfiguration.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/AsyncSyncConfiguration.java | package com.dealers.app.config;
import java.util.concurrent.Executor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SyncTaskExecutor;
@Configuration
public class AsyncSyncConfiguration {
@Bean(name = "taskExecutor")
public Executor taskExecutor() {
return new SyncTaskExecutor();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/WebConfigurerTestController.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/WebConfigurerTestController.java | package com.dealers.app.config;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WebConfigurerTestController {
@GetMapping("/api/test-cors")
public void testCorsOnApiPath() {}
@GetMapping("/test/test-cors")
public void testCorsOnOtherPath() {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/WebConfigurerTest.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/WebConfigurerTest.java | package com.dealers.app.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import jakarta.servlet.*;
import java.io.File;
import java.util.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.JHipsterProperties;
/**
* Unit tests for the {@link WebConfigurer} class.
*/
class WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
@BeforeEach
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.class)).when(servletContext).addFilter(anyString(), any(Filter.class));
doReturn(mock(ServletRegistration.Dynamic.class)).when(servletContext).addServlet(anyString(), any(Servlet.class));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
void shouldCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html");
assertThat(container.getMimeMappings().get("json")).isEqualTo("application/json");
if (container.getDocumentRoot() != null) {
assertThat(container.getDocumentRoot()).isEqualTo(new File("target/classes/static/"));
}
}
@Test
void shouldCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("other.domain.com"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc
.perform(
options("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")
)
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"))
.andExpect(header().string(HttpHeaders.VARY, "Origin"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc
.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
void shouldCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc
.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
void shouldCorsFilterDeactivatedForNullAllowedOrigins() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc
.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
void shouldCorsFilterDeactivatedForEmptyAllowedOrigins() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc
.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/SpringBootTestClassOrderer.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/SpringBootTestClassOrderer.java | package com.dealers.app.config;
import com.dealers.app.IntegrationTest;
import java.util.Comparator;
import org.junit.jupiter.api.ClassDescriptor;
import org.junit.jupiter.api.ClassOrderer;
import org.junit.jupiter.api.ClassOrdererContext;
public class SpringBootTestClassOrderer implements ClassOrderer {
@Override
public void orderClasses(ClassOrdererContext context) {
context.getClassDescriptors().sort(Comparator.comparingInt(SpringBootTestClassOrderer::getOrder));
}
private static int getOrder(ClassDescriptor classDescriptor) {
if (classDescriptor.findAnnotation(IntegrationTest.class).isPresent()) {
return 2;
}
return 1;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/timezone/HibernateTimeZoneIT.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/config/timezone/HibernateTimeZoneIT.java | package com.dealers.app.config.timezone;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import com.dealers.app.IntegrationTest;
import com.dealers.app.repository.timezone.DateTimeWrapper;
import com.dealers.app.repository.timezone.DateTimeWrapperRepository;
import java.time.*;
import java.time.format.DateTimeFormatter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.transaction.annotation.Transactional;
/**
* Integration tests for verifying the behavior of Hibernate in the context of storing various date and time types across different databases.
* The tests focus on ensuring that the stored values are correctly transformed and stored according to the configured timezone.
* Timezone is environment specific, and can be adjusted according to your needs.
*
* For more context, refer to:
* - GitHub Issue: https://github.com/jhipster/generator-jhipster/issues/22579
* - Pull Request: https://github.com/jhipster/generator-jhipster/pull/22946
*/
@IntegrationTest
class HibernateTimeZoneIT {
@Autowired
private DateTimeWrapperRepository dateTimeWrapperRepository;
@Autowired
private JdbcTemplate jdbcTemplate;
@Value("${spring.jpa.properties.hibernate.jdbc.time_zone:UTC}")
private String zoneId;
private DateTimeWrapper dateTimeWrapper;
private DateTimeFormatter dateTimeFormatter;
private DateTimeFormatter timeFormatter;
private DateTimeFormatter offsetTimeFormatter;
private DateTimeFormatter dateFormatter;
@BeforeEach
public void setup() {
dateTimeWrapper = new DateTimeWrapper();
dateTimeWrapper.setInstant(Instant.parse("2014-11-12T05:10:00.0Z"));
dateTimeWrapper.setLocalDateTime(LocalDateTime.parse("2014-11-12T07:20:00.0"));
dateTimeWrapper.setOffsetDateTime(OffsetDateTime.parse("2011-12-14T08:30:00.0Z"));
dateTimeWrapper.setZonedDateTime(ZonedDateTime.parse("2011-12-14T08:40:00.0Z"));
dateTimeWrapper.setLocalTime(LocalTime.parse("14:50:00"));
dateTimeWrapper.setOffsetTime(OffsetTime.parse("14:00:00+02:00"));
dateTimeWrapper.setLocalDate(LocalDate.parse("2016-09-10"));
dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S").withZone(ZoneId.of(zoneId));
timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss").withZone(ZoneId.of(zoneId));
offsetTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
}
@Test
@Transactional
void storeInstantWithZoneIdConfigShouldBeStoredOnConfiguredTimeZone() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("instant", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeFormatter.format(dateTimeWrapper.getInstant());
assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue);
}
@Test
@Transactional
void storeLocalDateTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZone() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("local_date_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper.getLocalDateTime().atZone(ZoneId.systemDefault()).format(dateTimeFormatter);
assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue);
}
@Test
@Transactional
void storeOffsetDateTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZone() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("offset_date_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper.getOffsetDateTime().format(dateTimeFormatter);
assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue);
}
@Test
@Transactional
void storeZoneDateTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZone() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("zoned_date_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper.getZonedDateTime().format(dateTimeFormatter);
assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue);
}
@Test
@Transactional
void storeLocalTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZoneAccordingToHis1stJan1970Value() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("local_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper
.getLocalTime()
.atDate(LocalDate.of(1970, Month.JANUARY, 1))
.atZone(ZoneId.systemDefault())
.format(timeFormatter);
assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue);
}
@Test
@Transactional
void storeOffsetTimeWithZoneIdConfigShouldBeStoredOnConfiguredTimeZoneAccordingToHis1stJan1970Value() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("offset_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper
.getOffsetTime()
// Convert to configured timezone
.withOffsetSameInstant(ZoneId.of(zoneId).getRules().getOffset(Instant.now()))
// Normalize to System TimeZone.
// TODO this behavior looks a bug, refer to https://github.com/jhipster/generator-jhipster/issues/22579.
.withOffsetSameLocal(OffsetDateTime.ofInstant(Instant.EPOCH, ZoneId.systemDefault()).getOffset())
// Convert the normalized value to configured timezone
.withOffsetSameInstant(ZoneId.of(zoneId).getRules().getOffset(Instant.EPOCH))
.format(offsetTimeFormatter);
assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue);
}
@Test
@Transactional
void storeLocalDateWithZoneIdConfigShouldBeStoredWithoutTransformation() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("local_date", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper.getLocalDate().format(dateFormatter);
assertThatValueFromSqlRowSetIsEqualToExpectedValue(resultSet, expectedValue);
}
private String generateSqlRequest(String fieldName, long id) {
return format("SELECT %s FROM jhi_date_time_wrapper where id=%d", fieldName, id);
}
private void assertThatValueFromSqlRowSetIsEqualToExpectedValue(SqlRowSet sqlRowSet, String expectedValue) {
while (sqlRowSet.next()) {
String dbValue = sqlRowSet.getString(1);
assertThat(dbValue).isNotNull();
assertThat(dbValue).isEqualTo(expectedValue);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/web/filter/SpaWebFilterIT.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/web/filter/SpaWebFilterIT.java | package com.dealers.app.web.filter;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.dealers.app.IntegrationTest;
import com.dealers.app.security.AuthoritiesConstants;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
@AutoConfigureMockMvc
@WithMockUser
@IntegrationTest
class SpaWebFilterIT {
@Autowired
private MockMvc mockMvc;
@Test
void testFilterForwardsToIndex() throws Exception {
mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html"));
}
@Test
@WithMockUser(authorities = AuthoritiesConstants.ADMIN)
void testFilterDoesNotForwardToIndexForV3ApiDocs() throws Exception {
mockMvc.perform(get("/v3/api-docs")).andExpect(status().isOk()).andExpect(forwardedUrl(null));
}
@Test
void testFilterDoesNotForwardToIndexForDotFile() throws Exception {
mockMvc.perform(get("/file.js")).andExpect(status().isNotFound());
}
@Test
void getBackendEndpoint() throws Exception {
mockMvc.perform(get("/test")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html"));
}
@Test
void forwardUnmappedFirstLevelMapping() throws Exception {
mockMvc.perform(get("/first-level")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html"));
}
@Test
void forwardUnmappedSecondLevelMapping() throws Exception {
mockMvc.perform(get("/first-level/second-level")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html"));
}
@Test
void forwardUnmappedThirdLevelMapping() throws Exception {
mockMvc.perform(get("/first-level/second-level/third-level")).andExpect(status().isOk()).andExpect(forwardedUrl("/index.html"));
}
@Test
void forwardUnmappedDeepMapping() throws Exception {
mockMvc.perform(get("/1/2/3/4/5/6/7/8/9/10")).andExpect(forwardedUrl("/index.html"));
}
@Test
void getUnmappedFirstLevelFile() throws Exception {
mockMvc.perform(get("/foo.js")).andExpect(status().isNotFound());
}
/**
* This test verifies that any files that aren't permitted by Spring Security will be forbidden.
* If you want to change this to return isNotFound(), you need to add a request mapping that
* allows this file in SecurityConfiguration.
*/
@Test
void getUnmappedSecondLevelFile() throws Exception {
mockMvc.perform(get("/foo/bar.js")).andExpect(status().isForbidden());
}
@Test
void getUnmappedThirdLevelFile() throws Exception {
mockMvc.perform(get("/foo/another/bar.js")).andExpect(status().isForbidden());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/web/rest/TestUtil.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/web/rest/TestUtil.java | package com.dealers.app.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import java.util.List;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.hamcrest.TypeSafeMatcher;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
/**
* Utility class for testing REST controllers.
*/
public final class TestUtil {
/**
* Create a byte array with a specific size filled with specified data.
*
* @param size the size of the byte array.
* @param data the data to put in the byte array.
* @return the JSON byte array.
*/
public static byte[] createByteArray(int size, String data) {
byte[] byteArray = new byte[size];
for (int i = 0; i < size; i++) {
byteArray[i] = Byte.parseByte(data, 2);
}
return byteArray;
}
/**
* A matcher that tests that the examined string represents the same instant as the reference datetime.
*/
public static class ZonedDateTimeMatcher extends TypeSafeDiagnosingMatcher<String> {
private final ZonedDateTime date;
public ZonedDateTimeMatcher(ZonedDateTime date) {
this.date = date;
}
@Override
protected boolean matchesSafely(String item, Description mismatchDescription) {
try {
if (!date.isEqual(ZonedDateTime.parse(item))) {
mismatchDescription.appendText("was ").appendValue(item);
return false;
}
return true;
} catch (DateTimeParseException e) {
mismatchDescription.appendText("was ").appendValue(item).appendText(", which could not be parsed as a ZonedDateTime");
return false;
}
}
@Override
public void describeTo(Description description) {
description.appendText("a String representing the same Instant as ").appendValue(date);
}
}
/**
* Creates a matcher that matches when the examined string represents the same instant as the reference datetime.
*
* @param date the reference datetime against which the examined string is checked.
*/
public static ZonedDateTimeMatcher sameInstant(ZonedDateTime date) {
return new ZonedDateTimeMatcher(date);
}
/**
* A matcher that tests that the examined number represents the same value - it can be Long, Double, etc - as the reference BigDecimal.
*/
public static class NumberMatcher extends TypeSafeMatcher<Number> {
final BigDecimal value;
public NumberMatcher(BigDecimal value) {
this.value = value;
}
@Override
public void describeTo(Description description) {
description.appendText("a numeric value is ").appendValue(value);
}
@Override
protected boolean matchesSafely(Number item) {
BigDecimal bigDecimal = asDecimal(item);
return bigDecimal != null && value.compareTo(bigDecimal) == 0;
}
private static BigDecimal asDecimal(Number item) {
if (item == null) {
return null;
}
if (item instanceof BigDecimal) {
return (BigDecimal) item;
} else if (item instanceof Long) {
return BigDecimal.valueOf((Long) item);
} else if (item instanceof Integer) {
return BigDecimal.valueOf((Integer) item);
} else if (item instanceof Double) {
return BigDecimal.valueOf((Double) item);
} else if (item instanceof Float) {
return BigDecimal.valueOf((Float) item);
} else {
return BigDecimal.valueOf(item.doubleValue());
}
}
}
/**
* Creates a matcher that matches when the examined number represents the same value as the reference BigDecimal.
*
* @param number the reference BigDecimal against which the examined number is checked.
*/
public static NumberMatcher sameNumber(BigDecimal number) {
return new NumberMatcher(number);
}
/**
* Verifies the equals/hashcode contract on the domain object.
*/
public static <T> void equalsVerifier(Class<T> clazz) throws Exception {
T domainObject1 = clazz.getConstructor().newInstance();
assertThat(domainObject1.toString()).isNotNull();
assertThat(domainObject1).isEqualTo(domainObject1);
assertThat(domainObject1).hasSameHashCodeAs(domainObject1);
// Test with an instance of another class
Object testOtherObject = new Object();
assertThat(domainObject1).isNotEqualTo(testOtherObject);
assertThat(domainObject1).isNotEqualTo(null);
// Test with an instance of the same class
T domainObject2 = clazz.getConstructor().newInstance();
assertThat(domainObject1).isNotEqualTo(domainObject2);
// HashCodes are equals because the objects are not persisted yet
assertThat(domainObject1).hasSameHashCodeAs(domainObject2);
}
/**
* Create a {@link FormattingConversionService} which use ISO date format, instead of the localized one.
* @return the {@link FormattingConversionService}.
*/
public static FormattingConversionService createFormattingConversionService() {
DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService();
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setUseIsoFormat(true);
registrar.registerFormatters(dfcs);
return dfcs;
}
/**
* Executes a query on the EntityManager finding all stored objects.
* @param <T> The type of objects to be searched
* @param em The instance of the EntityManager
* @param clazz The class type to be searched
* @return A list of all found objects
*/
public static <T> List<T> findAll(EntityManager em, Class<T> clazz) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(clazz);
Root<T> rootEntry = cq.from(clazz);
CriteriaQuery<T> all = cq.select(rootEntry);
TypedQuery<T> allQuery = em.createQuery(all);
return allQuery.getResultList();
}
@SuppressWarnings("unchecked")
public static <T> T createUpdateProxyForBean(T update, T original) {
Enhancer e = new Enhancer();
e.setSuperclass(original.getClass());
e.setCallback(
new MethodInterceptor() {
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
Object val = update.getClass().getMethod(method.getName(), method.getParameterTypes()).invoke(update, args);
if (val == null) {
return original.getClass().getMethod(method.getName(), method.getParameterTypes()).invoke(original, args);
}
return val;
}
}
);
return (T) e.create();
}
private TestUtil() {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/web/rest/WithUnauthenticatedMockUser.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/web/rest/WithUnauthenticatedMockUser.java | package com.dealers.app.web.rest;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.WithSecurityContext;
import org.springframework.security.test.context.support.WithSecurityContextFactory;
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithUnauthenticatedMockUser.Factory.class)
public @interface WithUnauthenticatedMockUser {
class Factory implements WithSecurityContextFactory<WithUnauthenticatedMockUser> {
@Override
public SecurityContext createSecurityContext(WithUnauthenticatedMockUser annotation) {
return SecurityContextHolder.createEmptyContext();
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/web/rest/errors/ExceptionTranslatorTestController.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/web/rest/errors/ExceptionTranslatorTestController.java | package com.dealers.app.web.rest.errors;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/exception-translator-test")
public class ExceptionTranslatorTestController {
@GetMapping("/concurrency-failure")
public void concurrencyFailure() {
throw new ConcurrencyFailureException("test concurrency failure");
}
@PostMapping("/method-argument")
public void methodArgument(@Valid @RequestBody TestDTO testDTO) {}
@GetMapping("/missing-servlet-request-part")
public void missingServletRequestPartException(@RequestPart("part") String part) {}
@GetMapping("/missing-servlet-request-parameter")
public void missingServletRequestParameterException(@RequestParam("param") String param) {}
@GetMapping("/access-denied")
public void accessdenied() {
throw new AccessDeniedException("test access denied!");
}
@GetMapping("/unauthorized")
public void unauthorized() {
throw new BadCredentialsException("test authentication failed!");
}
@GetMapping("/response-status")
public void exceptionWithResponseStatus() {
throw new TestResponseStatusException();
}
@GetMapping("/internal-server-error")
public void internalServerError() {
throw new RuntimeException();
}
public static class TestDTO {
@NotNull
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "test response status")
@SuppressWarnings("serial")
public static class TestResponseStatusException extends RuntimeException {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/web/rest/errors/ExceptionTranslatorIT.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/test/java/com/dealers/app/web/rest/errors/ExceptionTranslatorIT.java | package com.dealers.app.web.rest.errors;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.dealers.app.IntegrationTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
/**
* Integration tests {@link ExceptionTranslator} controller advice.
*/
@WithMockUser
@AutoConfigureMockMvc
@IntegrationTest
class ExceptionTranslatorIT {
@Autowired
private MockMvc mockMvc;
@Test
void testConcurrencyFailure() throws Exception {
mockMvc
.perform(get("/api/exception-translator-test/concurrency-failure"))
.andExpect(status().isConflict())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE));
}
@Test
void testMethodArgumentNotValid() throws Exception {
mockMvc
.perform(post("/api/exception-translator-test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION))
.andExpect(jsonPath("$.fieldErrors.[0].objectName").value("test"))
.andExpect(jsonPath("$.fieldErrors.[0].field").value("test"))
.andExpect(jsonPath("$.fieldErrors.[0].message").value("must not be null"));
}
@Test
void testMissingServletRequestPartException() throws Exception {
mockMvc
.perform(get("/api/exception-translator-test/missing-servlet-request-part"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.400"));
}
@Test
void testMissingServletRequestParameterException() throws Exception {
mockMvc
.perform(get("/api/exception-translator-test/missing-servlet-request-parameter"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.400"));
}
@Test
void testAccessDenied() throws Exception {
mockMvc
.perform(get("/api/exception-translator-test/access-denied"))
.andExpect(status().isForbidden())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.403"))
.andExpect(jsonPath("$.detail").value("test access denied!"));
}
@Test
void testUnauthorized() throws Exception {
mockMvc
.perform(get("/api/exception-translator-test/unauthorized"))
.andExpect(status().isUnauthorized())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.401"))
.andExpect(jsonPath("$.path").value("/api/exception-translator-test/unauthorized"))
.andExpect(jsonPath("$.detail").value("test authentication failed!"));
}
@Test
void testMethodNotSupported() throws Exception {
mockMvc
.perform(post("/api/exception-translator-test/access-denied"))
.andExpect(status().isMethodNotAllowed())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.405"))
.andExpect(jsonPath("$.detail").value("Request method 'POST' is not supported"));
}
@Test
void testExceptionWithResponseStatus() throws Exception {
mockMvc
.perform(get("/api/exception-translator-test/response-status"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.400"))
.andExpect(jsonPath("$.title").value("test response status"));
}
@Test
void testInternalServerError() throws Exception {
mockMvc
.perform(get("/api/exception-translator-test/internal-server-error"))
.andExpect(status().isInternalServerError())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.500"))
.andExpect(jsonPath("$.title").value("Internal Server Error"));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/ApplicationWebXml.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/ApplicationWebXml.java | package com.dealers.app;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import tech.jhipster.config.DefaultProfileUtil;
/**
* This is a helper Java class that provides an alternative to creating a {@code web.xml}.
* This will be invoked only when the application is deployed to a Servlet container like Tomcat, JBoss etc.
*/
public class ApplicationWebXml extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
// set a default to use when no profile is configured.
DefaultProfileUtil.addDefaultProfile(application.application());
return application.sources(DealerApp.class);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/package-info.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/package-info.java | /**
* Application root.
*/
package com.dealers.app;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/DealerApp.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/DealerApp.java | package com.dealers.app;
import com.dealers.app.config.ApplicationProperties;
import com.dealers.app.config.CRLFLogConverter;
import jakarta.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.env.Environment;
import tech.jhipster.config.DefaultProfileUtil;
import tech.jhipster.config.JHipsterConstants;
@SpringBootApplication
@EnableConfigurationProperties({ LiquibaseProperties.class, ApplicationProperties.class })
public class DealerApp {
private static final Logger log = LoggerFactory.getLogger(DealerApp.class);
private final Environment env;
public DealerApp(Environment env) {
this.env = env;
}
/**
* Initializes dealerApp.
* <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(DealerApp.class);
DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
logApplicationStartup(env);
}
private static void logApplicationStartup(Environment env) {
String protocol = Optional.ofNullable(env.getProperty("server.ssl.key-store")).map(key -> "https").orElse("http");
String applicationName = env.getProperty("spring.application.name");
String serverPort = env.getProperty("server.port");
String contextPath = Optional.ofNullable(env.getProperty("server.servlet.context-path"))
.filter(StringUtils::isNotBlank)
.orElse("/");
String hostAddress = "localhost";
try {
hostAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.warn("The host name could not be determined, using `localhost` as fallback");
}
log.info(
CRLFLogConverter.CRLF_SAFE_MARKER,
"""
----------------------------------------------------------
\tApplication '{}' is running! Access URLs:
\tLocal: \t\t{}://localhost:{}{}
\tExternal: \t{}://{}:{}{}
\tProfile(s): \t{}
----------------------------------------------------------""",
applicationName,
protocol,
serverPort,
contextPath,
protocol,
hostAddress,
serverPort,
contextPath,
env.getActiveProfiles().length == 0 ? env.getDefaultProfiles() : env.getActiveProfiles()
);
String configServerStatus = env.getProperty("configserver.status");
if (configServerStatus == null) {
configServerStatus = "Not found or not setup for this application";
}
log.info(
CRLFLogConverter.CRLF_SAFE_MARKER,
"\n----------------------------------------------------------\n\t" +
"Config Server: \t{}\n----------------------------------------------------------",
configServerStatus
);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/GeneratedByJHipster.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/GeneratedByJHipster.java | package com.dealers.app;
import jakarta.annotation.Generated;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Generated(value = "JHipster", comments = "Generated by JHipster 8.4.0")
@Retention(RetentionPolicy.SOURCE)
@Target({ ElementType.TYPE })
public @interface GeneratedByJHipster {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/management/package-info.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/management/package-info.java | /**
* Application management.
*/
package com.dealers.app.management;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/management/SecurityMetersService.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/management/SecurityMetersService.java | package com.dealers.app.management;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Service;
@Service
public class SecurityMetersService {
public static final String INVALID_TOKENS_METER_NAME = "security.authentication.invalid-tokens";
public static final String INVALID_TOKENS_METER_DESCRIPTION =
"Indicates validation error count of the tokens presented by the clients.";
public static final String INVALID_TOKENS_METER_BASE_UNIT = "errors";
public static final String INVALID_TOKENS_METER_CAUSE_DIMENSION = "cause";
private final Counter tokenInvalidSignatureCounter;
private final Counter tokenExpiredCounter;
private final Counter tokenUnsupportedCounter;
private final Counter tokenMalformedCounter;
public SecurityMetersService(MeterRegistry registry) {
this.tokenInvalidSignatureCounter = invalidTokensCounterForCauseBuilder("invalid-signature").register(registry);
this.tokenExpiredCounter = invalidTokensCounterForCauseBuilder("expired").register(registry);
this.tokenUnsupportedCounter = invalidTokensCounterForCauseBuilder("unsupported").register(registry);
this.tokenMalformedCounter = invalidTokensCounterForCauseBuilder("malformed").register(registry);
}
private Counter.Builder invalidTokensCounterForCauseBuilder(String cause) {
return Counter.builder(INVALID_TOKENS_METER_NAME)
.baseUnit(INVALID_TOKENS_METER_BASE_UNIT)
.description(INVALID_TOKENS_METER_DESCRIPTION)
.tag(INVALID_TOKENS_METER_CAUSE_DIMENSION, cause);
}
public void trackTokenInvalidSignature() {
this.tokenInvalidSignatureCounter.increment();
}
public void trackTokenExpired() {
this.tokenExpiredCounter.increment();
}
public void trackTokenUnsupported() {
this.tokenUnsupportedCounter.increment();
}
public void trackTokenMalformed() {
this.tokenMalformedCounter.increment();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/aop/logging/package-info.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/aop/logging/package-info.java | /**
* Logging aspect.
*/
package com.dealers.app.aop.logging;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/aop/logging/LoggingAspect.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/aop/logging/LoggingAspect.java | package com.dealers.app.aop.logging;
import java.util.Arrays;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import tech.jhipster.config.JHipsterConstants;
/**
* Aspect for logging execution of service and repository Spring components.
*
* By default, it only runs with the "dev" profile.
*/
@Aspect
public class LoggingAspect {
private final Environment env;
public LoggingAspect(Environment env) {
this.env = env;
}
/**
* Pointcut that matches all repositories, services and Web REST endpoints.
*/
@Pointcut(
"within(@org.springframework.stereotype.Repository *)" +
" || within(@org.springframework.stereotype.Service *)" +
" || within(@org.springframework.web.bind.annotation.RestController *)"
)
public void springBeanPointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
/**
* Pointcut that matches all Spring beans in the application's main packages.
*/
@Pointcut(
"within(com.dealers.app.repository..*)" + " || within(com.dealers.app.service..*)" + " || within(com.dealers.app.web.rest..*)"
)
public void applicationPackagePointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
/**
* Retrieves the {@link Logger} associated to the given {@link JoinPoint}.
*
* @param joinPoint join point we want the logger for.
* @return {@link Logger} associated to the given {@link JoinPoint}.
*/
private Logger logger(JoinPoint joinPoint) {
return LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringTypeName());
}
/**
* Advice that logs methods throwing exceptions.
*
* @param joinPoint join point for advice.
* @param e exception.
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
logger(joinPoint).error(
"Exception in {}() with cause = '{}' and exception = '{}'",
joinPoint.getSignature().getName(),
e.getCause() != null ? e.getCause() : "NULL",
e.getMessage(),
e
);
} else {
logger(joinPoint).error(
"Exception in {}() with cause = {}",
joinPoint.getSignature().getName(),
e.getCause() != null ? String.valueOf(e.getCause()) : "NULL"
);
}
}
/**
* Advice that logs when a method is entered and exited.
*
* @param joinPoint join point for advice.
* @return result.
* @throws Throwable throws {@link IllegalArgumentException}.
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
Logger log = logger(joinPoint);
if (log.isDebugEnabled()) {
log.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}() with result = {}", joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getName());
throw e;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/domain/package-info.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/domain/package-info.java | /**
* Domain objects.
*/
package com.dealers.app.domain;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/domain/AbstractAuditingEntity.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/domain/AbstractAuditingEntity.java | package com.dealers.app.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import java.io.Serializable;
import java.time.Instant;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
/**
* Base abstract class for entities which will hold definitions for created, last modified, created by,
* last modified by attributes.
*/
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = { "createdBy", "createdDate", "lastModifiedBy", "lastModifiedDate" }, allowGetters = true)
public abstract class AbstractAuditingEntity<T> implements Serializable {
private static final long serialVersionUID = 1L;
public abstract T getId();
@CreatedBy
@Column(name = "created_by", nullable = false, length = 50, updatable = false)
private String createdBy;
@CreatedDate
@Column(name = "created_date", updatable = false)
private Instant createdDate = Instant.now();
@LastModifiedBy
@Column(name = "last_modified_by", length = 50)
private String lastModifiedBy;
@LastModifiedDate
@Column(name = "last_modified_date")
private Instant lastModifiedDate = Instant.now();
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Instant getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/security/package-info.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/security/package-info.java | /**
* Application security utilities.
*/
package com.dealers.app.security;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/security/SpringSecurityAuditorAware.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/security/SpringSecurityAuditorAware.java | package com.dealers.app.security;
import com.dealers.app.config.Constants;
import java.util.Optional;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
/**
* Implementation of {@link AuditorAware} based on Spring Security.
*/
@Component
public class SpringSecurityAuditorAware implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
return Optional.of(SecurityUtils.getCurrentUserLogin().orElse(Constants.SYSTEM));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/security/SecurityUtils.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/security/SecurityUtils.java | package com.dealers.app.security;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Stream;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
/**
* Utility class for Spring Security.
*/
public final class SecurityUtils {
public static final MacAlgorithm JWT_ALGORITHM = MacAlgorithm.HS512;
public static final String AUTHORITIES_KEY = "auth";
private SecurityUtils() {}
/**
* Get the login of the current user.
*
* @return the login of the current user.
*/
public static Optional<String> getCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(extractPrincipal(securityContext.getAuthentication()));
}
private static String extractPrincipal(Authentication authentication) {
if (authentication == null) {
return null;
} else if (authentication.getPrincipal() instanceof UserDetails springSecurityUser) {
return springSecurityUser.getUsername();
} else if (authentication.getPrincipal() instanceof Jwt jwt) {
return jwt.getSubject();
} else if (authentication.getPrincipal() instanceof String s) {
return s;
}
return null;
}
/**
* Get the JWT of the current user.
*
* @return the JWT of the current user.
*/
public static Optional<String> getCurrentUserJWT() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.filter(authentication -> authentication.getCredentials() instanceof String)
.map(authentication -> (String) authentication.getCredentials());
}
/**
* Check if a user is authenticated.
*
* @return true if the user is authenticated, false otherwise.
*/
public static boolean isAuthenticated() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication != null && getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals);
}
/**
* Checks if the current user has any of the authorities.
*
* @param authorities the authorities to check.
* @return true if the current user has any of the authorities, false otherwise.
*/
public static boolean hasCurrentUserAnyOfAuthorities(String... authorities) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return (
authentication != null && getAuthorities(authentication).anyMatch(authority -> Arrays.asList(authorities).contains(authority))
);
}
/**
* Checks if the current user has none of the authorities.
*
* @param authorities the authorities to check.
* @return true if the current user has none of the authorities, false otherwise.
*/
public static boolean hasCurrentUserNoneOfAuthorities(String... authorities) {
return !hasCurrentUserAnyOfAuthorities(authorities);
}
/**
* Checks if the current user has a specific authority.
*
* @param authority the authority to check.
* @return true if the current user has the authority, false otherwise.
*/
public static boolean hasCurrentUserThisAuthority(String authority) {
return hasCurrentUserAnyOfAuthorities(authority);
}
private static Stream<String> getAuthorities(Authentication authentication) {
return authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/security/AuthoritiesConstants.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/security/AuthoritiesConstants.java | package com.dealers.app.security;
/**
* Constants for Spring Security authorities.
*/
public final class AuthoritiesConstants {
public static final String ADMIN = "ROLE_ADMIN";
public static final String USER = "ROLE_USER";
public static final String ANONYMOUS = "ROLE_ANONYMOUS";
private AuthoritiesConstants() {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/SecurityConfiguration.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/SecurityConfiguration.java | package com.dealers.app.config;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher;
import com.dealers.app.security.*;
import com.dealers.app.web.filter.SpaWebFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer.FrameOptionsConfig;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint;
import org.springframework.security.oauth2.server.resource.web.access.BearerTokenAccessDeniedHandler;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.JHipsterProperties;
@Configuration
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfiguration {
private final Environment env;
private final JHipsterProperties jHipsterProperties;
public SecurityConfiguration(Environment env, JHipsterProperties jHipsterProperties) {
this.env = env;
this.jHipsterProperties = jHipsterProperties;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http, MvcRequestMatcher.Builder mvc) throws Exception {
http
.csrf(csrf -> csrf.disable())
.addFilterAfter(new SpaWebFilter(), BasicAuthenticationFilter.class)
.headers(
headers ->
headers
.contentSecurityPolicy(csp -> csp.policyDirectives(jHipsterProperties.getSecurity().getContentSecurityPolicy()))
.frameOptions(FrameOptionsConfig::sameOrigin)
.referrerPolicy(
referrer -> referrer.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)
)
.permissionsPolicy(
permissions ->
permissions.policy(
"camera=(), fullscreen=(self), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), sync-xhr=()"
)
)
)
.authorizeHttpRequests(
authz ->
// prettier-ignore
authz
.requestMatchers(mvc.pattern("/index.html"), mvc.pattern("/*.js"), mvc.pattern("/*.txt"), mvc.pattern("/*.json"), mvc.pattern("/*.map"), mvc.pattern("/*.css")).permitAll()
.requestMatchers(mvc.pattern("/*.ico"), mvc.pattern("/*.png"), mvc.pattern("/*.svg"), mvc.pattern("/*.webapp")).permitAll()
.requestMatchers(mvc.pattern("/app/**")).permitAll()
.requestMatchers(mvc.pattern("/i18n/**")).permitAll()
.requestMatchers(mvc.pattern("/content/**")).permitAll()
.requestMatchers(mvc.pattern("/swagger-ui/**")).permitAll()
.requestMatchers(mvc.pattern(HttpMethod.POST, "/api/authenticate")).permitAll()
.requestMatchers(mvc.pattern(HttpMethod.GET, "/api/authenticate")).permitAll()
.requestMatchers(mvc.pattern("/api/admin/**")).hasAuthority(AuthoritiesConstants.ADMIN)
.requestMatchers(mvc.pattern("/api/**")).authenticated()
.requestMatchers(mvc.pattern("/v3/api-docs/**")).hasAuthority(AuthoritiesConstants.ADMIN)
.requestMatchers(mvc.pattern("/management/health")).permitAll()
.requestMatchers(mvc.pattern("/management/health/**")).permitAll()
.requestMatchers(mvc.pattern("/management/info")).permitAll()
.requestMatchers(mvc.pattern("/management/prometheus")).permitAll()
.requestMatchers(mvc.pattern("/management/**")).hasAuthority(AuthoritiesConstants.ADMIN)
)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(
exceptions ->
exceptions
.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
.accessDeniedHandler(new BearerTokenAccessDeniedHandler())
)
.oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults()));
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
http.authorizeHttpRequests(authz -> authz.requestMatchers(antMatcher("/h2-console/**")).permitAll());
}
return http.build();
}
@Bean
MvcRequestMatcher.Builder mvc(HandlerMappingIntrospector introspector) {
return new MvcRequestMatcher.Builder(introspector);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/ApplicationProperties.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/ApplicationProperties.java | package com.dealers.app.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Properties specific to Dealer App.
* <p>
* Properties are configured in the {@code application.yml} file.
* See {@link tech.jhipster.config.JHipsterProperties} for a good example.
*/
@ConfigurationProperties(prefix = "application", ignoreUnknownFields = false)
public class ApplicationProperties {
private final Liquibase liquibase = new Liquibase();
// jhipster-needle-application-properties-property
public Liquibase getLiquibase() {
return liquibase;
}
// jhipster-needle-application-properties-property-getter
public static class Liquibase {
private Boolean asyncStart;
public Boolean getAsyncStart() {
return asyncStart;
}
public void setAsyncStart(Boolean asyncStart) {
this.asyncStart = asyncStart;
}
}
// jhipster-needle-application-properties-property-class
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/DatabaseConfiguration.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/DatabaseConfiguration.java | package com.dealers.app.config;
import java.sql.SQLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.h2.H2ConfigurationHelper;
@Configuration
@EnableJpaRepositories({ "com.dealers.app.repository" })
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement
public class DatabaseConfiguration {
private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);
private final Environment env;
public DatabaseConfiguration(Environment env) {
this.env = env;
}
/**
* Open the TCP port for the H2 database, so it is available remotely.
*
* @return the H2 database TCP server.
* @throws SQLException if the server failed to start.
*/
@Bean(initMethod = "start", destroyMethod = "stop")
@Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)
public Object h2TCPServer() throws SQLException {
String port = getValidPortForH2();
log.debug("H2 database is available on port {}", port);
return H2ConfigurationHelper.createServer(port);
}
private String getValidPortForH2() {
int port = Integer.parseInt(env.getProperty("server.port"));
if (port < 10000) {
port = 10000 + port;
} else {
if (port < 63536) {
port = port + 2000;
} else {
port = port - 2000;
}
}
return String.valueOf(port);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/CacheConfiguration.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/CacheConfiguration.java | package com.dealers.app.config;
import com.hazelcast.config.*;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import jakarta.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.info.BuildProperties;
import org.springframework.boot.info.GitProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.JHipsterProperties;
import tech.jhipster.config.cache.PrefixedKeyGenerator;
@Configuration
@EnableCaching
public class CacheConfiguration {
private GitProperties gitProperties;
private BuildProperties buildProperties;
private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
private final Environment env;
private final ServerProperties serverProperties;
private final DiscoveryClient discoveryClient;
private Registration registration;
public CacheConfiguration(Environment env, ServerProperties serverProperties, DiscoveryClient discoveryClient) {
this.env = env;
this.serverProperties = serverProperties;
this.discoveryClient = discoveryClient;
}
@Autowired(required = false)
public void setRegistration(Registration registration) {
this.registration = registration;
}
@PreDestroy
public void destroy() {
log.info("Closing Cache Manager");
Hazelcast.shutdownAll();
}
@Bean
public CacheManager cacheManager(HazelcastInstance hazelcastInstance) {
log.debug("Starting HazelcastCacheManager");
return new com.hazelcast.spring.cache.HazelcastCacheManager(hazelcastInstance);
}
@Bean
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
log.debug("Configuring Hazelcast");
HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("dealerApp");
if (hazelCastInstance != null) {
log.debug("Hazelcast already initialized");
return hazelCastInstance;
}
Config config = new Config();
config.setInstanceName("dealerApp");
config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
if (this.registration == null) {
log.warn("No discovery service is set up, Hazelcast cannot create a cluster.");
} else {
// The serviceId is by default the application's name,
// see the "spring.application.name" standard Spring property
String serviceId = registration.getServiceId();
log.debug("Configuring Hazelcast clustering for instanceId: {}", serviceId);
// In development, everything goes through 127.0.0.1, with a different port
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
log.debug(
"Application is running with the \"dev\" profile, Hazelcast " + "cluster will only work with localhost instances"
);
config.getNetworkConfig().setPort(serverProperties.getPort() + 5701);
config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true);
for (ServiceInstance instance : discoveryClient.getInstances(serviceId)) {
String clusterMember = "127.0.0.1:" + (instance.getPort() + 5701);
log.debug("Adding Hazelcast (dev) cluster member {}", clusterMember);
config.getNetworkConfig().getJoin().getTcpIpConfig().addMember(clusterMember);
}
} else { // Production configuration, one host per instance all using port 5701
config.getNetworkConfig().setPort(5701);
config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true);
for (ServiceInstance instance : discoveryClient.getInstances(serviceId)) {
String clusterMember = instance.getHost() + ":5701";
log.debug("Adding Hazelcast (prod) cluster member {}", clusterMember);
config.getNetworkConfig().getJoin().getTcpIpConfig().addMember(clusterMember);
}
}
}
config.setManagementCenterConfig(new ManagementCenterConfig());
config.addMapConfig(initializeDefaultMapConfig(jHipsterProperties));
config.addMapConfig(initializeDomainMapConfig(jHipsterProperties));
return Hazelcast.newHazelcastInstance(config);
}
private MapConfig initializeDefaultMapConfig(JHipsterProperties jHipsterProperties) {
MapConfig mapConfig = new MapConfig("default");
/*
Number of backups. If 1 is set as the backup-count for example,
then all entries of the map will be copied to another JVM for
fail-safety. Valid numbers are 0 (no backup), 1, 2, 3.
*/
mapConfig.setBackupCount(jHipsterProperties.getCache().getHazelcast().getBackupCount());
/*
Valid values are:
NONE (no eviction),
LRU (Least Recently Used),
LFU (Least Frequently Used).
NONE is the default.
*/
mapConfig.getEvictionConfig().setEvictionPolicy(EvictionPolicy.LRU);
/*
Maximum size of the map. When max size is reached,
map is evicted based on the policy defined.
Any integer between 0 and Integer.MAX_VALUE. 0 means
Integer.MAX_VALUE. Default is 0.
*/
mapConfig.getEvictionConfig().setMaxSizePolicy(MaxSizePolicy.USED_HEAP_SIZE);
return mapConfig;
}
private MapConfig initializeDomainMapConfig(JHipsterProperties jHipsterProperties) {
MapConfig mapConfig = new MapConfig("com.dealers.app.domain.*");
mapConfig.setTimeToLiveSeconds(jHipsterProperties.getCache().getHazelcast().getTimeToLiveSeconds());
return mapConfig;
}
@Autowired(required = false)
public void setGitProperties(GitProperties gitProperties) {
this.gitProperties = gitProperties;
}
@Autowired(required = false)
public void setBuildProperties(BuildProperties buildProperties) {
this.buildProperties = buildProperties;
}
@Bean
public KeyGenerator keyGenerator() {
return new PrefixedKeyGenerator(this.gitProperties, this.buildProperties);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/package-info.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/package-info.java | /**
* Application configuration.
*/
package com.dealers.app.config;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/DateTimeFormatConfiguration.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/DateTimeFormatConfiguration.java | package com.dealers.app.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Configure the converters to use the ISO format for dates by default.
*/
@Configuration
public class DateTimeFormatConfiguration implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setUseIsoFormat(true);
registrar.registerFormatters(registry);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/CRLFLogConverter.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/CRLFLogConverter.java | package com.dealers.app.config;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.pattern.CompositeConverter;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.boot.ansi.AnsiColor;
import org.springframework.boot.ansi.AnsiElement;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.boot.ansi.AnsiStyle;
/**
* Log filter to prevent attackers from forging log entries by submitting input containing CRLF characters.
* CRLF characters are replaced with a red colored _ character.
*
* @see <a href="https://owasp.org/www-community/attacks/Log_Injection">Log Forging Description</a>
* @see <a href="https://github.com/jhipster/generator-jhipster/issues/14949">JHipster issue</a>
*/
public class CRLFLogConverter extends CompositeConverter<ILoggingEvent> {
public static final Marker CRLF_SAFE_MARKER = MarkerFactory.getMarker("CRLF_SAFE");
private static final String[] SAFE_LOGGERS = {
"org.hibernate",
"org.springframework.boot.autoconfigure",
"org.springframework.boot.diagnostics",
};
private static final Map<String, AnsiElement> ELEMENTS;
static {
Map<String, AnsiElement> ansiElements = new HashMap<>();
ansiElements.put("faint", AnsiStyle.FAINT);
ansiElements.put("red", AnsiColor.RED);
ansiElements.put("green", AnsiColor.GREEN);
ansiElements.put("yellow", AnsiColor.YELLOW);
ansiElements.put("blue", AnsiColor.BLUE);
ansiElements.put("magenta", AnsiColor.MAGENTA);
ansiElements.put("cyan", AnsiColor.CYAN);
ELEMENTS = Collections.unmodifiableMap(ansiElements);
}
@Override
protected String transform(ILoggingEvent event, String in) {
AnsiElement element = ELEMENTS.get(getFirstOption());
List<Marker> markers = event.getMarkerList();
if ((markers != null && !markers.isEmpty() && markers.get(0).contains(CRLF_SAFE_MARKER)) || isLoggerSafe(event)) {
return in;
}
String replacement = element == null ? "_" : toAnsiString("_", element);
return in.replaceAll("[\n\r\t]", replacement);
}
protected boolean isLoggerSafe(ILoggingEvent event) {
for (String safeLogger : SAFE_LOGGERS) {
if (event.getLoggerName().startsWith(safeLogger)) {
return true;
}
}
return false;
}
protected String toAnsiString(String in, AnsiElement element) {
return AnsiOutput.toString(element, in);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/AsyncConfiguration.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/AsyncConfiguration.java | package com.dealers.app.config;
import java.util.concurrent.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import tech.jhipster.async.ExceptionHandlingAsyncTaskExecutor;
@Configuration
@EnableAsync
@EnableScheduling
@Profile("!testdev & !testprod")
public class AsyncConfiguration implements AsyncConfigurer {
private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);
private final TaskExecutionProperties taskExecutionProperties;
public AsyncConfiguration(TaskExecutionProperties taskExecutionProperties) {
this.taskExecutionProperties = taskExecutionProperties;
}
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
log.debug("Creating Async Task Executor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(taskExecutionProperties.getPool().getCoreSize());
executor.setMaxPoolSize(taskExecutionProperties.getPool().getMaxSize());
executor.setQueueCapacity(taskExecutionProperties.getPool().getQueueCapacity());
executor.setThreadNamePrefix(taskExecutionProperties.getThreadNamePrefix());
return new ExceptionHandlingAsyncTaskExecutor(executor);
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/WebConfigurer.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/WebConfigurer.java | package com.dealers.app.config;
import static java.net.URLDecoder.decode;
import jakarta.servlet.*;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.server.*;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.util.CollectionUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.JHipsterProperties;
import tech.jhipster.config.h2.H2ConfigurationHelper;
/**
* Configuration of web application with Servlet 3.0 APIs.
*/
@Configuration
public class WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> {
private final Logger log = LoggerFactory.getLogger(WebConfigurer.class);
private final Environment env;
private final JHipsterProperties jHipsterProperties;
public WebConfigurer(Environment env, JHipsterProperties jHipsterProperties) {
this.env = env;
this.jHipsterProperties = jHipsterProperties;
}
@Override
public void onStartup(ServletContext servletContext) {
if (env.getActiveProfiles().length != 0) {
log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles());
}
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
initH2Console(servletContext);
}
log.info("Web application fully configured");
}
/**
* Customize the Servlet engine: Mime types, the document root, the cache.
*/
@Override
public void customize(WebServerFactory server) {
// When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets.
setLocationForStaticAssets(server);
}
private void setLocationForStaticAssets(WebServerFactory server) {
if (server instanceof ConfigurableServletWebServerFactory servletWebServer) {
File root;
String prefixPath = resolvePathPrefix();
root = new File(prefixPath + "target/classes/static/");
if (root.exists() && root.isDirectory()) {
servletWebServer.setDocumentRoot(root);
}
}
}
/**
* Resolve path prefix to static resources.
*/
private String resolvePathPrefix() {
String fullExecutablePath = decode(this.getClass().getResource("").getPath(), StandardCharsets.UTF_8);
String rootPath = Paths.get(".").toUri().normalize().getPath();
String extractedPath = fullExecutablePath.replace(rootPath, "");
int extractionEndIndex = extractedPath.indexOf("target/");
if (extractionEndIndex <= 0) {
return "";
}
return extractedPath.substring(0, extractionEndIndex);
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = jHipsterProperties.getCors();
if (!CollectionUtils.isEmpty(config.getAllowedOrigins()) || !CollectionUtils.isEmpty(config.getAllowedOriginPatterns())) {
log.debug("Registering CORS filter");
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/management/**", config);
source.registerCorsConfiguration("/v3/api-docs", config);
source.registerCorsConfiguration("/swagger-ui/**", config);
}
return new CorsFilter(source);
}
/**
* Initializes H2 console.
*/
private void initH2Console(ServletContext servletContext) {
log.debug("Initialize H2 console");
H2ConfigurationHelper.initH2Console(servletContext);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/JacksonConfiguration.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/JacksonConfiguration.java | package com.dealers.app.config;
import com.fasterxml.jackson.datatype.hibernate6.Hibernate6Module;
import com.fasterxml.jackson.datatype.hibernate6.Hibernate6Module.Feature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JacksonConfiguration {
/**
* Support for Java date and time API.
* @return the corresponding Jackson module.
*/
@Bean
public JavaTimeModule javaTimeModule() {
return new JavaTimeModule();
}
@Bean
public Jdk8Module jdk8TimeModule() {
return new Jdk8Module();
}
/*
* Support for Hibernate types in Jackson.
*/
@Bean
public Hibernate6Module hibernate6Module() {
return new Hibernate6Module().configure(Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS, true);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/LoggingConfiguration.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/LoggingConfiguration.java | package com.dealers.app.config;
import static tech.jhipster.config.logging.LoggingUtils.*;
import ch.qos.logback.classic.LoggerContext;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.info.BuildProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import tech.jhipster.config.JHipsterProperties;
/*
* Configures the console and Logstash log appenders from the app properties
*/
@Configuration
@RefreshScope
public class LoggingConfiguration {
public LoggingConfiguration(
@Value("${spring.application.name}") String appName,
@Value("${server.port}") String serverPort,
JHipsterProperties jHipsterProperties,
ObjectProvider<BuildProperties> buildProperties,
ObjectMapper mapper
) throws JsonProcessingException {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
Map<String, String> map = new HashMap<>();
map.put("app_name", appName);
map.put("app_port", serverPort);
buildProperties.ifAvailable(it -> map.put("version", it.getVersion()));
String customFields = mapper.writeValueAsString(map);
JHipsterProperties.Logging loggingProperties = jHipsterProperties.getLogging();
JHipsterProperties.Logging.Logstash logstashProperties = loggingProperties.getLogstash();
if (loggingProperties.isUseJsonFormat()) {
addJsonConsoleAppender(context, customFields);
}
if (logstashProperties.isEnabled()) {
addLogstashTcpSocketAppender(context, customFields, logstashProperties);
}
if (loggingProperties.isUseJsonFormat() || logstashProperties.isEnabled()) {
addContextListener(context, customFields, loggingProperties);
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/SecurityJwtConfiguration.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/SecurityJwtConfiguration.java | package com.dealers.app.config;
import static com.dealers.app.security.SecurityUtils.AUTHORITIES_KEY;
import static com.dealers.app.security.SecurityUtils.JWT_ALGORITHM;
import com.dealers.app.management.SecurityMetersService;
import com.nimbusds.jose.jwk.source.ImmutableSecret;
import com.nimbusds.jose.util.Base64;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
@Configuration
public class SecurityJwtConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityJwtConfiguration.class);
@Value("${jhipster.security.authentication.jwt.base64-secret}")
private String jwtKey;
@Bean
public JwtDecoder jwtDecoder(SecurityMetersService metersService) {
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withSecretKey(getSecretKey()).macAlgorithm(JWT_ALGORITHM).build();
return token -> {
try {
return jwtDecoder.decode(token);
} catch (Exception e) {
if (e.getMessage().contains("Invalid signature")) {
metersService.trackTokenInvalidSignature();
} else if (e.getMessage().contains("Jwt expired at")) {
metersService.trackTokenExpired();
} else if (
e.getMessage().contains("Invalid JWT serialization") ||
e.getMessage().contains("Malformed token") ||
e.getMessage().contains("Invalid unsecured/JWS/JWE")
) {
metersService.trackTokenMalformed();
} else {
log.error("Unknown JWT error {}", e.getMessage());
}
throw e;
}
};
}
@Bean
public JwtEncoder jwtEncoder() {
return new NimbusJwtEncoder(new ImmutableSecret<>(getSecretKey()));
}
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
grantedAuthoritiesConverter.setAuthorityPrefix("");
grantedAuthoritiesConverter.setAuthoritiesClaimName(AUTHORITIES_KEY);
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}
private SecretKey getSecretKey() {
byte[] keyBytes = Base64.from(jwtKey).decode();
return new SecretKeySpec(keyBytes, 0, keyBytes.length, JWT_ALGORITHM.getName());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/LiquibaseConfiguration.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/LiquibaseConfiguration.java | package com.dealers.app.config;
import java.util.concurrent.Executor;
import javax.sql.DataSource;
import liquibase.integration.spring.SpringLiquibase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseDataSource;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.liquibase.SpringLiquibaseUtil;
@Configuration
public class LiquibaseConfiguration {
private final Logger log = LoggerFactory.getLogger(LiquibaseConfiguration.class);
private final Environment env;
public LiquibaseConfiguration(Environment env) {
this.env = env;
}
@Value("${application.liquibase.async-start:true}")
private Boolean asyncStart;
@Bean
public SpringLiquibase liquibase(
@Qualifier("taskExecutor") Executor executor,
LiquibaseProperties liquibaseProperties,
@LiquibaseDataSource ObjectProvider<DataSource> liquibaseDataSource,
ObjectProvider<DataSource> dataSource,
DataSourceProperties dataSourceProperties
) {
SpringLiquibase liquibase;
if (Boolean.TRUE.equals(asyncStart)) {
liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase(
this.env,
executor,
liquibaseDataSource.getIfAvailable(),
liquibaseProperties,
dataSource.getIfUnique(),
dataSourceProperties
);
} else {
liquibase = SpringLiquibaseUtil.createSpringLiquibase(
liquibaseDataSource.getIfAvailable(),
liquibaseProperties,
dataSource.getIfUnique(),
dataSourceProperties
);
}
liquibase.setChangeLog("classpath:config/liquibase/master.xml");
liquibase.setContexts(liquibaseProperties.getContexts());
liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
liquibase.setLiquibaseSchema(liquibaseProperties.getLiquibaseSchema());
liquibase.setLiquibaseTablespace(liquibaseProperties.getLiquibaseTablespace());
liquibase.setDatabaseChangeLogLockTable(liquibaseProperties.getDatabaseChangeLogLockTable());
liquibase.setDatabaseChangeLogTable(liquibaseProperties.getDatabaseChangeLogTable());
liquibase.setDropFirst(liquibaseProperties.isDropFirst());
liquibase.setLabelFilter(liquibaseProperties.getLabelFilter());
liquibase.setChangeLogParameters(liquibaseProperties.getParameters());
liquibase.setRollbackFile(liquibaseProperties.getRollbackFile());
liquibase.setTestRollbackOnUpdate(liquibaseProperties.isTestRollbackOnUpdate());
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE))) {
liquibase.setShouldRun(false);
} else {
liquibase.setShouldRun(liquibaseProperties.isEnabled());
log.debug("Configuring Liquibase");
}
return liquibase;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/OpenApiConfiguration.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/OpenApiConfiguration.java | package com.dealers.app.config;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.JHipsterProperties;
import tech.jhipster.config.apidoc.customizer.JHipsterOpenApiCustomizer;
@Configuration
@Profile(JHipsterConstants.SPRING_PROFILE_API_DOCS)
public class OpenApiConfiguration {
public static final String API_FIRST_PACKAGE = "com.dealers.app.web.api";
@Bean
@ConditionalOnMissingBean(name = "apiFirstGroupedOpenAPI")
public GroupedOpenApi apiFirstGroupedOpenAPI(
JHipsterOpenApiCustomizer jhipsterOpenApiCustomizer,
JHipsterProperties jHipsterProperties
) {
JHipsterProperties.ApiDocs properties = jHipsterProperties.getApiDocs();
return GroupedOpenApi.builder()
.group("openapi")
.addOpenApiCustomizer(jhipsterOpenApiCustomizer)
.packagesToScan(API_FIRST_PACKAGE)
.pathsToMatch(properties.getDefaultIncludePattern())
.build();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/EurekaWorkaroundConfiguration.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/EurekaWorkaroundConfiguration.java | // This is a workaround for
// https://github.com/jhipster/jhipster-registry/issues/537
// https://github.com/jhipster/generator-jhipster/issues/18533
// The original issue will be fixed with spring cloud 2021.0.4
// https://github.com/spring-cloud/spring-cloud-netflix/issues/3941
package com.dealers.app.config;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class EurekaWorkaroundConfiguration implements HealthIndicator {
private boolean applicationIsUp = false;
@EventListener(ApplicationReadyEvent.class)
public void onStartup() {
this.applicationIsUp = true;
}
@Override
public Health health() {
if (!applicationIsUp) {
return Health.down().build();
}
return Health.up().build();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/StaticResourcesWebConfiguration.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/StaticResourcesWebConfiguration.java | package com.dealers.app.config;
import java.util.concurrent.TimeUnit;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.JHipsterProperties;
@Configuration
@Profile({ JHipsterConstants.SPRING_PROFILE_PRODUCTION })
public class StaticResourcesWebConfiguration implements WebMvcConfigurer {
protected static final String[] RESOURCE_LOCATIONS = { "classpath:/static/", "classpath:/static/content/", "classpath:/static/i18n/" };
protected static final String[] RESOURCE_PATHS = { "/*.js", "/*.css", "/*.svg", "/*.png", "*.ico", "/content/**", "/i18n/*" };
private final JHipsterProperties jhipsterProperties;
public StaticResourcesWebConfiguration(JHipsterProperties jHipsterProperties) {
this.jhipsterProperties = jHipsterProperties;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
ResourceHandlerRegistration resourceHandlerRegistration = appendResourceHandler(registry);
initializeResourceHandler(resourceHandlerRegistration);
}
protected ResourceHandlerRegistration appendResourceHandler(ResourceHandlerRegistry registry) {
return registry.addResourceHandler(RESOURCE_PATHS);
}
protected void initializeResourceHandler(ResourceHandlerRegistration resourceHandlerRegistration) {
resourceHandlerRegistration.addResourceLocations(RESOURCE_LOCATIONS).setCacheControl(getCacheControl());
}
protected CacheControl getCacheControl() {
return CacheControl.maxAge(getJHipsterHttpCacheProperty(), TimeUnit.DAYS).cachePublic();
}
private int getJHipsterHttpCacheProperty() {
return jhipsterProperties.getHttp().getCache().getTimeToLiveInDays();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/Constants.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/Constants.java | package com.dealers.app.config;
/**
* Application constants.
*/
public final class Constants {
public static final String SYSTEM = "system";
private Constants() {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/LoggingAspectConfiguration.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/config/LoggingAspectConfiguration.java | package com.dealers.app.config;
import com.dealers.app.aop.logging.LoggingAspect;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import tech.jhipster.config.JHipsterConstants;
@Configuration
@EnableAspectJAutoProxy
public class LoggingAspectConfiguration {
@Bean
@Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)
public LoggingAspect loggingAspect(Environment env) {
return new LoggingAspect(env);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/web/filter/SpaWebFilter.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/web/filter/SpaWebFilter.java | package com.dealers.app.web.filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.web.filter.OncePerRequestFilter;
public class SpaWebFilter extends OncePerRequestFilter {
/**
* Forwards any unmapped paths (except those containing a period) to the client {@code index.html}.
*/
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// Request URI includes the contextPath if any, removed it.
String path = request.getRequestURI().substring(request.getContextPath().length());
if (
!path.startsWith("/api") &&
!path.startsWith("/management") &&
!path.startsWith("/v3/api-docs") &&
!path.startsWith("/h2-console") &&
!path.contains(".") &&
path.matches("/(.*)")
) {
request.getRequestDispatcher("/index.html").forward(request, response);
return;
}
filterChain.doFilter(request, response);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/web/filter/package-info.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/web/filter/package-info.java | /**
* Request chain filters.
*/
package com.dealers.app.web.filter;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/web/rest/errors/package-info.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/web/rest/errors/package-info.java | /**
* Rest layer error handling.
*/
package com.dealers.app.web.rest.errors;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/web/rest/errors/ErrorConstants.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/web/rest/errors/ErrorConstants.java | package com.dealers.app.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");
private ErrorConstants() {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/web/rest/errors/FieldErrorVM.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/web/rest/errors/FieldErrorVM.java | package com.dealers.app.web.rest.errors;
import java.io.Serializable;
public class FieldErrorVM implements Serializable {
private static final long serialVersionUID = 1L;
private final String objectName;
private final String field;
private final String message;
public FieldErrorVM(String dto, String field, String message) {
this.objectName = dto;
this.field = field;
this.message = message;
}
public String getObjectName() {
return objectName;
}
public String getField() {
return field;
}
public String getMessage() {
return message;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/web/rest/errors/BadRequestAlertException.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/web/rest/errors/BadRequestAlertException.java | package com.dealers.app.web.rest.errors;
import java.net.URI;
import org.springframework.http.HttpStatus;
import org.springframework.web.ErrorResponseException;
import tech.jhipster.web.rest.errors.ProblemDetailWithCause;
import tech.jhipster.web.rest.errors.ProblemDetailWithCause.ProblemDetailWithCauseBuilder;
@SuppressWarnings("java:S110") // Inheritance tree of classes should not be too deep
public class BadRequestAlertException extends ErrorResponseException {
private static final long serialVersionUID = 1L;
private final String entityName;
private final String errorKey;
public BadRequestAlertException(String defaultMessage, String entityName, String errorKey) {
this(ErrorConstants.DEFAULT_TYPE, defaultMessage, entityName, errorKey);
}
public BadRequestAlertException(URI type, String defaultMessage, String entityName, String errorKey) {
super(
HttpStatus.BAD_REQUEST,
ProblemDetailWithCauseBuilder.instance()
.withStatus(HttpStatus.BAD_REQUEST.value())
.withType(type)
.withTitle(defaultMessage)
.withProperty("message", "error." + errorKey)
.withProperty("params", entityName)
.build(),
null
);
this.entityName = entityName;
this.errorKey = errorKey;
}
public String getEntityName() {
return entityName;
}
public String getErrorKey() {
return errorKey;
}
public ProblemDetailWithCause getProblemDetailWithCause() {
return (ProblemDetailWithCause) this.getBody();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/web/rest/errors/ExceptionTranslator.java | jhipster-8-modules/jhipster-8-microservice/dealer-app/src/main/java/com/dealers/app/web/rest/errors/ExceptionTranslator.java | package com.dealers.app.web.rest.errors;
import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation;
import jakarta.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.lang.Nullable;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.ErrorResponse;
import org.springframework.web.ErrorResponseException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.web.rest.errors.ProblemDetailWithCause;
import tech.jhipster.web.rest.errors.ProblemDetailWithCause.ProblemDetailWithCauseBuilder;
import tech.jhipster.web.util.HeaderUtil;
/**
* Controller advice to translate the server side exceptions to client-friendly json structures.
* The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807).
*/
@ControllerAdvice
public class ExceptionTranslator extends ResponseEntityExceptionHandler {
private static final String FIELD_ERRORS_KEY = "fieldErrors";
private static final String MESSAGE_KEY = "message";
private static final String PATH_KEY = "path";
private static final boolean CASUAL_CHAIN_ENABLED = false;
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final Environment env;
public ExceptionTranslator(Environment env) {
this.env = env;
}
@ExceptionHandler
public ResponseEntity<Object> handleAnyException(Throwable ex, NativeWebRequest request) {
ProblemDetailWithCause pdCause = wrapAndCustomizeProblem(ex, request);
return handleExceptionInternal((Exception) ex, pdCause, buildHeaders(ex), HttpStatusCode.valueOf(pdCause.getStatus()), request);
}
@Nullable
@Override
protected ResponseEntity<Object> handleExceptionInternal(
Exception ex,
@Nullable Object body,
HttpHeaders headers,
HttpStatusCode statusCode,
WebRequest request
) {
body = body == null ? wrapAndCustomizeProblem((Throwable) ex, (NativeWebRequest) request) : body;
return super.handleExceptionInternal(ex, body, headers, statusCode, request);
}
protected ProblemDetailWithCause wrapAndCustomizeProblem(Throwable ex, NativeWebRequest request) {
return customizeProblem(getProblemDetailWithCause(ex), ex, request);
}
private ProblemDetailWithCause getProblemDetailWithCause(Throwable ex) {
if (
ex instanceof ErrorResponseException exp && exp.getBody() instanceof ProblemDetailWithCause problemDetailWithCause
) return problemDetailWithCause;
return ProblemDetailWithCauseBuilder.instance().withStatus(toStatus(ex).value()).build();
}
protected ProblemDetailWithCause customizeProblem(ProblemDetailWithCause problem, Throwable err, NativeWebRequest request) {
if (problem.getStatus() <= 0) problem.setStatus(toStatus(err));
if (problem.getType() == null || problem.getType().equals(URI.create("about:blank"))) problem.setType(getMappedType(err));
// higher precedence to Custom/ResponseStatus types
String title = extractTitle(err, problem.getStatus());
String problemTitle = problem.getTitle();
if (problemTitle == null || !problemTitle.equals(title)) {
problem.setTitle(title);
}
if (problem.getDetail() == null) {
// higher precedence to cause
problem.setDetail(getCustomizedErrorDetails(err));
}
Map<String, Object> problemProperties = problem.getProperties();
if (problemProperties == null || !problemProperties.containsKey(MESSAGE_KEY)) problem.setProperty(
MESSAGE_KEY,
getMappedMessageKey(err) != null ? getMappedMessageKey(err) : "error.http." + problem.getStatus()
);
if (problemProperties == null || !problemProperties.containsKey(PATH_KEY)) problem.setProperty(PATH_KEY, getPathValue(request));
if (
(err instanceof MethodArgumentNotValidException fieldException) &&
(problemProperties == null || !problemProperties.containsKey(FIELD_ERRORS_KEY))
) problem.setProperty(FIELD_ERRORS_KEY, getFieldErrors(fieldException));
problem.setCause(buildCause(err.getCause(), request).orElse(null));
return problem;
}
private String extractTitle(Throwable err, int statusCode) {
return getCustomizedTitle(err) != null ? getCustomizedTitle(err) : extractTitleForResponseStatus(err, statusCode);
}
private List<FieldErrorVM> getFieldErrors(MethodArgumentNotValidException ex) {
return ex
.getBindingResult()
.getFieldErrors()
.stream()
.map(
f ->
new FieldErrorVM(
f.getObjectName().replaceFirst("DTO$", ""),
f.getField(),
StringUtils.isNotBlank(f.getDefaultMessage()) ? f.getDefaultMessage() : f.getCode()
)
)
.toList();
}
private String extractTitleForResponseStatus(Throwable err, int statusCode) {
ResponseStatus specialStatus = extractResponseStatus(err);
return specialStatus == null ? HttpStatus.valueOf(statusCode).getReasonPhrase() : specialStatus.reason();
}
private String extractURI(NativeWebRequest request) {
HttpServletRequest nativeRequest = request.getNativeRequest(HttpServletRequest.class);
return nativeRequest != null ? nativeRequest.getRequestURI() : StringUtils.EMPTY;
}
private HttpStatus toStatus(final Throwable throwable) {
// Let the ErrorResponse take this responsibility
if (throwable instanceof ErrorResponse err) return HttpStatus.valueOf(err.getBody().getStatus());
return Optional.ofNullable(getMappedStatus(throwable)).orElse(
Optional.ofNullable(resolveResponseStatus(throwable)).map(ResponseStatus::value).orElse(HttpStatus.INTERNAL_SERVER_ERROR)
);
}
private ResponseStatus extractResponseStatus(final Throwable throwable) {
return Optional.ofNullable(resolveResponseStatus(throwable)).orElse(null);
}
private ResponseStatus resolveResponseStatus(final Throwable type) {
final ResponseStatus candidate = findMergedAnnotation(type.getClass(), ResponseStatus.class);
return candidate == null && type.getCause() != null ? resolveResponseStatus(type.getCause()) : candidate;
}
private URI getMappedType(Throwable err) {
if (err instanceof MethodArgumentNotValidException) return ErrorConstants.CONSTRAINT_VIOLATION_TYPE;
return ErrorConstants.DEFAULT_TYPE;
}
private String getMappedMessageKey(Throwable err) {
if (err instanceof MethodArgumentNotValidException) {
return ErrorConstants.ERR_VALIDATION;
} else if (err instanceof ConcurrencyFailureException || err.getCause() instanceof ConcurrencyFailureException) {
return ErrorConstants.ERR_CONCURRENCY_FAILURE;
}
return null;
}
private String getCustomizedTitle(Throwable err) {
if (err instanceof MethodArgumentNotValidException) return "Method argument not valid";
return null;
}
private String getCustomizedErrorDetails(Throwable err) {
Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) {
if (err instanceof HttpMessageConversionException) return "Unable to convert http message";
if (err instanceof DataAccessException) return "Failure during data access";
if (containsPackageName(err.getMessage())) return "Unexpected runtime exception";
}
return err.getCause() != null ? err.getCause().getMessage() : err.getMessage();
}
private HttpStatus getMappedStatus(Throwable err) {
// Where we disagree with Spring defaults
if (err instanceof AccessDeniedException) return HttpStatus.FORBIDDEN;
if (err instanceof ConcurrencyFailureException) return HttpStatus.CONFLICT;
if (err instanceof BadCredentialsException) return HttpStatus.UNAUTHORIZED;
return null;
}
private URI getPathValue(NativeWebRequest request) {
if (request == null) return URI.create("about:blank");
return URI.create(extractURI(request));
}
private HttpHeaders buildHeaders(Throwable err) {
return err instanceof BadRequestAlertException badRequestAlertException
? HeaderUtil.createFailureAlert(
applicationName,
true,
badRequestAlertException.getEntityName(),
badRequestAlertException.getErrorKey(),
badRequestAlertException.getMessage()
)
: null;
}
public Optional<ProblemDetailWithCause> buildCause(final Throwable throwable, NativeWebRequest request) {
if (throwable != null && isCasualChainEnabled()) {
return Optional.of(customizeProblem(getProblemDetailWithCause(throwable), throwable, request));
}
return Optional.ofNullable(null);
}
private boolean isCasualChainEnabled() {
// Customize as per the needs
return CASUAL_CHAIN_ENABLED;
}
private boolean containsPackageName(String message) {
// This list is for sure not complete
return StringUtils.containsAny(message, "org.", "java.", "net.", "jakarta.", "javax.", "com.", "io.", "de.", "com.dealers.app");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/IntegrationTest.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/IntegrationTest.java | package com.gateway;
import com.gateway.config.AsyncSyncConfiguration;
import com.gateway.config.EmbeddedSQL;
import com.gateway.config.JacksonConfiguration;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.test.context.SpringBootTest;
/**
* Base composite annotation for integration tests.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SpringBootTest(classes = { GatewayApp.class, JacksonConfiguration.class, AsyncSyncConfiguration.class })
@EmbeddedSQL
public @interface IntegrationTest {
// 5s is Spring's default https://github.com/spring-projects/spring-framework/blob/main/spring-test/src/main/java/org/springframework/test/web/reactive/server/DefaultWebTestClient.java#L106
String DEFAULT_TIMEOUT = "PT5S";
String DEFAULT_ENTITY_TIMEOUT = "PT5S";
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/TechnicalStructureTest.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/TechnicalStructureTest.java | package com.gateway;
import static com.tngtech.archunit.base.DescribedPredicate.alwaysTrue;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.belongToAnyOf;
import static com.tngtech.archunit.library.Architectures.layeredArchitecture;
import com.tngtech.archunit.core.importer.ImportOption.DoNotIncludeTests;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
@AnalyzeClasses(packagesOf = GatewayApp.class, importOptions = DoNotIncludeTests.class)
class TechnicalStructureTest {
// prettier-ignore
@ArchTest
static final ArchRule respectsTechnicalArchitectureLayers = layeredArchitecture()
.consideringAllDependencies()
.layer("Config").definedBy("..config..")
.layer("Web").definedBy("..web..")
.optionalLayer("Service").definedBy("..service..")
.layer("Security").definedBy("..security..")
.optionalLayer("Persistence").definedBy("..repository..")
.layer("Domain").definedBy("..domain..")
.whereLayer("Config").mayNotBeAccessedByAnyLayer()
.whereLayer("Web").mayOnlyBeAccessedByLayers("Config")
.whereLayer("Service").mayOnlyBeAccessedByLayers("Web", "Config")
.whereLayer("Security").mayOnlyBeAccessedByLayers("Config", "Service", "Web")
.whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service", "Security", "Web", "Config")
.whereLayer("Domain").mayOnlyBeAccessedByLayers("Persistence", "Service", "Security", "Web", "Config")
.ignoreDependency(belongToAnyOf(GatewayApp.class), alwaysTrue())
.ignoreDependency(alwaysTrue(), belongToAnyOf(
com.gateway.config.Constants.class,
com.gateway.config.ApplicationProperties.class
));
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/management/SecurityMetersServiceTests.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/management/SecurityMetersServiceTests.java | package com.gateway.management;
import static org.assertj.core.api.Assertions.assertThat;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.util.Collection;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class SecurityMetersServiceTests {
private static final String INVALID_TOKENS_METER_EXPECTED_NAME = "security.authentication.invalid-tokens";
private MeterRegistry meterRegistry;
private SecurityMetersService securityMetersService;
@BeforeEach
public void setup() {
meterRegistry = new SimpleMeterRegistry();
securityMetersService = new SecurityMetersService(meterRegistry);
}
@Test
void testInvalidTokensCountersByCauseAreCreated() {
meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).counter();
meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter();
meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "unsupported").counter();
meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter();
meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter();
Collection<Counter> counters = meterRegistry.find(INVALID_TOKENS_METER_EXPECTED_NAME).counters();
assertThat(counters).hasSize(4);
}
@Test
void testCountMethodsShouldBeBoundToCorrectCounters() {
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count()).isZero();
securityMetersService.trackTokenExpired();
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count()).isEqualTo(1);
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "unsupported").counter().count()).isZero();
securityMetersService.trackTokenUnsupported();
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "unsupported").counter().count()).isEqualTo(1);
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count()).isZero();
securityMetersService.trackTokenInvalidSignature();
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count()).isEqualTo(1);
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isZero();
securityMetersService.trackTokenMalformed();
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isEqualTo(1);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/service/MailServiceIT.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/service/MailServiceIT.java | package com.gateway.service;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import com.gateway.IntegrationTest;
import com.gateway.config.Constants;
import com.gateway.domain.User;
import jakarta.mail.Multipart;
import jakarta.mail.Session;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import tech.jhipster.config.JHipsterProperties;
/**
* Integration tests for {@link MailService}.
*/
@IntegrationTest
class MailServiceIT {
private static final String[] languages = {
// jhipster-needle-i18n-language-constant - JHipster will add/remove languages in this array
};
private static final Pattern PATTERN_LOCALE_3 = Pattern.compile("([a-z]{2})-([a-zA-Z]{4})-([a-z]{2})");
private static final Pattern PATTERN_LOCALE_2 = Pattern.compile("([a-z]{2})-([a-z]{2})");
@Autowired
private JHipsterProperties jHipsterProperties;
@MockBean
private JavaMailSender javaMailSender;
@Captor
private ArgumentCaptor<MimeMessage> messageCaptor;
@Autowired
private MailService mailService;
@BeforeEach
public void setup() {
doNothing().when(javaMailSender).send(any(MimeMessage.class));
when(javaMailSender.createMimeMessage()).thenReturn(new MimeMessage((Session) null));
}
@Test
void testSendEmail() throws Exception {
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0]).hasToString("john.doe@example.com");
assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent()).isInstanceOf(String.class);
assertThat(message.getContent()).hasToString("testContent");
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
@Test
void testSendHtmlEmail() throws Exception {
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, true);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0]).hasToString("john.doe@example.com");
assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent()).isInstanceOf(String.class);
assertThat(message.getContent()).hasToString("testContent");
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
void testSendMultipartEmail() throws Exception {
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, false);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
MimeMultipart mp = (MimeMultipart) message.getContent();
MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
part.writeTo(aos);
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0]).hasToString("john.doe@example.com");
assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent()).isInstanceOf(Multipart.class);
assertThat(aos).hasToString("\r\ntestContent");
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
@Test
void testSendMultipartHtmlEmail() throws Exception {
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, true);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
MimeMultipart mp = (MimeMultipart) message.getContent();
MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
part.writeTo(aos);
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0]).hasToString("john.doe@example.com");
assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent()).isInstanceOf(Multipart.class);
assertThat(aos).hasToString("\r\ntestContent");
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
void testSendEmailFromTemplate() throws Exception {
User user = new User();
user.setLangKey(Constants.DEFAULT_LANGUAGE);
user.setLogin("john");
user.setEmail("john.doe@example.com");
mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title");
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getSubject()).isEqualTo("test title");
assertThat(message.getAllRecipients()[0]).hasToString(user.getEmail());
assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("<html>test title, http://127.0.0.1:8080, john</html>\n");
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
void testSendActivationEmail() throws Exception {
User user = new User();
user.setLangKey(Constants.DEFAULT_LANGUAGE);
user.setLogin("john");
user.setEmail("john.doe@example.com");
mailService.sendActivationEmail(user);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getAllRecipients()[0]).hasToString(user.getEmail());
assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent().toString()).isNotEmpty();
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
void testCreationEmail() throws Exception {
User user = new User();
user.setLangKey(Constants.DEFAULT_LANGUAGE);
user.setLogin("john");
user.setEmail("john.doe@example.com");
mailService.sendCreationEmail(user);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getAllRecipients()[0]).hasToString(user.getEmail());
assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent().toString()).isNotEmpty();
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
void testSendPasswordResetMail() throws Exception {
User user = new User();
user.setLangKey(Constants.DEFAULT_LANGUAGE);
user.setLogin("john");
user.setEmail("john.doe@example.com");
mailService.sendPasswordResetMail(user);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getAllRecipients()[0]).hasToString(user.getEmail());
assertThat(message.getFrom()[0]).hasToString(jHipsterProperties.getMail().getFrom());
assertThat(message.getContent().toString()).isNotEmpty();
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
void testSendEmailWithException() {
doThrow(MailSendException.class).when(javaMailSender).send(any(MimeMessage.class));
try {
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false);
} catch (Exception e) {
fail("Exception shouldn't have been thrown");
}
}
@Test
void testSendLocalizedEmailForAllSupportedLanguages() throws Exception {
User user = new User();
user.setLogin("john");
user.setEmail("john.doe@example.com");
for (String langKey : languages) {
user.setLangKey(langKey);
mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title");
verify(javaMailSender, atLeastOnce()).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
String propertyFilePath = "i18n/messages_" + getMessageSourceSuffixForLanguage(langKey) + ".properties";
URL resource = this.getClass().getClassLoader().getResource(propertyFilePath);
File file = new File(new URI(resource.getFile()).getPath());
Properties properties = new Properties();
properties.load(new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")));
String emailTitle = (String) properties.get("email.test.title");
assertThat(message.getSubject()).isEqualTo(emailTitle);
assertThat(message.getContent().toString()).isEqualToNormalizingNewlines(
"<html>" + emailTitle + ", http://127.0.0.1:8080, john</html>\n"
);
}
}
/**
* Convert a lang key to the Java locale.
*/
private String getMessageSourceSuffixForLanguage(String langKey) {
String javaLangKey = langKey;
Matcher matcher2 = PATTERN_LOCALE_2.matcher(langKey);
if (matcher2.matches()) {
javaLangKey = matcher2.group(1) + "_" + matcher2.group(2).toUpperCase();
}
Matcher matcher3 = PATTERN_LOCALE_3.matcher(langKey);
if (matcher3.matches()) {
javaLangKey = matcher3.group(1) + "_" + matcher3.group(2) + "_" + matcher3.group(3).toUpperCase();
}
return javaLangKey;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/service/UserServiceIT.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/service/UserServiceIT.java | package com.gateway.service;
import static org.assertj.core.api.Assertions.assertThat;
import com.gateway.IntegrationTest;
import com.gateway.config.Constants;
import com.gateway.domain.User;
import com.gateway.repository.UserRepository;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import tech.jhipster.security.RandomUtil;
/**
* Integration tests for {@link UserService}.
*/
@IntegrationTest
class UserServiceIT {
private static final String DEFAULT_LOGIN = "johndoe";
private static final String DEFAULT_EMAIL = "johndoe@localhost";
private static final String DEFAULT_FIRSTNAME = "john";
private static final String DEFAULT_LASTNAME = "doe";
private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50";
private static final String DEFAULT_LANGKEY = "dummy";
@Autowired
private UserRepository userRepository;
@Autowired
private UserService userService;
private User user;
@BeforeEach
public void init() {
userRepository.deleteAllUserAuthorities().block();
userRepository.deleteAll().block();
user = new User();
user.setLogin(DEFAULT_LOGIN);
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
user.setEmail(DEFAULT_EMAIL);
user.setFirstName(DEFAULT_FIRSTNAME);
user.setLastName(DEFAULT_LASTNAME);
user.setImageUrl(DEFAULT_IMAGEURL);
user.setLangKey(DEFAULT_LANGKEY);
user.setCreatedBy(Constants.SYSTEM);
}
@Test
void assertThatUserMustExistToResetPassword() {
userRepository.save(user).block();
Optional<User> maybeUser = userService.requestPasswordReset("invalid.login@localhost").blockOptional();
assertThat(maybeUser).isNotPresent();
maybeUser = userService.requestPasswordReset(user.getEmail()).blockOptional();
assertThat(maybeUser).isPresent();
assertThat(maybeUser.orElse(null).getEmail()).isEqualTo(user.getEmail());
assertThat(maybeUser.orElse(null).getResetDate()).isNotNull();
assertThat(maybeUser.orElse(null).getResetKey()).isNotNull();
}
@Test
void assertThatOnlyActivatedUserCanRequestPasswordReset() {
user.setActivated(false);
userRepository.save(user).block();
Optional<User> maybeUser = userService.requestPasswordReset(user.getLogin()).blockOptional();
assertThat(maybeUser).isNotPresent();
userRepository.delete(user).block();
}
@Test
void assertThatResetKeyMustNotBeOlderThan24Hours() {
Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
String resetKey = RandomUtil.generateResetKey();
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey(resetKey);
userRepository.save(user).block();
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()).blockOptional();
assertThat(maybeUser).isNotPresent();
userRepository.delete(user).block();
}
@Test
void assertThatResetKeyMustBeValid() {
Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey("1234");
userRepository.save(user).block();
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()).blockOptional();
assertThat(maybeUser).isNotPresent();
userRepository.delete(user).block();
}
@Test
void assertThatUserCanResetPassword() {
String oldPassword = user.getPassword();
Instant daysAgo = Instant.now().minus(2, ChronoUnit.HOURS);
String resetKey = RandomUtil.generateResetKey();
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey(resetKey);
userRepository.save(user).block();
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey()).blockOptional();
assertThat(maybeUser).isPresent();
assertThat(maybeUser.orElse(null).getResetDate()).isNull();
assertThat(maybeUser.orElse(null).getResetKey()).isNull();
assertThat(maybeUser.orElse(null).getPassword()).isNotEqualTo(oldPassword);
userRepository.delete(user).block();
}
@Test
void assertThatNotActivatedUsersWithNotNullActivationKeyCreatedBefore3DaysAreDeleted() {
Instant now = Instant.now();
user.setActivated(false);
user.setActivationKey(RandomStringUtils.random(20));
User dbUser = userRepository.save(user).block();
dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS));
userRepository.save(user).block();
LocalDateTime threeDaysAgo = LocalDateTime.ofInstant(now.minus(3, ChronoUnit.DAYS), ZoneOffset.UTC);
List<User> users = userRepository
.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo)
.collectList()
.block();
assertThat(users).isNotEmpty();
userService.removeNotActivatedUsers();
users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo).collectList().block();
assertThat(users).isEmpty();
}
@Test
void assertThatNotActivatedUsersWithNullActivationKeyCreatedBefore3DaysAreNotDeleted() {
Instant now = Instant.now();
user.setActivated(false);
User dbUser = userRepository.save(user).block();
dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS));
userRepository.save(user).block();
LocalDateTime threeDaysAgo = LocalDateTime.ofInstant(now.minus(3, ChronoUnit.DAYS), ZoneOffset.UTC);
List<User> users = userRepository
.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(threeDaysAgo)
.collectList()
.block();
assertThat(users).isEmpty();
userService.removeNotActivatedUsers();
Optional<User> maybeDbUser = userRepository.findById(dbUser.getId()).blockOptional();
assertThat(maybeDbUser).contains(dbUser);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/service/mapper/UserMapperTest.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/service/mapper/UserMapperTest.java | package com.gateway.service.mapper;
import static org.assertj.core.api.Assertions.assertThat;
import com.gateway.domain.User;
import com.gateway.service.dto.AdminUserDTO;
import com.gateway.service.dto.UserDTO;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link UserMapper}.
*/
class UserMapperTest {
private static final String DEFAULT_LOGIN = "johndoe";
private static final Long DEFAULT_ID = 1L;
private UserMapper userMapper;
private User user;
private AdminUserDTO userDto;
@BeforeEach
public void init() {
userMapper = new UserMapper();
user = new User();
user.setLogin(DEFAULT_LOGIN);
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
user.setEmail("johndoe@localhost");
user.setFirstName("john");
user.setLastName("doe");
user.setImageUrl("image_url");
user.setLangKey("en");
userDto = new AdminUserDTO(user);
}
@Test
void usersToUserDTOsShouldMapOnlyNonNullUsers() {
List<User> users = new ArrayList<>();
users.add(user);
users.add(null);
List<UserDTO> userDTOS = userMapper.usersToUserDTOs(users);
assertThat(userDTOS).isNotEmpty().size().isEqualTo(1);
}
@Test
void userDTOsToUsersShouldMapOnlyNonNullUsers() {
List<AdminUserDTO> usersDto = new ArrayList<>();
usersDto.add(userDto);
usersDto.add(null);
List<User> users = userMapper.userDTOsToUsers(usersDto);
assertThat(users).isNotEmpty().size().isEqualTo(1);
}
@Test
void userDTOsToUsersWithAuthoritiesStringShouldMapToUsersWithAuthoritiesDomain() {
Set<String> authoritiesAsString = new HashSet<>();
authoritiesAsString.add("ADMIN");
userDto.setAuthorities(authoritiesAsString);
List<AdminUserDTO> usersDto = new ArrayList<>();
usersDto.add(userDto);
List<User> users = userMapper.userDTOsToUsers(usersDto);
assertThat(users).isNotEmpty().size().isEqualTo(1);
assertThat(users.get(0).getAuthorities()).isNotNull();
assertThat(users.get(0).getAuthorities()).isNotEmpty();
assertThat(users.get(0).getAuthorities().iterator().next().getName()).isEqualTo("ADMIN");
}
@Test
void userDTOsToUsersMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() {
userDto.setAuthorities(null);
List<AdminUserDTO> usersDto = new ArrayList<>();
usersDto.add(userDto);
List<User> users = userMapper.userDTOsToUsers(usersDto);
assertThat(users).isNotEmpty().size().isEqualTo(1);
assertThat(users.get(0).getAuthorities()).isNotNull();
assertThat(users.get(0).getAuthorities()).isEmpty();
}
@Test
void userDTOToUserMapWithAuthoritiesStringShouldReturnUserWithAuthorities() {
Set<String> authoritiesAsString = new HashSet<>();
authoritiesAsString.add("ADMIN");
userDto.setAuthorities(authoritiesAsString);
User user = userMapper.userDTOToUser(userDto);
assertThat(user).isNotNull();
assertThat(user.getAuthorities()).isNotNull();
assertThat(user.getAuthorities()).isNotEmpty();
assertThat(user.getAuthorities().iterator().next().getName()).isEqualTo("ADMIN");
}
@Test
void userDTOToUserMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() {
userDto.setAuthorities(null);
User user = userMapper.userDTOToUser(userDto);
assertThat(user).isNotNull();
assertThat(user.getAuthorities()).isNotNull();
assertThat(user.getAuthorities()).isEmpty();
}
@Test
void userDTOToUserMapWithNullUserShouldReturnNull() {
assertThat(userMapper.userDTOToUser(null)).isNull();
}
@Test
void testUserFromId() {
assertThat(userMapper.userFromId(DEFAULT_ID).getId()).isEqualTo(DEFAULT_ID);
assertThat(userMapper.userFromId(null)).isNull();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/domain/AssertUtils.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/domain/AssertUtils.java | package com.gateway.domain;
import java.math.BigDecimal;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Comparator;
public class AssertUtils {
public static Comparator<ZonedDateTime> zonedDataTimeSameInstant = Comparator.nullsFirst(
(e1, a2) -> e1.withZoneSameInstant(ZoneOffset.UTC).compareTo(a2.withZoneSameInstant(ZoneOffset.UTC))
);
public static Comparator<BigDecimal> bigDecimalCompareTo = Comparator.nullsFirst((e1, a2) -> e1.compareTo(a2));
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/domain/AuthorityTest.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/domain/AuthorityTest.java | package com.gateway.domain;
import static com.gateway.domain.AuthorityTestSamples.*;
import static org.assertj.core.api.Assertions.assertThat;
import com.gateway.web.rest.TestUtil;
import org.junit.jupiter.api.Test;
class AuthorityTest {
@Test
void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Authority.class);
Authority authority1 = getAuthoritySample1();
Authority authority2 = new Authority();
assertThat(authority1).isNotEqualTo(authority2);
authority2.setName(authority1.getName());
assertThat(authority1).isEqualTo(authority2);
authority2 = getAuthoritySample2();
assertThat(authority1).isNotEqualTo(authority2);
}
@Test
void hashCodeVerifier() throws Exception {
Authority authority = new Authority();
assertThat(authority.hashCode()).isZero();
Authority authority1 = getAuthoritySample1();
authority.setName(authority1.getName());
assertThat(authority).hasSameHashCodeAs(authority1);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/domain/AuthorityAsserts.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/domain/AuthorityAsserts.java | package com.gateway.domain;
import static org.assertj.core.api.Assertions.assertThat;
public class AuthorityAsserts {
/**
* Asserts that the entity has all properties (fields/relationships) set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertAuthorityAllPropertiesEquals(Authority expected, Authority actual) {
assertAuthorityAutoGeneratedPropertiesEquals(expected, actual);
assertAuthorityAllUpdatablePropertiesEquals(expected, actual);
}
/**
* Asserts that the entity has all updatable properties (fields/relationships) set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertAuthorityAllUpdatablePropertiesEquals(Authority expected, Authority actual) {
assertAuthorityUpdatableFieldsEquals(expected, actual);
assertAuthorityUpdatableRelationshipsEquals(expected, actual);
}
/**
* Asserts that the entity has all the auto generated properties (fields/relationships) set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertAuthorityAutoGeneratedPropertiesEquals(Authority expected, Authority actual) {}
/**
* Asserts that the entity has all the updatable fields set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertAuthorityUpdatableFieldsEquals(Authority expected, Authority actual) {
assertThat(expected)
.as("Verify Authority relevant properties")
.satisfies(e -> assertThat(e.getName()).as("check name").isEqualTo(actual.getName()));
}
/**
* Asserts that the entity has all the updatable relationships set.
*
* @param expected the expected entity
* @param actual the actual entity
*/
public static void assertAuthorityUpdatableRelationshipsEquals(Authority expected, Authority actual) {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/domain/AuthorityTestSamples.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/domain/AuthorityTestSamples.java | package com.gateway.domain;
import java.util.UUID;
public class AuthorityTestSamples {
public static Authority getAuthoritySample1() {
return new Authority().name("name1");
}
public static Authority getAuthoritySample2() {
return new Authority().name("name2");
}
public static Authority getAuthorityRandomSampleGenerator() {
return new Authority().name(UUID.randomUUID().toString());
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/security/DomainUserDetailsServiceIT.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/security/DomainUserDetailsServiceIT.java | package com.gateway.security;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import com.gateway.IntegrationTest;
import com.gateway.config.Constants;
import com.gateway.domain.User;
import com.gateway.repository.UserRepository;
import java.util.Locale;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
/**
* Integrations tests for {@link DomainUserDetailsService}.
*/
@IntegrationTest
class DomainUserDetailsServiceIT {
private static final String USER_ONE_LOGIN = "test-user-one";
private static final String USER_ONE_EMAIL = "test-user-one@localhost";
private static final String USER_TWO_LOGIN = "test-user-two";
private static final String USER_TWO_EMAIL = "test-user-two@localhost";
private static final String USER_THREE_LOGIN = "test-user-three";
private static final String USER_THREE_EMAIL = "test-user-three@localhost";
@Autowired
private UserRepository userRepository;
@Autowired
@Qualifier("userDetailsService")
private ReactiveUserDetailsService domainUserDetailsService;
@BeforeEach
public void init() {
userRepository.deleteAllUserAuthorities().block();
userRepository.deleteAll().block();
User userOne = new User();
userOne.setLogin(USER_ONE_LOGIN);
userOne.setPassword(RandomStringUtils.randomAlphanumeric(60));
userOne.setActivated(true);
userOne.setEmail(USER_ONE_EMAIL);
userOne.setFirstName("userOne");
userOne.setLastName("doe");
userOne.setLangKey("en");
userOne.setCreatedBy(Constants.SYSTEM);
userRepository.save(userOne).block();
User userTwo = new User();
userTwo.setLogin(USER_TWO_LOGIN);
userTwo.setPassword(RandomStringUtils.randomAlphanumeric(60));
userTwo.setActivated(true);
userTwo.setEmail(USER_TWO_EMAIL);
userTwo.setFirstName("userTwo");
userTwo.setLastName("doe");
userTwo.setLangKey("en");
userTwo.setCreatedBy(Constants.SYSTEM);
userRepository.save(userTwo).block();
User userThree = new User();
userThree.setLogin(USER_THREE_LOGIN);
userThree.setPassword(RandomStringUtils.randomAlphanumeric(60));
userThree.setActivated(false);
userThree.setEmail(USER_THREE_EMAIL);
userThree.setFirstName("userThree");
userThree.setLastName("doe");
userThree.setLangKey("en");
userThree.setCreatedBy(Constants.SYSTEM);
userRepository.save(userThree).block();
}
@Test
void assertThatUserCanBeFoundByLogin() {
UserDetails userDetails = domainUserDetailsService.findByUsername(USER_ONE_LOGIN).block();
assertThat(userDetails).isNotNull();
assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN);
}
@Test
void assertThatUserCanBeFoundByLoginIgnoreCase() {
UserDetails userDetails = domainUserDetailsService.findByUsername(USER_ONE_LOGIN.toUpperCase(Locale.ENGLISH)).block();
assertThat(userDetails).isNotNull();
assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN);
}
@Test
void assertThatUserCanBeFoundByEmail() {
UserDetails userDetails = domainUserDetailsService.findByUsername(USER_TWO_EMAIL).block();
assertThat(userDetails).isNotNull();
assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN);
}
@Test
void assertThatUserCanBeFoundByEmailIgnoreCase() {
UserDetails userDetails = domainUserDetailsService.findByUsername(USER_TWO_EMAIL.toUpperCase(Locale.ENGLISH)).block();
assertThat(userDetails).isNotNull();
assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN);
}
@Test
void assertThatEmailIsPrioritizedOverLogin() {
UserDetails userDetails = domainUserDetailsService.findByUsername(USER_ONE_EMAIL).block();
assertThat(userDetails).isNotNull();
assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN);
}
@Test
void assertThatUserNotActivatedExceptionIsThrownForNotActivatedUsers() {
assertThatExceptionOfType(UserNotActivatedException.class).isThrownBy(
() -> domainUserDetailsService.findByUsername(USER_THREE_LOGIN).block()
);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/security/SecurityUtilsUnitTest.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/security/SecurityUtilsUnitTest.java | package com.gateway.security;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Collection;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import reactor.util.context.Context;
/**
* Test class for the {@link SecurityUtils} utility class.
*/
class SecurityUtilsUnitTest {
@Test
void testgetCurrentUserLogin() {
String login = SecurityUtils.getCurrentUserLogin()
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")))
.block();
assertThat(login).isEqualTo("admin");
}
@Test
void testgetCurrentUserJWT() {
String jwt = SecurityUtils.getCurrentUserJWT()
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(new UsernamePasswordAuthenticationToken("admin", "token")))
.block();
assertThat(jwt).isEqualTo("token");
}
@Test
void testIsAuthenticated() {
Boolean isAuthenticated = SecurityUtils.isAuthenticated()
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")))
.block();
assertThat(isAuthenticated).isTrue();
}
@Test
void testAnonymousIsNotAuthenticated() {
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
Boolean isAuthenticated = SecurityUtils.isAuthenticated()
.contextWrite(
ReactiveSecurityContextHolder.withAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin", authorities))
)
.block();
assertThat(isAuthenticated).isFalse();
}
@Test
void testHasCurrentUserAnyOfAuthorities() {
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
Context context = ReactiveSecurityContextHolder.withAuthentication(
new UsernamePasswordAuthenticationToken("admin", "admin", authorities)
);
Boolean hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserAnyOfAuthorities(
AuthoritiesConstants.USER,
AuthoritiesConstants.ADMIN
)
.contextWrite(context)
.block();
assertThat(hasCurrentUserThisAuthority).isTrue();
hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserAnyOfAuthorities(
AuthoritiesConstants.ANONYMOUS,
AuthoritiesConstants.ADMIN
)
.contextWrite(context)
.block();
assertThat(hasCurrentUserThisAuthority).isFalse();
}
@Test
void testHasCurrentUserNoneOfAuthorities() {
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
Context context = ReactiveSecurityContextHolder.withAuthentication(
new UsernamePasswordAuthenticationToken("admin", "admin", authorities)
);
Boolean hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserNoneOfAuthorities(
AuthoritiesConstants.USER,
AuthoritiesConstants.ADMIN
)
.contextWrite(context)
.block();
assertThat(hasCurrentUserThisAuthority).isFalse();
hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserNoneOfAuthorities(
AuthoritiesConstants.ANONYMOUS,
AuthoritiesConstants.ADMIN
)
.contextWrite(context)
.block();
assertThat(hasCurrentUserThisAuthority).isTrue();
}
@Test
void testHasCurrentUserThisAuthority() {
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
Context context = ReactiveSecurityContextHolder.withAuthentication(
new UsernamePasswordAuthenticationToken("admin", "admin", authorities)
);
Boolean hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.USER)
.contextWrite(context)
.block();
assertThat(hasCurrentUserThisAuthority).isTrue();
hasCurrentUserThisAuthority = SecurityUtils.hasCurrentUserThisAuthority(AuthoritiesConstants.ADMIN).contextWrite(context).block();
assertThat(hasCurrentUserThisAuthority).isFalse();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/security/jwt/AuthenticationIntegrationTest.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/security/jwt/AuthenticationIntegrationTest.java | package com.gateway.security.jwt;
import com.gateway.config.SecurityConfiguration;
import com.gateway.config.SecurityJwtConfiguration;
import com.gateway.config.WebConfigurer;
import com.gateway.management.SecurityMetersService;
import com.gateway.web.rest.AuthenticateController;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import tech.jhipster.config.JHipsterProperties;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(
{
JHipsterProperties.class,
WebConfigurer.class,
SecurityConfiguration.class,
SecurityJwtConfiguration.class,
SecurityMetersService.class,
JwtAuthenticationTestUtils.class,
}
)
@WebFluxTest(
controllers = { AuthenticateController.class },
properties = {
"jhipster.security.authentication.jwt.base64-secret=fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8",
"jhipster.security.authentication.jwt.token-validity-in-seconds=60000",
}
)
@ComponentScan({})
public @interface AuthenticationIntegrationTest {
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/security/jwt/TokenAuthenticationSecurityMetersIT.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/security/jwt/TokenAuthenticationSecurityMetersIT.java | package com.gateway.security.jwt;
import static com.gateway.security.jwt.JwtAuthenticationTestUtils.*;
import static org.assertj.core.api.Assertions.assertThat;
import com.gateway.IntegrationTest;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import java.util.Collection;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.test.web.reactive.server.WebTestClient;
@AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT)
@AuthenticationIntegrationTest
class TokenAuthenticationSecurityMetersIT {
private static final String INVALID_TOKENS_METER_EXPECTED_NAME = "security.authentication.invalid-tokens";
@Autowired
private WebTestClient webTestClient;
@Value("${jhipster.security.authentication.jwt.base64-secret}")
private String jwtKey;
@Autowired
private MeterRegistry meterRegistry;
@Test
void testValidTokenShouldNotCountAnything() throws Exception {
Collection<Counter> counters = meterRegistry.find(INVALID_TOKENS_METER_EXPECTED_NAME).counters();
var count = aggregate(counters);
tryToAuthenticate(createValidToken(jwtKey));
assertThat(aggregate(counters)).isEqualTo(count);
}
@Test
void testTokenExpiredCount() throws Exception {
var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count();
tryToAuthenticate(createExpiredToken(jwtKey));
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "expired").counter().count()).isEqualTo(count + 1);
}
@Test
void testTokenSignatureInvalidCount() throws Exception {
var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count();
tryToAuthenticate(createTokenWithDifferentSignature());
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "invalid-signature").counter().count()).isEqualTo(
count + 1
);
}
@Test
void testTokenMalformedCount() throws Exception {
var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count();
tryToAuthenticate(createSignedInvalidJwt(jwtKey));
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isEqualTo(count + 1);
}
@Test
void testTokenInvalidCount() throws Exception {
var count = meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count();
tryToAuthenticate(createInvalidToken(jwtKey));
assertThat(meterRegistry.get(INVALID_TOKENS_METER_EXPECTED_NAME).tag("cause", "malformed").counter().count()).isEqualTo(count + 1);
}
private void tryToAuthenticate(String token) {
webTestClient
.get()
.uri("/api/authenticate")
.headers(headers -> headers.setBearerAuth(token))
.exchange()
.returnResult(String.class)
.getResponseBody()
.blockLast();
}
private double aggregate(Collection<Counter> counters) {
return counters.stream().mapToDouble(Counter::count).sum();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/security/jwt/TokenAuthenticationIT.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/security/jwt/TokenAuthenticationIT.java | package com.gateway.security.jwt;
import static com.gateway.security.jwt.JwtAuthenticationTestUtils.*;
import com.gateway.IntegrationTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.test.web.reactive.server.WebTestClient;
@AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT)
@AuthenticationIntegrationTest
class TokenAuthenticationIT {
@Autowired
private WebTestClient webTestClient;
@Value("${jhipster.security.authentication.jwt.base64-secret}")
private String jwtKey;
@Test
void testLoginWithValidToken() throws Exception {
expectOk(createValidToken(jwtKey));
}
@Test
void testReturnFalseWhenJWThasInvalidSignature() throws Exception {
expectUnauthorized(createTokenWithDifferentSignature());
}
@Test
void testReturnFalseWhenJWTisMalformed() throws Exception {
expectUnauthorized(createSignedInvalidJwt(jwtKey));
}
@Test
void testReturnFalseWhenJWTisExpired() throws Exception {
expectUnauthorized(createExpiredToken(jwtKey));
}
private void expectOk(String token) {
webTestClient.get().uri("/api/authenticate").headers(headers -> headers.setBearerAuth(token)).exchange().expectStatus().isOk();
}
private void expectUnauthorized(String token) {
webTestClient
.get()
.uri("/api/authenticate")
.headers(headers -> headers.setBearerAuth(token))
.exchange()
.expectStatus()
.isUnauthorized();
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/security/jwt/JwtAuthenticationTestUtils.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/security/jwt/JwtAuthenticationTestUtils.java | package com.gateway.security.jwt;
import static com.gateway.security.SecurityUtils.AUTHORITIES_KEY;
import static com.gateway.security.SecurityUtils.JWT_ALGORITHM;
import com.gateway.repository.UserRepository;
import com.nimbusds.jose.jwk.source.ImmutableSecret;
import com.nimbusds.jose.util.Base64;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.time.Instant;
import java.util.Collections;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
public class JwtAuthenticationTestUtils {
@Bean
private MeterRegistry meterRegistry() {
return new SimpleMeterRegistry();
}
@MockBean
private ReactiveUserDetailsService userDetailsService;
@MockBean
private UserRepository userRepository;
public static String createValidToken(String jwtKey) {
return createValidTokenForUser(jwtKey, "anonymous");
}
public static String createValidTokenForUser(String jwtKey, String user) {
JwtEncoder encoder = jwtEncoder(jwtKey);
var now = Instant.now();
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuedAt(now)
.expiresAt(now.plusSeconds(60))
.subject(user)
.claims(customClaim -> customClaim.put(AUTHORITIES_KEY, Collections.singletonList("ROLE_ADMIN")))
.build();
JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build();
return encoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue();
}
public static String createTokenWithDifferentSignature() {
JwtEncoder encoder = jwtEncoder("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8");
var now = Instant.now();
var past = now.plusSeconds(60);
JwtClaimsSet claims = JwtClaimsSet.builder().issuedAt(now).expiresAt(past).subject("anonymous").build();
JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build();
return encoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue();
}
public static String createExpiredToken(String jwtKey) {
JwtEncoder encoder = jwtEncoder(jwtKey);
var now = Instant.now();
var past = now.minusSeconds(600);
JwtClaimsSet claims = JwtClaimsSet.builder().issuedAt(past).expiresAt(past.plusSeconds(1)).subject("anonymous").build();
JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build();
return encoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue();
}
public static String createInvalidToken(String jwtKey) {
return createValidToken(jwtKey).substring(1);
}
public static String createSignedInvalidJwt(String jwtKey) throws Exception {
return calculateHMAC("foo", jwtKey);
}
private static JwtEncoder jwtEncoder(String jwtKey) {
return new NimbusJwtEncoder(new ImmutableSecret<>(getSecretKey(jwtKey)));
}
private static SecretKey getSecretKey(String jwtKey) {
byte[] keyBytes = Base64.from(jwtKey).decode();
return new SecretKeySpec(keyBytes, 0, keyBytes.length, JWT_ALGORITHM.getName());
}
private static String calculateHMAC(String data, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.from(key).decode(), "HmacSHA512");
Mac mac = Mac.getInstance("HmacSHA512");
mac.init(secretKeySpec);
return String.copyValueOf(Hex.encode(mac.doFinal(data.getBytes())));
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.