Merge branch 'master' into master
This commit is contained in:
commit
428ec8cc6f
|
@ -12,10 +12,10 @@ public class EpochTimeToLocalDateTimeConverterUnitTest {
|
|||
@Test
|
||||
public void testConvertEpochTimeToLocalDateTime() {
|
||||
long epochTimeMillis = 1624962431000L; // Example epoch time in milliseconds
|
||||
LocalDateTime expectedDateTime = LocalDateTime.of(2021, 6, 29, 12, 13, 51);
|
||||
LocalDateTime expectedDateTime = LocalDateTime.of(2021, 6, 29, 10, 27, 11);
|
||||
|
||||
Instant instant = Instant.ofEpochMilli(epochTimeMillis);
|
||||
ZoneId zoneId = ZoneId.systemDefault();
|
||||
ZoneId zoneId = ZoneId.of("UTC");
|
||||
LocalDateTime actualDateTime = instant.atZone(zoneId).toLocalDateTime();
|
||||
|
||||
assertEquals(expectedDateTime, actualDateTime);
|
||||
|
|
|
@ -35,7 +35,7 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<spring.version>6.0.10</spring.version>
|
||||
<spring.version>6.0.12</spring.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -4,4 +4,4 @@ This module contains articles about RSocket in Spring Framework 6.
|
|||
|
||||
### Relevant articles
|
||||
- [RSocket Interface in Spring 6](https://www.baeldung.com/spring-rsocket)
|
||||
- [Introduction to RSocket](#)
|
||||
|
||||
|
|
|
@ -9,9 +9,10 @@
|
|||
<description>This is simple boot application for Spring boot actuator test</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.spring-boot-modules</groupId>
|
||||
<artifactId>spring-boot-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-3</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -39,16 +40,6 @@
|
|||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
|
|
|
@ -1,36 +1,56 @@
|
|||
package com.baeldung.endpoints.enabling;
|
||||
|
||||
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
|
||||
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
@Configuration
|
||||
public class SecurityConfiguration {
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
|
||||
auth.inMemoryAuthentication()
|
||||
.withUser("user")
|
||||
.password(encoder.encode("password"))
|
||||
.roles("USER")
|
||||
.and()
|
||||
.withUser("admin")
|
||||
.password(encoder.encode("admin"))
|
||||
.roles("USER", "ADMIN");
|
||||
@Bean
|
||||
MvcRequestMatcher.Builder mvc(HandlerMappingIntrospector introspector) {
|
||||
return new MvcRequestMatcher.Builder(introspector);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.requestMatcher(EndpointRequest.toAnyEndpoint())
|
||||
.authorizeRequests((requests) -> requests.anyRequest()
|
||||
.hasRole("ADMIN"));
|
||||
http.httpBasic();
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http, MvcRequestMatcher.Builder mvc) throws Exception {
|
||||
http.httpBasic(Customizer.withDefaults());
|
||||
http.securityMatcher(EndpointRequest.toAnyEndpoint());
|
||||
http.authorizeHttpRequests(authz -> {
|
||||
authz.requestMatchers(mvc.pattern("/actuator/**"))
|
||||
.hasRole("ADMIN")
|
||||
.anyRequest()
|
||||
.authenticated();
|
||||
});
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Bean
|
||||
public InMemoryUserDetailsManager userDetailsService() {
|
||||
UserDetails user = User.withDefaultPasswordEncoder()
|
||||
.username("user")
|
||||
.password("password")
|
||||
.roles("USER")
|
||||
.build();
|
||||
UserDetails admin = User.withDefaultPasswordEncoder()
|
||||
.username("admin")
|
||||
.password("password")
|
||||
.roles("USER", "ADMIN")
|
||||
.build();
|
||||
return new InMemoryUserDetailsManager(user, admin);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
package com.baeldung.endpoints.info;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
|
|
|
@ -15,7 +15,7 @@ import org.springframework.context.annotation.ComponentScan;
|
|||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.web.context.request.RequestContextListener;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import jakarta.servlet.ServletContext;
|
||||
|
||||
@EnableScheduling
|
||||
@ComponentScan("com.baeldung.metrics")
|
||||
|
|
|
@ -7,14 +7,14 @@ import org.springframework.stereotype.Component;
|
|||
import org.springframework.web.context.WebApplicationContext;
|
||||
import org.springframework.web.context.support.WebApplicationContextUtils;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.FilterConfig;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.Filter;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.FilterConfig;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.ServletRequest;
|
||||
import jakarta.servlet.ServletResponse;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
@Component
|
||||
public class MetricFilter implements Filter {
|
||||
|
|
|
@ -13,20 +13,20 @@ import org.springframework.test.web.servlet.MockMvc;
|
|||
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
public class EndpointEnablingIntegrationTest {
|
||||
class EndpointEnablingIntegrationTest {
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "user", password = "password", roles = "USER")
|
||||
public void givenWrongAuthentication_whenCallingActuator_thenReturns401() throws Exception {
|
||||
void givenWrongAuthentication_whenCallingActuator_thenReturns401() throws Exception {
|
||||
mockMvc.perform(get("/actuator"))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "admin", password = "admin", roles = "ADMIN")
|
||||
public void givenProperAuthentication_whenCallingActuator_thenReturnsExpectedEndpoints() throws Exception {
|
||||
void givenProperAuthentication_whenCallingActuator_thenReturnsExpectedEndpoints() throws Exception {
|
||||
mockMvc.perform(get("/actuator"))
|
||||
.andExpect(jsonPath("$._links").exists())
|
||||
.andExpect(jsonPath("$._links.beans").exists())
|
||||
|
|
|
@ -9,9 +9,10 @@
|
|||
<description>Module For Spring Boot MVC Web</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.spring-boot-modules</groupId>
|
||||
<artifactId>spring-boot-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-3</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
|
|
@ -4,10 +4,10 @@ import java.io.IOException;
|
|||
import java.io.PrintWriter;
|
||||
import java.util.Objects;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServlet;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
public class HelloWorldServlet extends HttpServlet {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
|
|
@ -4,10 +4,10 @@ import java.io.IOException;
|
|||
import java.io.PrintWriter;
|
||||
import java.util.Objects;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServlet;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
public class SpringHelloWorldServlet extends HttpServlet {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
|
|
@ -2,7 +2,7 @@ package com.baeldung.common.error;
|
|||
|
||||
import org.springframework.boot.web.servlet.ServletRegistrationBean;
|
||||
|
||||
import javax.servlet.Servlet;
|
||||
import jakarta.servlet.Servlet;
|
||||
|
||||
public class SpringHelloServletRegistrationBean extends ServletRegistrationBean {
|
||||
|
||||
|
|
|
@ -4,9 +4,9 @@ import org.springframework.web.WebApplicationInitializer;
|
|||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
import org.springframework.web.context.support.XmlWebApplicationContext;
|
||||
import org.springframework.web.servlet.DispatcherServlet;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRegistration;
|
||||
import jakarta.servlet.ServletContext;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.ServletRegistration;
|
||||
|
||||
public class WebAppInitializer implements WebApplicationInitializer {
|
||||
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
package com.baeldung.servlets.servlets;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServlet;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
package com.baeldung.servlets.servlets.javaee;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.annotation.WebServlet;
|
||||
import jakarta.servlet.http.HttpServlet;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@WebServlet(name = "AnnotationServlet", description = "Example Servlet Using Annotations", urlPatterns = { "/annotationservlet" })
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
package com.baeldung.servlets.servlets.javaee;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServlet;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package com.baeldung.utils;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import jakarta.annotation.security.RolesAllowed;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package com.baeldung.utils.controller;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
|
|
|
@ -1,32 +1,34 @@
|
|||
package com.baeldung.utils;
|
||||
|
||||
import com.baeldung.utils.controller.UtilsController;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import static org.mockito.MockitoAnnotations.openMocks;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
public class UtilsControllerIntegrationTest {
|
||||
class UtilsControllerIntegrationTest {
|
||||
|
||||
@InjectMocks
|
||||
private UtilsController utilsController;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Before
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
openMocks(this);
|
||||
this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController).build();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception {
|
||||
void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception {
|
||||
String param = "testparam";
|
||||
this.mockMvc.perform(post("/setParam").param("param", param).sessionAttr("parameter", param)).andExpect(status().isOk());
|
||||
}
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
## Spring Cloud Gateway
|
||||
|
||||
This module contains articles about Spring Cloud Gateway
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Exploring the New Spring Cloud Gateway](http://www.baeldung.com/spring-cloud-gateway)
|
|
@ -0,0 +1,54 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>gateway-2</artifactId>
|
||||
<name>gateway-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit</groupId>
|
||||
<artifactId>junit-bom</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>${spring-cloud-dependencies.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-dependencies</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-gateway</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<spring-cloud-dependencies.version>2021.0.3</spring-cloud-dependencies.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.springcloudgateway.custompredicates;
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
|
||||
@SpringBootApplication
|
||||
public class CustomPredicatesApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
new SpringApplicationBuilder(CustomPredicatesApplication.class)
|
||||
.profiles("customroutes")
|
||||
.run(args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.springcloudgateway.custompredicates.config;
|
||||
|
||||
import org.springframework.cloud.gateway.route.RouteLocator;
|
||||
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.baeldung.springcloudgateway.custompredicates.factories.GoldenCustomerRoutePredicateFactory;
|
||||
import com.baeldung.springcloudgateway.custompredicates.factories.GoldenCustomerRoutePredicateFactory.Config;
|
||||
import com.baeldung.springcloudgateway.custompredicates.service.GoldenCustomerService;
|
||||
|
||||
@Configuration
|
||||
public class CustomPredicatesConfig {
|
||||
|
||||
|
||||
@Bean
|
||||
public GoldenCustomerRoutePredicateFactory goldenCustomer(GoldenCustomerService goldenCustomerService) {
|
||||
return new GoldenCustomerRoutePredicateFactory(goldenCustomerService);
|
||||
}
|
||||
|
||||
|
||||
//@Bean
|
||||
public RouteLocator routes(RouteLocatorBuilder builder, GoldenCustomerRoutePredicateFactory gf ) {
|
||||
|
||||
return builder.routes()
|
||||
.route("dsl_golden_route", r ->
|
||||
r.predicate(gf.apply(new Config(true, "customerId")))
|
||||
.and()
|
||||
.path("/dsl_api/**")
|
||||
.filters(f -> f.stripPrefix(1))
|
||||
.uri("https://httpbin.org")
|
||||
)
|
||||
.route("dsl_common_route", r ->
|
||||
r.predicate(gf.apply(new Config(false, "customerId")))
|
||||
.and()
|
||||
.path("/dsl_api/**")
|
||||
.filters(f -> f.stripPrefix(1))
|
||||
.uri("https://httpbin.org")
|
||||
)
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,102 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.springcloudgateway.custompredicates.factories;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
|
||||
import org.springframework.http.HttpCookie;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
import com.baeldung.springcloudgateway.custompredicates.service.GoldenCustomerService;
|
||||
|
||||
/**
|
||||
* @author Philippe
|
||||
*
|
||||
*/
|
||||
public class GoldenCustomerRoutePredicateFactory extends AbstractRoutePredicateFactory<GoldenCustomerRoutePredicateFactory.Config> {
|
||||
|
||||
private final GoldenCustomerService goldenCustomerService;
|
||||
|
||||
public GoldenCustomerRoutePredicateFactory(GoldenCustomerService goldenCustomerService ) {
|
||||
super(Config.class);
|
||||
this.goldenCustomerService = goldenCustomerService;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<String> shortcutFieldOrder() {
|
||||
return Arrays.asList("isGolden","customerIdCookie");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Predicate<ServerWebExchange> apply(Config config) {
|
||||
|
||||
return (ServerWebExchange t) -> {
|
||||
List<HttpCookie> cookies = t.getRequest()
|
||||
.getCookies()
|
||||
.get(config.getCustomerIdCookie());
|
||||
|
||||
boolean isGolden;
|
||||
if ( cookies == null || cookies.isEmpty()) {
|
||||
isGolden = false;
|
||||
}
|
||||
else {
|
||||
String customerId = cookies.get(0).getValue();
|
||||
isGolden = goldenCustomerService.isGoldenCustomer(customerId);
|
||||
}
|
||||
|
||||
return config.isGolden()?isGolden:!isGolden;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@Validated
|
||||
public static class Config {
|
||||
boolean isGolden = true;
|
||||
|
||||
@NotEmpty
|
||||
String customerIdCookie = "customerId";
|
||||
|
||||
|
||||
public Config() {}
|
||||
|
||||
public Config( boolean isGolden, String customerIdCookie) {
|
||||
this.isGolden = isGolden;
|
||||
this.customerIdCookie = customerIdCookie;
|
||||
}
|
||||
|
||||
public boolean isGolden() {
|
||||
return isGolden;
|
||||
}
|
||||
|
||||
public void setGolden(boolean value) {
|
||||
this.isGolden = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the customerIdCookie
|
||||
*/
|
||||
public String getCustomerIdCookie() {
|
||||
return customerIdCookie;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param customerIdCookie the customerIdCookie to set
|
||||
*/
|
||||
public void setCustomerIdCookie(String customerIdCookie) {
|
||||
this.customerIdCookie = customerIdCookie;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.springcloudgateway.custompredicates.service;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @author Philippe
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class GoldenCustomerService {
|
||||
|
||||
public boolean isGoldenCustomer(String customerId) {
|
||||
|
||||
// TODO: Add some AI logic to check is this customer deserves a "golden" status ;^)
|
||||
if ( "baeldung".equalsIgnoreCase(customerId)) {
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.springcloudgateway.introduction;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
|
||||
@SpringBootApplication
|
||||
@PropertySource("classpath:introduction-application.properties")
|
||||
public class IntroductionGatewayApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(IntroductionGatewayApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
spring:
|
||||
cloud:
|
||||
gateway:
|
||||
routes:
|
||||
- id: golden_route
|
||||
uri: https://httpbin.org
|
||||
predicates:
|
||||
- Path=/api/**
|
||||
- GoldenCustomer=true
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
- AddRequestHeader=GoldenCustomer,true
|
||||
- id: common_route
|
||||
uri: https://httpbin.org
|
||||
predicates:
|
||||
- Path=/api/**
|
||||
- name: GoldenCustomer
|
||||
args:
|
||||
golden: false
|
||||
customerIdCookie: customerId
|
||||
filters:
|
||||
- StripPrefix=1
|
||||
- AddRequestHeader=GoldenCustomer,false
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
logging:
|
||||
level:
|
||||
org.springframework.cloud.gateway: DEBUG
|
||||
reactor.netty.http.client: DEBUG
|
|
@ -0,0 +1,7 @@
|
|||
spring.cloud.gateway.routes[0].id=baeldung_route
|
||||
spring.cloud.gateway.routes[0].uri=http://www.baeldung.com
|
||||
spring.cloud.gateway.routes[0].predicates[0]=Path=/baeldung
|
||||
|
||||
management.endpoints.web.exposure.include=*
|
||||
|
||||
server.port=80
|
|
@ -0,0 +1,13 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
|
@ -0,0 +1,67 @@
|
|||
package com.baeldung.springcloudgateway.custompredicates;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.json.JSONTokener;
|
||||
import org.junit.Before;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.boot.web.server.LocalServerPort;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.RequestEntity;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
/**
|
||||
* This test requires
|
||||
*/
|
||||
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
|
||||
@ActiveProfiles("customroutes")
|
||||
public class CustomPredicatesApplicationLiveTest {
|
||||
|
||||
@LocalServerPort
|
||||
String serverPort;
|
||||
|
||||
@Autowired
|
||||
private TestRestTemplate restTemplate;
|
||||
|
||||
@Test
|
||||
void givenNormalCustomer_whenCallHeadersApi_thenResponseForNormalCustomer() throws JSONException {
|
||||
|
||||
String url = "http://localhost:" + serverPort + "/api/headers";
|
||||
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
|
||||
JSONObject json = new JSONObject(response.getBody());
|
||||
JSONObject headers = json.getJSONObject("headers");
|
||||
assertThat(headers.getString("Goldencustomer")).isEqualTo("false");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenGoldenCustomer_whenCallHeadersApi_thenResponseForGoldenCustomer() throws JSONException {
|
||||
|
||||
String url = "http://localhost:" + serverPort + "/api/headers";
|
||||
RequestEntity<Void> request = RequestEntity
|
||||
.get(URI.create(url))
|
||||
.header("Cookie", "customerId=baeldung")
|
||||
.build();
|
||||
|
||||
ResponseEntity<String> response = restTemplate.exchange(request, String.class);
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
|
||||
JSONObject json = new JSONObject(response.getBody());
|
||||
JSONObject headers = json.getJSONObject("headers");
|
||||
assertThat(headers.getString("Goldencustomer")).isEqualTo("true");
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.springcloudgateway.introduction;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.AppenderBase;
|
||||
|
||||
public class LoggerListAppender extends AppenderBase<ILoggingEvent> {
|
||||
|
||||
static private List<ILoggingEvent> events = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
protected void append(ILoggingEvent eventObject) {
|
||||
events.add(eventObject);
|
||||
}
|
||||
|
||||
public static List<ILoggingEvent> getEvents() {
|
||||
return events;
|
||||
}
|
||||
|
||||
public static void clearEventList() {
|
||||
events.clear();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.springcloudgateway.introduction;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.baeldung.springcloudgateway.introduction.IntroductionGatewayApplication;
|
||||
|
||||
|
||||
@SpringBootTest(classes = IntroductionGatewayApplication.class)
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="LISTAPPENDER"
|
||||
class="com.baeldung.springcloudgateway.introduction.LoggerListAppender">
|
||||
</appender>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
<root level="info">
|
||||
<appender-ref ref="LISTAPPENDER" />
|
||||
</root>
|
||||
<root level="info">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
|
@ -18,6 +18,7 @@
|
|||
<module>config</module>
|
||||
<module>discovery</module>
|
||||
<module>gateway</module>
|
||||
<module>gateway-2</module>
|
||||
<module>svc-book</module>
|
||||
<module>svc-rating</module>
|
||||
<module>customer-service</module>
|
||||
|
|
Loading…
Reference in New Issue