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/gateway-app/src/test/java/com/gateway/config/PostgreSqlTestContainer.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/config/PostgreSqlTestContainer.java | package com.gateway.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("gatewayApp")
.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/gateway-app/src/test/java/com/gateway/config/SqlTestContainer.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/config/SqlTestContainer.java | package com.gateway.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/gateway-app/src/test/java/com/gateway/config/EmbeddedSQL.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/config/EmbeddedSQL.java | package com.gateway.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/gateway-app/src/test/java/com/gateway/config/SqlTestContainersSpringContextCustomizerFactory.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/config/SqlTestContainersSpringContextCustomizerFactory.java | package com.gateway.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.r2dbc.url=" + prodTestContainer.getTestContainer().getJdbcUrl().replace("jdbc", "r2dbc") + ""
);
testValues = testValues.and("spring.r2dbc.username=" + prodTestContainer.getTestContainer().getUsername());
testValues = testValues.and("spring.r2dbc.password=" + prodTestContainer.getTestContainer().getPassword());
testValues = testValues.and("spring.liquibase.url=" + prodTestContainer.getTestContainer().getJdbcUrl() + "");
}
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/gateway-app/src/test/java/com/gateway/config/JHipsterBlockHoundIntegration.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/config/JHipsterBlockHoundIntegration.java | package com.gateway.config;
import reactor.blockhound.BlockHound;
import reactor.blockhound.integration.BlockHoundIntegration;
public class JHipsterBlockHoundIntegration implements BlockHoundIntegration {
@Override
public void applyTo(BlockHound.Builder builder) {
builder.allowBlockingCallsInside("org.springframework.validation.beanvalidation.SpringValidatorAdapter", "validate");
builder.allowBlockingCallsInside("com.gateway.service.MailService", "sendEmailFromTemplate");
builder.allowBlockingCallsInside("com.gateway.security.DomainUserDetailsService", "createSpringSecurityUser");
builder.allowBlockingCallsInside("org.springframework.web.reactive.result.method.InvocableHandlerMethod", "invoke");
builder.allowBlockingCallsInside("org.springdoc.core.service.OpenAPIService", "build");
builder.allowBlockingCallsInside("org.springdoc.core.service.AbstractRequestService", "build");
// jhipster-needle-blockhound-integration - JHipster will add additional gradle plugins here
}
}
| 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/config/AsyncSyncConfiguration.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/config/AsyncSyncConfiguration.java | package com.gateway.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/gateway-app/src/test/java/com/gateway/config/SpringBootTestClassOrderer.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/config/SpringBootTestClassOrderer.java | package com.gateway.config;
import com.gateway.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/gateway-app/src/test/java/com/gateway/web/filter/ModifyServersOpenApiFilterTest.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/web/filter/ModifyServersOpenApiFilterTest.java | package com.gateway.web.filter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPOutputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
class ModifyServersOpenApiFilterTest {
private static final Logger log = LoggerFactory.getLogger(ModifyServersOpenApiFilterTest.class);
private final GatewayFilterChain filterChain = mock(GatewayFilterChain.class);
private final ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor.forClass(ServerWebExchange.class);
@BeforeEach
void setup() {
when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());
}
@Test
void shouldCallCreateModifyServersOpenApiInterceptorWhenGetOpenApiSpec() {
// dummy api url to filter
String sample_url = "/services/service-test/instance-test/v3/api-docs";
// create request
MockServerHttpRequest request = MockServerHttpRequest.get(sample_url).build();
ServerWebExchange exchange = MockServerWebExchange.from(request);
// apply the filter to the request
ModifyServersOpenApiFilter modifyServersOpenApiFilter = spy(new ModifyServersOpenApiFilter());
modifyServersOpenApiFilter.filter(exchange, filterChain).subscribe();
verify(modifyServersOpenApiFilter, times(1)).createModifyServersOpenApiInterceptor(
sample_url,
exchange.getResponse(),
exchange.getResponse().bufferFactory()
);
}
@Test
void shouldNotCallCreateModifyServersOpenApiInterceptorWhenNotGetOpenApiSpec() {
// dummy api url to filter
String sample_url = "/services/service-test/instance-test/api";
// create request
MockServerHttpRequest request = MockServerHttpRequest.get(sample_url).build();
ServerWebExchange exchange = MockServerWebExchange.from(request);
// apply the filter to the request
ModifyServersOpenApiFilter modifyServersOpenApiFilter = spy(new ModifyServersOpenApiFilter());
modifyServersOpenApiFilter.filter(exchange, filterChain).subscribe();
verify(modifyServersOpenApiFilter, times(0)).createModifyServersOpenApiInterceptor(
sample_url,
exchange.getResponse(),
exchange.getResponse().bufferFactory()
);
}
@Test
void shouldOrderToMinusOne() {
ModifyServersOpenApiFilter modifyServersOpenApiFilter = new ModifyServersOpenApiFilter();
assertEquals(modifyServersOpenApiFilter.getOrder(), -1);
}
@Nested
class ModifyServersOpenApiInterceptorTest {
private final String path = "/services/service-test/instance-test/v3/api-docs";
private final MockServerHttpRequest request = MockServerHttpRequest.get(path).build();
private final ServerWebExchange exchange = MockServerWebExchange.from(request);
private final ModifyServersOpenApiFilter modifyServersOpenApiFilter = new ModifyServersOpenApiFilter();
@Test
void shouldRewriteBodyWhenBodyIsFluxAndResponseIsNotZipped() {
ModifyServersOpenApiFilter.ModifyServersOpenApiInterceptor interceptor =
modifyServersOpenApiFilter.createModifyServersOpenApiInterceptor(
path,
exchange.getResponse(),
exchange.getResponse().bufferFactory()
);
byte[] bytes = "{}".getBytes();
DataBuffer body = exchange.getResponse().bufferFactory().wrap(bytes);
interceptor.writeWith(Flux.just(body)).subscribe();
assertThat(
interceptor
.getRewritedBody()
.contains("\"servers\":[{\"url\":\"/services/service-test/instance-test\",\"description\":\"added by global filter\"}]")
).isTrue();
}
@Test
void shouldRewriteBodyWhenBodyIsFluxAndResponseIsZipped() {
exchange.getResponse().getHeaders().set(HttpHeaders.CONTENT_ENCODING, "gzip");
ModifyServersOpenApiFilter.ModifyServersOpenApiInterceptor interceptor =
modifyServersOpenApiFilter.createModifyServersOpenApiInterceptor(
path,
exchange.getResponse(),
exchange.getResponse().bufferFactory()
);
byte[] bytes = zipContent();
DataBuffer body = exchange.getResponse().bufferFactory().wrap(bytes);
interceptor.writeWith(Flux.just(body)).subscribe();
assertThat(
interceptor
.getRewritedBody()
.contains("\"servers\":[{\"url\":\"/services/service-test/instance-test\",\"description\":\"added by global filter\"}]")
).isTrue();
}
@Test
void shouldNotRewriteBodyWhenBodyIsNotFlux() {
ModifyServersOpenApiFilter.ModifyServersOpenApiInterceptor interceptor =
modifyServersOpenApiFilter.createModifyServersOpenApiInterceptor(
path,
exchange.getResponse(),
exchange.getResponse().bufferFactory()
);
byte[] bytes = "{}".getBytes();
DataBuffer body = exchange.getResponse().bufferFactory().wrap(bytes);
interceptor.writeWith(Mono.just(body)).subscribe();
assertThat(interceptor.getRewritedBody()).isEmpty();
}
private byte[] zipContent() {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream("{}".length());
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
gzipOutputStream.write("{}".getBytes(StandardCharsets.UTF_8));
gzipOutputStream.flush();
gzipOutputStream.close();
return byteArrayOutputStream.toByteArray();
} catch (IOException e) {
log.error("Error in test when zip content during modify servers from api-doc of {}: {}", path, e.getMessage());
}
return "{}".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/gateway-app/src/test/java/com/gateway/web/filter/SpaWebFilterTestController.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/web/filter/SpaWebFilterTestController.java | package com.gateway.web.filter;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SpaWebFilterTestController {
public static final String INDEX_HTML_TEST_CONTENT = "<html>test</html>";
@GetMapping(value = "/index.html", produces = MediaType.TEXT_HTML_VALUE)
public String getIndexHtmlTestContent() {
return INDEX_HTML_TEST_CONTENT;
}
}
| 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/web/filter/SpaWebFilterIT.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/web/filter/SpaWebFilterIT.java | package com.gateway.web.filter;
import com.gateway.IntegrationTest;
import com.gateway.security.AuthoritiesConstants;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.reactive.server.WebTestClient;
@AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT)
@WithMockUser
@IntegrationTest
class SpaWebFilterIT {
@Autowired
private WebTestClient webTestClient;
@Test
void testFilterForwardsToIndex() {
webTestClient
.get()
.uri("/")
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.contentType("text/html;charset=UTF-8")
.expectBody(String.class)
.isEqualTo(SpaWebFilterTestController.INDEX_HTML_TEST_CONTENT);
}
@Test
void testFilterDoesNotForwardToIndexForApi() {
webTestClient.get().uri("/api/authenticate").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("user");
}
@Test
@WithMockUser(authorities = AuthoritiesConstants.ADMIN)
void testFilterDoesNotForwardToIndexForV3ApiDocs() {
webTestClient
.mutate()
.responseTimeout(Duration.ofMillis(10000))
.build()
.get()
.uri("/v3/api-docs")
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.contentType(MediaType.APPLICATION_JSON);
}
@Test
void testFilterDoesNotForwardToIndexForDotFile() {
webTestClient.get().uri("/file.js").exchange().expectStatus().isNotFound();
}
@Test
void getBackendEndpoint() {
webTestClient
.get()
.uri("/test")
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.contentType("text/html;charset=UTF-8")
.expectBody(String.class)
.isEqualTo(SpaWebFilterTestController.INDEX_HTML_TEST_CONTENT);
}
@Test
void forwardUnmappedFirstLevelMapping() {
webTestClient
.get()
.uri("/first-level")
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.contentType("text/html;charset=UTF-8")
.expectBody(String.class)
.isEqualTo(SpaWebFilterTestController.INDEX_HTML_TEST_CONTENT);
}
@Test
void forwardUnmappedSecondLevelMapping() {
webTestClient
.get()
.uri("/first-level/second-level")
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.contentType("text/html;charset=UTF-8")
.expectBody(String.class)
.isEqualTo(SpaWebFilterTestController.INDEX_HTML_TEST_CONTENT);
}
@Test
void forwardUnmappedThirdLevelMapping() {
webTestClient
.get()
.uri("/first-level/second-level/third-level")
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.contentType("text/html;charset=UTF-8")
.expectBody(String.class)
.isEqualTo(SpaWebFilterTestController.INDEX_HTML_TEST_CONTENT);
}
@Test
void forwardUnmappedDeepMapping() {
webTestClient
.get()
.uri("/1/2/3/4/5/6/7/8/9/10")
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.contentType("text/html;charset=UTF-8")
.expectBody(String.class)
.isEqualTo(SpaWebFilterTestController.INDEX_HTML_TEST_CONTENT);
}
@Test
void getUnmappedFirstLevelFile() {
webTestClient.get().uri("/foo.js").exchange().expectStatus().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() {
webTestClient.get().uri("/foo/bar.js").exchange().expectStatus().isForbidden();
}
@Test
void getUnmappedThirdLevelFile() {
webTestClient.get().uri("/foo/another/bar.js").exchange().expectStatus().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/gateway-app/src/test/java/com/gateway/web/rest/TestUtil.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/web/rest/TestUtil.java | package com.gateway.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;
/**
* 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);
}
/**
* 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/gateway-app/src/test/java/com/gateway/web/rest/PublicUserResourceIT.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/web/rest/PublicUserResourceIT.java | package com.gateway.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import com.gateway.IntegrationTest;
import com.gateway.domain.User;
import com.gateway.repository.EntityManager;
import com.gateway.repository.UserRepository;
import com.gateway.security.AuthoritiesConstants;
import com.gateway.service.dto.UserDTO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.reactive.server.WebTestClient;
/**
* Integration tests for the {@link PublicUserResource} REST controller.
*/
@AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT)
@WithMockUser(authorities = AuthoritiesConstants.ADMIN)
@IntegrationTest
class PublicUserResourceIT {
private static final String DEFAULT_LOGIN = "johndoe";
@Autowired
private UserRepository userRepository;
@Autowired
private EntityManager em;
@Autowired
private WebTestClient webTestClient;
private User user;
@BeforeEach
public void initTest() {
user = UserResourceIT.initTestUser(userRepository, em);
}
@Test
void getAllPublicUsers() {
// Initialize the database
userRepository.save(user).block();
// Get all the users
UserDTO foundUser = webTestClient
.get()
.uri("/api/users?sort=id,desc")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.contentType(MediaType.APPLICATION_JSON)
.returnResult(UserDTO.class)
.getResponseBody()
.blockFirst();
assertThat(foundUser.getLogin()).isEqualTo(DEFAULT_LOGIN);
}
@Test
void getAllUsersSortedByParameters() throws Exception {
// Initialize the database
userRepository.save(user).block();
webTestClient
.get()
.uri("/api/users?sort=resetKey,desc")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isBadRequest();
webTestClient
.get()
.uri("/api/users?sort=password,desc")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isBadRequest();
webTestClient
.get()
.uri("/api/users?sort=resetKey,desc&sort=id,desc")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isBadRequest();
webTestClient.get().uri("/api/users?sort=id,desc").accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk();
}
}
| 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/web/rest/UserResourceIT.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/web/rest/UserResourceIT.java | package com.gateway.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gateway.IntegrationTest;
import com.gateway.config.Constants;
import com.gateway.domain.Authority;
import com.gateway.domain.User;
import com.gateway.repository.AuthorityRepository;
import com.gateway.repository.EntityManager;
import com.gateway.repository.UserRepository;
import com.gateway.security.AuthoritiesConstants;
import com.gateway.service.dto.AdminUserDTO;
import com.gateway.service.mapper.UserMapper;
import java.time.Instant;
import java.util.*;
import java.util.function.Consumer;
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.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.reactive.server.WebTestClient;
/**
* Integration tests for the {@link UserResource} REST controller.
*/
@AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT)
@WithMockUser(authorities = AuthoritiesConstants.ADMIN)
@IntegrationTest
class UserResourceIT {
private static final String DEFAULT_LOGIN = "johndoe";
private static final String UPDATED_LOGIN = "jhipster";
private static final Long DEFAULT_ID = 1L;
private static final String DEFAULT_PASSWORD = "passjohndoe";
private static final String UPDATED_PASSWORD = "passjhipster";
private static final String DEFAULT_EMAIL = "johndoe@localhost";
private static final String UPDATED_EMAIL = "jhipster@localhost";
private static final String DEFAULT_FIRSTNAME = "john";
private static final String UPDATED_FIRSTNAME = "jhipsterFirstName";
private static final String DEFAULT_LASTNAME = "doe";
private static final String UPDATED_LASTNAME = "jhipsterLastName";
private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50";
private static final String UPDATED_IMAGEURL = "http://placehold.it/40x40";
private static final String DEFAULT_LANGKEY = "en";
private static final String UPDATED_LANGKEY = "fr";
@Autowired
private ObjectMapper om;
@Autowired
private UserRepository userRepository;
@Autowired
private AuthorityRepository authorityRepository;
@Autowired
private UserMapper userMapper;
@Autowired
private EntityManager em;
@Autowired
private WebTestClient webTestClient;
private User user;
/**
* Create a User.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which has a required relationship to the User entity.
*/
public static User createEntity(EntityManager em) {
User user = new User();
user.setLogin(DEFAULT_LOGIN + RandomStringUtils.randomAlphabetic(5));
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
user.setEmail(RandomStringUtils.randomAlphabetic(5) + DEFAULT_EMAIL);
user.setFirstName(DEFAULT_FIRSTNAME);
user.setLastName(DEFAULT_LASTNAME);
user.setImageUrl(DEFAULT_IMAGEURL);
user.setLangKey(DEFAULT_LANGKEY);
user.setCreatedBy(Constants.SYSTEM);
return user;
}
/**
* Delete all the users from the database.
*/
public static void deleteEntities(EntityManager em) {
try {
em.deleteAll("jhi_user_authority").block();
em.deleteAll(User.class).block();
} catch (Exception e) {
// It can fail, if other entities are still referring this - it will be removed later.
}
}
/**
* Setups the database with one user.
*/
public static User initTestUser(UserRepository userRepository, EntityManager em) {
userRepository.deleteAllUserAuthorities().block();
userRepository.deleteAll().block();
User user = createEntity(em);
user.setLogin(DEFAULT_LOGIN);
user.setEmail(DEFAULT_EMAIL);
return user;
}
@BeforeEach
public void initTest() {
user = initTestUser(userRepository, em);
}
@Test
void createUser() throws Exception {
int databaseSizeBeforeCreate = userRepository.findAll().collectList().block().size();
// Create the User
AdminUserDTO user = new AdminUserDTO();
user.setLogin(DEFAULT_LOGIN);
user.setFirstName(DEFAULT_FIRSTNAME);
user.setLastName(DEFAULT_LASTNAME);
user.setEmail(DEFAULT_EMAIL);
user.setActivated(true);
user.setImageUrl(DEFAULT_IMAGEURL);
user.setLangKey(DEFAULT_LANGKEY);
user.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
webTestClient
.post()
.uri("/api/admin/users")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(user))
.exchange()
.expectStatus()
.isCreated();
// Validate the User in the database
assertPersistedUsers(users -> {
assertThat(users).hasSize(databaseSizeBeforeCreate + 1);
User testUser = users.get(users.size() - 1);
assertThat(testUser.getLogin()).isEqualTo(DEFAULT_LOGIN);
assertThat(testUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
assertThat(testUser.getLastName()).isEqualTo(DEFAULT_LASTNAME);
assertThat(testUser.getEmail()).isEqualTo(DEFAULT_EMAIL);
assertThat(testUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
assertThat(testUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
});
}
@Test
void createUserWithExistingId() throws Exception {
int databaseSizeBeforeCreate = userRepository.findAll().collectList().block().size();
AdminUserDTO user = new AdminUserDTO();
user.setId(DEFAULT_ID);
user.setLogin(DEFAULT_LOGIN);
user.setFirstName(DEFAULT_FIRSTNAME);
user.setLastName(DEFAULT_LASTNAME);
user.setEmail(DEFAULT_EMAIL);
user.setActivated(true);
user.setImageUrl(DEFAULT_IMAGEURL);
user.setLangKey(DEFAULT_LANGKEY);
user.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// An entity with an existing ID cannot be created, so this API call must fail
webTestClient
.post()
.uri("/api/admin/users")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(user))
.exchange()
.expectStatus()
.isBadRequest();
// Validate the User in the database
assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate));
}
@Test
void createUserWithExistingLogin() throws Exception {
// Initialize the database
userRepository.save(user).block();
int databaseSizeBeforeCreate = userRepository.findAll().collectList().block().size();
AdminUserDTO user = new AdminUserDTO();
user.setLogin(DEFAULT_LOGIN); // this login should already be used
user.setFirstName(DEFAULT_FIRSTNAME);
user.setLastName(DEFAULT_LASTNAME);
user.setEmail("anothermail@localhost");
user.setActivated(true);
user.setImageUrl(DEFAULT_IMAGEURL);
user.setLangKey(DEFAULT_LANGKEY);
user.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Create the User
webTestClient
.post()
.uri("/api/admin/users")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(user))
.exchange()
.expectStatus()
.isBadRequest();
// Validate the User in the database
assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate));
}
@Test
void createUserWithExistingEmail() throws Exception {
// Initialize the database
userRepository.save(user).block();
int databaseSizeBeforeCreate = userRepository.findAll().collectList().block().size();
AdminUserDTO user = new AdminUserDTO();
user.setLogin("anotherlogin");
user.setFirstName(DEFAULT_FIRSTNAME);
user.setLastName(DEFAULT_LASTNAME);
user.setEmail(DEFAULT_EMAIL); // this email should already be used
user.setActivated(true);
user.setImageUrl(DEFAULT_IMAGEURL);
user.setLangKey(DEFAULT_LANGKEY);
user.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Create the User
webTestClient
.post()
.uri("/api/admin/users")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(user))
.exchange()
.expectStatus()
.isBadRequest();
// Validate the User in the database
assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate));
}
@Test
void getAllUsers() {
// Initialize the database
userRepository.save(user).block();
authorityRepository
.findById(AuthoritiesConstants.USER)
.flatMap(authority -> userRepository.saveUserAuthority(user.getId(), authority.getName()))
.block();
// Get all the users
AdminUserDTO foundUser = webTestClient
.get()
.uri("/api/admin/users?sort=id,desc")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.contentType(MediaType.APPLICATION_JSON)
.returnResult(AdminUserDTO.class)
.getResponseBody()
.blockFirst();
assertThat(foundUser.getLogin()).isEqualTo(DEFAULT_LOGIN);
assertThat(foundUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
assertThat(foundUser.getLastName()).isEqualTo(DEFAULT_LASTNAME);
assertThat(foundUser.getEmail()).isEqualTo(DEFAULT_EMAIL);
assertThat(foundUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
assertThat(foundUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
assertThat(foundUser.getAuthorities()).containsExactly(AuthoritiesConstants.USER);
}
@Test
void getUser() {
// Initialize the database
userRepository.save(user).block();
authorityRepository
.findById(AuthoritiesConstants.USER)
.flatMap(authority -> userRepository.saveUserAuthority(user.getId(), authority.getName()))
.block();
// Get the user
webTestClient
.get()
.uri("/api/admin/users/{login}", user.getLogin())
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.contentType(MediaType.APPLICATION_JSON)
.expectBody()
.jsonPath("$.login")
.isEqualTo(user.getLogin())
.jsonPath("$.firstName")
.isEqualTo(DEFAULT_FIRSTNAME)
.jsonPath("$.lastName")
.isEqualTo(DEFAULT_LASTNAME)
.jsonPath("$.email")
.isEqualTo(DEFAULT_EMAIL)
.jsonPath("$.imageUrl")
.isEqualTo(DEFAULT_IMAGEURL)
.jsonPath("$.langKey")
.isEqualTo(DEFAULT_LANGKEY)
.jsonPath("$.authorities")
.isEqualTo(AuthoritiesConstants.USER);
}
@Test
void getNonExistingUser() {
webTestClient.get().uri("/api/admin/users/unknown").exchange().expectStatus().isNotFound();
}
@Test
void updateUser() throws Exception {
// Initialize the database
userRepository.save(user).block();
int databaseSizeBeforeUpdate = userRepository.findAll().collectList().block().size();
// Update the user
User updatedUser = userRepository.findById(user.getId()).block();
AdminUserDTO user = new AdminUserDTO();
user.setId(updatedUser.getId());
user.setLogin(updatedUser.getLogin());
user.setFirstName(UPDATED_FIRSTNAME);
user.setLastName(UPDATED_LASTNAME);
user.setEmail(UPDATED_EMAIL);
user.setActivated(updatedUser.isActivated());
user.setImageUrl(UPDATED_IMAGEURL);
user.setLangKey(UPDATED_LANGKEY);
user.setCreatedBy(updatedUser.getCreatedBy());
user.setCreatedDate(updatedUser.getCreatedDate());
user.setLastModifiedBy(updatedUser.getLastModifiedBy());
user.setLastModifiedDate(updatedUser.getLastModifiedDate());
user.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
webTestClient
.put()
.uri("/api/admin/users")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(user))
.exchange()
.expectStatus()
.isOk();
// Validate the User in the database
assertPersistedUsers(users -> {
assertThat(users).hasSize(databaseSizeBeforeUpdate);
User testUser = users.stream().filter(usr -> usr.getId().equals(updatedUser.getId())).findFirst().orElseThrow();
assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME);
assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME);
assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL);
assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL);
assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY);
});
}
@Test
void updateUserLogin() throws Exception {
// Initialize the database
userRepository.save(user).block();
int databaseSizeBeforeUpdate = userRepository.findAll().collectList().block().size();
// Update the user
User updatedUser = userRepository.findById(user.getId()).block();
AdminUserDTO user = new AdminUserDTO();
user.setId(updatedUser.getId());
user.setLogin(UPDATED_LOGIN);
user.setFirstName(UPDATED_FIRSTNAME);
user.setLastName(UPDATED_LASTNAME);
user.setEmail(UPDATED_EMAIL);
user.setActivated(updatedUser.isActivated());
user.setImageUrl(UPDATED_IMAGEURL);
user.setLangKey(UPDATED_LANGKEY);
user.setCreatedBy(updatedUser.getCreatedBy());
user.setCreatedDate(updatedUser.getCreatedDate());
user.setLastModifiedBy(updatedUser.getLastModifiedBy());
user.setLastModifiedDate(updatedUser.getLastModifiedDate());
user.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
webTestClient
.put()
.uri("/api/admin/users")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(user))
.exchange()
.expectStatus()
.isOk();
// Validate the User in the database
assertPersistedUsers(users -> {
assertThat(users).hasSize(databaseSizeBeforeUpdate);
User testUser = users.stream().filter(usr -> usr.getId().equals(updatedUser.getId())).findFirst().orElseThrow();
assertThat(testUser.getLogin()).isEqualTo(UPDATED_LOGIN);
assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME);
assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME);
assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL);
assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL);
assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY);
});
}
@Test
void updateUserExistingEmail() throws Exception {
// Initialize the database with 2 users
userRepository.save(user).block();
User anotherUser = new User();
anotherUser.setLogin("jhipster");
anotherUser.setPassword(RandomStringUtils.randomAlphanumeric(60));
anotherUser.setActivated(true);
anotherUser.setEmail("jhipster@localhost");
anotherUser.setFirstName("java");
anotherUser.setLastName("hipster");
anotherUser.setImageUrl("");
anotherUser.setLangKey("en");
anotherUser.setCreatedBy(Constants.SYSTEM);
userRepository.save(anotherUser).block();
// Update the user
User updatedUser = userRepository.findById(user.getId()).block();
AdminUserDTO user = new AdminUserDTO();
user.setId(updatedUser.getId());
user.setLogin(updatedUser.getLogin());
user.setFirstName(updatedUser.getFirstName());
user.setLastName(updatedUser.getLastName());
user.setEmail("jhipster@localhost"); // this email should already be used by anotherUser
user.setActivated(updatedUser.isActivated());
user.setImageUrl(updatedUser.getImageUrl());
user.setLangKey(updatedUser.getLangKey());
user.setCreatedBy(updatedUser.getCreatedBy());
user.setCreatedDate(updatedUser.getCreatedDate());
user.setLastModifiedBy(updatedUser.getLastModifiedBy());
user.setLastModifiedDate(updatedUser.getLastModifiedDate());
user.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
webTestClient
.put()
.uri("/api/admin/users")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(user))
.exchange()
.expectStatus()
.isBadRequest();
}
@Test
void updateUserExistingLogin() throws Exception {
// Initialize the database
userRepository.save(user).block();
User anotherUser = new User();
anotherUser.setLogin("jhipster");
anotherUser.setPassword(RandomStringUtils.randomAlphanumeric(60));
anotherUser.setActivated(true);
anotherUser.setEmail("jhipster@localhost");
anotherUser.setFirstName("java");
anotherUser.setLastName("hipster");
anotherUser.setImageUrl("");
anotherUser.setLangKey("en");
anotherUser.setCreatedBy(Constants.SYSTEM);
userRepository.save(anotherUser).block();
// Update the user
User updatedUser = userRepository.findById(user.getId()).block();
AdminUserDTO user = new AdminUserDTO();
user.setId(updatedUser.getId());
user.setLogin("jhipster"); // this login should already be used by anotherUser
user.setFirstName(updatedUser.getFirstName());
user.setLastName(updatedUser.getLastName());
user.setEmail(updatedUser.getEmail());
user.setActivated(updatedUser.isActivated());
user.setImageUrl(updatedUser.getImageUrl());
user.setLangKey(updatedUser.getLangKey());
user.setCreatedBy(updatedUser.getCreatedBy());
user.setCreatedDate(updatedUser.getCreatedDate());
user.setLastModifiedBy(updatedUser.getLastModifiedBy());
user.setLastModifiedDate(updatedUser.getLastModifiedDate());
user.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
webTestClient
.put()
.uri("/api/admin/users")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(user))
.exchange()
.expectStatus()
.isBadRequest();
}
@Test
void deleteUser() {
// Initialize the database
userRepository.save(user).block();
int databaseSizeBeforeDelete = userRepository.findAll().collectList().block().size();
// Delete the user
webTestClient
.delete()
.uri("/api/admin/users/{login}", user.getLogin())
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isNoContent();
// Validate the database is empty
assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeDelete - 1));
}
@Test
void testUserEquals() throws Exception {
TestUtil.equalsVerifier(User.class);
User user1 = new User();
user1.setId(DEFAULT_ID);
User user2 = new User();
user2.setId(user1.getId());
assertThat(user1).isEqualTo(user2);
user2.setId(2L);
assertThat(user1).isNotEqualTo(user2);
user1.setId(null);
assertThat(user1).isNotEqualTo(user2);
}
@Test
void testUserDTOtoUser() {
AdminUserDTO userDTO = new AdminUserDTO();
userDTO.setId(DEFAULT_ID);
userDTO.setLogin(DEFAULT_LOGIN);
userDTO.setFirstName(DEFAULT_FIRSTNAME);
userDTO.setLastName(DEFAULT_LASTNAME);
userDTO.setEmail(DEFAULT_EMAIL);
userDTO.setActivated(true);
userDTO.setImageUrl(DEFAULT_IMAGEURL);
userDTO.setLangKey(DEFAULT_LANGKEY);
userDTO.setCreatedBy(DEFAULT_LOGIN);
userDTO.setLastModifiedBy(DEFAULT_LOGIN);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
User user = userMapper.userDTOToUser(userDTO);
assertThat(user.getId()).isEqualTo(DEFAULT_ID);
assertThat(user.getLogin()).isEqualTo(DEFAULT_LOGIN);
assertThat(user.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
assertThat(user.getLastName()).isEqualTo(DEFAULT_LASTNAME);
assertThat(user.getEmail()).isEqualTo(DEFAULT_EMAIL);
assertThat(user.isActivated()).isTrue();
assertThat(user.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
assertThat(user.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
assertThat(user.getCreatedBy()).isNull();
assertThat(user.getCreatedDate()).isNotNull();
assertThat(user.getLastModifiedBy()).isNull();
assertThat(user.getLastModifiedDate()).isNotNull();
assertThat(user.getAuthorities()).extracting("name").containsExactly(AuthoritiesConstants.USER);
}
@Test
void testUserToUserDTO() {
user.setId(DEFAULT_ID);
user.setCreatedBy(DEFAULT_LOGIN);
user.setCreatedDate(Instant.now());
user.setLastModifiedBy(DEFAULT_LOGIN);
user.setLastModifiedDate(Instant.now());
Set<Authority> authorities = new HashSet<>();
Authority authority = new Authority();
authority.setName(AuthoritiesConstants.USER);
authorities.add(authority);
user.setAuthorities(authorities);
AdminUserDTO userDTO = userMapper.userToAdminUserDTO(user);
assertThat(userDTO.getId()).isEqualTo(DEFAULT_ID);
assertThat(userDTO.getLogin()).isEqualTo(DEFAULT_LOGIN);
assertThat(userDTO.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
assertThat(userDTO.getLastName()).isEqualTo(DEFAULT_LASTNAME);
assertThat(userDTO.getEmail()).isEqualTo(DEFAULT_EMAIL);
assertThat(userDTO.isActivated()).isTrue();
assertThat(userDTO.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
assertThat(userDTO.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
assertThat(userDTO.getCreatedBy()).isEqualTo(DEFAULT_LOGIN);
assertThat(userDTO.getCreatedDate()).isEqualTo(user.getCreatedDate());
assertThat(userDTO.getLastModifiedBy()).isEqualTo(DEFAULT_LOGIN);
assertThat(userDTO.getLastModifiedDate()).isEqualTo(user.getLastModifiedDate());
assertThat(userDTO.getAuthorities()).containsExactly(AuthoritiesConstants.USER);
assertThat(userDTO.toString()).isNotNull();
}
private void assertPersistedUsers(Consumer<List<User>> userAssertion) {
userAssertion.accept(userRepository.findAll().collectList().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/web/rest/AuthorityResourceIT.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/web/rest/AuthorityResourceIT.java | package com.gateway.web.rest;
import static com.gateway.domain.AuthorityAsserts.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gateway.IntegrationTest;
import com.gateway.domain.Authority;
import com.gateway.repository.AuthorityRepository;
import com.gateway.repository.EntityManager;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.reactive.server.WebTestClient;
/**
* Integration tests for the {@link AuthorityResource} REST controller.
*/
@IntegrationTest
@AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_ENTITY_TIMEOUT)
@WithMockUser(authorities = { "ROLE_ADMIN" })
class AuthorityResourceIT {
private static final String ENTITY_API_URL = "/api/authorities";
private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{name}";
@Autowired
private ObjectMapper om;
@Autowired
private AuthorityRepository authorityRepository;
@Autowired
private EntityManager em;
@Autowired
private WebTestClient webTestClient;
private Authority authority;
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Authority createEntity(EntityManager em) {
Authority authority = new Authority().name(UUID.randomUUID().toString());
return authority;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Authority createUpdatedEntity(EntityManager em) {
Authority authority = new Authority().name(UUID.randomUUID().toString());
return authority;
}
public static void deleteEntities(EntityManager em) {
try {
em.deleteAll(Authority.class).block();
} catch (Exception e) {
// It can fail, if other entities are still referring this - it will be removed later.
}
}
@AfterEach
public void cleanup() {
deleteEntities(em);
}
@BeforeEach
public void initTest() {
deleteEntities(em);
authority = createEntity(em);
}
@Test
void createAuthority() throws Exception {
long databaseSizeBeforeCreate = getRepositoryCount();
// Create the Authority
var returnedAuthority = webTestClient
.post()
.uri(ENTITY_API_URL)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(authority))
.exchange()
.expectStatus()
.isCreated()
.expectBody(Authority.class)
.returnResult()
.getResponseBody();
// Validate the Authority in the database
assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
assertAuthorityUpdatableFieldsEquals(returnedAuthority, getPersistedAuthority(returnedAuthority));
}
@Test
void createAuthorityWithExistingId() throws Exception {
// Create the Authority with an existing ID
authorityRepository.save(authority).block();
long databaseSizeBeforeCreate = getRepositoryCount();
// An entity with an existing ID cannot be created, so this API call must fail
webTestClient
.post()
.uri(ENTITY_API_URL)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(authority))
.exchange()
.expectStatus()
.isBadRequest();
// Validate the Authority in the database
assertSameRepositoryCount(databaseSizeBeforeCreate);
}
@Test
void getAllAuthoritiesAsStream() {
// Initialize the database
authority.setName(UUID.randomUUID().toString());
authorityRepository.save(authority).block();
List<Authority> authorityList = webTestClient
.get()
.uri(ENTITY_API_URL)
.accept(MediaType.APPLICATION_NDJSON)
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.contentTypeCompatibleWith(MediaType.APPLICATION_NDJSON)
.returnResult(Authority.class)
.getResponseBody()
.filter(authority::equals)
.collectList()
.block(Duration.ofSeconds(5));
assertThat(authorityList).isNotNull();
assertThat(authorityList).hasSize(1);
Authority testAuthority = authorityList.get(0);
// Test fails because reactive api returns an empty object instead of null
// assertAuthorityAllPropertiesEquals(authority, testAuthority);
assertAuthorityUpdatableFieldsEquals(authority, testAuthority);
}
@Test
void getAllAuthorities() {
// Initialize the database
authority.setName(UUID.randomUUID().toString());
authorityRepository.save(authority).block();
// Get all the authorityList
webTestClient
.get()
.uri(ENTITY_API_URL + "?sort=name,desc")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.contentType(MediaType.APPLICATION_JSON)
.expectBody()
.jsonPath("$.[*].name")
.value(hasItem(authority.getName()));
}
@Test
void getAuthority() {
// Initialize the database
authority.setName(UUID.randomUUID().toString());
authorityRepository.save(authority).block();
// Get the authority
webTestClient
.get()
.uri(ENTITY_API_URL_ID, authority.getName())
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.contentType(MediaType.APPLICATION_JSON)
.expectBody()
.jsonPath("$.name")
.value(is(authority.getName()));
}
@Test
void getNonExistingAuthority() {
// Get the authority
webTestClient
.get()
.uri(ENTITY_API_URL_ID, Long.MAX_VALUE)
.accept(MediaType.APPLICATION_PROBLEM_JSON)
.exchange()
.expectStatus()
.isNotFound();
}
@Test
void deleteAuthority() {
// Initialize the database
authority.setName(UUID.randomUUID().toString());
authorityRepository.save(authority).block();
long databaseSizeBeforeDelete = getRepositoryCount();
// Delete the authority
webTestClient
.delete()
.uri(ENTITY_API_URL_ID, authority.getName())
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isNoContent();
// Validate the database contains one less item
assertDecrementedRepositoryCount(databaseSizeBeforeDelete);
}
protected long getRepositoryCount() {
return authorityRepository.count().block();
}
protected void assertIncrementedRepositoryCount(long countBefore) {
assertThat(countBefore + 1).isEqualTo(getRepositoryCount());
}
protected void assertDecrementedRepositoryCount(long countBefore) {
assertThat(countBefore - 1).isEqualTo(getRepositoryCount());
}
protected void assertSameRepositoryCount(long countBefore) {
assertThat(countBefore).isEqualTo(getRepositoryCount());
}
protected Authority getPersistedAuthority(Authority authority) {
return authorityRepository.findById(authority.getName()).block();
}
protected void assertPersistedAuthorityToMatchAllProperties(Authority expectedAuthority) {
// Test fails because reactive api returns an empty object instead of null
// assertAuthorityAllPropertiesEquals(expectedAuthority, getPersistedAuthority(expectedAuthority));
assertAuthorityUpdatableFieldsEquals(expectedAuthority, getPersistedAuthority(expectedAuthority));
}
protected void assertPersistedAuthorityToMatchUpdatableProperties(Authority expectedAuthority) {
// Test fails because reactive api returns an empty object instead of null
// assertAuthorityAllUpdatablePropertiesEquals(expectedAuthority, getPersistedAuthority(expectedAuthority));
assertAuthorityUpdatableFieldsEquals(expectedAuthority, getPersistedAuthority(expectedAuthority));
}
}
| 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/web/rest/AuthenticateControllerIT.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/web/rest/AuthenticateControllerIT.java | package com.gateway.web.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gateway.IntegrationTest;
import com.gateway.config.Constants;
import com.gateway.domain.User;
import com.gateway.repository.UserRepository;
import com.gateway.web.rest.vm.LoginVM;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.web.reactive.server.WebTestClient;
/**
* Integration tests for the {@link AuthenticateController} REST controller.
*/
@AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT)
@IntegrationTest
class AuthenticateControllerIT {
@Autowired
private ObjectMapper om;
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private WebTestClient webTestClient;
@Test
void testAuthorize() throws Exception {
User user = new User();
user.setLogin("user-jwt-controller");
user.setEmail("user-jwt-controller@example.com");
user.setActivated(true);
user.setPassword(passwordEncoder.encode("test"));
user.setCreatedBy(Constants.SYSTEM);
userRepository.save(user).block();
LoginVM login = new LoginVM();
login.setUsername("user-jwt-controller");
login.setPassword("test");
webTestClient
.post()
.uri("/api/authenticate")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(login))
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.valueMatches("Authorization", "Bearer .+")
.expectBody()
.jsonPath("$.id_token")
.isNotEmpty();
}
@Test
void testAuthorizeWithRememberMe() throws Exception {
User user = new User();
user.setLogin("user-jwt-controller-remember-me");
user.setEmail("user-jwt-controller-remember-me@example.com");
user.setActivated(true);
user.setPassword(passwordEncoder.encode("test"));
user.setCreatedBy(Constants.SYSTEM);
userRepository.save(user).block();
LoginVM login = new LoginVM();
login.setUsername("user-jwt-controller-remember-me");
login.setPassword("test");
login.setRememberMe(true);
webTestClient
.post()
.uri("/api/authenticate")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(login))
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.valueMatches("Authorization", "Bearer .+")
.expectBody()
.jsonPath("$.id_token")
.isNotEmpty();
}
@Test
void testAuthorizeFails() throws Exception {
LoginVM login = new LoginVM();
login.setUsername("wrong-user");
login.setPassword("wrong password");
webTestClient
.post()
.uri("/api/authenticate")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(login))
.exchange()
.expectStatus()
.isUnauthorized()
.expectHeader()
.doesNotExist("Authorization")
.expectBody()
.jsonPath("$.id_token")
.doesNotExist();
}
}
| 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/web/rest/AccountResourceIT.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/web/rest/AccountResourceIT.java | package com.gateway.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gateway.IntegrationTest;
import com.gateway.config.Constants;
import com.gateway.domain.User;
import com.gateway.repository.AuthorityRepository;
import com.gateway.repository.UserRepository;
import com.gateway.security.AuthoritiesConstants;
import com.gateway.service.UserService;
import com.gateway.service.dto.AdminUserDTO;
import com.gateway.service.dto.PasswordChangeDTO;
import com.gateway.web.rest.vm.KeyAndPasswordVM;
import com.gateway.web.rest.vm.ManagedUserVM;
import java.time.Instant;
import java.util.*;
import java.util.stream.Stream;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.reactive.server.WebTestClient;
/**
* Integration tests for the {@link AccountResource} REST controller.
*/
@AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT)
@IntegrationTest
class AccountResourceIT {
static final String TEST_USER_LOGIN = "test";
@Autowired
private ObjectMapper om;
@Autowired
private UserRepository userRepository;
@Autowired
private AuthorityRepository authorityRepository;
@Autowired
private UserService userService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private WebTestClient accountWebTestClient;
@Test
@WithUnauthenticatedMockUser
void testNonAuthenticatedUser() {
accountWebTestClient
.get()
.uri("/api/authenticate")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectBody()
.isEmpty();
}
@Test
@WithMockUser(TEST_USER_LOGIN)
void testAuthenticatedUser() {
accountWebTestClient
.get()
.uri("/api/authenticate")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo(TEST_USER_LOGIN);
}
@Test
@WithMockUser(TEST_USER_LOGIN)
void testGetExistingAccount() {
Set<String> authorities = new HashSet<>();
authorities.add(AuthoritiesConstants.ADMIN);
AdminUserDTO user = new AdminUserDTO();
user.setLogin(TEST_USER_LOGIN);
user.setFirstName("john");
user.setLastName("doe");
user.setEmail("john.doe@jhipster.com");
user.setImageUrl("http://placehold.it/50x50");
user.setLangKey("en");
user.setAuthorities(authorities);
userService.createUser(user).block();
accountWebTestClient
.get()
.uri("/api/account")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectHeader()
.contentType(MediaType.APPLICATION_JSON_VALUE)
.expectBody()
.jsonPath("$.login")
.isEqualTo(TEST_USER_LOGIN)
.jsonPath("$.firstName")
.isEqualTo("john")
.jsonPath("$.lastName")
.isEqualTo("doe")
.jsonPath("$.email")
.isEqualTo("john.doe@jhipster.com")
.jsonPath("$.imageUrl")
.isEqualTo("http://placehold.it/50x50")
.jsonPath("$.langKey")
.isEqualTo("en")
.jsonPath("$.authorities")
.isEqualTo(AuthoritiesConstants.ADMIN);
}
@Test
void testGetUnknownAccount() {
accountWebTestClient
.get()
.uri("/api/account")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
void testRegisterValid() throws Exception {
ManagedUserVM validUser = new ManagedUserVM();
validUser.setLogin("test-register-valid");
validUser.setPassword("password");
validUser.setFirstName("Alice");
validUser.setLastName("Test");
validUser.setEmail("test-register-valid@example.com");
validUser.setImageUrl("http://placehold.it/50x50");
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
assertThat(userRepository.findOneByLogin("test-register-valid").blockOptional()).isEmpty();
accountWebTestClient
.post()
.uri("/api/register")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(validUser))
.exchange()
.expectStatus()
.isCreated();
assertThat(userRepository.findOneByLogin("test-register-valid").blockOptional()).isPresent();
}
@Test
void testRegisterInvalidLogin() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("funky-log(n"); // <-- invalid
invalidUser.setPassword("password");
invalidUser.setFirstName("Funky");
invalidUser.setLastName("One");
invalidUser.setEmail("funky@example.com");
invalidUser.setActivated(true);
invalidUser.setImageUrl("http://placehold.it/50x50");
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
accountWebTestClient
.post()
.uri("/api/register")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(invalidUser))
.exchange()
.expectStatus()
.isBadRequest();
Optional<User> user = userRepository.findOneByEmailIgnoreCase("funky@example.com").blockOptional();
assertThat(user).isEmpty();
}
static Stream<ManagedUserVM> invalidUsers() {
return Stream.of(
createInvalidUser("bob", "password", "Bob", "Green", "invalid", true), // <-- invalid
createInvalidUser("bob", "123", "Bob", "Green", "bob@example.com", true), // password with only 3 digits
createInvalidUser("bob", null, "Bob", "Green", "bob@example.com", true) // invalid null password
);
}
@ParameterizedTest
@MethodSource("invalidUsers")
void testRegisterInvalidUsers(ManagedUserVM invalidUser) throws Exception {
accountWebTestClient
.post()
.uri("/api/register")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(invalidUser))
.exchange()
.expectStatus()
.isBadRequest();
Optional<User> user = userRepository.findOneByLogin("bob").blockOptional();
assertThat(user).isEmpty();
}
private static ManagedUserVM createInvalidUser(
String login,
String password,
String firstName,
String lastName,
String email,
boolean activated
) {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin(login);
invalidUser.setPassword(password);
invalidUser.setFirstName(firstName);
invalidUser.setLastName(lastName);
invalidUser.setEmail(email);
invalidUser.setActivated(activated);
invalidUser.setImageUrl("http://placehold.it/50x50");
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
return invalidUser;
}
@Test
void testRegisterDuplicateLogin() throws Exception {
// First registration
ManagedUserVM firstUser = new ManagedUserVM();
firstUser.setLogin("alice");
firstUser.setPassword("password");
firstUser.setFirstName("Alice");
firstUser.setLastName("Something");
firstUser.setEmail("alice@example.com");
firstUser.setImageUrl("http://placehold.it/50x50");
firstUser.setLangKey(Constants.DEFAULT_LANGUAGE);
firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Duplicate login, different email
ManagedUserVM secondUser = new ManagedUserVM();
secondUser.setLogin(firstUser.getLogin());
secondUser.setPassword(firstUser.getPassword());
secondUser.setFirstName(firstUser.getFirstName());
secondUser.setLastName(firstUser.getLastName());
secondUser.setEmail("alice2@example.com");
secondUser.setImageUrl(firstUser.getImageUrl());
secondUser.setLangKey(firstUser.getLangKey());
secondUser.setCreatedBy(firstUser.getCreatedBy());
secondUser.setCreatedDate(firstUser.getCreatedDate());
secondUser.setLastModifiedBy(firstUser.getLastModifiedBy());
secondUser.setLastModifiedDate(firstUser.getLastModifiedDate());
secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
// First user
accountWebTestClient
.post()
.uri("/api/register")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(firstUser))
.exchange()
.expectStatus()
.isCreated();
// Second (non activated) user
accountWebTestClient
.post()
.uri("/api/register")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(secondUser))
.exchange()
.expectStatus()
.isCreated();
Optional<User> testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com").blockOptional();
assertThat(testUser).isPresent();
testUser.orElseThrow().setActivated(true);
userRepository.save(testUser.orElseThrow()).block();
// Second (already activated) user
accountWebTestClient
.post()
.uri("/api/register")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(secondUser))
.exchange()
.expectStatus()
.isBadRequest();
}
@Test
void testRegisterDuplicateEmail() throws Exception {
// First user
ManagedUserVM firstUser = new ManagedUserVM();
firstUser.setLogin("test-register-duplicate-email");
firstUser.setPassword("password");
firstUser.setFirstName("Alice");
firstUser.setLastName("Test");
firstUser.setEmail("test-register-duplicate-email@example.com");
firstUser.setImageUrl("http://placehold.it/50x50");
firstUser.setLangKey(Constants.DEFAULT_LANGUAGE);
firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Register first user
accountWebTestClient
.post()
.uri("/api/register")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(firstUser))
.exchange()
.expectStatus()
.isCreated();
Optional<User> testUser1 = userRepository.findOneByLogin("test-register-duplicate-email").blockOptional();
assertThat(testUser1).isPresent();
// Duplicate email, different login
ManagedUserVM secondUser = new ManagedUserVM();
secondUser.setLogin("test-register-duplicate-email-2");
secondUser.setPassword(firstUser.getPassword());
secondUser.setFirstName(firstUser.getFirstName());
secondUser.setLastName(firstUser.getLastName());
secondUser.setEmail(firstUser.getEmail());
secondUser.setImageUrl(firstUser.getImageUrl());
secondUser.setLangKey(firstUser.getLangKey());
secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
// Register second (non activated) user
accountWebTestClient
.post()
.uri("/api/register")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(secondUser))
.exchange()
.expectStatus()
.isCreated();
Optional<User> testUser2 = userRepository.findOneByLogin("test-register-duplicate-email").blockOptional();
assertThat(testUser2).isEmpty();
Optional<User> testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2").blockOptional();
assertThat(testUser3).isPresent();
// Duplicate email - with uppercase email address
ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM();
userWithUpperCaseEmail.setId(firstUser.getId());
userWithUpperCaseEmail.setLogin("test-register-duplicate-email-3");
userWithUpperCaseEmail.setPassword(firstUser.getPassword());
userWithUpperCaseEmail.setFirstName(firstUser.getFirstName());
userWithUpperCaseEmail.setLastName(firstUser.getLastName());
userWithUpperCaseEmail.setEmail("TEST-register-duplicate-email@example.com");
userWithUpperCaseEmail.setImageUrl(firstUser.getImageUrl());
userWithUpperCaseEmail.setLangKey(firstUser.getLangKey());
userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
// Register third (not activated) user
accountWebTestClient
.post()
.uri("/api/register")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(userWithUpperCaseEmail))
.exchange()
.expectStatus()
.isCreated();
Optional<User> testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3").blockOptional();
assertThat(testUser4).isPresent();
assertThat(testUser4.orElseThrow().getEmail()).isEqualTo("test-register-duplicate-email@example.com");
testUser4.orElseThrow().setActivated(true);
userService.updateUser((new AdminUserDTO(testUser4.orElseThrow()))).block();
// Register 4th (already activated) user
accountWebTestClient
.post()
.uri("/api/register")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(secondUser))
.exchange()
.expectStatus()
.is4xxClientError();
}
@Test
void testRegisterAdminIsIgnored() throws Exception {
ManagedUserVM validUser = new ManagedUserVM();
validUser.setLogin("badguy");
validUser.setPassword("password");
validUser.setFirstName("Bad");
validUser.setLastName("Guy");
validUser.setEmail("badguy@example.com");
validUser.setActivated(true);
validUser.setImageUrl("http://placehold.it/50x50");
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
accountWebTestClient
.post()
.uri("/api/register")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(validUser))
.exchange()
.expectStatus()
.isCreated();
Optional<User> userDup = userRepository.findOneWithAuthoritiesByLogin("badguy").blockOptional();
assertThat(userDup).isPresent();
assertThat(userDup.orElseThrow().getAuthorities())
.hasSize(1)
.containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).block());
}
@Test
void testActivateAccount() {
final String activationKey = "some activation key";
User user = new User();
user.setLogin("activate-account");
user.setEmail("activate-account@example.com");
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(false);
user.setActivationKey(activationKey);
user.setCreatedBy(Constants.SYSTEM);
userRepository.save(user).block();
accountWebTestClient.get().uri("/api/activate?key={activationKey}", activationKey).exchange().expectStatus().isOk();
user = userRepository.findOneByLogin(user.getLogin()).block();
assertThat(user.isActivated()).isTrue();
}
@Test
void testActivateAccountWithWrongKey() {
accountWebTestClient
.get()
.uri("/api/activate?key=wrongActivationKey")
.exchange()
.expectStatus()
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
}
@Test
@WithMockUser("save-account")
void testSaveAccount() throws Exception {
User user = new User();
user.setLogin("save-account");
user.setEmail("save-account@example.com");
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
user.setCreatedBy(Constants.SYSTEM);
userRepository.save(user).block();
AdminUserDTO userDTO = new AdminUserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("save-account@example.com");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
accountWebTestClient
.post()
.uri("/api/account")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(userDTO))
.exchange()
.expectStatus()
.isOk();
User updatedUser = userRepository.findOneWithAuthoritiesByLogin(user.getLogin()).block();
assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName());
assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName());
assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail());
assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey());
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl());
assertThat(updatedUser.isActivated()).isTrue();
assertThat(updatedUser.getAuthorities()).isEmpty();
}
@Test
@WithMockUser("save-invalid-email")
void testSaveInvalidEmail() throws Exception {
User user = new User();
user.setLogin("save-invalid-email");
user.setEmail("save-invalid-email@example.com");
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
user.setCreatedBy(Constants.SYSTEM);
userRepository.save(user).block();
AdminUserDTO userDTO = new AdminUserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("invalid email");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
accountWebTestClient
.post()
.uri("/api/account")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(userDTO))
.exchange()
.expectStatus()
.isBadRequest();
assertThat(userRepository.findOneByEmailIgnoreCase("invalid email").blockOptional()).isNotPresent();
}
@Test
@WithMockUser("save-existing-email")
void testSaveExistingEmail() throws Exception {
User user = new User();
user.setLogin("save-existing-email");
user.setEmail("save-existing-email@example.com");
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
user.setCreatedBy(Constants.SYSTEM);
userRepository.save(user).block();
User anotherUser = new User();
anotherUser.setLogin("save-existing-email2");
anotherUser.setEmail("save-existing-email2@example.com");
anotherUser.setPassword(RandomStringUtils.randomAlphanumeric(60));
anotherUser.setActivated(true);
anotherUser.setCreatedBy(Constants.SYSTEM);
userRepository.save(anotherUser).block();
AdminUserDTO userDTO = new AdminUserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("save-existing-email2@example.com");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
accountWebTestClient
.post()
.uri("/api/account")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(userDTO))
.exchange()
.expectStatus()
.isBadRequest();
User updatedUser = userRepository.findOneByLogin("save-existing-email").block();
assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com");
}
@Test
@WithMockUser("save-existing-email-and-login")
void testSaveExistingEmailAndLogin() throws Exception {
User user = new User();
user.setLogin("save-existing-email-and-login");
user.setEmail("save-existing-email-and-login@example.com");
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
user.setCreatedBy(Constants.SYSTEM);
userRepository.save(user).block();
AdminUserDTO userDTO = new AdminUserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("save-existing-email-and-login@example.com");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
accountWebTestClient
.post()
.uri("/api/account")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(userDTO))
.exchange()
.expectStatus()
.isOk();
User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").block();
assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email-and-login@example.com");
}
@Test
@WithMockUser("change-password-wrong-existing-password")
void testChangePasswordWrongExistingPassword() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.randomAlphanumeric(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-wrong-existing-password");
user.setEmail("change-password-wrong-existing-password@example.com");
user.setCreatedBy(Constants.SYSTEM);
userRepository.save(user).block();
accountWebTestClient
.post()
.uri("/api/account/change-password")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(new PasswordChangeDTO("1" + currentPassword, "new password")))
.exchange()
.expectStatus()
.isBadRequest();
User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").block();
assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse();
assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue();
}
@Test
@WithMockUser("change-password")
void testChangePassword() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.randomAlphanumeric(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password");
user.setEmail("change-password@example.com");
user.setCreatedBy(Constants.SYSTEM);
userRepository.save(user).block();
accountWebTestClient
.post()
.uri("/api/account/change-password")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(new PasswordChangeDTO(currentPassword, "new password")))
.exchange()
.expectStatus()
.isOk();
User updatedUser = userRepository.findOneByLogin("change-password").block();
assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue();
}
@Test
@WithMockUser("change-password-too-small")
void testChangePasswordTooSmall() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.randomAlphanumeric(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-too-small");
user.setEmail("change-password-too-small@example.com");
user.setCreatedBy(Constants.SYSTEM);
userRepository.save(user).block();
String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1);
accountWebTestClient
.post()
.uri("/api/account/change-password")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(new PasswordChangeDTO(currentPassword, newPassword)))
.exchange()
.expectStatus()
.isBadRequest();
User updatedUser = userRepository.findOneByLogin("change-password-too-small").block();
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
@WithMockUser("change-password-too-long")
void testChangePasswordTooLong() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.randomAlphanumeric(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-too-long");
user.setEmail("change-password-too-long@example.com");
user.setCreatedBy(Constants.SYSTEM);
userRepository.save(user).block();
String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1);
accountWebTestClient
.post()
.uri("/api/account/change-password")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(new PasswordChangeDTO(currentPassword, newPassword)))
.exchange()
.expectStatus()
.isBadRequest();
User updatedUser = userRepository.findOneByLogin("change-password-too-long").block();
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
@WithMockUser("change-password-empty")
void testChangePasswordEmpty() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.randomAlphanumeric(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-empty");
user.setEmail("change-password-empty@example.com");
user.setCreatedBy(Constants.SYSTEM);
userRepository.save(user).block();
accountWebTestClient
.post()
.uri("/api/account/change-password")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(new PasswordChangeDTO(currentPassword, "")))
.exchange()
.expectStatus()
.isBadRequest();
User updatedUser = userRepository.findOneByLogin("change-password-empty").block();
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
void testRequestPasswordReset() {
User user = new User();
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
user.setLogin("password-reset");
user.setEmail("password-reset@example.com");
user.setLangKey("en");
user.setCreatedBy(Constants.SYSTEM);
userRepository.save(user).block();
accountWebTestClient
.post()
.uri("/api/account/reset-password/init")
.bodyValue("password-reset@example.com")
.exchange()
.expectStatus()
.isOk();
}
@Test
void testRequestPasswordResetUpperCaseEmail() {
User user = new User();
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setActivated(true);
user.setLogin("password-reset-upper-case");
user.setEmail("password-reset-upper-case@example.com");
user.setLangKey("en");
user.setCreatedBy(Constants.SYSTEM);
userRepository.save(user).block();
accountWebTestClient
.post()
.uri("/api/account/reset-password/init")
.bodyValue("password-reset-upper-case@EXAMPLE.COM")
.exchange()
.expectStatus()
.isOk();
}
@Test
void testRequestPasswordResetWrongEmail() {
accountWebTestClient
.post()
.uri("/api/account/reset-password/init")
.bodyValue("password-reset-wrong-email@example.com")
.exchange()
.expectStatus()
.isOk();
}
@Test
void testFinishPasswordReset() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setLogin("finish-password-reset");
user.setEmail("finish-password-reset@example.com");
user.setResetDate(Instant.now().plusSeconds(60));
user.setResetKey("reset key");
user.setCreatedBy(Constants.SYSTEM);
userRepository.save(user).block();
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey(user.getResetKey());
keyAndPassword.setNewPassword("new password");
accountWebTestClient
.post()
.uri("/api/account/reset-password/finish")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(keyAndPassword))
.exchange()
.expectStatus()
.isOk();
User updatedUser = userRepository.findOneByLogin(user.getLogin()).block();
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue();
}
@Test
void testFinishPasswordResetTooSmall() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.randomAlphanumeric(60));
user.setLogin("finish-password-reset-too-small");
user.setEmail("finish-password-reset-too-small@example.com");
user.setResetDate(Instant.now().plusSeconds(60));
user.setResetKey("reset key too small");
user.setCreatedBy(Constants.SYSTEM);
userRepository.save(user).block();
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey(user.getResetKey());
keyAndPassword.setNewPassword("foo");
accountWebTestClient
.post()
.uri("/api/account/reset-password/finish")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(om.writeValueAsBytes(keyAndPassword))
.exchange()
.expectStatus()
.isBadRequest();
User updatedUser = userRepository.findOneByLogin(user.getLogin()).block();
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse();
}
@Test
void testFinishPasswordResetWrongKey() throws Exception {
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey("wrong reset key");
keyAndPassword.setNewPassword("new password");
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | true |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/web/rest/WithUnauthenticatedMockUser.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/web/rest/WithUnauthenticatedMockUser.java | package com.gateway.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/gateway-app/src/test/java/com/gateway/web/rest/errors/ExceptionTranslatorTestController.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/web/rest/errors/ExceptionTranslatorTestController.java | package com.gateway.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(message = "must not be null")
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/gateway-app/src/test/java/com/gateway/web/rest/errors/ExceptionTranslatorIT.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/test/java/com/gateway/web/rest/errors/ExceptionTranslatorIT.java | package com.gateway.web.rest.errors;
import com.gateway.IntegrationTest;
import org.hamcrest.core.AnyOf;
import org.hamcrest.core.IsEqual;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.reactive.server.WebTestClient;
/**
* Integration tests {@link ExceptionTranslator} controller advice.
*/
@WithMockUser
@AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT)
@IntegrationTest
class ExceptionTranslatorIT {
@Autowired
private WebTestClient webTestClient;
@Test
void testConcurrencyFailure() {
webTestClient
.get()
.uri("/api/exception-translator-test/concurrency-failure")
.exchange()
.expectStatus()
.isEqualTo(HttpStatus.CONFLICT)
.expectHeader()
.contentType(MediaType.APPLICATION_PROBLEM_JSON)
.expectBody()
.jsonPath("$.message")
.isEqualTo(ErrorConstants.ERR_CONCURRENCY_FAILURE);
}
@Test
void testMethodArgumentNotValid() {
webTestClient
.post()
.uri("/api/exception-translator-test/method-argument")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue("{}")
.exchange()
.expectHeader()
.contentType(MediaType.APPLICATION_PROBLEM_JSON)
.expectBody()
.jsonPath("$.message")
.isEqualTo(ErrorConstants.ERR_VALIDATION)
.jsonPath("$.fieldErrors.[0].objectName")
.isEqualTo("test")
.jsonPath("$.fieldErrors.[0].field")
.isEqualTo("test")
.jsonPath("$.fieldErrors.[0].message")
.isEqualTo("must not be null");
}
@Test
void testMissingRequestPart() {
webTestClient
.get()
.uri("/api/exception-translator-test/missing-servlet-request-part")
.exchange()
.expectStatus()
.isBadRequest()
.expectHeader()
.contentType(MediaType.APPLICATION_PROBLEM_JSON)
.expectBody()
.jsonPath("$.message")
.isEqualTo("error.http.400");
}
@Test
void testMissingRequestParameter() {
webTestClient
.get()
.uri("/api/exception-translator-test/missing-servlet-request-parameter")
.exchange()
.expectStatus()
.isBadRequest()
.expectHeader()
.contentType(MediaType.APPLICATION_PROBLEM_JSON)
.expectBody()
.jsonPath("$.message")
.isEqualTo("error.http.400");
}
@Test
void testAccessDenied() {
webTestClient
.get()
.uri("/api/exception-translator-test/access-denied")
.exchange()
.expectStatus()
.isForbidden()
.expectHeader()
.contentType(MediaType.APPLICATION_PROBLEM_JSON)
.expectBody()
.jsonPath("$.message")
.isEqualTo("error.http.403")
.jsonPath("$.detail")
.isEqualTo("test access denied!");
}
@Test
void testUnauthorized() {
webTestClient
.get()
.uri("/api/exception-translator-test/unauthorized")
.exchange()
.expectStatus()
.isUnauthorized()
.expectHeader()
.contentType(MediaType.APPLICATION_PROBLEM_JSON)
.expectBody()
.jsonPath("$.message")
.isEqualTo("error.http.401")
.jsonPath("$.path")
.isEqualTo("/api/exception-translator-test/unauthorized")
.jsonPath("$.detail")
.value(AnyOf.anyOf(IsEqual.equalTo("test authentication failed!"), IsEqual.equalTo("Invalid credentials")));
}
@Test
void testMethodNotSupported() {
webTestClient
.post()
.uri("/api/exception-translator-test/access-denied")
.exchange()
.expectStatus()
.isEqualTo(HttpStatus.METHOD_NOT_ALLOWED)
.expectHeader()
.contentType(MediaType.APPLICATION_PROBLEM_JSON)
.expectBody()
.jsonPath("$.message")
.isEqualTo("error.http.405")
.jsonPath("$.detail")
.isEqualTo("405 METHOD_NOT_ALLOWED \"Request method 'POST' is not supported.\"");
}
@Test
void testExceptionWithResponseStatus() {
webTestClient
.get()
.uri("/api/exception-translator-test/response-status")
.exchange()
.expectStatus()
.isBadRequest()
.expectHeader()
.contentType(MediaType.APPLICATION_PROBLEM_JSON)
.expectBody()
.jsonPath("$.message")
.isEqualTo("error.http.400")
.jsonPath("$.title")
.isEqualTo("test response status");
}
@Test
void testInternalServerError() {
webTestClient
.get()
.uri("/api/exception-translator-test/internal-server-error")
.exchange()
.expectHeader()
.contentType(MediaType.APPLICATION_PROBLEM_JSON)
.expectBody()
.jsonPath("$.message")
.isEqualTo("error.http.500")
.jsonPath("$.title")
.isEqualTo("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/gateway-app/src/main/java/com/gateway/GatewayApp.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/GatewayApp.java | package com.gateway;
import com.gateway.config.ApplicationProperties;
import com.gateway.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 GatewayApp {
private static final Logger log = LoggerFactory.getLogger(GatewayApp.class);
private final Environment env;
public GatewayApp(Environment env) {
this.env = env;
}
/**
* Initializes gatewayApp.
* <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(GatewayApp.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/gateway-app/src/main/java/com/gateway/package-info.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/package-info.java | /**
* Application root.
*/
package com.gateway;
| 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/main/java/com/gateway/GeneratedByJHipster.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/GeneratedByJHipster.java | package com.gateway;
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/gateway-app/src/main/java/com/gateway/management/package-info.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/management/package-info.java | /**
* Application management.
*/
package com.gateway.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/gateway-app/src/main/java/com/gateway/management/SecurityMetersService.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/management/SecurityMetersService.java | package com.gateway.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/gateway-app/src/main/java/com/gateway/service/InvalidPasswordException.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/service/InvalidPasswordException.java | package com.gateway.service;
public class InvalidPasswordException extends RuntimeException {
private static final long serialVersionUID = 1L;
public InvalidPasswordException() {
super("Incorrect password");
}
}
| 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/main/java/com/gateway/service/UserService.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/service/UserService.java | package com.gateway.service;
import com.gateway.config.Constants;
import com.gateway.domain.Authority;
import com.gateway.domain.User;
import com.gateway.repository.AuthorityRepository;
import com.gateway.repository.UserRepository;
import com.gateway.security.AuthoritiesConstants;
import com.gateway.security.SecurityUtils;
import com.gateway.service.dto.AdminUserDTO;
import com.gateway.service.dto.UserDTO;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import tech.jhipster.security.RandomUtil;
/**
* Service class for managing users.
*/
@Service
public class UserService {
private final Logger log = LoggerFactory.getLogger(UserService.class);
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final AuthorityRepository authorityRepository;
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, AuthorityRepository authorityRepository) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.authorityRepository = authorityRepository;
}
@Transactional
public Mono<User> activateRegistration(String key) {
log.debug("Activating user for activation key {}", key);
return userRepository
.findOneByActivationKey(key)
.flatMap(user -> {
// activate given user for the registration key.
user.setActivated(true);
user.setActivationKey(null);
return saveUser(user);
})
.doOnNext(user -> log.debug("Activated user: {}", user));
}
@Transactional
public Mono<User> completePasswordReset(String newPassword, String key) {
log.debug("Reset user password for reset key {}", key);
return userRepository
.findOneByResetKey(key)
.filter(user -> user.getResetDate().isAfter(Instant.now().minus(1, ChronoUnit.DAYS)))
.publishOn(Schedulers.boundedElastic())
.map(user -> {
user.setPassword(passwordEncoder.encode(newPassword));
user.setResetKey(null);
user.setResetDate(null);
return user;
})
.flatMap(this::saveUser);
}
@Transactional
public Mono<User> requestPasswordReset(String mail) {
return userRepository
.findOneByEmailIgnoreCase(mail)
.filter(User::isActivated)
.publishOn(Schedulers.boundedElastic())
.map(user -> {
user.setResetKey(RandomUtil.generateResetKey());
user.setResetDate(Instant.now());
return user;
})
.flatMap(this::saveUser);
}
@Transactional
public Mono<User> registerUser(AdminUserDTO userDTO, String password) {
return userRepository
.findOneByLogin(userDTO.getLogin().toLowerCase())
.flatMap(existingUser -> {
if (!existingUser.isActivated()) {
return userRepository.delete(existingUser);
} else {
return Mono.error(new UsernameAlreadyUsedException());
}
})
.then(userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()))
.flatMap(existingUser -> {
if (!existingUser.isActivated()) {
return userRepository.delete(existingUser);
} else {
return Mono.error(new EmailAlreadyUsedException());
}
})
.publishOn(Schedulers.boundedElastic())
.then(
Mono.fromCallable(() -> {
User newUser = new User();
String encryptedPassword = passwordEncoder.encode(password);
newUser.setLogin(userDTO.getLogin().toLowerCase());
// new user gets initially a generated password
newUser.setPassword(encryptedPassword);
newUser.setFirstName(userDTO.getFirstName());
newUser.setLastName(userDTO.getLastName());
if (userDTO.getEmail() != null) {
newUser.setEmail(userDTO.getEmail().toLowerCase());
}
newUser.setImageUrl(userDTO.getImageUrl());
newUser.setLangKey(userDTO.getLangKey());
// new user is not active
newUser.setActivated(false);
// new user gets registration key
newUser.setActivationKey(RandomUtil.generateActivationKey());
return newUser;
})
)
.flatMap(newUser -> {
Set<Authority> authorities = new HashSet<>();
return authorityRepository
.findById(AuthoritiesConstants.USER)
.map(authorities::add)
.thenReturn(newUser)
.doOnNext(user -> user.setAuthorities(authorities))
.flatMap(this::saveUser)
.doOnNext(user -> log.debug("Created Information for User: {}", user));
});
}
@Transactional
public Mono<User> createUser(AdminUserDTO userDTO) {
User user = new User();
user.setLogin(userDTO.getLogin().toLowerCase());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
if (userDTO.getEmail() != null) {
user.setEmail(userDTO.getEmail().toLowerCase());
}
user.setImageUrl(userDTO.getImageUrl());
if (userDTO.getLangKey() == null) {
user.setLangKey(Constants.DEFAULT_LANGUAGE); // default language
} else {
user.setLangKey(userDTO.getLangKey());
}
return Flux.fromIterable(userDTO.getAuthorities() != null ? userDTO.getAuthorities() : new HashSet<>())
.flatMap(authorityRepository::findById)
.doOnNext(authority -> user.getAuthorities().add(authority))
.then(Mono.just(user))
.publishOn(Schedulers.boundedElastic())
.map(newUser -> {
String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword());
newUser.setPassword(encryptedPassword);
newUser.setResetKey(RandomUtil.generateResetKey());
newUser.setResetDate(Instant.now());
newUser.setActivated(true);
return newUser;
})
.flatMap(this::saveUser)
.doOnNext(user1 -> log.debug("Created Information for User: {}", user1));
}
/**
* Update all information for a specific user, and return the modified user.
*
* @param userDTO user to update.
* @return updated user.
*/
@Transactional
public Mono<AdminUserDTO> updateUser(AdminUserDTO userDTO) {
return userRepository
.findById(userDTO.getId())
.flatMap(user -> {
user.setLogin(userDTO.getLogin().toLowerCase());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
if (userDTO.getEmail() != null) {
user.setEmail(userDTO.getEmail().toLowerCase());
}
user.setImageUrl(userDTO.getImageUrl());
user.setActivated(userDTO.isActivated());
user.setLangKey(userDTO.getLangKey());
Set<Authority> managedAuthorities = user.getAuthorities();
managedAuthorities.clear();
return userRepository
.deleteUserAuthorities(user.getId())
.thenMany(Flux.fromIterable(userDTO.getAuthorities()))
.flatMap(authorityRepository::findById)
.map(managedAuthorities::add)
.then(Mono.just(user));
})
.flatMap(this::saveUser)
.doOnNext(user -> log.debug("Changed Information for User: {}", user))
.map(AdminUserDTO::new);
}
@Transactional
public Mono<Void> deleteUser(String login) {
return userRepository
.findOneByLogin(login)
.flatMap(user -> userRepository.delete(user).thenReturn(user))
.doOnNext(user -> log.debug("Deleted User: {}", user))
.then();
}
/**
* Update basic information (first name, last name, email, language) for the current user.
*
* @param firstName first name of user.
* @param lastName last name of user.
* @param email email id of user.
* @param langKey language key.
* @param imageUrl image URL of user.
* @return a completed {@link Mono}.
*/
@Transactional
public Mono<Void> updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) {
return SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.flatMap(user -> {
user.setFirstName(firstName);
user.setLastName(lastName);
if (email != null) {
user.setEmail(email.toLowerCase());
}
user.setLangKey(langKey);
user.setImageUrl(imageUrl);
return saveUser(user);
})
.doOnNext(user -> log.debug("Changed Information for User: {}", user))
.then();
}
@Transactional
public Mono<User> saveUser(User user) {
return SecurityUtils.getCurrentUserLogin()
.switchIfEmpty(Mono.just(Constants.SYSTEM))
.flatMap(login -> {
if (user.getCreatedBy() == null) {
user.setCreatedBy(login);
}
user.setLastModifiedBy(login);
// Saving the relationship can be done in an entity callback
// once https://github.com/spring-projects/spring-data-r2dbc/issues/215 is done
return userRepository
.save(user)
.flatMap(
savedUser ->
Flux.fromIterable(user.getAuthorities())
.flatMap(authority -> userRepository.saveUserAuthority(savedUser.getId(), authority.getName()))
.then(Mono.just(savedUser))
);
});
}
@Transactional
public Mono<Void> changePassword(String currentClearTextPassword, String newPassword) {
return SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.publishOn(Schedulers.boundedElastic())
.map(user -> {
String currentEncryptedPassword = user.getPassword();
if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) {
throw new InvalidPasswordException();
}
String encryptedPassword = passwordEncoder.encode(newPassword);
user.setPassword(encryptedPassword);
return user;
})
.flatMap(this::saveUser)
.doOnNext(user -> log.debug("Changed password for User: {}", user))
.then();
}
@Transactional(readOnly = true)
public Flux<AdminUserDTO> getAllManagedUsers(Pageable pageable) {
return userRepository.findAllWithAuthorities(pageable).map(AdminUserDTO::new);
}
@Transactional(readOnly = true)
public Flux<UserDTO> getAllPublicUsers(Pageable pageable) {
return userRepository.findAllByIdNotNullAndActivatedIsTrue(pageable).map(UserDTO::new);
}
@Transactional(readOnly = true)
public Mono<Long> countManagedUsers() {
return userRepository.count();
}
@Transactional(readOnly = true)
public Mono<User> getUserWithAuthoritiesByLogin(String login) {
return userRepository.findOneWithAuthoritiesByLogin(login);
}
@Transactional(readOnly = true)
public Mono<User> getUserWithAuthorities() {
return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin);
}
/**
* Not activated users should be automatically deleted after 3 days.
* <p>
* This is scheduled to get fired everyday, at 01:00 (am).
*/
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
removeNotActivatedUsersReactively().blockLast();
}
@Transactional
public Flux<User> removeNotActivatedUsersReactively() {
return userRepository
.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(
LocalDateTime.ofInstant(Instant.now().minus(3, ChronoUnit.DAYS), ZoneOffset.UTC)
)
.flatMap(user -> userRepository.delete(user).thenReturn(user))
.doOnNext(user -> log.debug("Deleted User: {}", user));
}
/**
* Gets a list of all the authorities.
* @return a list of all the authorities.
*/
@Transactional(readOnly = true)
public Flux<String> getAuthorities() {
return authorityRepository.findAll().map(Authority::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/gateway-app/src/main/java/com/gateway/service/UsernameAlreadyUsedException.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/service/UsernameAlreadyUsedException.java | package com.gateway.service;
public class UsernameAlreadyUsedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public UsernameAlreadyUsedException() {
super("Login name already used!");
}
}
| 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/main/java/com/gateway/service/package-info.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/service/package-info.java | /**
* Service layer.
*/
package com.gateway.service;
| 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/main/java/com/gateway/service/MailService.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/service/MailService.java | package com.gateway.service;
import com.gateway.domain.User;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring6.SpringTemplateEngine;
import reactor.core.publisher.Mono;
import tech.jhipster.config.JHipsterProperties;
/**
* Service for sending emails asynchronously.
*/
@Service
public class MailService {
private final Logger log = LoggerFactory.getLogger(MailService.class);
private static final String USER = "user";
private static final String BASE_URL = "baseUrl";
private final JHipsterProperties jHipsterProperties;
private final JavaMailSender javaMailSender;
private final MessageSource messageSource;
private final SpringTemplateEngine templateEngine;
public MailService(
JHipsterProperties jHipsterProperties,
JavaMailSender javaMailSender,
MessageSource messageSource,
SpringTemplateEngine templateEngine
) {
this.jHipsterProperties = jHipsterProperties;
this.javaMailSender = javaMailSender;
this.messageSource = messageSource;
this.templateEngine = templateEngine;
}
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
Mono.defer(() -> {
this.sendEmailSync(to, subject, content, isMultipart, isHtml);
return Mono.empty();
}).subscribe();
}
private void sendEmailSync(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
log.debug(
"Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
isMultipart,
isHtml,
to,
subject,
content
);
// Prepare message using a Spring helper
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name());
message.setTo(to);
message.setFrom(jHipsterProperties.getMail().getFrom());
message.setSubject(subject);
message.setText(content, isHtml);
javaMailSender.send(mimeMessage);
log.debug("Sent email to User '{}'", to);
} catch (MailException | MessagingException e) {
log.warn("Email could not be sent to user '{}'", to, e);
}
}
public void sendEmailFromTemplate(User user, String templateName, String titleKey) {
Mono.defer(() -> {
this.sendEmailFromTemplateSync(user, templateName, titleKey);
return Mono.empty();
}).subscribe();
}
private void sendEmailFromTemplateSync(User user, String templateName, String titleKey) {
if (user.getEmail() == null) {
log.debug("Email doesn't exist for user '{}'", user.getLogin());
return;
}
Locale locale = Locale.forLanguageTag(user.getLangKey());
Context context = new Context(locale);
context.setVariable(USER, user);
context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
String content = templateEngine.process(templateName, context);
String subject = messageSource.getMessage(titleKey, null, locale);
this.sendEmailSync(user.getEmail(), subject, content, false, true);
}
public void sendActivationEmail(User user) {
log.debug("Sending activation email to '{}'", user.getEmail());
this.sendEmailFromTemplate(user, "mail/activationEmail", "email.activation.title");
}
public void sendCreationEmail(User user) {
log.debug("Sending creation email to '{}'", user.getEmail());
this.sendEmailFromTemplate(user, "mail/creationEmail", "email.activation.title");
}
public void sendPasswordResetMail(User user) {
log.debug("Sending password reset email to '{}'", user.getEmail());
this.sendEmailFromTemplate(user, "mail/passwordResetEmail", "email.reset.title");
}
}
| 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/main/java/com/gateway/service/EmailAlreadyUsedException.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/service/EmailAlreadyUsedException.java | package com.gateway.service;
public class EmailAlreadyUsedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public EmailAlreadyUsedException() {
super("Email is already in use!");
}
}
| 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/main/java/com/gateway/service/dto/package-info.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/service/dto/package-info.java | /**
* Data transfer objects for rest mapping.
*/
package com.gateway.service.dto;
| 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/main/java/com/gateway/service/dto/PasswordChangeDTO.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/service/dto/PasswordChangeDTO.java | package com.gateway.service.dto;
import java.io.Serializable;
/**
* A DTO representing a password change required data - current and new password.
*/
public class PasswordChangeDTO implements Serializable {
private static final long serialVersionUID = 1L;
private String currentPassword;
private String newPassword;
public PasswordChangeDTO() {
// Empty constructor needed for Jackson.
}
public PasswordChangeDTO(String currentPassword, String newPassword) {
this.currentPassword = currentPassword;
this.newPassword = newPassword;
}
public String getCurrentPassword() {
return currentPassword;
}
public void setCurrentPassword(String currentPassword) {
this.currentPassword = currentPassword;
}
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/service/dto/UserDTO.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/service/dto/UserDTO.java | package com.gateway.service.dto;
import com.gateway.domain.User;
import java.io.Serializable;
/**
* A DTO representing a user, with only the public attributes.
*/
public class UserDTO implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String login;
public UserDTO() {
// Empty constructor needed for Jackson.
}
public UserDTO(User user) {
this.id = user.getId();
// Customize it here if you need, or not, firstName/lastName/etc
this.login = user.getLogin();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
// prettier-ignore
@Override
public String toString() {
return "UserDTO{" +
"id='" + id + '\'' +
", login='" + login + '\'' +
"}";
}
}
| 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/main/java/com/gateway/service/dto/AdminUserDTO.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/service/dto/AdminUserDTO.java | package com.gateway.service.dto;
import com.gateway.config.Constants;
import com.gateway.domain.Authority;
import com.gateway.domain.User;
import jakarta.validation.constraints.*;
import java.io.Serializable;
import java.time.Instant;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A DTO representing a user, with his authorities.
*/
public class AdminUserDTO implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
@NotBlank
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
private String login;
@Size(max = 50)
private String firstName;
@Size(max = 50)
private String lastName;
@Email
@Size(min = 5, max = 254)
private String email;
@Size(max = 256)
private String imageUrl;
private boolean activated = false;
@Size(min = 2, max = 10)
private String langKey;
private String createdBy;
private Instant createdDate;
private String lastModifiedBy;
private Instant lastModifiedDate;
private Set<String> authorities;
public AdminUserDTO() {
// Empty constructor needed for Jackson.
}
public AdminUserDTO(User user) {
this.id = user.getId();
this.login = user.getLogin();
this.firstName = user.getFirstName();
this.lastName = user.getLastName();
this.email = user.getEmail();
this.activated = user.isActivated();
this.imageUrl = user.getImageUrl();
this.langKey = user.getLangKey();
this.createdBy = user.getCreatedBy();
this.createdDate = user.getCreatedDate();
this.lastModifiedBy = user.getLastModifiedBy();
this.lastModifiedDate = user.getLastModifiedDate();
this.authorities = user.getAuthorities().stream().map(Authority::getName).collect(Collectors.toSet());
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
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;
}
public Set<String> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<String> authorities) {
this.authorities = authorities;
}
// prettier-ignore
@Override
public String toString() {
return "AdminUserDTO{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated=" + activated +
", langKey='" + langKey + '\'' +
", createdBy=" + createdBy +
", createdDate=" + createdDate +
", lastModifiedBy='" + lastModifiedBy + '\'' +
", lastModifiedDate=" + lastModifiedDate +
", authorities=" + authorities +
"}";
}
}
| 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/main/java/com/gateway/service/mapper/package-info.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/service/mapper/package-info.java | /**
* Data transfer objects mappers.
*/
package com.gateway.service.mapper;
| 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/main/java/com/gateway/service/mapper/UserMapper.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/service/mapper/UserMapper.java | package com.gateway.service.mapper;
import com.gateway.domain.Authority;
import com.gateway.domain.User;
import com.gateway.service.dto.AdminUserDTO;
import com.gateway.service.dto.UserDTO;
import java.util.*;
import java.util.stream.Collectors;
import org.mapstruct.BeanMapping;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import org.springframework.stereotype.Service;
/**
* Mapper for the entity {@link User} and its DTO called {@link UserDTO}.
*
* Normal mappers are generated using MapStruct, this one is hand-coded as MapStruct
* support is still in beta, and requires a manual step with an IDE.
*/
@Service
public class UserMapper {
public List<UserDTO> usersToUserDTOs(List<User> users) {
return users.stream().filter(Objects::nonNull).map(this::userToUserDTO).toList();
}
public UserDTO userToUserDTO(User user) {
return new UserDTO(user);
}
public List<AdminUserDTO> usersToAdminUserDTOs(List<User> users) {
return users.stream().filter(Objects::nonNull).map(this::userToAdminUserDTO).toList();
}
public AdminUserDTO userToAdminUserDTO(User user) {
return new AdminUserDTO(user);
}
public List<User> userDTOsToUsers(List<AdminUserDTO> userDTOs) {
return userDTOs.stream().filter(Objects::nonNull).map(this::userDTOToUser).toList();
}
public User userDTOToUser(AdminUserDTO userDTO) {
if (userDTO == null) {
return null;
} else {
User user = new User();
user.setId(userDTO.getId());
user.setLogin(userDTO.getLogin());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail());
user.setImageUrl(userDTO.getImageUrl());
user.setActivated(userDTO.isActivated());
user.setLangKey(userDTO.getLangKey());
Set<Authority> authorities = this.authoritiesFromStrings(userDTO.getAuthorities());
user.setAuthorities(authorities);
return user;
}
}
private Set<Authority> authoritiesFromStrings(Set<String> authoritiesAsString) {
Set<Authority> authorities = new HashSet<>();
if (authoritiesAsString != null) {
authorities = authoritiesAsString
.stream()
.map(string -> {
Authority auth = new Authority();
auth.setName(string);
return auth;
})
.collect(Collectors.toSet());
}
return authorities;
}
public User userFromId(Long id) {
if (id == null) {
return null;
}
User user = new User();
user.setId(id);
return user;
}
@Named("id")
@BeanMapping(ignoreByDefault = true)
@Mapping(target = "id", source = "id")
public UserDTO toDtoId(User user) {
if (user == null) {
return null;
}
UserDTO userDto = new UserDTO();
userDto.setId(user.getId());
return userDto;
}
@Named("idSet")
@BeanMapping(ignoreByDefault = true)
@Mapping(target = "id", source = "id")
public Set<UserDTO> toDtoIdSet(Set<User> users) {
if (users == null) {
return Collections.emptySet();
}
Set<UserDTO> userSet = new HashSet<>();
for (User userEntity : users) {
userSet.add(this.toDtoId(userEntity));
}
return userSet;
}
@Named("login")
@BeanMapping(ignoreByDefault = true)
@Mapping(target = "id", source = "id")
@Mapping(target = "login", source = "login")
public UserDTO toDtoLogin(User user) {
if (user == null) {
return null;
}
UserDTO userDto = new UserDTO();
userDto.setId(user.getId());
userDto.setLogin(user.getLogin());
return userDto;
}
@Named("loginSet")
@BeanMapping(ignoreByDefault = true)
@Mapping(target = "id", source = "id")
@Mapping(target = "login", source = "login")
public Set<UserDTO> toDtoLoginSet(Set<User> users) {
if (users == null) {
return Collections.emptySet();
}
Set<UserDTO> userSet = new HashSet<>();
for (User userEntity : users) {
userSet.add(this.toDtoLogin(userEntity));
}
return userSet;
}
}
| 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/main/java/com/gateway/aop/logging/package-info.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/aop/logging/package-info.java | /**
* Logging aspect.
*/
package com.gateway.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/gateway-app/src/main/java/com/gateway/aop/logging/LoggingAspect.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/aop/logging/LoggingAspect.java | package com.gateway.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.gateway.repository..*)" + " || within(com.gateway.service..*)" + " || within(com.gateway.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/gateway-app/src/main/java/com/gateway/domain/package-info.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/domain/package-info.java | /**
* Domain objects.
*/
package com.gateway.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/gateway-app/src/main/java/com/gateway/domain/Authority.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/domain/Authority.java | package com.gateway.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.domain.Persistable;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
/**
* A Authority.
*/
@Table("jhi_authority")
@JsonIgnoreProperties(value = { "new", "id" })
@SuppressWarnings("common-java:DuplicatedBlocks")
public class Authority implements Serializable, Persistable<String> {
private static final long serialVersionUID = 1L;
@NotNull(message = "must not be null")
@Size(max = 50)
@Id
@Column("name")
private String name;
@Transient
private boolean isPersisted;
// jhipster-needle-entity-add-field - JHipster will add fields here
public String getName() {
return this.name;
}
public Authority name(String name) {
this.setName(name);
return this;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getId() {
return this.name;
}
@Transient
@Override
public boolean isNew() {
return !this.isPersisted;
}
public Authority setIsPersisted() {
this.isPersisted = true;
return this;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Authority)) {
return false;
}
return getName() != null && getName().equals(((Authority) o).getName());
}
@Override
public int hashCode() {
return Objects.hashCode(getName());
}
// prettier-ignore
@Override
public String toString() {
return "Authority{" +
"name=" + 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/gateway-app/src/main/java/com/gateway/domain/AuthorityCallback.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/domain/AuthorityCallback.java | package com.gateway.domain;
import org.reactivestreams.Publisher;
import org.springframework.data.r2dbc.mapping.OutboundRow;
import org.springframework.data.r2dbc.mapping.event.AfterConvertCallback;
import org.springframework.data.r2dbc.mapping.event.AfterSaveCallback;
import org.springframework.data.relational.core.sql.SqlIdentifier;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
@Component
public class AuthorityCallback implements AfterSaveCallback<Authority>, AfterConvertCallback<Authority> {
@Override
public Publisher<Authority> onAfterConvert(Authority entity, SqlIdentifier table) {
return Mono.just(entity.setIsPersisted());
}
@Override
public Publisher<Authority> onAfterSave(Authority entity, OutboundRow outboundRow, SqlIdentifier table) {
return Mono.just(entity.setIsPersisted());
}
}
| 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/main/java/com/gateway/domain/User.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/domain/User.java | package com.gateway.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.gateway.config.Constants;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import java.io.Serializable;
import java.time.Instant;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
/**
* A user.
*/
@Table("jhi_user")
public class User extends AbstractAuditingEntity<Long> implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Long id;
@NotNull
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
private String login;
@JsonIgnore
@NotNull
@Size(min = 60, max = 60)
@Column("password_hash")
private String password;
@Size(max = 50)
@Column("first_name")
private String firstName;
@Size(max = 50)
@Column("last_name")
private String lastName;
@Email
@Size(min = 5, max = 254)
private String email;
@NotNull
private boolean activated = false;
@Size(min = 2, max = 10)
@Column("lang_key")
private String langKey;
@Size(max = 256)
@Column("image_url")
private String imageUrl;
@Size(max = 20)
@Column("activation_key")
@JsonIgnore
private String activationKey;
@Size(max = 20)
@Column("reset_key")
@JsonIgnore
private String resetKey;
@Column("reset_date")
private Instant resetDate = null;
@JsonIgnore
@Transient
private Set<Authority> authorities = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
// Lowercase the login before saving it in database
public void setLogin(String login) {
this.login = StringUtils.lowerCase(login, Locale.ENGLISH);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public Instant getResetDate() {
return resetDate;
}
public void setResetDate(Instant resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
return id != null && id.equals(((User) o).id);
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
}
| 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/main/java/com/gateway/domain/AbstractAuditingEntity.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/domain/AbstractAuditingEntity.java | package com.gateway.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.Column;
import java.io.Serializable;
import java.time.Instant;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
/**
* Base abstract class for entities which will hold definitions for created, last modified, created by,
* last modified by attributes.
*/
@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();
@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();
@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/gateway-app/src/main/java/com/gateway/repository/UserRepository.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/repository/UserRepository.java | package com.gateway.repository;
import static org.springframework.data.relational.core.query.Criteria.where;
import static org.springframework.data.relational.core.query.Query.query;
import com.gateway.domain.Authority;
import com.gateway.domain.User;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.beanutils.BeanComparator;
import org.springframework.data.domain.*;
import org.springframework.data.domain.Sort;
import org.springframework.data.r2dbc.convert.R2dbcConverter;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.r2dbc.repository.R2dbcRepository;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
/**
* Spring Data R2DBC repository for the {@link User} entity.
*/
@Repository
public interface UserRepository extends R2dbcRepository<User, Long>, UserRepositoryInternal {
Mono<User> findOneByActivationKey(String activationKey);
Flux<User> findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(LocalDateTime dateTime);
Mono<User> findOneByResetKey(String resetKey);
Mono<User> findOneByEmailIgnoreCase(String email);
Mono<User> findOneByLogin(String login);
Flux<User> findAllByIdNotNull(Pageable pageable);
Flux<User> findAllByIdNotNullAndActivatedIsTrue(Pageable pageable);
Mono<Long> count();
@Query("INSERT INTO jhi_user_authority VALUES(:userId, :authority)")
Mono<Void> saveUserAuthority(Long userId, String authority);
@Query("DELETE FROM jhi_user_authority")
Mono<Void> deleteAllUserAuthorities();
@Query("DELETE FROM jhi_user_authority WHERE user_id = :userId")
Mono<Void> deleteUserAuthorities(Long userId);
}
interface DeleteExtended<T> {
Mono<Void> delete(T user);
}
interface UserRepositoryInternal extends DeleteExtended<User> {
Mono<User> findOneWithAuthoritiesByLogin(String login);
Mono<User> findOneWithAuthoritiesByEmailIgnoreCase(String email);
Flux<User> findAllWithAuthorities(Pageable pageable);
}
class UserRepositoryInternalImpl implements UserRepositoryInternal {
private final DatabaseClient db;
private final R2dbcEntityTemplate r2dbcEntityTemplate;
private final R2dbcConverter r2dbcConverter;
public UserRepositoryInternalImpl(DatabaseClient db, R2dbcEntityTemplate r2dbcEntityTemplate, R2dbcConverter r2dbcConverter) {
this.db = db;
this.r2dbcEntityTemplate = r2dbcEntityTemplate;
this.r2dbcConverter = r2dbcConverter;
}
@Override
public Mono<User> findOneWithAuthoritiesByLogin(String login) {
return findOneWithAuthoritiesBy("login", login);
}
@Override
public Mono<User> findOneWithAuthoritiesByEmailIgnoreCase(String email) {
return findOneWithAuthoritiesBy("email", email.toLowerCase());
}
@Override
public Flux<User> findAllWithAuthorities(Pageable pageable) {
String property = pageable.getSort().stream().map(Sort.Order::getProperty).findFirst().orElse("id");
String direction = String.valueOf(
pageable.getSort().stream().map(Sort.Order::getDirection).findFirst().orElse(Sort.DEFAULT_DIRECTION)
);
long page = pageable.getPageNumber();
long size = pageable.getPageSize();
return db
.sql("SELECT * FROM jhi_user u LEFT JOIN jhi_user_authority ua ON u.id=ua.user_id")
.map(
(row, metadata) ->
Tuples.of(r2dbcConverter.read(User.class, row, metadata), Optional.ofNullable(row.get("authority_name", String.class)))
)
.all()
.groupBy(t -> t.getT1().getLogin())
.flatMap(l -> l.collectList().map(t -> updateUserWithAuthorities(t.get(0).getT1(), t)))
.sort(
Sort.Direction.fromString(direction) == Sort.DEFAULT_DIRECTION
? new BeanComparator<>(property)
: new BeanComparator<>(property).reversed()
)
.skip(page * size)
.take(size);
}
@Override
public Mono<Void> delete(User user) {
return db
.sql("DELETE FROM jhi_user_authority WHERE user_id = :userId")
.bind("userId", user.getId())
.then()
.then(r2dbcEntityTemplate.delete(User.class).matching(query(where("id").is(user.getId()))).all().then());
}
private Mono<User> findOneWithAuthoritiesBy(String fieldName, Object fieldValue) {
return db
.sql("SELECT * FROM jhi_user u LEFT JOIN jhi_user_authority ua ON u.id=ua.user_id WHERE u." + fieldName + " = :" + fieldName)
.bind(fieldName, fieldValue)
.map(
(row, metadata) ->
Tuples.of(r2dbcConverter.read(User.class, row, metadata), Optional.ofNullable(row.get("authority_name", String.class)))
)
.all()
.collectList()
.filter(l -> !l.isEmpty())
.map(l -> updateUserWithAuthorities(l.get(0).getT1(), l));
}
private User updateUserWithAuthorities(User user, List<Tuple2<User, Optional<String>>> tuples) {
user.setAuthorities(
tuples
.stream()
.filter(t -> t.getT2().isPresent())
.map(t -> {
Authority authority = new Authority();
authority.setName(t.getT2().orElseThrow());
return authority;
})
.collect(Collectors.toSet())
);
return user;
}
}
| 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/main/java/com/gateway/repository/UserSqlHelper.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/repository/UserSqlHelper.java | package com.gateway.repository;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.relational.core.sql.Column;
import org.springframework.data.relational.core.sql.Expression;
import org.springframework.data.relational.core.sql.Table;
public class UserSqlHelper {
public static List<Expression> getColumns(Table table, String columnPrefix) {
List<Expression> columns = new ArrayList<>();
columns.add(Column.aliased("id", table, columnPrefix + "_id"));
columns.add(Column.aliased("login", table, columnPrefix + "_login"));
columns.add(Column.aliased("password_hash", table, columnPrefix + "_password"));
columns.add(Column.aliased("first_name", table, columnPrefix + "_first_name"));
columns.add(Column.aliased("last_name", table, columnPrefix + "_last_name"));
columns.add(Column.aliased("email", table, columnPrefix + "_email"));
columns.add(Column.aliased("activated", table, columnPrefix + "_activated"));
columns.add(Column.aliased("lang_key", table, columnPrefix + "_lang_key"));
columns.add(Column.aliased("image_url", table, columnPrefix + "_image_url"));
columns.add(Column.aliased("activation_key", table, columnPrefix + "_activation_key"));
columns.add(Column.aliased("reset_key", table, columnPrefix + "_reset_key"));
columns.add(Column.aliased("reset_date", table, columnPrefix + "_reset_date"));
return columns;
}
}
| 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/main/java/com/gateway/repository/package-info.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/repository/package-info.java | /**
* Repository layer.
*/
package com.gateway.repository;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/repository/AuthorityRepository.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/repository/AuthorityRepository.java | package com.gateway.repository;
import com.gateway.domain.Authority;
import org.springframework.data.r2dbc.repository.R2dbcRepository;
import org.springframework.stereotype.Repository;
/**
* Spring Data R2DBC repository for the Authority entity.
*/
@SuppressWarnings("unused")
@Repository
public interface AuthorityRepository extends R2dbcRepository<Authority, String> {}
| 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/main/java/com/gateway/repository/EntityManager.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/repository/EntityManager.java | package com.gateway.repository;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.r2dbc.core.StatementMapper;
import org.springframework.data.r2dbc.query.UpdateMapper;
import org.springframework.data.relational.core.mapping.RelationalPersistentEntity;
import org.springframework.data.relational.core.query.Criteria;
import org.springframework.data.relational.core.sql.Column;
import org.springframework.data.relational.core.sql.Condition;
import org.springframework.data.relational.core.sql.OrderByField;
import org.springframework.data.relational.core.sql.Select;
import org.springframework.data.relational.core.sql.SelectBuilder.SelectFromAndJoin;
import org.springframework.data.relational.core.sql.SelectBuilder.SelectFromAndJoinCondition;
import org.springframework.data.relational.core.sql.SelectBuilder.SelectOrdered;
import org.springframework.data.relational.core.sql.Table;
import org.springframework.data.relational.core.sql.render.SqlRenderer;
import org.springframework.r2dbc.core.Parameter;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* Helper class to create SQL selects based on the entity, paging parameters and criteria.
*
*/
@Component
public class EntityManager {
public static final String ENTITY_ALIAS = "e";
public static final String ALIAS_PREFIX = "e_";
public static class LinkTable {
final String tableName;
final String idColumn;
final String referenceColumn;
public LinkTable(String tableName, String idColumn, String referenceColumn) {
Assert.notNull(tableName, "tableName is null");
Assert.notNull(idColumn, "idColumn is null");
Assert.notNull(referenceColumn, "referenceColumn is null");
this.tableName = tableName;
this.idColumn = idColumn;
this.referenceColumn = referenceColumn;
}
}
private final SqlRenderer sqlRenderer;
private final UpdateMapper updateMapper;
private final R2dbcEntityTemplate r2dbcEntityTemplate;
private final StatementMapper statementMapper;
public EntityManager(SqlRenderer sqlRenderer, UpdateMapper updateMapper, R2dbcEntityTemplate r2dbcEntityTemplate) {
this.sqlRenderer = sqlRenderer;
this.updateMapper = updateMapper;
this.r2dbcEntityTemplate = r2dbcEntityTemplate;
this.statementMapper = r2dbcEntityTemplate.getDataAccessStrategy().getStatementMapper();
}
/**
* Creates an SQL select statement from the given fragment and pagination parameters.
* @param selectFrom a representation of a select statement.
* @param entityType the entity type which holds the table name.
* @param pageable page parameter, or null, if everything needs to be returned.
* @param where condition or null. The condition to apply as where clause.
* @return sql select statement
*/
public String createSelect(SelectFromAndJoin selectFrom, Class<?> entityType, Pageable pageable, Condition where) {
if (pageable != null) {
if (where != null) {
return createSelectImpl(
selectFrom.limitOffset(pageable.getPageSize(), pageable.getOffset()).where(where),
entityType,
pageable.getSort()
);
} else {
return createSelectImpl(
selectFrom.limitOffset(pageable.getPageSize(), pageable.getOffset()),
entityType,
pageable.getSort()
);
}
} else {
if (where != null) {
return createSelectImpl(selectFrom.where(where), entityType, null);
} else {
return createSelectImpl(selectFrom, entityType, null);
}
}
}
/**
* Creates an SQL select statement from the given fragment and pagination parameters.
* @param selectFrom a representation of a select statement.
* @param entityType the entity type which holds the table name.
* @param pageable page parameter, or null, if everything needs to be returned
* @param where condition or null. The condition to apply as where clause.
* @return sql select statement
*/
public String createSelect(SelectFromAndJoinCondition selectFrom, Class<?> entityType, Pageable pageable, Condition where) {
if (pageable != null) {
if (where != null) {
return createSelectImpl(
selectFrom.limitOffset(pageable.getPageSize(), pageable.getOffset()).where(where),
entityType,
pageable.getSort()
);
} else {
return createSelectImpl(
selectFrom.limitOffset(pageable.getPageSize(), pageable.getOffset()),
entityType,
pageable.getSort()
);
}
} else {
if (where != null) {
return createSelectImpl(selectFrom.where(where), entityType, null);
} else {
return createSelectImpl(selectFrom, entityType, null);
}
}
}
/**
* Generate an actual SQL from the given {@link Select}.
* @param select a representation of a select statement.
* @return the generated SQL select.
*/
public String createSelect(Select select) {
return sqlRenderer.render(select);
}
/**
* Delete all the entity with the given type, and return the number of deletions.
* @param entityType the entity type which holds the table name.
* @return the number of deleted entity
*/
public Mono<Long> deleteAll(Class<?> entityType) {
return r2dbcEntityTemplate.delete(entityType).all();
}
/**
* Delete all the rows from the given table, and return the number of deletions.
* @param tableName the name of the table to delete.
* @return the number of deleted rows.
*/
public Mono<Long> deleteAll(String tableName) {
StatementMapper.DeleteSpec delete = statementMapper.createDelete(tableName);
return r2dbcEntityTemplate.getDatabaseClient().sql(statementMapper.getMappedObject(delete)).fetch().rowsUpdated();
}
/**
* Inserts the given entity into the database - and sets the id, if it's an autoincrement field.
* @param <S> the type of the persisted entity.
* @param entity the entity to be inserted into the database.
* @return the persisted entity.
*/
public <S> Mono<S> insert(S entity) {
return r2dbcEntityTemplate.insert(entity);
}
/**
* Updates the table, which links the entity with the referred entities.
* @param table describes the link table, it contains a table name, the column name for the id, and for the referred entity id.
* @param entityId the id of the entity, for which the links are created.
* @param referencedIds the id of the referred entities.
* @return the number of inserted rows.
*/
public Mono<Long> updateLinkTable(LinkTable table, Object entityId, Stream<?> referencedIds) {
return deleteFromLinkTable(table, entityId).then(
Flux.fromStream(referencedIds)
.flatMap((Object referenceId) -> {
StatementMapper.InsertSpec insert = r2dbcEntityTemplate
.getDataAccessStrategy()
.getStatementMapper()
.createInsert(table.tableName)
.withColumn(table.idColumn, Parameter.from(entityId))
.withColumn(table.referenceColumn, Parameter.from(referenceId));
return r2dbcEntityTemplate.getDatabaseClient().sql(statementMapper.getMappedObject(insert)).fetch().rowsUpdated();
})
.collectList()
.map((List<Long> updates) -> updates.stream().reduce(Long::sum).orElse(0l))
);
}
public Mono<Void> deleteFromLinkTable(LinkTable table, Object entityId) {
Assert.notNull(entityId, "entityId is null");
StatementMapper.DeleteSpec deleteSpec = r2dbcEntityTemplate
.getDataAccessStrategy()
.getStatementMapper()
.createDelete(table.tableName)
.withCriteria(Criteria.from(Criteria.where(table.idColumn).is(entityId)));
return r2dbcEntityTemplate.getDatabaseClient().sql(statementMapper.getMappedObject(deleteSpec)).then();
}
private String createSelectImpl(SelectOrdered selectFrom, Class<?> entityType, Sort sortParameter) {
if (sortParameter != null && sortParameter.isSorted()) {
RelationalPersistentEntity<?> entity = getPersistentEntity(entityType);
if (entity != null) {
Sort sort = updateMapper.getMappedObject(sortParameter, entity);
selectFrom = selectFrom.orderBy(
createOrderByFields(Table.create(entity.getTableName()).as(EntityManager.ENTITY_ALIAS), sort)
);
}
}
return createSelect(selectFrom.build());
}
private RelationalPersistentEntity<?> getPersistentEntity(Class<?> entityType) {
return r2dbcEntityTemplate.getConverter().getMappingContext().getPersistentEntity(entityType);
}
private static Collection<? extends OrderByField> createOrderByFields(Table table, Sort sortToUse) {
List<OrderByField> fields = new ArrayList<>();
for (Sort.Order order : sortToUse) {
String propertyName = order.getProperty();
OrderByField orderByField = !propertyName.contains(".")
? OrderByField.from(table.column(propertyName).as(EntityManager.ALIAS_PREFIX + propertyName))
: createOrderByField(propertyName);
fields.add(order.isAscending() ? orderByField.asc() : orderByField.desc());
}
return fields;
}
/**
* Creates an OrderByField instance for sorting a query by the specified property.
*
* @param propertyName The full property name in the format "tableName.columnName".
* @return An OrderByField instance for sorting by the specified property.
*/
private static OrderByField createOrderByField(String propertyName) {
// Split the propertyName into table name and column name
String[] parts = propertyName.split("\\.");
String tableName = parts[0];
String columnName = parts[1];
// Create and return an OrderByField instance
return OrderByField.from(
// Create a column with the given name and alias it with the table name and column name
Column.aliased(
columnName,
// Create a table alias with the same name as the table
Table.aliased(camelCaseToSnakeCase(tableName), tableName),
// Use a composite alias of "tableName_columnName"
String.format("%s_%s", tableName, columnName)
)
);
}
/**
* Converts a camel case string to snake case.
*
* @param input The camel case string to be converted to snake case.
* @return The input string converted to snake case.
*/
public static String camelCaseToSnakeCase(String input) {
// Regular Expression
String regex = "([a-z])([A-Z]+)";
// Replacement string
String replacement = "$1_$2";
// Replace the given regex
// with replacement string
// and convert it to lower case.
return input.replaceAll(regex, replacement).toLowerCase();
}
}
| 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/main/java/com/gateway/repository/rowmapper/package-info.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/repository/rowmapper/package-info.java | /**
* Webflux database column mapper.
*/
package com.gateway.repository.rowmapper;
| 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/main/java/com/gateway/repository/rowmapper/ColumnConverter.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/repository/rowmapper/ColumnConverter.java | package com.gateway.repository.rowmapper;
import io.r2dbc.spi.Row;
import org.springframework.core.convert.ConversionService;
import org.springframework.data.r2dbc.convert.R2dbcConverter;
import org.springframework.data.r2dbc.convert.R2dbcCustomConversions;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import tech.jhipster.service.ColumnConverterReactive;
/**
* This service provides helper function dealing with the low level {@link Row} and Spring's {@link R2dbcCustomConversions}, so type conversions can be applied.
*/
@Component
public class ColumnConverter implements ColumnConverterReactive {
private final ConversionService conversionService;
private final R2dbcCustomConversions conversions;
public ColumnConverter(R2dbcCustomConversions conversions, R2dbcConverter r2dbcConverter) {
this.conversionService = r2dbcConverter.getConversionService();
this.conversions = conversions;
}
/**
* Converts the value to the target class with the help of the {@link ConversionService}.
* @param value to convert.
* @param target class.
* @param <T> the parameter for the intended type.
* @return the value which can be constructed from the input.
*/
@Override
@SuppressWarnings("unchecked")
public <T> T convert(@Nullable Object value, @Nullable Class<T> target) {
if (value == null || target == null || ClassUtils.isAssignableValue(target, value)) {
return (T) value;
}
if (conversions.hasCustomReadTarget(value.getClass(), target)) {
return conversionService.convert(value, target);
}
if (Enum.class.isAssignableFrom(target)) {
return (T) Enum.valueOf((Class<Enum>) target, value.toString());
}
return conversionService.convert(value, target);
}
/**
* Convert a value from the {@link Row} to a type - throws an exception, if it's impossible.
* @param row which contains the column values.
* @param target class.
* @param columnName the name of the column which to convert.
* @param <T> the parameter for the intended type.
* @return the value which can be constructed from the input.
*/
public <T> T fromRow(Row row, String columnName, Class<T> target) {
try {
// try, directly the driver
return row.get(columnName, target);
} catch (Exception e) {
Object obj = row.get(columnName);
return convert(obj, target);
}
}
}
| 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/main/java/com/gateway/repository/rowmapper/UserRowMapper.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/repository/rowmapper/UserRowMapper.java | package com.gateway.repository.rowmapper;
import com.gateway.domain.User;
import io.r2dbc.spi.Row;
import java.time.Instant;
import java.util.function.BiFunction;
import org.springframework.stereotype.Service;
/**
* Converter between {@link Row} to {@link User}, with proper type conversions.
*/
@Service
public class UserRowMapper implements BiFunction<Row, String, User> {
private final ColumnConverter converter;
public UserRowMapper(ColumnConverter converter) {
this.converter = converter;
}
/**
* Take a {@link Row} and a column prefix, and extract all the fields.
* @return the {@link User} stored in the database.
*/
@Override
public User apply(Row row, String prefix) {
User entity = new User();
entity.setId(row.get(prefix + "_id", Long.class));
entity.setLogin(converter.fromRow(row, prefix + "_login", String.class));
entity.setPassword(converter.fromRow(row, prefix + "_password", String.class));
entity.setFirstName(converter.fromRow(row, prefix + "_first_name", String.class));
entity.setLastName(converter.fromRow(row, prefix + "_last_name", String.class));
entity.setEmail(converter.fromRow(row, prefix + "_email", String.class));
entity.setActivated(Boolean.TRUE.equals(converter.fromRow(row, prefix + "_activated", Boolean.class)));
entity.setLangKey(converter.fromRow(row, prefix + "_lang_key", String.class));
entity.setImageUrl(converter.fromRow(row, prefix + "_image_url", String.class));
entity.setActivationKey(converter.fromRow(row, prefix + "_activation_key", String.class));
entity.setResetKey(converter.fromRow(row, prefix + "_reset_key", String.class));
entity.setResetDate(converter.fromRow(row, prefix + "_reset_date", Instant.class));
return entity;
}
}
| 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/main/java/com/gateway/security/package-info.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/security/package-info.java | /**
* Application security utilities.
*/
package com.gateway.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/gateway-app/src/main/java/com/gateway/security/UserNotActivatedException.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/security/UserNotActivatedException.java | package com.gateway.security;
import org.springframework.security.core.AuthenticationException;
/**
* This exception is thrown in case of a not activated user trying to authenticate.
*/
public class UserNotActivatedException extends AuthenticationException {
private static final long serialVersionUID = 1L;
public UserNotActivatedException(String message) {
super(message);
}
public UserNotActivatedException(String message, Throwable t) {
super(message, t);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/security/SecurityUtils.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/security/SecurityUtils.java | package com.gateway.security;
import java.util.Arrays;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
import reactor.core.publisher.Mono;
/**
* 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 Mono<String> getCurrentUserLogin() {
return ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.flatMap(authentication -> Mono.justOrEmpty(extractPrincipal(authentication)));
}
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 Mono<String> getCurrentUserJWT() {
return ReactiveSecurityContextHolder.getContext()
.map(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 Mono<Boolean> isAuthenticated() {
return ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.map(Authentication::getAuthorities)
.map(authorities -> authorities.stream().map(GrantedAuthority::getAuthority).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 Mono<Boolean> hasCurrentUserAnyOfAuthorities(String... authorities) {
return ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.map(Authentication::getAuthorities)
.map(
authorityList ->
authorityList
.stream()
.map(GrantedAuthority::getAuthority)
.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 Mono<Boolean> hasCurrentUserNoneOfAuthorities(String... authorities) {
return hasCurrentUserAnyOfAuthorities(authorities).map(result -> !result);
}
/**
* 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 Mono<Boolean> hasCurrentUserThisAuthority(String authority) {
return hasCurrentUserAnyOfAuthorities(authority);
}
}
| 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/main/java/com/gateway/security/AuthoritiesConstants.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/security/AuthoritiesConstants.java | package com.gateway.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/gateway-app/src/main/java/com/gateway/security/DomainUserDetailsService.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/security/DomainUserDetailsService.java | package com.gateway.security;
import com.gateway.domain.Authority;
import com.gateway.domain.User;
import com.gateway.repository.UserRepository;
import java.util.*;
import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Mono;
/**
* Authenticate a user from the database.
*/
@Component("userDetailsService")
public class DomainUserDetailsService implements ReactiveUserDetailsService {
private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class);
private final UserRepository userRepository;
public DomainUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
@Transactional(readOnly = true)
public Mono<UserDetails> findByUsername(final String login) {
log.debug("Authenticating {}", login);
if (new EmailValidator().isValid(login, null)) {
return userRepository
.findOneWithAuthoritiesByEmailIgnoreCase(login)
.switchIfEmpty(Mono.error(new UsernameNotFoundException("User with email " + login + " was not found in the database")))
.map(user -> createSpringSecurityUser(login, user));
}
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
return userRepository
.findOneWithAuthoritiesByLogin(lowercaseLogin)
.switchIfEmpty(Mono.error(new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database")))
.map(user -> createSpringSecurityUser(lowercaseLogin, user));
}
private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) {
if (!user.isActivated()) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
List<SimpleGrantedAuthority> grantedAuthorities = user
.getAuthorities()
.stream()
.map(Authority::getName)
.map(SimpleGrantedAuthority::new)
.toList();
return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), grantedAuthorities);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/security/jwt/package-info.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/security/jwt/package-info.java | /**
* This package file was generated by JHipster
*/
package com.gateway.security.jwt;
| 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/main/java/com/gateway/security/jwt/JWTRelayGatewayFilterFactory.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/security/jwt/JWTRelayGatewayFilterFactory.java | package com.gateway.security.jwt;
import static org.springframework.http.HttpHeaders.AUTHORIZATION;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
@Component
public class JWTRelayGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
private static final String BEARER = "Bearer ";
private ReactiveJwtDecoder jwtDecoder;
public JWTRelayGatewayFilterFactory(ReactiveJwtDecoder jwtDecoder) {
this.jwtDecoder = jwtDecoder;
}
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
String bearerToken = exchange.getRequest().getHeaders().getFirst(AUTHORIZATION);
if (bearerToken == null) {
// Allow anonymous requests.
return chain.filter(exchange);
}
String token = this.extractToken(bearerToken);
return jwtDecoder.decode(token).thenReturn(withBearerAuth(exchange, token)).flatMap(chain::filter);
};
}
private String extractToken(String bearerToken) {
if (StringUtils.hasText(bearerToken) && bearerToken.length() > 7 && bearerToken.startsWith(BEARER)) {
return bearerToken.substring(7);
}
throw new IllegalArgumentException("Invalid token in Authorization header");
}
private ServerWebExchange withBearerAuth(ServerWebExchange exchange, String authorizeToken) {
return exchange.mutate().request(r -> r.headers(headers -> headers.setBearerAuth(authorizeToken))).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/gateway-app/src/main/java/com/gateway/config/SecurityConfiguration.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/SecurityConfiguration.java | package com.gateway.config;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers.pathMatchers;
import com.gateway.security.AuthoritiesConstants;
import com.gateway.web.filter.SpaWebFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
import org.springframework.security.config.web.server.SecurityWebFiltersOrder;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.header.ReferrerPolicyServerHttpHeadersWriter;
import org.springframework.security.web.server.header.XFrameOptionsServerHttpHeadersWriter.Mode;
import org.springframework.security.web.server.util.matcher.NegatedServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.OrServerWebExchangeMatcher;
import tech.jhipster.config.JHipsterProperties;
@Configuration
@EnableReactiveMethodSecurity
public class SecurityConfiguration {
private final JHipsterProperties jHipsterProperties;
public SecurityConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public ReactiveAuthenticationManager reactiveAuthenticationManager(ReactiveUserDetailsService userDetailsService) {
UserDetailsRepositoryReactiveAuthenticationManager authenticationManager = new UserDetailsRepositoryReactiveAuthenticationManager(
userDetailsService
);
authenticationManager.setPasswordEncoder(passwordEncoder());
return authenticationManager;
}
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.securityMatcher(
new NegatedServerWebExchangeMatcher(
new OrServerWebExchangeMatcher(pathMatchers("/app/**", "/i18n/**", "/content/**", "/swagger-ui/**"))
)
)
.cors(withDefaults())
.csrf(csrf -> csrf.disable())
.addFilterAfter(new SpaWebFilter(), SecurityWebFiltersOrder.HTTPS_REDIRECT)
.headers(
headers ->
headers
.contentSecurityPolicy(csp -> csp.policyDirectives(jHipsterProperties.getSecurity().getContentSecurityPolicy()))
.frameOptions(frameOptions -> frameOptions.mode(Mode.DENY))
.referrerPolicy(
referrer ->
referrer.policy(ReferrerPolicyServerHttpHeadersWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)
)
.permissionsPolicy(
permissions ->
permissions.policy(
"camera=(), fullscreen=(self), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), sync-xhr=()"
)
)
)
.authorizeExchange(
authz ->
// prettier-ignore
authz
.pathMatchers("/").permitAll()
.pathMatchers("/*.*").permitAll()
.pathMatchers("/api/authenticate").permitAll()
.pathMatchers("/api/register").permitAll()
.pathMatchers("/api/activate").permitAll()
.pathMatchers("/api/account/reset-password/init").permitAll()
.pathMatchers("/api/account/reset-password/finish").permitAll()
.pathMatchers("/api/admin/**").hasAuthority(AuthoritiesConstants.ADMIN)
.pathMatchers("/api/**").authenticated()
.pathMatchers("/services/*/management/health/readiness").permitAll()
.pathMatchers("/services/*/v3/api-docs").hasAuthority(AuthoritiesConstants.ADMIN)
.pathMatchers("/services/**").authenticated()
.pathMatchers("/v3/api-docs/**").hasAuthority(AuthoritiesConstants.ADMIN)
.pathMatchers("/management/health").permitAll()
.pathMatchers("/management/health/**").permitAll()
.pathMatchers("/management/info").permitAll()
.pathMatchers("/management/prometheus").permitAll()
.pathMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
)
.httpBasic(basic -> basic.disable())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults()));
return http.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/gateway-app/src/main/java/com/gateway/config/ApplicationProperties.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/ApplicationProperties.java | package com.gateway.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Properties specific to Gateway 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 {
// jhipster-needle-application-properties-property
// jhipster-needle-application-properties-property-getter
// 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/gateway-app/src/main/java/com/gateway/config/DatabaseConfiguration.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/DatabaseConfiguration.java | package com.gateway.config;
import io.r2dbc.spi.ConnectionFactory;
import java.sql.SQLException;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
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.convert.converter.Converter;
import org.springframework.core.env.Environment;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.WritingConverter;
import org.springframework.data.r2dbc.convert.MappingR2dbcConverter;
import org.springframework.data.r2dbc.convert.R2dbcCustomConversions;
import org.springframework.data.r2dbc.dialect.DialectResolver;
import org.springframework.data.r2dbc.dialect.R2dbcDialect;
import org.springframework.data.r2dbc.query.UpdateMapper;
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories;
import org.springframework.data.relational.core.dialect.RenderContextFactory;
import org.springframework.data.relational.core.sql.render.SqlRenderer;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.h2.H2ConfigurationHelper;
@Configuration
@EnableR2dbcRepositories({ "com.gateway.repository" })
@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);
}
// LocalDateTime seems to be the only type that is supported across all drivers atm
// See https://github.com/r2dbc/r2dbc-h2/pull/139 https://github.com/mirromutth/r2dbc-mysql/issues/105
@Bean
public R2dbcCustomConversions r2dbcCustomConversions(R2dbcDialect dialect) {
List<Object> converters = new ArrayList<>();
converters.add(InstantWriteConverter.INSTANCE);
converters.add(InstantReadConverter.INSTANCE);
converters.add(BitSetReadConverter.INSTANCE);
converters.add(DurationWriteConverter.INSTANCE);
converters.add(DurationReadConverter.INSTANCE);
converters.add(ZonedDateTimeReadConverter.INSTANCE);
converters.add(ZonedDateTimeWriteConverter.INSTANCE);
return R2dbcCustomConversions.of(dialect, converters);
}
@Bean
public R2dbcDialect dialect(ConnectionFactory connectionFactory) {
return DialectResolver.getDialect(connectionFactory);
}
@Bean
public UpdateMapper updateMapper(R2dbcDialect dialect, MappingR2dbcConverter mappingR2dbcConverter) {
return new UpdateMapper(dialect, mappingR2dbcConverter);
}
@Bean
public SqlRenderer sqlRenderer(R2dbcDialect dialect) {
RenderContextFactory factory = new RenderContextFactory(dialect);
return SqlRenderer.create(factory.createRenderContext());
}
@WritingConverter
public enum InstantWriteConverter implements Converter<Instant, LocalDateTime> {
INSTANCE;
public LocalDateTime convert(Instant source) {
return LocalDateTime.ofInstant(source, ZoneOffset.UTC);
}
}
@ReadingConverter
public enum InstantReadConverter implements Converter<LocalDateTime, Instant> {
INSTANCE;
@Override
public Instant convert(LocalDateTime localDateTime) {
return localDateTime.toInstant(ZoneOffset.UTC);
}
}
@ReadingConverter
public enum BitSetReadConverter implements Converter<BitSet, Boolean> {
INSTANCE;
@Override
public Boolean convert(BitSet bitSet) {
return bitSet.get(0);
}
}
@ReadingConverter
public enum ZonedDateTimeReadConverter implements Converter<LocalDateTime, ZonedDateTime> {
INSTANCE;
@Override
public ZonedDateTime convert(LocalDateTime localDateTime) {
// Be aware - we are using the UTC timezone
return ZonedDateTime.of(localDateTime, ZoneOffset.UTC);
}
}
@WritingConverter
public enum ZonedDateTimeWriteConverter implements Converter<ZonedDateTime, LocalDateTime> {
INSTANCE;
@Override
public LocalDateTime convert(ZonedDateTime zonedDateTime) {
return zonedDateTime.toLocalDateTime();
}
}
@WritingConverter
public enum DurationWriteConverter implements Converter<Duration, Long> {
INSTANCE;
@Override
public Long convert(Duration source) {
return source != null ? source.toMillis() : null;
}
}
@ReadingConverter
public enum DurationReadConverter implements Converter<Long, Duration> {
INSTANCE;
@Override
public Duration convert(Long source) {
return source != null ? Duration.ofMillis(source) : null;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/package-info.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/package-info.java | /**
* Application configuration.
*/
package com.gateway.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/gateway-app/src/main/java/com/gateway/config/DateTimeFormatConfiguration.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/DateTimeFormatConfiguration.java | package com.gateway.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.web.reactive.config.WebFluxConfigurer;
/**
* Configure the converters to use the ISO format for dates by default.
*/
@Configuration
public class DateTimeFormatConfiguration implements WebFluxConfigurer {
@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/gateway-app/src/main/java/com/gateway/config/CRLFLogConverter.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/CRLFLogConverter.java | package com.gateway.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/gateway-app/src/main/java/com/gateway/config/AsyncConfiguration.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/AsyncConfiguration.java | package com.gateway.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/gateway-app/src/main/java/com/gateway/config/WebConfigurer.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/WebConfigurer.java | package com.gateway.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gateway.web.rest.errors.ExceptionTranslator;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.reactive.ResourceHandlerRegistrationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.data.web.ReactivePageableHandlerMethodArgumentResolver;
import org.springframework.data.web.ReactiveSortHandlerMethodArgumentResolver;
import org.springframework.util.CollectionUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver;
import org.springframework.web.server.WebExceptionHandler;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.config.JHipsterProperties;
import tech.jhipster.config.h2.H2ConfigurationHelper;
import tech.jhipster.web.filter.reactive.CachingHttpHeadersFilter;
import tech.jhipster.web.rest.errors.ReactiveWebExceptionHandler;
/**
* Configuration of web application with Servlet 3.0 APIs.
*/
@Configuration
public class WebConfigurer implements WebFluxConfigurer {
private final Logger log = LoggerFactory.getLogger(WebConfigurer.class);
private final JHipsterProperties jHipsterProperties;
public WebConfigurer(Environment env, JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
try {
H2ConfigurationHelper.initH2Console();
} catch (Exception e) {
// Console may already be running on another app or after a refresh.
e.printStackTrace();
}
}
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
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);
source.registerCorsConfiguration("/*/api/**", config);
source.registerCorsConfiguration("/services/*/api/**", config);
source.registerCorsConfiguration("/*/management/**", config);
}
return source;
}
// TODO: remove when this is supported in spring-boot
@Bean
HandlerMethodArgumentResolver reactivePageableHandlerMethodArgumentResolver() {
return new ReactivePageableHandlerMethodArgumentResolver();
}
// TODO: remove when this is supported in spring-boot
@Bean
HandlerMethodArgumentResolver reactiveSortHandlerMethodArgumentResolver() {
return new ReactiveSortHandlerMethodArgumentResolver();
}
@Bean
@Order(-2) // The handler must have precedence over WebFluxResponseStatusExceptionHandler and Spring Boot's ErrorWebExceptionHandler
public WebExceptionHandler problemExceptionHandler(ObjectMapper mapper, ExceptionTranslator problemHandling) {
return new ReactiveWebExceptionHandler(problemHandling, mapper);
}
@Bean
ResourceHandlerRegistrationCustomizer registrationCustomizer() {
// Disable built-in cache control to use our custom filter instead
return registration -> registration.setCacheControl(null);
}
@Bean
@Profile(JHipsterConstants.SPRING_PROFILE_PRODUCTION)
public CachingHttpHeadersFilter cachingHttpHeadersFilter() {
// Use a cache filter that only match selected paths
return new CachingHttpHeadersFilter(TimeUnit.DAYS.toMillis(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/gateway-app/src/main/java/com/gateway/config/JacksonConfiguration.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/JacksonConfiguration.java | package com.gateway.config;
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();
}
}
| 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/main/java/com/gateway/config/LoggingConfiguration.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/LoggingConfiguration.java | package com.gateway.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/gateway-app/src/main/java/com/gateway/config/SecurityJwtConfiguration.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/SecurityJwtConfiguration.java | package com.gateway.config;
import static com.gateway.security.SecurityUtils.AUTHORITIES_KEY;
import static com.gateway.security.SecurityUtils.JWT_ALGORITHM;
import com.gateway.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.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtGrantedAuthoritiesConverterAdapter;
@Configuration
public class SecurityJwtConfiguration {
private final Logger log = LoggerFactory.getLogger(SecurityJwtConfiguration.class);
@Value("${jhipster.security.authentication.jwt.base64-secret}")
private String jwtKey;
@Bean
public ReactiveJwtDecoder jwtDecoder(SecurityMetersService metersService) {
NimbusReactiveJwtDecoder jwtDecoder = NimbusReactiveJwtDecoder.withSecretKey(getSecretKey()).macAlgorithm(JWT_ALGORITHM).build();
return token -> {
try {
return jwtDecoder
.decode(token)
.doOnError(e -> {
if (e.getMessage().contains("Jwt expired at")) {
metersService.trackTokenExpired();
} else if (e.getMessage().contains("Failed to validate the token")) {
metersService.trackTokenInvalidSignature();
} else if (
e.getMessage().contains("Invalid JWT serialization:") ||
e.getMessage().contains("Invalid unsecured/JWS/JWE header:")
) {
metersService.trackTokenMalformed();
} else {
log.error("Unknown JWT reactive error {}", e.getMessage());
}
});
} catch (Exception e) {
if (e.getMessage().contains("An error occurred while attempting to decode the Jwt")) {
metersService.trackTokenMalformed();
} else if (e.getMessage().contains("Failed to validate the token")) {
metersService.trackTokenInvalidSignature();
} else {
log.error("Unknown JWT error {}", e.getMessage());
}
throw e;
}
};
}
@Bean
public JwtEncoder jwtEncoder() {
return new NimbusJwtEncoder(new ImmutableSecret<>(getSecretKey()));
}
@Bean
public ReactiveJwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
grantedAuthoritiesConverter.setAuthorityPrefix("");
grantedAuthoritiesConverter.setAuthoritiesClaimName(AUTHORITIES_KEY);
ReactiveJwtAuthenticationConverter jwtAuthenticationConverter = new ReactiveJwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(
new ReactiveJwtGrantedAuthoritiesConverterAdapter(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/gateway-app/src/main/java/com/gateway/config/LiquibaseConfiguration.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/LiquibaseConfiguration.java | package com.gateway.config;
import java.util.Optional;
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.annotation.Qualifier;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.autoconfigure.r2dbc.R2dbcProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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.AsyncSpringLiquibase;
@Configuration
public class LiquibaseConfiguration {
private final Logger log = LoggerFactory.getLogger(LiquibaseConfiguration.class);
private final Environment env;
public LiquibaseConfiguration(Environment env) {
this.env = env;
}
@Bean
public SpringLiquibase liquibase(
@Qualifier("taskExecutor") Executor executor,
LiquibaseProperties liquibaseProperties,
R2dbcProperties dataSourceProperties
) {
SpringLiquibase liquibase = new AsyncSpringLiquibase(executor, env);
liquibase.setDataSource(createLiquibaseDataSource(liquibaseProperties, 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;
}
private static DataSource createLiquibaseDataSource(LiquibaseProperties liquibaseProperties, R2dbcProperties dataSourceProperties) {
String user = Optional.ofNullable(liquibaseProperties.getUser()).orElse(dataSourceProperties.getUsername());
String password = Optional.ofNullable(liquibaseProperties.getPassword()).orElse(dataSourceProperties.getPassword());
return DataSourceBuilder.create().url(liquibaseProperties.getUrl()).username(user).password(password).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/gateway-app/src/main/java/com/gateway/config/OpenApiConfiguration.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/OpenApiConfiguration.java | package com.gateway.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.gateway.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/gateway-app/src/main/java/com/gateway/config/EurekaWorkaroundConfiguration.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/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.gateway.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/gateway-app/src/main/java/com/gateway/config/Constants.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/Constants.java | package com.gateway.config;
/**
* Application constants.
*/
public final class Constants {
// Regex for acceptable logins
public static final String LOGIN_REGEX = "^(?>[a-zA-Z0-9!$&*+=?^_`{|}~.-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*)|(?>[_.@A-Za-z0-9-]+)$";
public static final String SYSTEM = "system";
public static final String DEFAULT_LANGUAGE = "en";
private Constants() {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/LoggingAspectConfiguration.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/LoggingAspectConfiguration.java | package com.gateway.config;
import com.gateway.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/gateway-app/src/main/java/com/gateway/config/ReactorConfiguration.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/config/ReactorConfiguration.java | package com.gateway.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import reactor.core.publisher.Hooks;
import tech.jhipster.config.JHipsterConstants;
@Configuration
@Profile("!" + JHipsterConstants.SPRING_PROFILE_PRODUCTION)
public class ReactorConfiguration {
public ReactorConfiguration() {
Hooks.onOperatorDebug();
}
}
| 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/main/java/com/gateway/web/filter/SpaWebFilter.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/filter/SpaWebFilter.java | package com.gateway.web.filter;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
public class SpaWebFilter implements WebFilter {
/**
* Forwards any unmapped paths (except those containing a period) to the client {@code index.html}.
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
String path = exchange.getRequest().getURI().getPath();
if (
!path.startsWith("/api") &&
!path.startsWith("/management") &&
!path.startsWith("/v3/api-docs") &&
!path.startsWith("/services") &&
!path.contains(".") &&
path.matches("/(.*)")
) {
return chain.filter(exchange.mutate().request(exchange.getRequest().mutate().path("/index.html").build()).build());
}
return chain.filter(exchange);
}
}
| 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/main/java/com/gateway/web/filter/package-info.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/filter/package-info.java | /**
* Request chain filters.
*/
package com.gateway.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/gateway-app/src/main/java/com/gateway/web/filter/ModifyServersOpenApiFilter.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/filter/ModifyServersOpenApiFilter.java | package com.gateway.web.filter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Component
public class ModifyServersOpenApiFilter implements GlobalFilter, Ordered {
private static final String OPEN_API_PATH = "/v3/api-docs";
private static final Logger log = LoggerFactory.getLogger(ModifyServersOpenApiFilter.class);
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String path = exchange.getRequest().getURI().getPath();
if (path.startsWith("/services") && path.contains(OPEN_API_PATH)) {
ServerHttpResponse originalResponse = exchange.getResponse();
DataBufferFactory bufferFactory = originalResponse.bufferFactory();
ServerHttpResponseDecorator decoratedResponse = createModifyServersOpenApiInterceptor(path, originalResponse, bufferFactory);
// replace response with decorator
return chain.filter(exchange.mutate().response(decoratedResponse).build());
} else {
return chain.filter(exchange);
}
}
@Override
public int getOrder() {
return -1;
}
public ModifyServersOpenApiInterceptor createModifyServersOpenApiInterceptor(
String path,
ServerHttpResponse originalResponse,
DataBufferFactory bufferFactory
) {
return new ModifyServersOpenApiInterceptor(path, originalResponse, bufferFactory);
}
public class ModifyServersOpenApiInterceptor extends ServerHttpResponseDecorator {
private final String path;
private final ServerHttpResponse originalResponse;
private final DataBufferFactory bufferFactory;
private String rewritedBody = "";
private ModifyServersOpenApiInterceptor(String path, ServerHttpResponse originalResponse, DataBufferFactory bufferFactory) {
super(originalResponse);
this.path = path;
this.originalResponse = originalResponse;
this.bufferFactory = bufferFactory;
}
public String getRewritedBody() {
return rewritedBody;
}
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
rewritedBody = "";
if (body instanceof Flux) {
Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
return super.writeWith(fluxBody.buffer().map(dataBuffers -> rewriteBodyWithServers(dataBuffers)));
}
// when body is not a flux
return super.writeWith(body);
}
private DataBuffer rewriteBodyWithServers(List<? extends DataBuffer> dataBuffers) {
DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
DataBuffer join = dataBufferFactory.join(dataBuffers);
byte[] content = new byte[join.readableByteCount()];
join.read(content);
// release memory
DataBufferUtils.release(join);
String strBody = contentToString(content);
try {
// create custom server
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonBody = mapper.readTree(strBody);
ObjectNode serversToJson = mapper.createObjectNode();
serversToJson.set("url", mapper.valueToTree(path.replaceFirst(OPEN_API_PATH + "(/.*)?$", "")));
serversToJson.set("description", mapper.valueToTree("added by global filter"));
// add custom server
ArrayNode servers = mapper.createArrayNode();
servers.add(serversToJson);
((ObjectNode) jsonBody).set("servers", servers);
rewritedBody = jsonBody.toString();
return rewritedBodyToDataBuffer();
} catch (JsonProcessingException e) {
log.error("Error when modify servers from api-doc of {}: {}", path, e.getMessage());
}
return join;
}
private DataBuffer rewritedBodyToDataBuffer() {
if (isZippedResponse()) {
byte[] zippedBody = zipContent(rewritedBody);
originalResponse.getHeaders().setContentLength(zippedBody.length);
return bufferFactory.wrap(zippedBody);
}
originalResponse.getHeaders().setContentLength(rewritedBody.getBytes().length);
return bufferFactory.wrap(rewritedBody.getBytes());
}
private String contentToString(byte[] content) {
if (isZippedResponse()) {
byte[] unzippedContent = unzipContent(content);
return new String(unzippedContent, StandardCharsets.UTF_8);
}
return new String(content, StandardCharsets.UTF_8);
}
private boolean isZippedResponse() {
return (
!originalResponse.getHeaders().isEmpty() &&
originalResponse.getHeaders().get(HttpHeaders.CONTENT_ENCODING) != null &&
Objects.requireNonNull(originalResponse.getHeaders().get(HttpHeaders.CONTENT_ENCODING)).contains("gzip")
);
}
private byte[] unzipContent(byte[] content) {
try {
GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(content));
byte[] unzippedContent = gzipInputStream.readAllBytes();
gzipInputStream.close();
return unzippedContent;
} catch (IOException e) {
log.error("Error when unzip content during modify servers from api-doc of {}: {}", path, e.getMessage());
}
return content;
}
private byte[] zipContent(String content) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(content.length());
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
gzipOutputStream.write(content.getBytes(StandardCharsets.UTF_8));
gzipOutputStream.flush();
gzipOutputStream.close();
return byteArrayOutputStream.toByteArray();
} catch (IOException e) {
log.error("Error when zip content during modify servers from api-doc of {}: {}", path, e.getMessage());
}
return content.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/gateway-app/src/main/java/com/gateway/web/rest/AccountResource.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/AccountResource.java | package com.gateway.web.rest;
import com.gateway.repository.UserRepository;
import com.gateway.security.SecurityUtils;
import com.gateway.service.MailService;
import com.gateway.service.UserService;
import com.gateway.service.dto.AdminUserDTO;
import com.gateway.service.dto.PasswordChangeDTO;
import com.gateway.web.rest.errors.*;
import com.gateway.web.rest.vm.KeyAndPasswordVM;
import com.gateway.web.rest.vm.ManagedUserVM;
import jakarta.validation.Valid;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
/**
* REST controller for managing the current user's account.
*/
@RestController
@RequestMapping("/api")
public class AccountResource {
private static class AccountResourceException extends RuntimeException {
private AccountResourceException(String message) {
super(message);
}
}
private final Logger log = LoggerFactory.getLogger(AccountResource.class);
private final UserRepository userRepository;
private final UserService userService;
private final MailService mailService;
public AccountResource(UserRepository userRepository, UserService userService, MailService mailService) {
this.userRepository = userRepository;
this.userService = userService;
this.mailService = mailService;
}
/**
* {@code POST /register} : register the user.
*
* @param managedUserVM the managed user View Model.
* @throws InvalidPasswordException {@code 400 (Bad Request)} if the password is incorrect.
* @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already used.
* @throws LoginAlreadyUsedException {@code 400 (Bad Request)} if the login is already used.
*/
@PostMapping("/register")
@ResponseStatus(HttpStatus.CREATED)
public Mono<Void> registerAccount(@Valid @RequestBody ManagedUserVM managedUserVM) {
if (isPasswordLengthInvalid(managedUserVM.getPassword())) {
throw new InvalidPasswordException();
}
return userService.registerUser(managedUserVM, managedUserVM.getPassword()).doOnSuccess(mailService::sendActivationEmail).then();
}
/**
* {@code GET /activate} : activate the registered user.
*
* @param key the activation key.
* @throws RuntimeException {@code 500 (Internal Server Error)} if the user couldn't be activated.
*/
@GetMapping("/activate")
public Mono<Void> activateAccount(@RequestParam(value = "key") String key) {
return userService
.activateRegistration(key)
.switchIfEmpty(Mono.error(new AccountResourceException("No user was found for this activation key")))
.then();
}
/**
* {@code GET /account} : get the current user.
*
* @return the current user.
* @throws RuntimeException {@code 500 (Internal Server Error)} if the user couldn't be returned.
*/
@GetMapping("/account")
public Mono<AdminUserDTO> getAccount() {
return userService
.getUserWithAuthorities()
.map(AdminUserDTO::new)
.switchIfEmpty(Mono.error(new AccountResourceException("User could not be found")));
}
/**
* {@code POST /account} : update the current user information.
*
* @param userDTO the current user information.
* @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already used.
* @throws RuntimeException {@code 500 (Internal Server Error)} if the user login wasn't found.
*/
@PostMapping("/account")
public Mono<Void> saveAccount(@Valid @RequestBody AdminUserDTO userDTO) {
return SecurityUtils.getCurrentUserLogin()
.switchIfEmpty(Mono.error(new AccountResourceException("Current user login not found")))
.flatMap(userLogin ->
userRepository
.findOneByEmailIgnoreCase(userDTO.getEmail())
.filter(existingUser -> !existingUser.getLogin().equalsIgnoreCase(userLogin))
.hasElement()
.flatMap(emailExists -> {
if (emailExists) {
throw new EmailAlreadyUsedException();
}
return userRepository.findOneByLogin(userLogin);
}))
.switchIfEmpty(Mono.error(new AccountResourceException("User could not be found")))
.flatMap(
user ->
userService.updateUser(
userDTO.getFirstName(),
userDTO.getLastName(),
userDTO.getEmail(),
userDTO.getLangKey(),
userDTO.getImageUrl()
)
);
}
/**
* {@code POST /account/change-password} : changes the current user's password.
*
* @param passwordChangeDto current and new password.
* @throws InvalidPasswordException {@code 400 (Bad Request)} if the new password is incorrect.
*/
@PostMapping(path = "/account/change-password")
public Mono<Void> changePassword(@RequestBody PasswordChangeDTO passwordChangeDto) {
if (isPasswordLengthInvalid(passwordChangeDto.getNewPassword())) {
throw new InvalidPasswordException();
}
return userService.changePassword(passwordChangeDto.getCurrentPassword(), passwordChangeDto.getNewPassword());
}
/**
* {@code POST /account/reset-password/init} : Send an email to reset the password of the user.
*
* @param mail the mail of the user.
*/
@PostMapping(path = "/account/reset-password/init")
public Mono<Void> requestPasswordReset(@RequestBody String mail) {
return userService
.requestPasswordReset(mail)
.doOnSuccess(user -> {
if (Objects.nonNull(user)) {
mailService.sendPasswordResetMail(user);
} else {
// Pretend the request has been successful to prevent checking which emails really exist
// but log that an invalid attempt has been made
log.warn("Password reset requested for non existing mail");
}
})
.then();
}
/**
* {@code POST /account/reset-password/finish} : Finish to reset the password of the user.
*
* @param keyAndPassword the generated key and the new password.
* @throws InvalidPasswordException {@code 400 (Bad Request)} if the password is incorrect.
* @throws RuntimeException {@code 500 (Internal Server Error)} if the password could not be reset.
*/
@PostMapping(path = "/account/reset-password/finish")
public Mono<Void> finishPasswordReset(@RequestBody KeyAndPasswordVM keyAndPassword) {
if (isPasswordLengthInvalid(keyAndPassword.getNewPassword())) {
throw new InvalidPasswordException();
}
return userService
.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey())
.switchIfEmpty(Mono.error(new AccountResourceException("No user was found for this reset key")))
.then();
}
private static boolean isPasswordLengthInvalid(String password) {
return (
StringUtils.isEmpty(password) ||
password.length() < ManagedUserVM.PASSWORD_MIN_LENGTH ||
password.length() > ManagedUserVM.PASSWORD_MAX_LENGTH
);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/GatewayResource.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/GatewayResource.java | package com.gateway.web.rest;
import com.gateway.security.AuthoritiesConstants;
import com.gateway.web.rest.vm.RouteVM;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.http.*;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
/**
* REST controller for managing Gateway configuration.
*/
@RestController
@RequestMapping("/api/gateway")
public class GatewayResource {
private final RouteLocator routeLocator;
private final DiscoveryClient discoveryClient;
@Value("${spring.application.name}")
private String appName;
public GatewayResource(RouteLocator routeLocator, DiscoveryClient discoveryClient) {
this.routeLocator = routeLocator;
this.discoveryClient = discoveryClient;
}
/**
* {@code GET /routes} : get the active routes.
*
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the list of routes.
*/
@GetMapping("/routes")
@Secured(AuthoritiesConstants.ADMIN)
public ResponseEntity<List<RouteVM>> activeRoutes() {
Flux<Route> routes = routeLocator.getRoutes();
List<RouteVM> routeVMs = new ArrayList<>();
routes.subscribe(route -> {
RouteVM routeVM = new RouteVM();
// Manipulate strings to make Gateway routes look like Zuul's
String predicate = route.getPredicate().toString();
String path = predicate.substring(predicate.indexOf("[") + 1, predicate.indexOf("]"));
routeVM.setPath(path);
String serviceId = route.getId().substring(route.getId().indexOf("_") + 1).toLowerCase();
routeVM.setServiceId(serviceId);
// Exclude gateway app from routes
if (!serviceId.equalsIgnoreCase(appName)) {
routeVM.setServiceInstances(discoveryClient.getInstances(serviceId));
routeVMs.add(routeVM);
}
});
return ResponseEntity.ok(routeVMs);
}
}
| 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/main/java/com/gateway/web/rest/AuthenticateController.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/AuthenticateController.java | package com.gateway.web.rest;
import static com.gateway.security.SecurityUtils.AUTHORITIES_KEY;
import static com.gateway.security.SecurityUtils.JWT_ALGORITHM;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.gateway.web.rest.vm.LoginVM;
import jakarta.validation.Valid;
import java.security.Principal;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* Controller to authenticate users.
*/
@RestController
@RequestMapping("/api")
public class AuthenticateController {
private final Logger log = LoggerFactory.getLogger(AuthenticateController.class);
private final JwtEncoder jwtEncoder;
@Value("${jhipster.security.authentication.jwt.token-validity-in-seconds:0}")
private long tokenValidityInSeconds;
@Value("${jhipster.security.authentication.jwt.token-validity-in-seconds-for-remember-me:0}")
private long tokenValidityInSecondsForRememberMe;
private final ReactiveAuthenticationManager authenticationManager;
public AuthenticateController(JwtEncoder jwtEncoder, ReactiveAuthenticationManager authenticationManager) {
this.jwtEncoder = jwtEncoder;
this.authenticationManager = authenticationManager;
}
@PostMapping("/authenticate")
public Mono<ResponseEntity<JWTToken>> authorize(@Valid @RequestBody Mono<LoginVM> loginVM) {
return loginVM
.flatMap(
login ->
authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword()))
.flatMap(auth -> Mono.fromCallable(() -> this.createToken(auth, login.isRememberMe())))
)
.map(jwt -> {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setBearerAuth(jwt);
return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK);
});
}
/**
* {@code GET /authenticate} : check if the user is authenticated, and return its login.
*
* @param request the HTTP request.
* @return the login if the user is authenticated.
*/
@GetMapping("/authenticate")
public Mono<String> isAuthenticated(ServerWebExchange request) {
log.debug("REST request to check if the current user is authenticated");
return request.getPrincipal().map(Principal::getName);
}
public String createToken(Authentication authentication, boolean rememberMe) {
String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(" "));
Instant now = Instant.now();
Instant validity;
if (rememberMe) {
validity = now.plus(this.tokenValidityInSecondsForRememberMe, ChronoUnit.SECONDS);
} else {
validity = now.plus(this.tokenValidityInSeconds, ChronoUnit.SECONDS);
}
// @formatter:off
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuedAt(now)
.expiresAt(validity)
.subject(authentication.getName())
.claim(AUTHORITIES_KEY, authorities)
.build();
JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build();
return this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue();
}
/**
* Object to return as body in JWT Authentication.
*/
static class JWTToken {
private String idToken;
JWTToken(String idToken) {
this.idToken = idToken;
}
@JsonProperty("id_token")
String getIdToken() {
return idToken;
}
void setIdToken(String idToken) {
this.idToken = idToken;
}
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/package-info.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/package-info.java | /**
* Rest layer.
*/
package com.gateway.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/gateway-app/src/main/java/com/gateway/web/rest/PublicUserResource.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/PublicUserResource.java | package com.gateway.web.rest;
import com.gateway.service.UserService;
import com.gateway.service.dto.UserDTO;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.ForwardedHeaderUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import tech.jhipster.web.util.PaginationUtil;
@RestController
@RequestMapping("/api")
public class PublicUserResource {
private static final List<String> ALLOWED_ORDERED_PROPERTIES = Collections.unmodifiableList(
Arrays.asList("id", "login", "firstName", "lastName", "email", "activated", "langKey")
);
private final Logger log = LoggerFactory.getLogger(PublicUserResource.class);
private final UserService userService;
public PublicUserResource(UserService userService) {
this.userService = userService;
}
/**
* {@code GET /users} : get all users with only public information - calling this method is allowed for anyone.
*
* @param request a {@link ServerHttpRequest} request.
* @param pageable the pagination information.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users.
*/
@GetMapping("/users")
public Mono<ResponseEntity<Flux<UserDTO>>> getAllPublicUsers(
ServerHttpRequest request,
@org.springdoc.core.annotations.ParameterObject Pageable pageable
) {
log.debug("REST request to get all public User names");
if (!onlyContainsAllowedProperties(pageable)) {
return Mono.just(ResponseEntity.badRequest().build());
}
return userService
.countManagedUsers()
.map(total -> new PageImpl<>(new ArrayList<>(), pageable, total))
.map(
page ->
PaginationUtil.generatePaginationHttpHeaders(
ForwardedHeaderUtils.adaptFromForwardedHeaders(request.getURI(), request.getHeaders()),
page
)
)
.map(headers -> ResponseEntity.ok().headers(headers).body(userService.getAllPublicUsers(pageable)));
}
private boolean onlyContainsAllowedProperties(Pageable pageable) {
return pageable.getSort().stream().map(Sort.Order::getProperty).allMatch(ALLOWED_ORDERED_PROPERTIES::contains);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/UserResource.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/UserResource.java | package com.gateway.web.rest;
import com.gateway.config.Constants;
import com.gateway.domain.User;
import com.gateway.repository.UserRepository;
import com.gateway.security.AuthoritiesConstants;
import com.gateway.service.MailService;
import com.gateway.service.UserService;
import com.gateway.service.dto.AdminUserDTO;
import com.gateway.web.rest.errors.BadRequestAlertException;
import com.gateway.web.rest.errors.EmailAlreadyUsedException;
import com.gateway.web.rest.errors.LoginAlreadyUsedException;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Pattern;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.util.ForwardedHeaderUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.PaginationUtil;
/**
* REST controller for managing users.
* <p>
* This class accesses the {@link com.gateway.domain.User} entity, and needs to fetch its collection of authorities.
* <p>
* For a normal use-case, it would be better to have an eager relationship between User and Authority,
* and send everything to the client side: there would be no View Model and DTO, a lot less code, and an outer-join
* which would be good for performance.
* <p>
* We use a View Model and a DTO for 3 reasons:
* <ul>
* <li>We want to keep a lazy association between the user and the authorities, because people will
* quite often do relationships with the user, and we don't want them to get the authorities all
* the time for nothing (for performance reasons). This is the #1 goal: we should not impact our users'
* application because of this use-case.</li>
* <li> Not having an outer join causes n+1 requests to the database. This is not a real issue as
* we have by default a second-level cache. This means on the first HTTP call we do the n+1 requests,
* but then all authorities come from the cache, so in fact it's much better than doing an outer join
* (which will get lots of data from the database, for each HTTP call).</li>
* <li> As this manages users, for security reasons, we'd rather have a DTO layer.</li>
* </ul>
* <p>
* Another option would be to have a specific JPA entity graph to handle this case.
*/
@RestController
@RequestMapping("/api/admin")
public class UserResource {
private static final List<String> ALLOWED_ORDERED_PROPERTIES = Collections.unmodifiableList(
Arrays.asList(
"id",
"login",
"firstName",
"lastName",
"email",
"activated",
"langKey",
"createdBy",
"createdDate",
"lastModifiedBy",
"lastModifiedDate"
)
);
private final Logger log = LoggerFactory.getLogger(UserResource.class);
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final UserService userService;
private final UserRepository userRepository;
private final MailService mailService;
public UserResource(UserService userService, UserRepository userRepository, MailService mailService) {
this.userService = userService;
this.userRepository = userRepository;
this.mailService = mailService;
}
/**
* {@code POST /admin/users} : Creates a new user.
* <p>
* Creates a new user if the login and email are not already used, and sends an
* mail with an activation link.
* The user needs to be activated on creation.
*
* @param userDTO the user to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new user, or with status {@code 400 (Bad Request)} if the login or email is already in use.
* @throws BadRequestAlertException {@code 400 (Bad Request)} if the login or email is already in use.
*/
@PostMapping("/users")
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
public Mono<ResponseEntity<User>> createUser(@Valid @RequestBody AdminUserDTO userDTO) {
log.debug("REST request to save User : {}", userDTO);
if (userDTO.getId() != null) {
throw new BadRequestAlertException("A new user cannot already have an ID", "userManagement", "idexists");
// Lowercase the user login before comparing with database
}
return userRepository
.findOneByLogin(userDTO.getLogin().toLowerCase())
.hasElement()
.flatMap(loginExists -> {
if (Boolean.TRUE.equals(loginExists)) {
return Mono.error(new LoginAlreadyUsedException());
}
return userRepository.findOneByEmailIgnoreCase(userDTO.getEmail());
})
.hasElement()
.flatMap(emailExists -> {
if (Boolean.TRUE.equals(emailExists)) {
return Mono.error(new EmailAlreadyUsedException());
}
return userService.createUser(userDTO);
})
.doOnSuccess(mailService::sendCreationEmail)
.map(user -> {
try {
return ResponseEntity.created(new URI("/api/admin/users/" + user.getLogin()))
.headers(
HeaderUtil.createAlert(applicationName, "A user is created with identifier " + user.getLogin(), user.getLogin())
)
.body(user);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
});
}
/**
* {@code PUT /admin/users} : Updates an existing User.
*
* @param userDTO the user to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated user.
* @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already in use.
* @throws LoginAlreadyUsedException {@code 400 (Bad Request)} if the login is already in use.
*/
@PutMapping({ "/users", "/users/{login}" })
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
public Mono<ResponseEntity<AdminUserDTO>> updateUser(
@PathVariable(name = "login", required = false) @Pattern(regexp = Constants.LOGIN_REGEX) String login,
@Valid @RequestBody AdminUserDTO userDTO
) {
log.debug("REST request to update User : {}", userDTO);
return userRepository
.findOneByEmailIgnoreCase(userDTO.getEmail())
.filter(user -> !user.getId().equals(userDTO.getId()))
.hasElement()
.flatMap(emailExists -> {
if (Boolean.TRUE.equals(emailExists)) {
return Mono.error(new EmailAlreadyUsedException());
}
return userRepository.findOneByLogin(userDTO.getLogin().toLowerCase());
})
.filter(user -> !user.getId().equals(userDTO.getId()))
.hasElement()
.flatMap(loginExists -> {
if (Boolean.TRUE.equals(loginExists)) {
return Mono.error(new LoginAlreadyUsedException());
}
return userService.updateUser(userDTO);
})
.switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND)))
.map(
user ->
ResponseEntity.ok()
.headers(
HeaderUtil.createAlert(
applicationName,
"A user is updated with identifier " + userDTO.getLogin(),
userDTO.getLogin()
)
)
.body(user)
);
}
/**
* {@code GET /admin/users} : get all users with all the details - calling this are only allowed for the administrators.
*
* @param request a {@link ServerHttpRequest} request.
* @param pageable the pagination information.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users.
*/
@GetMapping("/users")
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
public Mono<ResponseEntity<Flux<AdminUserDTO>>> getAllUsers(
@org.springdoc.core.annotations.ParameterObject ServerHttpRequest request,
@org.springdoc.core.annotations.ParameterObject Pageable pageable
) {
log.debug("REST request to get all User for an admin");
if (!onlyContainsAllowedProperties(pageable)) {
return Mono.just(ResponseEntity.badRequest().build());
}
return userService
.countManagedUsers()
.map(total -> new PageImpl<>(new ArrayList<>(), pageable, total))
.map(
page ->
PaginationUtil.generatePaginationHttpHeaders(
ForwardedHeaderUtils.adaptFromForwardedHeaders(request.getURI(), request.getHeaders()),
page
)
)
.map(headers -> ResponseEntity.ok().headers(headers).body(userService.getAllManagedUsers(pageable)));
}
private boolean onlyContainsAllowedProperties(Pageable pageable) {
return pageable.getSort().stream().map(Sort.Order::getProperty).allMatch(ALLOWED_ORDERED_PROPERTIES::contains);
}
/**
* {@code GET /admin/users/:login} : get the "login" user.
*
* @param login the login of the user to find.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the "login" user, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/users/{login}")
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
public Mono<AdminUserDTO> getUser(@PathVariable("login") String login) {
log.debug("REST request to get User : {}", login);
return userService
.getUserWithAuthoritiesByLogin(login)
.map(AdminUserDTO::new)
.switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND)));
}
/**
* {@code DELETE /admin/users/:login} : delete the "login" User.
*
* @param login the login of the user to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/users/{login}")
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
public Mono<ResponseEntity<Void>> deleteUser(@PathVariable("login") @Pattern(regexp = Constants.LOGIN_REGEX) String login) {
log.debug("REST request to delete User: {}", login);
return userService
.deleteUser(login)
.then(
Mono.just(
ResponseEntity.noContent()
.headers(HeaderUtil.createAlert(applicationName, "A user is deleted with identifier " + login, login))
.build()
)
);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/AuthorityResource.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/AuthorityResource.java | package com.gateway.web.rest;
import com.gateway.domain.Authority;
import com.gateway.repository.AuthorityRepository;
import com.gateway.web.rest.errors.BadRequestAlertException;
import jakarta.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.reactive.ResponseUtil;
/**
* REST controller for managing {@link com.gateway.domain.Authority}.
*/
@RestController
@RequestMapping("/api/authorities")
@Transactional
public class AuthorityResource {
private final Logger log = LoggerFactory.getLogger(AuthorityResource.class);
private static final String ENTITY_NAME = "adminAuthority";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final AuthorityRepository authorityRepository;
public AuthorityResource(AuthorityRepository authorityRepository) {
this.authorityRepository = authorityRepository;
}
/**
* {@code POST /authorities} : Create a new authority.
*
* @param authority the authority to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new authority, or with status {@code 400 (Bad Request)} if the authority has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("")
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
public Mono<ResponseEntity<Authority>> createAuthority(@Valid @RequestBody Authority authority) throws URISyntaxException {
log.debug("REST request to save Authority : {}", authority);
return authorityRepository
.existsById(authority.getName())
.flatMap(exists -> {
if (exists) {
return Mono.error(new BadRequestAlertException("authority already exists", ENTITY_NAME, "idexists"));
}
return authorityRepository
.save(authority)
.map(result -> {
try {
return ResponseEntity.created(new URI("/api/authorities/" + result.getName()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getName()))
.body(result);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
});
});
}
/**
* {@code GET /authorities} : get all the authorities.
*
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of authorities in body.
*/
@GetMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
public Mono<List<Authority>> getAllAuthorities() {
log.debug("REST request to get all Authorities");
return authorityRepository.findAll().collectList();
}
/**
* {@code GET /authorities} : get all the authorities as a stream.
* @return the {@link Flux} of authorities.
*/
@GetMapping(value = "", produces = MediaType.APPLICATION_NDJSON_VALUE)
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
public Flux<Authority> getAllAuthoritiesAsStream() {
log.debug("REST request to get all Authorities as a stream");
return authorityRepository.findAll();
}
/**
* {@code GET /authorities/:id} : get the "id" authority.
*
* @param id the id of the authority to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the authority, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/{id}")
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
public Mono<ResponseEntity<Authority>> getAuthority(@PathVariable("id") String id) {
log.debug("REST request to get Authority : {}", id);
Mono<Authority> authority = authorityRepository.findById(id);
return ResponseUtil.wrapOrNotFound(authority);
}
/**
* {@code DELETE /authorities/:id} : delete the "id" authority.
*
* @param id the id of the authority to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/{id}")
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN')")
public Mono<ResponseEntity<Void>> deleteAuthority(@PathVariable("id") String id) {
log.debug("REST request to delete Authority : {}", id);
return authorityRepository
.deleteById(id)
.then(
Mono.just(
ResponseEntity.noContent()
.headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id))
.build()
)
);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/errors/InvalidPasswordException.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/errors/InvalidPasswordException.java | package com.gateway.web.rest.errors;
import org.springframework.http.HttpStatus;
import org.springframework.web.ErrorResponseException;
import tech.jhipster.web.rest.errors.ProblemDetailWithCause.ProblemDetailWithCauseBuilder;
@SuppressWarnings("java:S110") // Inheritance tree of classes should not be too deep
public class InvalidPasswordException extends ErrorResponseException {
private static final long serialVersionUID = 1L;
public InvalidPasswordException() {
super(
HttpStatus.BAD_REQUEST,
ProblemDetailWithCauseBuilder.instance()
.withStatus(HttpStatus.BAD_REQUEST.value())
.withType(ErrorConstants.INVALID_PASSWORD_TYPE)
.withTitle("Incorrect password")
.build(),
null
);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/errors/package-info.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/errors/package-info.java | /**
* Rest layer error handling.
*/
package com.gateway.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/gateway-app/src/main/java/com/gateway/web/rest/errors/LoginAlreadyUsedException.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/errors/LoginAlreadyUsedException.java | package com.gateway.web.rest.errors;
@SuppressWarnings("java:S110") // Inheritance tree of classes should not be too deep
public class LoginAlreadyUsedException extends BadRequestAlertException {
private static final long serialVersionUID = 1L;
public LoginAlreadyUsedException() {
super(ErrorConstants.LOGIN_ALREADY_USED_TYPE, "Login name already used!", "userManagement", "userexists");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/errors/ErrorConstants.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/errors/ErrorConstants.java | package com.gateway.web.rest.errors;
import java.net.URI;
public final class ErrorConstants {
public static final String ERR_CONCURRENCY_FAILURE = "error.concurrencyFailure";
public static final String ERR_VALIDATION = "error.validation";
public static final String PROBLEM_BASE_URL = "https://www.jhipster.tech/problem";
public static final URI DEFAULT_TYPE = URI.create(PROBLEM_BASE_URL + "/problem-with-message");
public static final URI CONSTRAINT_VIOLATION_TYPE = URI.create(PROBLEM_BASE_URL + "/constraint-violation");
public static final URI INVALID_PASSWORD_TYPE = URI.create(PROBLEM_BASE_URL + "/invalid-password");
public static final URI EMAIL_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/email-already-used");
public static final URI LOGIN_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/login-already-used");
private ErrorConstants() {}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/errors/FieldErrorVM.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/errors/FieldErrorVM.java | package com.gateway.web.rest.errors;
import java.io.Serializable;
public class FieldErrorVM implements Serializable {
private static final long serialVersionUID = 1L;
private final String objectName;
private final String field;
private final String message;
public FieldErrorVM(String dto, String field, String message) {
this.objectName = dto;
this.field = field;
this.message = message;
}
public String getObjectName() {
return objectName;
}
public String getField() {
return field;
}
public String getMessage() {
return message;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/errors/EmailAlreadyUsedException.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/errors/EmailAlreadyUsedException.java | package com.gateway.web.rest.errors;
@SuppressWarnings("java:S110") // Inheritance tree of classes should not be too deep
public class EmailAlreadyUsedException extends BadRequestAlertException {
private static final long serialVersionUID = 1L;
public EmailAlreadyUsedException() {
super(ErrorConstants.EMAIL_ALREADY_USED_TYPE, "Email is already in use!", "userManagement", "emailexists");
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/errors/BadRequestAlertException.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/errors/BadRequestAlertException.java | package com.gateway.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/gateway-app/src/main/java/com/gateway/web/rest/errors/ExceptionTranslator.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/errors/ExceptionTranslator.java | package com.gateway.web.rest.errors;
import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation;
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.MediaType;
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.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
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.bind.support.WebExchangeBindException;
import org.springframework.web.reactive.result.method.annotation.ResponseEntityExceptionHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import tech.jhipster.config.JHipsterConstants;
import tech.jhipster.web.rest.errors.ExceptionTranslation;
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
@Component("jhiExceptionTranslator")
public class ExceptionTranslator extends ResponseEntityExceptionHandler implements ExceptionTranslation {
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
@Override
public Mono<ResponseEntity<Object>> handleAnyException(Throwable ex, ServerWebExchange request) {
ProblemDetailWithCause pdCause = wrapAndCustomizeProblem(ex, request);
return handleExceptionInternal((Exception) ex, pdCause, buildHeaders(ex), HttpStatusCode.valueOf(pdCause.getStatus()), request);
}
@Nullable
@Override
protected Mono<ResponseEntity<Object>> handleExceptionInternal(
Exception ex,
@Nullable Object body,
HttpHeaders headers,
HttpStatusCode statusCode,
ServerWebExchange request
) {
body = body == null ? wrapAndCustomizeProblem((Throwable) ex, (ServerWebExchange) request) : body;
if (request.getResponse().isCommitted()) {
return Mono.error(ex);
}
return Mono.just(
new ResponseEntity<>(body, updateContentType(headers), HttpStatusCode.valueOf(((ProblemDetailWithCause) body).getStatus()))
);
}
protected ProblemDetailWithCause wrapAndCustomizeProblem(Throwable ex, ServerWebExchange request) {
return customizeProblem(getProblemDetailWithCause(ex), ex, request);
}
private ProblemDetailWithCause getProblemDetailWithCause(Throwable ex) {
if (ex instanceof com.gateway.service.UsernameAlreadyUsedException) return (ProblemDetailWithCause) new LoginAlreadyUsedException()
.getBody();
if (ex instanceof com.gateway.service.EmailAlreadyUsedException) return (ProblemDetailWithCause) new EmailAlreadyUsedException()
.getBody();
if (ex instanceof com.gateway.service.InvalidPasswordException) return (ProblemDetailWithCause) new InvalidPasswordException()
.getBody();
if (ex instanceof AuthenticationException) {
// Ensure no information about existing users is revealed via failed authentication attempts
return ProblemDetailWithCauseBuilder.instance()
.withStatus(toStatus(ex).value())
.withTitle("Unauthorized")
.withDetail("Invalid credentials")
.build();
}
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, ServerWebExchange 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 WebExchangeBindException 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(WebExchangeBindException 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 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;
} else if (err instanceof WebExchangeBindException) {
return ErrorConstants.ERR_VALIDATION;
}
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;
if (err instanceof UsernameNotFoundException) return HttpStatus.UNAUTHORIZED;
return null;
}
private URI getPathValue(ServerWebExchange request) {
if (request == null) return URI.create("about:blank");
return request.getRequest().getURI();
}
private HttpHeaders buildHeaders(Throwable err) {
return err instanceof BadRequestAlertException badRequestAlertException
? HeaderUtil.createFailureAlert(
applicationName,
true,
badRequestAlertException.getEntityName(),
badRequestAlertException.getErrorKey(),
badRequestAlertException.getMessage()
)
: null;
}
private HttpHeaders updateContentType(HttpHeaders headers) {
if (headers == null) {
headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PROBLEM_JSON);
}
return headers;
}
public Optional<ProblemDetailWithCause> buildCause(final Throwable throwable, ServerWebExchange 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.gateway");
}
}
| 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/main/java/com/gateway/web/rest/vm/package-info.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/vm/package-info.java | /**
* Rest layer visual models.
*/
package com.gateway.web.rest.vm;
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/vm/RouteVM.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/vm/RouteVM.java | package com.gateway.web.rest.vm;
import java.util.List;
import org.springframework.cloud.client.ServiceInstance;
/**
* View Model that stores a route managed by the Gateway.
*/
public class RouteVM {
private String path;
private String serviceId;
private List<ServiceInstance> serviceInstances;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getServiceId() {
return serviceId;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public List<ServiceInstance> getServiceInstances() {
return serviceInstances;
}
public void setServiceInstances(List<ServiceInstance> serviceInstances) {
this.serviceInstances = serviceInstances;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/vm/KeyAndPasswordVM.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/vm/KeyAndPasswordVM.java | package com.gateway.web.rest.vm;
/**
* View Model object for storing the user's key and password.
*/
public class KeyAndPasswordVM {
private String key;
private String newPassword;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/vm/ManagedUserVM.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/vm/ManagedUserVM.java | package com.gateway.web.rest.vm;
import com.gateway.service.dto.AdminUserDTO;
import jakarta.validation.constraints.Size;
/**
* View Model extending the AdminUserDTO, which is meant to be used in the user management UI.
*/
public class ManagedUserVM extends AdminUserDTO {
public static final int PASSWORD_MIN_LENGTH = 4;
public static final int PASSWORD_MAX_LENGTH = 100;
@Size(min = PASSWORD_MIN_LENGTH, max = PASSWORD_MAX_LENGTH)
private String password;
public ManagedUserVM() {
// Empty constructor needed for Jackson.
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
// prettier-ignore
@Override
public String toString() {
return "ManagedUserVM{" + super.toString() + "} ";
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/vm/LoginVM.java | jhipster-8-modules/jhipster-8-microservice/gateway-app/src/main/java/com/gateway/web/rest/vm/LoginVM.java | package com.gateway.web.rest.vm;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
/**
* View Model object for storing a user's credentials.
*/
public class LoginVM {
@NotNull
@Size(min = 1, max = 50)
private String username;
@NotNull
@Size(min = 4, max = 100)
private String password;
private boolean rememberMe;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isRememberMe() {
return rememberMe;
}
public void setRememberMe(boolean rememberMe) {
this.rememberMe = rememberMe;
}
// prettier-ignore
@Override
public String toString() {
return "LoginVM{" +
"username='" + username + '\'' +
", rememberMe=" + rememberMe +
'}';
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java | security-modules/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/CallbackServlet.java | package com.baeldung.oauth2.client;
import org.eclipse.microprofile.config.Config;
import javax.inject.Inject;
import javax.json.JsonObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
@WebServlet(urlPatterns = "/callback")
public class CallbackServlet extends AbstractServlet {
@Inject
private Config config;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String clientId = config.getValue("client.clientId", String.class);
String clientSecret = config.getValue("client.clientSecret", String.class);
//Error:
String error = request.getParameter("error");
if (error != null) {
request.setAttribute("error", error);
dispatch("/", request, response);
return;
}
String localState = (String) request.getSession().getAttribute("CLIENT_LOCAL_STATE");
if (!localState.equals(request.getParameter("state"))) {
request.setAttribute("error", "The state attribute doesn't match !!");
dispatch("/", request, response);
return;
}
String code = request.getParameter("code");
Client client = ClientBuilder.newClient();
WebTarget target = client.target(config.getValue("provider.tokenUri", String.class));
Form form = new Form();
form.param("grant_type", "authorization_code");
form.param("code", code);
form.param("redirect_uri", config.getValue("client.redirectUri", String.class));
try {
JsonObject tokenResponse = target.request(MediaType.APPLICATION_JSON_TYPE)
.header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret))
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), JsonObject.class);
request.getSession().setAttribute("tokenResponse", tokenResponse);
} catch (Exception ex) {
System.out.println(ex.getMessage());
request.setAttribute("error", ex.getMessage());
}
dispatch("/", request, response);
}
}
| java | MIT | 4463e58ffb73fe599bac2479abd84598c6e70a1a | 2026-01-04T14:45:57.069771Z | false |
eugenp/tutorials | https://github.com/eugenp/tutorials/blob/4463e58ffb73fe599bac2479abd84598c6e70a1a/security-modules/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AbstractServlet.java | security-modules/oauth2-framework-impl/oauth2-client/src/main/java/com/baeldung/oauth2/client/AbstractServlet.java | package com.baeldung.oauth2.client;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;
public abstract class AbstractServlet extends HttpServlet {
protected void dispatch(String location, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher requestDispatcher = request.getRequestDispatcher(location);
requestDispatcher.forward(request, response);
}
protected String getAuthorizationHeaderValue(String clientId, String clientSecret) {
String token = clientId + ":" + clientSecret;
String encodedString = Base64.getEncoder().encodeToString(token.getBytes());
return "Basic " + encodedString;
}
}
| 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.