Merge branch 'eugenp:master' into master
This commit is contained in:
@@ -85,7 +85,7 @@
|
||||
<module>spring-boot-redis</module>
|
||||
<module>spring-boot-cassandre</module>
|
||||
<module>spring-boot-react</module>
|
||||
<module>spring-boot-3</module>
|
||||
<!-- <module>spring-boot-3</module> --> <!-- JAVA-20931 -->
|
||||
<module>spring-boot-3-native</module>
|
||||
<module>spring-boot-3-observation</module>
|
||||
<module>spring-boot-3-test-pitfalls</module>
|
||||
|
||||
@@ -56,10 +56,15 @@
|
||||
<configuration>
|
||||
<jvmArguments> -agentlib:native-image-agent=config-output-dir=target/native-image
|
||||
</jvmArguments>
|
||||
<systemPropertyVariables>
|
||||
<springAot>true</springAot>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>process-aot</id>
|
||||
<goals>
|
||||
<goal>process-aot</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin> -->
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
|
||||
@@ -116,6 +116,7 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.virtualthreads.VirtualThreadsApp</mainClass>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
@@ -131,15 +132,23 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<java.version>19</java.version>
|
||||
<mapstruct.version>1.5.2.Final</mapstruct.version>
|
||||
<springdoc.version>2.0.0</springdoc.version>
|
||||
<maven-surefire-plugin.version>3.0.0-M7</maven-surefire-plugin.version>
|
||||
<start-class>com.baeldung.sample.TodoApplication</start-class>
|
||||
<mockserver.version>5.14.0</mockserver.version>
|
||||
<mockserver.version>5.14.0</mockserver.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.virtualthreads;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class VirtualThreadsApp {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(VirtualThreadsApp.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.virtualthreads.config;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.web.embedded.tomcat.TomcatProtocolHandlerCustomizer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.task.AsyncTaskExecutor;
|
||||
import org.springframework.core.task.support.TaskExecutorAdapter;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
@EnableAsync
|
||||
@Configuration
|
||||
@ConditionalOnProperty(
|
||||
value = "spring.thread-executor",
|
||||
havingValue = "virtual"
|
||||
)
|
||||
public class ThreadConfig {
|
||||
|
||||
@Bean
|
||||
public AsyncTaskExecutor applicationTaskExecutor() {
|
||||
return new TaskExecutorAdapter(Executors.newVirtualThreadPerTaskExecutor());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public TomcatProtocolHandlerCustomizer<?> protocolHandlerVirtualThreadExecutorCustomizer() {
|
||||
return protocolHandler -> {
|
||||
protocolHandler.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.virtualthreads.controller;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/load")
|
||||
public class LoadTestController {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(LoadTestController.class);
|
||||
|
||||
@GetMapping
|
||||
public void doSomething() throws InterruptedException {
|
||||
LOG.info("hey, I'm doing something");
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.virtualthreads.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/thread")
|
||||
public class ThreadController {
|
||||
|
||||
@GetMapping("/name")
|
||||
public String getThreadName() {
|
||||
return Thread.currentThread().toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -14,8 +14,10 @@ spring:
|
||||
properties:
|
||||
hibernate:
|
||||
dialect: org.hibernate.dialect.H2Dialect
|
||||
thread-executor: standard
|
||||
|
||||
# Custom Properties
|
||||
cors:
|
||||
allow:
|
||||
origins: ${CORS_ALLOWED_ORIGINS:*}
|
||||
credentials: ${CORS_ALLOW_CREDENTIALS:false}
|
||||
credentials: ${CORS_ALLOW_CREDENTIALS:false}
|
||||
@@ -0,0 +1,125 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.5">
|
||||
<hashTree>
|
||||
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Test Plan" enabled="true">
|
||||
<stringProp name="TestPlan.comments"></stringProp>
|
||||
<boolProp name="TestPlan.functional_mode">false</boolProp>
|
||||
<boolProp name="TestPlan.tearDown_on_shutdown">true</boolProp>
|
||||
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
|
||||
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
|
||||
<collectionProp name="Arguments.arguments"/>
|
||||
</elementProp>
|
||||
<stringProp name="TestPlan.user_define_classpath"></stringProp>
|
||||
</TestPlan>
|
||||
<hashTree>
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Thread Group" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">stoptest</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<intProp name="LoopController.loops">-1</intProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">1000</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">10</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">true</boolProp>
|
||||
<stringProp name="ThreadGroup.duration">100</stringProp>
|
||||
<stringProp name="ThreadGroup.delay"></stringProp>
|
||||
<boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Load Request " enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
|
||||
<collectionProp name="Arguments.arguments"/>
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">localhost</stringProp>
|
||||
<stringProp name="HTTPSampler.port">8080</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol"></stringProp>
|
||||
<stringProp name="HTTPSampler.contentEncoding"></stringProp>
|
||||
<stringProp name="HTTPSampler.path">/load</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">true</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
<stringProp name="HTTPSampler.embedded_url_re"></stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout"></stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout"></stringProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree/>
|
||||
</hashTree>
|
||||
<ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="View Results Tree" enabled="true">
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
<objProp>
|
||||
<name>saveConfig</name>
|
||||
<value class="SampleSaveConfiguration">
|
||||
<time>true</time>
|
||||
<latency>true</latency>
|
||||
<timestamp>true</timestamp>
|
||||
<success>true</success>
|
||||
<label>true</label>
|
||||
<code>true</code>
|
||||
<message>true</message>
|
||||
<threadName>true</threadName>
|
||||
<dataType>true</dataType>
|
||||
<encoding>false</encoding>
|
||||
<assertions>true</assertions>
|
||||
<subresults>true</subresults>
|
||||
<responseData>false</responseData>
|
||||
<samplerData>false</samplerData>
|
||||
<xml>false</xml>
|
||||
<fieldNames>true</fieldNames>
|
||||
<responseHeaders>false</responseHeaders>
|
||||
<requestHeaders>false</requestHeaders>
|
||||
<responseDataOnError>false</responseDataOnError>
|
||||
<saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
|
||||
<assertionsResultsToSave>0</assertionsResultsToSave>
|
||||
<bytes>true</bytes>
|
||||
<sentBytes>true</sentBytes>
|
||||
<url>true</url>
|
||||
<threadCounts>true</threadCounts>
|
||||
<idleTime>true</idleTime>
|
||||
<connectTime>true</connectTime>
|
||||
</value>
|
||||
</objProp>
|
||||
<stringProp name="filename"></stringProp>
|
||||
</ResultCollector>
|
||||
<hashTree/>
|
||||
<ResultCollector guiclass="RespTimeGraphVisualizer" testclass="ResultCollector" testname="Response Time Graph" enabled="true">
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
<objProp>
|
||||
<name>saveConfig</name>
|
||||
<value class="SampleSaveConfiguration">
|
||||
<time>true</time>
|
||||
<latency>true</latency>
|
||||
<timestamp>true</timestamp>
|
||||
<success>true</success>
|
||||
<label>true</label>
|
||||
<code>true</code>
|
||||
<message>true</message>
|
||||
<threadName>true</threadName>
|
||||
<dataType>true</dataType>
|
||||
<encoding>false</encoding>
|
||||
<assertions>true</assertions>
|
||||
<subresults>true</subresults>
|
||||
<responseData>false</responseData>
|
||||
<samplerData>false</samplerData>
|
||||
<xml>false</xml>
|
||||
<fieldNames>true</fieldNames>
|
||||
<responseHeaders>false</responseHeaders>
|
||||
<requestHeaders>false</requestHeaders>
|
||||
<responseDataOnError>false</responseDataOnError>
|
||||
<saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
|
||||
<assertionsResultsToSave>0</assertionsResultsToSave>
|
||||
<bytes>true</bytes>
|
||||
<sentBytes>true</sentBytes>
|
||||
<url>true</url>
|
||||
<threadCounts>true</threadCounts>
|
||||
<idleTime>true</idleTime>
|
||||
<connectTime>true</connectTime>
|
||||
</value>
|
||||
</objProp>
|
||||
<stringProp name="filename"></stringProp>
|
||||
</ResultCollector>
|
||||
<hashTree/>
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
</jmeterTestPlan>
|
||||
@@ -0,0 +1,38 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
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>spring-boot-cli</artifactId>
|
||||
<name>spring-boot-cli</name>
|
||||
<packaging>jar</packaging>
|
||||
<description></description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.spring-boot-modules</groupId>
|
||||
<artifactId>spring-boot-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class LoginController {
|
||||
|
||||
@GetMapping("/")
|
||||
public String hello() {
|
||||
return "Hello World!";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
spring.security.user.name=baeldung
|
||||
# Encoded password with SpringBoot CLI, the decoded password is baeldungPassword
|
||||
spring.security.user.password={bcrypt}$2y$10$R8VIwFiQ7aUST17YqMaWJuxjkCYqk3jjPlSxyDLLzqCTOwFuJNq2a
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.encoding;
|
||||
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
|
||||
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
@AutoConfigureMockMvc
|
||||
public class PasswordEncodingUnitTest {
|
||||
private final static String userName = "baeldung";
|
||||
private final static String passwordDecoded = "baeldungPassword";
|
||||
|
||||
private MockMvc mvc;
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext webApplicationContext;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
|
||||
.apply(springSecurity())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestWithWrongPassword_shouldFailWith401() throws Exception {
|
||||
mvc.perform(get("/").with(httpBasic(userName, "wrongPassword")))
|
||||
.andExpect(status().isUnauthorized());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestWithCorrectDecodedPassword_houldSucceedWith200() throws Exception {
|
||||
mvc.perform(get("/").with(httpBasic(userName, passwordDecoded)))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
### Relevant Articles:
|
||||
- [Spring Data JPA – Run an App Without a Database](https://www.baeldung.com/spring-data-jpa-run-app-without-db)
|
||||
- [Integrate AWS Secrets Manager in Spring Boot](https://www.baeldung.com/spring-boot-integrate-aws-secrets-manager)
|
||||
- [Fix Spring Data JPA Exception: No Property Found for Type](https://www.baeldung.com/spring-data-jpa-exception-no-property-found-for-type)
|
||||
|
||||
@@ -9,4 +9,5 @@ This module contains articles about various Spring Boot libraries
|
||||
- [An Introduction to Kong](https://www.baeldung.com/kong)
|
||||
- [Scanning Java Annotations At Runtime](https://www.baeldung.com/java-scan-annotations-runtime)
|
||||
- [Guide to Resilience4j With Spring Boot](https://www.baeldung.com/spring-boot-resilience4j)
|
||||
More articles: [[prev -->]](/spring-boot-modules/spring-boot-libraries)
|
||||
- [Using OpenAI ChatGPT APIs in Spring Boot](https://www.baeldung.com/spring-boot-chatgpt-api-openai)
|
||||
- More articles: [[prev -->]](/spring-boot-modules/spring-boot-libraries)
|
||||
|
||||
@@ -11,6 +11,18 @@
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.experimental</groupId>
|
||||
<artifactId>spring-modulith-bom</artifactId>
|
||||
<version>0.5.1</version>
|
||||
<scope>import</scope>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
@@ -87,6 +99,15 @@
|
||||
<version>2.34.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.experimental</groupId>
|
||||
<artifactId>spring-modulith-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.experimental</groupId>
|
||||
<artifactId>spring-modulith-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.modulith;
|
||||
|
||||
import com.baeldung.modulith.product.ProductService;
|
||||
import com.baeldung.modulith.product.internal.Product;
|
||||
import org.jobrunr.autoconfigure.JobRunrAutoConfiguration;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
|
||||
@EnableAsync
|
||||
@SpringBootApplication
|
||||
@EnableAutoConfiguration(exclude = { JobRunrAutoConfiguration.class})
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args)
|
||||
.getBean(ProductService.class)
|
||||
.create(new Product("baeldung", "course", 10));
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.modulith.notification;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class NotificationDTO {
|
||||
private Date date;
|
||||
private String format;
|
||||
private String productName;
|
||||
|
||||
public NotificationDTO(Date date, String format, String productName) {
|
||||
this.date = date;
|
||||
this.format = format;
|
||||
this.productName = productName;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public String getFormat() {
|
||||
return format;
|
||||
}
|
||||
|
||||
public void setFormat(String format) {
|
||||
this.format = format;
|
||||
}
|
||||
|
||||
public String getProductName() {
|
||||
return productName;
|
||||
}
|
||||
|
||||
public void setProductName(String productName) {
|
||||
this.productName = productName;
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.modulith.notification;
|
||||
|
||||
import com.baeldung.modulith.notification.internal.Notification;
|
||||
import com.baeldung.modulith.notification.internal.NotificationType;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.modulith.ApplicationModuleListener;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class NotificationService {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(NotificationService.class);
|
||||
|
||||
public void createNotification(NotificationDTO notificationDTO) {
|
||||
Notification notification = toEntity(notificationDTO);
|
||||
LOG.info("Received notification by module dependency for product {} in date {} by {}.", notification.getProductName()
|
||||
, notification.getDate(), notification.getFormat());
|
||||
}
|
||||
|
||||
@Async
|
||||
@ApplicationModuleListener
|
||||
public void notificationEvent(NotificationDTO event) {
|
||||
Notification notification = toEntity(event);
|
||||
LOG.info("Received notification by event for product {} in date {} by {}.", notification.getProductName()
|
||||
, notification.getDate(), notification.getFormat());
|
||||
}
|
||||
|
||||
private Notification toEntity(NotificationDTO notificationDTO) {
|
||||
Notification notification = new Notification();
|
||||
notification.setDate(notificationDTO.getDate());
|
||||
if (notificationDTO.getFormat().equals("SMS")) {
|
||||
notification.setFormat(NotificationType.SMS);
|
||||
}
|
||||
if (notificationDTO.getFormat().equals("EMAIL")) {
|
||||
notification.setFormat(NotificationType.EMAIL);
|
||||
}
|
||||
notification.setProductName(notificationDTO.getProductName());
|
||||
return notification;
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.modulith.notification.internal;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class Notification {
|
||||
private Date date;
|
||||
private NotificationType format;
|
||||
private String productName;
|
||||
|
||||
public Notification() {
|
||||
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public NotificationType getFormat() {
|
||||
return format;
|
||||
}
|
||||
|
||||
public void setFormat(NotificationType format) {
|
||||
this.format = format;
|
||||
}
|
||||
|
||||
public String getProductName() {
|
||||
return productName;
|
||||
}
|
||||
|
||||
public void setProductName(String productName) {
|
||||
this.productName = productName;
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.modulith.notification.internal;
|
||||
|
||||
public enum NotificationType {
|
||||
EMAIL, SMS
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.modulith.product;
|
||||
|
||||
import com.baeldung.modulith.notification.NotificationDTO;
|
||||
import com.baeldung.modulith.notification.NotificationService;
|
||||
import com.baeldung.modulith.product.internal.Product;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
@Service
|
||||
public class ProductService {
|
||||
|
||||
private final ApplicationEventPublisher events;
|
||||
private final NotificationService notificationService;
|
||||
|
||||
public ProductService(ApplicationEventPublisher events, NotificationService notificationService) {
|
||||
this.events = events;
|
||||
this.notificationService = notificationService;
|
||||
}
|
||||
|
||||
public void create(Product product) {
|
||||
notificationService.createNotification(new NotificationDTO(new Date(), "SMS", product.getName()));
|
||||
events.publishEvent(new NotificationDTO(new Date(), "SMS", product.getName()));
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.modulith.product.internal;
|
||||
|
||||
public class Product {
|
||||
|
||||
private String name;
|
||||
private String description;
|
||||
private int price;
|
||||
|
||||
public Product(String name, String description, int price) {
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public int getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(int price) {
|
||||
this.price = price;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.openapi.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@Configuration
|
||||
public class OpenAIRestTemplateConfig {
|
||||
|
||||
@Value("${openai.api.key}")
|
||||
private String openaiApiKey;
|
||||
|
||||
@Bean
|
||||
@Qualifier("openaiRestTemplate")
|
||||
public RestTemplate openaiRestTemplate() {
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
restTemplate.getInterceptors().add((request, body, execution) -> {
|
||||
request.getHeaders().add("Authorization", "Bearer " + openaiApiKey);
|
||||
return execution.execute(request, body);
|
||||
});
|
||||
return restTemplate;
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.openapi.controller;
|
||||
|
||||
import com.baeldung.openapi.dto.ChatRequest;
|
||||
import com.baeldung.openapi.dto.ChatResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@RestController
|
||||
public class ChatController {
|
||||
|
||||
@Qualifier("openaiRestTemplate")
|
||||
@Autowired
|
||||
private RestTemplate restTemplate;
|
||||
|
||||
@Value("${openai.model}")
|
||||
private String model;
|
||||
|
||||
@Value("${openai.api.url}")
|
||||
private String apiUrl;
|
||||
|
||||
/**
|
||||
* Creates a chat request and sends it to the OpenAI API
|
||||
* Returns the first message from the API response
|
||||
*
|
||||
* @param prompt the prompt to send to the API
|
||||
* @return first message from the API response
|
||||
*/
|
||||
@GetMapping("/chat")
|
||||
public String chat(@RequestParam String prompt) {
|
||||
ChatRequest request = new ChatRequest(model, prompt);
|
||||
|
||||
ChatResponse response = restTemplate.postForObject(
|
||||
apiUrl,
|
||||
request,
|
||||
ChatResponse.class);
|
||||
|
||||
if (response == null || response.getChoices() == null || response.getChoices().isEmpty()) {
|
||||
return "No response";
|
||||
}
|
||||
|
||||
return response.getChoices().get(0).getMessage().getContent();
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.openapi.dto;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ChatRequest {
|
||||
private String model;
|
||||
private List<Message> messages;
|
||||
|
||||
public ChatRequest(String model, String prompt) {
|
||||
this.model = model;
|
||||
|
||||
this.messages = new ArrayList<>();
|
||||
this.messages.add(new Message("user", prompt));
|
||||
}
|
||||
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public void setModel(String model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public List<Message> getMessages() {
|
||||
return messages;
|
||||
}
|
||||
|
||||
public void setMessages(List<Message> messages) {
|
||||
this.messages = messages;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.openapi.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ChatResponse {
|
||||
|
||||
private List<Choice> choices;
|
||||
|
||||
public static class Choice {
|
||||
|
||||
private int index;
|
||||
private Message message;
|
||||
|
||||
public int getIndex() {
|
||||
return index;
|
||||
}
|
||||
|
||||
public void setIndex(int index) {
|
||||
this.index = index;
|
||||
}
|
||||
|
||||
public Message getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(Message message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
|
||||
public List<Choice> getChoices() {
|
||||
return choices;
|
||||
}
|
||||
|
||||
public void setChoices(List<Choice> choices) {
|
||||
this.choices = choices;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.openapi.dto;
|
||||
|
||||
public class Message {
|
||||
|
||||
private String role;
|
||||
private String content;
|
||||
|
||||
Message(String role, String content) {
|
||||
this.role = role;
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
Message() {
|
||||
}
|
||||
|
||||
public String getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(String role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -47,4 +47,8 @@ resilience4j.ratelimiter.instances.rateLimiterApi.limit-refresh-period=60s
|
||||
resilience4j.ratelimiter.instances.rateLimiterApi.timeout-duration=0s
|
||||
resilience4j.ratelimiter.instances.rateLimiterApi.allow-health-indicator-to-fail=true
|
||||
resilience4j.ratelimiter.instances.rateLimiterApi.subscribe-for-events=true
|
||||
resilience4j.ratelimiter.instances.rateLimiterApi.event-consumer-buffer-size=50
|
||||
resilience4j.ratelimiter.instances.rateLimiterApi.event-consumer-buffer-size=50
|
||||
|
||||
openai.model=gpt-3.5-turbo
|
||||
openai.api.url=https://api.openai.com/v1/chat/completions
|
||||
openai.api.key=your-api-key
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.modulith;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.modulith.core.ApplicationModules;
|
||||
import org.springframework.modulith.docs.Documenter;
|
||||
|
||||
class ApplicationModularityUnitTest {
|
||||
|
||||
ApplicationModules modules = ApplicationModules.of(Application.class);
|
||||
|
||||
@Test
|
||||
void verifiesModularStructure() {
|
||||
modules.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createModuleDocumentation() {
|
||||
new Documenter(modules)
|
||||
.writeDocumentation()
|
||||
.writeIndividualModulesAsPlantUml();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createApplicationModuleModel() {
|
||||
modules.forEach(System.out::println);
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.springboot.swagger.controller;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.springboot.swagger.model.Author;
|
||||
import com.baeldung.springboot.swagger.service.AuthorService;
|
||||
import com.baeldung.springboot.swagger.views.Views;
|
||||
import com.fasterxml.jackson.annotation.JsonView;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/authors")
|
||||
public class AuthorsController {
|
||||
|
||||
@Autowired
|
||||
AuthorService authorService;
|
||||
|
||||
@JsonView(Views.Public.class)
|
||||
@GetMapping
|
||||
public List<Author> getAllAuthors() {
|
||||
return authorService.getAllAuthors();
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public void addAuthor(@RequestBody @JsonView(Views.Public.class) Author author){
|
||||
authorService.addAuthors(author);
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.springboot.swagger.model;
|
||||
|
||||
import com.baeldung.springboot.swagger.views.Views;
|
||||
import com.fasterxml.jackson.annotation.JsonView;
|
||||
|
||||
public class Author {
|
||||
|
||||
@JsonView(Views.Private.class)
|
||||
private Integer id;
|
||||
|
||||
@JsonView(Views.Public.class)
|
||||
private String name;
|
||||
|
||||
@JsonView(Views.Public.class)
|
||||
private String email;
|
||||
|
||||
public Author() {
|
||||
}
|
||||
|
||||
public Author(String name, String email) {
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.springboot.swagger.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.baeldung.springboot.swagger.model.Author;
|
||||
|
||||
@Service
|
||||
public class AuthorService {
|
||||
private List<Author> authors = new ArrayList<>();
|
||||
|
||||
public List<Author> getAllAuthors(){
|
||||
return authors;
|
||||
}
|
||||
|
||||
public void addAuthors(Author author){
|
||||
author.setId(authors.size()+1);
|
||||
authors.add(author);
|
||||
}
|
||||
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.springboot.swagger.views;
|
||||
|
||||
public class Views {
|
||||
public static class Public {
|
||||
}
|
||||
|
||||
public static class Private {
|
||||
}
|
||||
}
|
||||
@@ -11,4 +11,5 @@
|
||||
- [IntelliJ – Cannot Resolve Spring Boot Configuration Properties Error](https://www.baeldung.com/intellij-resolve-spring-boot-configuration-properties)
|
||||
- [Log Properties in a Spring Boot Application](https://www.baeldung.com/spring-boot-log-properties)
|
||||
- [Using Environment Variables in Spring Boot’s application.properties](https://www.baeldung.com/spring-boot-properties-env-variables)
|
||||
- [Loading Multiple YAML Configuration Files in Spring Boot](https://www.baeldung.com/spring-boot-load-multiple-yaml-configuration-files)
|
||||
- More articles: [[<-- prev]](../spring-boot-properties-2)
|
||||
|
||||
+6
-10
@@ -14,7 +14,6 @@ import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
|
||||
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.*;
|
||||
@@ -210,23 +209,20 @@ class ResilientAppControllerIntegrationTest {
|
||||
EXTERNAL_SERVICE.stubFor(WireMock.get("/api/external").willReturn(ok()));
|
||||
Map<Integer, Integer> responseStatusCount = new ConcurrentHashMap<>();
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(5);
|
||||
CountDownLatch latch = new CountDownLatch(5);
|
||||
|
||||
List<Callable<Integer>> tasks = new ArrayList<>();
|
||||
IntStream.rangeClosed(1, 5)
|
||||
.forEach(
|
||||
i ->
|
||||
tasks.add(
|
||||
executorService.execute(
|
||||
() -> {
|
||||
ResponseEntity<String> response =
|
||||
restTemplate.getForEntity("/api/bulkhead", String.class);
|
||||
return response.getStatusCodeValue();
|
||||
int statusCode = response.getStatusCodeValue();
|
||||
responseStatusCount.merge(statusCode, 1, Integer::sum);
|
||||
latch.countDown();
|
||||
}));
|
||||
|
||||
List<Future<Integer>> futures = executorService.invokeAll(tasks);
|
||||
for (Future<Integer> future : futures) {
|
||||
int statusCode = future.get();
|
||||
responseStatusCount.merge(statusCode, 1, Integer::sum);
|
||||
}
|
||||
latch.await();
|
||||
executorService.shutdown();
|
||||
|
||||
assertEquals(2, responseStatusCount.keySet().size());
|
||||
|
||||
@@ -146,7 +146,7 @@
|
||||
<plugin>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-maven-plugin</artifactId>
|
||||
<version>1.4</version>
|
||||
<version>${springdoc-openapi-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
@@ -167,9 +167,10 @@
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<springdoc.version>1.6.8</springdoc.version>
|
||||
<springdoc.version>1.7.0</springdoc.version>
|
||||
<asciidoctor-plugin.version>1.5.6</asciidoctor-plugin.version>
|
||||
<snippetsDirectory>${project.build.directory}/generated-snippets</snippetsDirectory>
|
||||
<springdoc-openapi-maven-plugin.version>1.4</springdoc-openapi-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -1,75 +1,72 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
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>spring-boot-swagger-keycloak</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>spring-boot-swagger-keycloak</name>
|
||||
<packaging>jar</packaging>
|
||||
<description>Module For Spring Boot Swagger UI with Keycloak</description>
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
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>spring-boot-swagger-keycloak</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>spring-boot-swagger-keycloak</name>
|
||||
<packaging>jar</packaging>
|
||||
<description>Module For Spring Boot Swagger UI with Keycloak</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.spring-boot-modules</groupId>
|
||||
<artifactId>spring-boot-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-3</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.keycloak.bom</groupId>
|
||||
<artifactId>keycloak-adapter-bom</artifactId>
|
||||
<version>${keycloak.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-bom</artifactId>
|
||||
<version>${log4j2.version}</version>
|
||||
<scope>import</scope>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-bom</artifactId>
|
||||
<version>${log4j2.version}</version>
|
||||
<scope>import</scope>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.springfox</groupId>
|
||||
<artifactId>springfox-boot-starter</artifactId>
|
||||
<version>${springfox.version}</version>
|
||||
</dependency>
|
||||
<!-- Authentication with with Keycloak -->
|
||||
<dependency>
|
||||
<groupId>org.keycloak</groupId>
|
||||
<artifactId>keycloak-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<!-- Authorization with MethodSecurity (@Secured) - optional -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
|
||||
</dependency>
|
||||
<!-- Authorization with MethodSecurity (@Secured) - optional -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
<version>${springdoc.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.annotation</groupId>
|
||||
<artifactId>javax.annotation-api</artifactId>
|
||||
<version>${javax.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<spring-boot.version>2.4.5</spring-boot.version>
|
||||
<springfox.version>3.0.0</springfox.version>
|
||||
<keycloak.version>15.0.2</keycloak.version>
|
||||
<log4j2.version>2.17.1</log4j2.version>
|
||||
</properties>
|
||||
<properties>
|
||||
<springdoc.version>2.1.0</springdoc.version>
|
||||
<log4j2.version>2.17.1</log4j2.version>
|
||||
<javax.version>1.3.2</javax.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+23
-42
@@ -1,59 +1,40 @@
|
||||
package com.baeldung.swaggerkeycloak;
|
||||
|
||||
import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
|
||||
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
|
||||
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
|
||||
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
|
||||
import org.springframework.security.core.session.SessionRegistryImpl;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
|
||||
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
|
||||
|
||||
@KeycloakConfiguration
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
public class GlobalSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
|
||||
public class GlobalSecurityConfig {
|
||||
|
||||
@Override
|
||||
@Bean
|
||||
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
|
||||
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
|
||||
}
|
||||
|
||||
// otherwise, we'll get an error 'permitAll only works with HttpSecurity.authorizeRequests()'
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
super.configure(http);
|
||||
http
|
||||
.csrf().disable()
|
||||
.authorizeRequests()
|
||||
// we can set up authorization here alternatively to @Secured methods
|
||||
.antMatchers(HttpMethod.OPTIONS).permitAll()
|
||||
.antMatchers("/api/**").authenticated()
|
||||
// force authentication for all requests (and use global method security)
|
||||
.anyRequest().permitAll();
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http.csrf()
|
||||
.disable()
|
||||
.authorizeRequests()
|
||||
.requestMatchers(HttpMethod.OPTIONS)
|
||||
.permitAll()
|
||||
.requestMatchers("/api/**")
|
||||
.authenticated()
|
||||
.anyRequest()
|
||||
.permitAll();
|
||||
http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
/*
|
||||
* re-configure Spring Security to use
|
||||
* registers the KeycloakAuthenticationProvider with the authentication manager
|
||||
*/
|
||||
@Autowired
|
||||
void configureGlobal(AuthenticationManagerBuilder auth) {
|
||||
KeycloakAuthenticationProvider provider = keycloakAuthenticationProvider();
|
||||
provider.setGrantedAuthoritiesMapper(authoritiesMapper());
|
||||
auth.authenticationProvider(provider);
|
||||
}
|
||||
|
||||
GrantedAuthoritiesMapper authoritiesMapper() {
|
||||
SimpleAuthorityMapper mapper = new SimpleAuthorityMapper();
|
||||
mapper.setPrefix("ROLE_"); // Spring Security adds a prefix to the authority/role names (we use the default here)
|
||||
mapper.setConvertToUpperCase(true); // convert names to uppercase
|
||||
mapper.setDefaultAuthority("ROLE_ANONYMOUS"); // set a default authority
|
||||
return mapper;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package com.baeldung.swaggerkeycloak;
|
||||
|
||||
import org.keycloak.adapters.KeycloakConfigResolver;
|
||||
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class KeycloakConfigResolverConfig {
|
||||
|
||||
/*
|
||||
* re-configure keycloak adapter for Spring Boot environment,
|
||||
* i.e. to read config from application.yml
|
||||
* (otherwise, we need a keycloak.json file)
|
||||
*/
|
||||
@Bean
|
||||
public KeycloakConfigResolver configResolver() {
|
||||
return new KeycloakSpringBootConfigResolver();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
+34
-63
@@ -1,22 +1,17 @@
|
||||
package com.baeldung.swaggerkeycloak;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import springfox.documentation.builders.OAuth2SchemeBuilder;
|
||||
import springfox.documentation.service.AuthorizationScope;
|
||||
import springfox.documentation.service.SecurityReference;
|
||||
import springfox.documentation.service.SecurityScheme;
|
||||
import springfox.documentation.spi.service.contexts.SecurityContext;
|
||||
import springfox.documentation.spring.web.plugins.Docket;
|
||||
import springfox.documentation.swagger.web.SecurityConfiguration;
|
||||
import springfox.documentation.swagger.web.SecurityConfigurationBuilder;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import io.swagger.v3.oas.models.Components;
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import io.swagger.v3.oas.models.security.OAuthFlow;
|
||||
import io.swagger.v3.oas.models.security.OAuthFlows;
|
||||
import io.swagger.v3.oas.models.security.Scopes;
|
||||
import io.swagger.v3.oas.models.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.models.security.SecurityScheme;
|
||||
|
||||
@Configuration
|
||||
public class OpenAPISecurityConfig {
|
||||
@@ -25,59 +20,35 @@ public class OpenAPISecurityConfig {
|
||||
String authServerUrl;
|
||||
@Value("${keycloak.realm}")
|
||||
String realm;
|
||||
@Value("${keycloak.resource}")
|
||||
private String clientId;
|
||||
@Value("${keycloak.credentials.secret}")
|
||||
private String clientSecret;
|
||||
|
||||
@Autowired
|
||||
void addSecurity(Docket docket) {
|
||||
docket
|
||||
.securitySchemes(Collections.singletonList(authenticationScheme()))
|
||||
.securityContexts(Collections.singletonList(securityContext()));
|
||||
}
|
||||
|
||||
private SecurityScheme authenticationScheme() {
|
||||
return new OAuth2SchemeBuilder("implicit")
|
||||
.name("my_oAuth_security_schema")
|
||||
.authorizationUrl(authServerUrl + "/realms/" + realm)
|
||||
.scopes(authorizationScopes())
|
||||
.build();
|
||||
}
|
||||
|
||||
private List<AuthorizationScope> authorizationScopes() {
|
||||
return Arrays.asList(
|
||||
new AuthorizationScope("read_access", "read data"),
|
||||
new AuthorizationScope("write_access", "modify data")
|
||||
);
|
||||
}
|
||||
|
||||
private SecurityContext securityContext() {
|
||||
return SecurityContext.
|
||||
builder().
|
||||
securityReferences(readAccessAuth())
|
||||
.operationSelector(operationContext -> HttpMethod.GET.equals(operationContext.httpMethod()))
|
||||
.build();
|
||||
}
|
||||
|
||||
private List<SecurityReference> readAccessAuth() {
|
||||
AuthorizationScope[] authorizationScopes = new AuthorizationScope[] { authorizationScopes().get(0) };
|
||||
return Collections.singletonList(
|
||||
new SecurityReference("my_oAuth_security_schema", authorizationScopes)
|
||||
);
|
||||
}
|
||||
private static final String OAUTH_SCHEME_NAME = "my_oAuth_security_schema";
|
||||
|
||||
@Bean
|
||||
public SecurityConfiguration security() {
|
||||
return SecurityConfigurationBuilder.builder()
|
||||
.clientId(clientId)
|
||||
.clientSecret(clientSecret)
|
||||
.realm(realm)
|
||||
.appName(clientId)
|
||||
.scopeSeparator(",")
|
||||
.additionalQueryStringParams(null)
|
||||
.useBasicAuthenticationWithAccessCodeGrant(false)
|
||||
.build();
|
||||
public OpenAPI openAPI() {
|
||||
return new OpenAPI().components(new Components()
|
||||
.addSecuritySchemes(OAUTH_SCHEME_NAME, createOAuthScheme()))
|
||||
.addSecurityItem(new SecurityRequirement().addList(OAUTH_SCHEME_NAME))
|
||||
.info(new Info().title("Todos Management Service")
|
||||
.description("A service providing todos.")
|
||||
.version("1.0"));
|
||||
}
|
||||
|
||||
private SecurityScheme createOAuthScheme() {
|
||||
OAuthFlows flows = createOAuthFlows();
|
||||
return new SecurityScheme().type(SecurityScheme.Type.OAUTH2)
|
||||
.flows(flows);
|
||||
}
|
||||
|
||||
private OAuthFlows createOAuthFlows() {
|
||||
OAuthFlow flow = createAuthorizationCodeFlow();
|
||||
return new OAuthFlows().implicit(flow);
|
||||
}
|
||||
|
||||
private OAuthFlow createAuthorizationCodeFlow() {
|
||||
return new OAuthFlow()
|
||||
.authorizationUrl(authServerUrl + "/realms/" + realm + "/protocol/openid-connect/auth")
|
||||
.scopes(new Scopes().addString("read_access", "read data")
|
||||
.addString("write_access", "modify data"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
package com.baeldung.swaggerkeycloak;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import springfox.documentation.builders.ApiInfoBuilder;
|
||||
import springfox.documentation.builders.PathSelectors;
|
||||
import springfox.documentation.oas.annotations.EnableOpenApi;
|
||||
import springfox.documentation.service.ApiInfo;
|
||||
import springfox.documentation.spi.DocumentationType;
|
||||
import springfox.documentation.spring.web.plugins.Docket;
|
||||
|
||||
import static springfox.documentation.builders.RequestHandlerSelectors.basePackage;
|
||||
|
||||
@EnableOpenApi
|
||||
@Configuration
|
||||
class SwaggerUIConfig {
|
||||
|
||||
@Bean
|
||||
Docket api() {
|
||||
return new Docket(DocumentationType.OAS_30)
|
||||
.useDefaultResponseMessages(false)
|
||||
.select()
|
||||
.apis(basePackage(TodosApplication.class.getPackage().getName()))
|
||||
.paths(PathSelectors.any())
|
||||
.build()
|
||||
.apiInfo(apiInfo());
|
||||
}
|
||||
|
||||
private ApiInfo apiInfo() {
|
||||
return new ApiInfoBuilder().title("Todos Management Service")
|
||||
.description("A service providing todos.")
|
||||
.version("1.0")
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
||||
+6
-8
@@ -1,14 +1,15 @@
|
||||
package com.baeldung.swaggerkeycloak;
|
||||
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.ApiResponse;
|
||||
import io.swagger.annotations.ApiResponses;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Collection;
|
||||
@@ -28,13 +29,10 @@ public class TodosController {
|
||||
}
|
||||
|
||||
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
@ApiOperation("Read all todos")
|
||||
@ApiResponses({
|
||||
@ApiResponse(code = 200, message = "The todos were found and returned.")
|
||||
})
|
||||
@Operation(description = "Read all todos")
|
||||
@ApiResponses({ @ApiResponse(responseCode = "200", description = "The todos were found and returned.") })
|
||||
@PreAuthorize("hasAuthority('SCOPE_read_access')")
|
||||
public Collection<Todo> readAll() {
|
||||
return todos.values();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
BIN
Binary file not shown.
|
Before Width: | Height: | Size: 665 B |
BIN
Binary file not shown.
|
Before Width: | Height: | Size: 628 B |
-75
@@ -1,75 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en-US">
|
||||
<head>
|
||||
<title>Swagger UI: OAuth2 Redirect</title>
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
'use strict';
|
||||
function run () {
|
||||
var oauth2 = window.opener.swaggerUIRedirectOauth2;
|
||||
var sentState = oauth2.state;
|
||||
var redirectUrl = oauth2.redirectUrl;
|
||||
var isValid, qp, arr;
|
||||
|
||||
if (/code|token|error/.test(window.location.hash)) {
|
||||
qp = window.location.hash.substring(1);
|
||||
} else {
|
||||
qp = location.search.substring(1);
|
||||
}
|
||||
|
||||
arr = qp.split("&");
|
||||
arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';});
|
||||
qp = qp ? JSON.parse('{' + arr.join() + '}',
|
||||
function (key, value) {
|
||||
return key === "" ? value : decodeURIComponent(value);
|
||||
}
|
||||
) : {};
|
||||
|
||||
isValid = qp.state === sentState;
|
||||
|
||||
if ((
|
||||
oauth2.auth.schema.get("flow") === "accessCode" ||
|
||||
oauth2.auth.schema.get("flow") === "authorizationCode" ||
|
||||
oauth2.auth.schema.get("flow") === "authorization_code"
|
||||
) && !oauth2.auth.code) {
|
||||
if (!isValid) {
|
||||
oauth2.errCb({
|
||||
authId: oauth2.auth.name,
|
||||
source: "auth",
|
||||
level: "warning",
|
||||
message: "Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server"
|
||||
});
|
||||
}
|
||||
|
||||
if (qp.code) {
|
||||
delete oauth2.state;
|
||||
oauth2.auth.code = qp.code;
|
||||
oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
|
||||
} else {
|
||||
let oauthErrorMsg;
|
||||
if (qp.error) {
|
||||
oauthErrorMsg = "["+qp.error+"]: " +
|
||||
(qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") +
|
||||
(qp.error_uri ? "More info: "+qp.error_uri : "");
|
||||
}
|
||||
|
||||
oauth2.errCb({
|
||||
authId: oauth2.auth.name,
|
||||
source: "auth",
|
||||
level: "error",
|
||||
message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server"
|
||||
});
|
||||
}
|
||||
} else {
|
||||
oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl});
|
||||
}
|
||||
window.close();
|
||||
}
|
||||
|
||||
window.addEventListener('DOMContentLoaded', function () {
|
||||
run();
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
-4
File diff suppressed because one or more lines are too long
+18
-7
@@ -1,8 +1,19 @@
|
||||
server:
|
||||
port: 8081
|
||||
|
||||
keycloak:
|
||||
auth-server-url: https://api.example.com/auth # Keycloak server url
|
||||
realm: todos-service-realm # Keycloak Realm
|
||||
resource: todos-service-clients # Keycloak Client
|
||||
principal-attribute: preferred_username
|
||||
ssl-required: external
|
||||
credentials:
|
||||
secret: 00000000-0000-0000-0000-000000000000
|
||||
auth-server-url: http://localhost:8080 # Keycloak server url
|
||||
realm: SpringBootKeycloak # Keycloak Realm
|
||||
|
||||
spring:
|
||||
security:
|
||||
oauth2:
|
||||
resourceserver:
|
||||
jwt.issuer-uri: http://localhost:8080/realms/SpringBootKeycloak
|
||||
|
||||
springdoc:
|
||||
swagger-ui:
|
||||
oauth:
|
||||
client-id: login-app
|
||||
|
||||
|
||||
|
||||
@@ -147,8 +147,8 @@
|
||||
<!-- The main class to start by executing java -jar -->
|
||||
<start-class>com.baeldung.boot.Application</start-class>
|
||||
<git-commit-id-plugin.version>2.2.4</git-commit-id-plugin.version>
|
||||
<spock.version>2.4-M1-groovy-3.0</spock.version>
|
||||
<gmavenplus-plugin.version>2.0.0</gmavenplus-plugin.version>
|
||||
<spock.version>2.4-M1-groovy-4.0</spock.version>
|
||||
<gmavenplus-plugin.version>2.1.0</gmavenplus-plugin.version>
|
||||
<maven-compiler-plugin.version>3.10.1</maven-compiler-plugin.version>
|
||||
<redis.version>0.7.2</redis.version>
|
||||
<spring-boot.version>2.5.0</spring-boot.version>
|
||||
|
||||
@@ -6,3 +6,4 @@
|
||||
- [Using Multiple Cache Managers in Spring](https://www.baeldung.com/spring-multiple-cache-managers)
|
||||
- [Testing @Cacheable on Spring Data Repositories](https://www.baeldung.com/spring-data-testing-cacheable)
|
||||
- [Spring Boot Ehcache Example](https://www.baeldung.com/spring-boot-ehcache)
|
||||
- [Get All Cached Keys with Caffeine Cache in Spring Boot](https://www.baeldung.com/spring-boot-caffeine-spring-get-all-keys)
|
||||
|
||||
Reference in New Issue
Block a user