diff --git a/core-java-modules/core-java-os/src/main/java/com/baeldung/shell/StreamGobbler.java b/core-java-modules/core-java-os/src/main/java/com/baeldung/shell/StreamGobbler.java new file mode 100644 index 0000000000..9c7fcae627 --- /dev/null +++ b/core-java-modules/core-java-os/src/main/java/com/baeldung/shell/StreamGobbler.java @@ -0,0 +1,21 @@ +package com.baeldung.shell; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.function.Consumer; + +public class StreamGobbler implements Runnable { + private final InputStream inputStream; + private final Consumer consumer; + + public StreamGobbler(InputStream inputStream, Consumer consumer) { + this.inputStream = inputStream; + this.consumer = consumer; + } + + @Override + public void run() { + new BufferedReader(new InputStreamReader(inputStream)).lines().forEach(consumer); + } +} diff --git a/core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java index 9d24dd1578..7bb0cfdf00 100644 --- a/core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/shell/JavaProcessUnitIntegrationTest.java @@ -5,10 +5,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.io.BufferedReader; import java.io.File; -import java.io.InputStream; -import java.io.InputStreamReader; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @@ -21,21 +18,6 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; public class JavaProcessUnitIntegrationTest { private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows"); - private static class StreamGobbler implements Runnable { - private InputStream inputStream; - private Consumer consumer; - - public StreamGobbler(InputStream inputStream, Consumer consumer) { - this.inputStream = inputStream; - this.consumer = consumer; - } - - @Override - public void run() { - new BufferedReader(new InputStreamReader(inputStream)).lines().forEach(consumer); - } - } - private Consumer consumer = Assert::assertNotNull; private String homeDirectory = System.getProperty("user.home"); @@ -58,7 +40,7 @@ public class JavaProcessUnitIntegrationTest { if (IS_WINDOWS) { process = Runtime.getRuntime().exec(String.format("cmd.exe /c dir %s", homeDirectory)); } else { - process = Runtime.getRuntime().exec(String.format("sh -c ls %s", homeDirectory)); + process = Runtime.getRuntime().exec(String.format("/bin/sh -c ls %s", homeDirectory)); } StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer); @@ -70,13 +52,34 @@ public class JavaProcessUnitIntegrationTest { assertEquals(0, exitCode); } + @Test + public void shouldExecuteCommandWithPipesWithRuntimeProcess(){ + Process process; + try { +if (IS_WINDOWS) { + process = Runtime.getRuntime().exec(String.format("cmd.exe /c dir %s | findstr \"Desktop\"", homeDirectory)); +} else { + process = Runtime.getRuntime().exec(String.format("/bin/sh -c ls %s | grep \"Desktop\"", homeDirectory)); +} + StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer); + + Future future = executorService.submit(streamGobbler); + int exitCode = process.waitFor(); + + // verify the stream output from the process + assertDoesNotThrow(() -> future.get(10, TimeUnit.SECONDS)); + assertEquals(0, exitCode); + } catch (Exception e) { + e.printStackTrace(); + } + } @Test public void givenProcess_whenCreatingViaProcessBuilder_shouldSucceed() throws Exception { ProcessBuilder builder = new ProcessBuilder(); if (IS_WINDOWS) { builder.command("cmd.exe", "/c", "dir"); } else { - builder.command("sh", "-c", "ls"); + builder.command("/bin/sh", "-c", "ls"); } builder.directory(new File(homeDirectory)); Process process = builder.start(); diff --git a/core-java-modules/core-java-os/src/test/java/com/baeldung/system/exit/SystemExitUnitTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/system/exit/SystemExitUnitTest.java index 6d5f9c2f34..8ad3f75623 100644 --- a/core-java-modules/core-java-os/src/test/java/com/baeldung/system/exit/SystemExitUnitTest.java +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/system/exit/SystemExitUnitTest.java @@ -1,15 +1,41 @@ package com.baeldung.system.exit; -import static org.junit.Assert.assertEquals; - -import java.security.Permission; - import org.junit.After; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; +import java.security.Permission; + +import static org.junit.Assert.assertEquals; + +@Ignore("This test is ignored because it tests deprecated code") public class SystemExitUnitTest { + private SecurityManager securityManager; + private SystemExitExample example; + + @Before + public void setUp() { + example = new SystemExitExample(); + securityManager = System.getSecurityManager(); + System.setSecurityManager(new NoExitSecurityManager()); + } + + @After + public void tearDown() throws Exception { + System.setSecurityManager(securityManager); + } + + @Test + public void testExit() throws Exception { + try { + example.readFile(); + } catch (ExitException e) { + assertEquals("Exit status", 2, e.status); + } + } + protected static class ExitException extends SecurityException { private static final long serialVersionUID = 1L; @@ -35,29 +61,4 @@ public class SystemExitUnitTest { throw new ExitException(status); } } - - private SecurityManager securityManager; - - private SystemExitExample example; - - @Before - public void setUp() throws Exception { - example = new SystemExitExample(); - securityManager = System.getSecurityManager(); - System.setSecurityManager(new NoExitSecurityManager()); - } - - @After - public void tearDown() throws Exception { - System.setSecurityManager(securityManager); - } - - @Test - public void testExit() throws Exception { - try { - example.readFile(); - } catch (ExitException e) { - assertEquals("Exit status", 2, e.status); - } - } } \ No newline at end of file diff --git a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDGenerator.java b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDGenerator.java index 264744dcba..2170a72644 100644 --- a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDGenerator.java +++ b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDGenerator.java @@ -3,8 +3,6 @@ package com.baeldung.uuid; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.time.Duration; -import java.time.LocalDateTime; import java.util.Arrays; import java.util.Random; import java.util.UUID; @@ -13,7 +11,8 @@ public final class UUIDGenerator { private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); - private UUIDGenerator() {} + private UUIDGenerator() { + } /** * Type 1 UUID Generation @@ -33,14 +32,12 @@ public final class UUIDGenerator { } private static long get64MostSignificantBitsForVersion1() { - final LocalDateTime start = LocalDateTime.of(1582, 10, 15, 0, 0, 0); - final Duration duration = Duration.between(start, LocalDateTime.now()); - final long seconds = duration.getSeconds(); - final long nanos = duration.getNano(); - final long timeForUuidIn100Nanos = seconds * 10000000 + nanos * 100; - final long least12SignificantBitOfTime = (timeForUuidIn100Nanos & 0x000000000000FFFFL) >> 4; + final long timeForUuidIn100Nanos = System.currentTimeMillis(); + final long time_low = (timeForUuidIn100Nanos & 0x0000_0000_FFFF_FFFFL) << 32; + final long time_mid = ((timeForUuidIn100Nanos >> 32) & 0xFFFF) << 16; final long version = 1 << 12; - return (timeForUuidIn100Nanos & 0xFFFFFFFFFFFF0000L) + version + least12SignificantBitOfTime; + final long time_hi = ((timeForUuidIn100Nanos >> 48) & 0x0FFF); + return time_low + time_mid + version + time_hi; } /** @@ -94,32 +91,14 @@ public final class UUIDGenerator { long lsb = 0; assert data.length == 16 : "data must be 16 bytes in length"; - for (int i = 0; i < 8; i++) {msb = (msb << 8) | (data[i] & 0xff);} - - for (int i = 8; i < 16; i++) {lsb = (lsb << 8) | (data[i] & 0xff);} - return new UUID(msb, lsb); - } - - /** - * Unique Keys Generation Using Message Digest and Type 4 UUID - * @throws NoSuchAlgorithmException - */ - public static String generateUniqueKeysWithUUIDAndMessageDigest() throws NoSuchAlgorithmException { - final MessageDigest salt = MessageDigest.getInstance("SHA-256"); - salt.update(UUID.randomUUID() - .toString() - .getBytes(StandardCharsets.UTF_8)); - return bytesToHex(salt.digest()); - } - - private static String bytesToHex(byte[] bytes) { - final char[] hexChars = new char[bytes.length * 2]; - for (int j = 0; j < bytes.length; j++) { - final int v = bytes[j] & 0xFF; - hexChars[j * 2] = hexArray[v >>> 4]; - hexChars[j * 2 + 1] = hexArray[v & 0x0F]; + for (int i = 0; i < 8; i++) { + msb = (msb << 8) | (data[i] & 0xff); } - return new String(hexChars); + + for (int i = 8; i < 16; i++) { + lsb = (lsb << 8) | (data[i] & 0xff); + } + return new UUID(msb, lsb); } private static byte[] bytesFromUUID(String uuidHexString) { diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDGeneratorUnitTest.java index cf0d7656ff..3c85eee3ff 100644 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDGeneratorUnitTest.java +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDGeneratorUnitTest.java @@ -3,6 +3,10 @@ package com.baeldung.uuid; import org.junit.jupiter.api.Test; import java.io.UnsupportedEncodingException; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -13,17 +17,23 @@ class UUIDGeneratorUnitTest { private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; @Test - public void version_1_UUID_is_generated_with_correct_length_version_and_variant() { - + void shouldGenerateType1UUIDWithCorrectVersionAndVariant() { UUID uuid = UUIDGenerator.generateType1UUID(); - assertEquals(36, uuid.toString().length()); assertEquals(1, uuid.version()); assertEquals(2, uuid.variant()); } @Test - public void version_3_UUID_is_correctly_generated_for_domain_baeldung_com() throws UnsupportedEncodingException { + void shouldGenerateType1UUIDWithTheCurrentDate() { + UUID uuid = UUIDGenerator.generateType1UUID(); + long time = uuid.timestamp(); + LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()); + assertEquals(LocalDate.now(), dateTime.toLocalDate()); + } + + @Test + void version_3_UUID_is_correctly_generated_for_domain_baeldung_com() { UUID uuid = UUIDGenerator.generateType3UUID(NAMESPACE_DNS, "baeldung.com"); @@ -33,7 +43,7 @@ class UUIDGeneratorUnitTest { } @Test - public void version_3_UUID_is_correctly_generated_for_domain_d() throws UnsupportedEncodingException { + void version_3_UUID_is_correctly_generated_for_domain_d() { UUID uuid = UUIDGenerator.generateType3UUID(NAMESPACE_DNS, "d"); diff --git a/lombok-modules/lombok-2/lombok.config b/lombok-modules/lombok-2/lombok.config index f68b99fb85..f33d9d905f 100644 --- a/lombok-modules/lombok-2/lombok.config +++ b/lombok-modules/lombok-2/lombok.config @@ -1,2 +1,2 @@ config.stopBubbling = true -lombok.experimental.flagUsage = warning +lombok.experimental.flagUsage = warning \ No newline at end of file diff --git a/lombok-modules/lombok-2/pom.xml b/lombok-modules/lombok-2/pom.xml index c92feed739..23c907b4a1 100644 --- a/lombok-modules/lombok-2/pom.xml +++ b/lombok-modules/lombok-2/pom.xml @@ -20,6 +20,15 @@ ${lombok.version} provided + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + 2.14.1 + + \ No newline at end of file diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/jackson/Employee.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/jackson/Employee.java new file mode 100644 index 0000000000..48df7de757 --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/jackson/Employee.java @@ -0,0 +1,39 @@ +package com.baeldung.lombok.jackson; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; + +@Data +@Builder(builderClassName = "EmployeeBuilder") +@JsonDeserialize(builder = Employee.EmployeeBuilder.class) +@AllArgsConstructor +public class Employee { + + private int identity; + private String firstName; + + @JsonPOJOBuilder(buildMethodName = "createEmployee", withPrefix = "construct") + public static class EmployeeBuilder { + + private int idValue; + private String nameValue; + + public EmployeeBuilder constructId(int id) { + idValue = id; + return this; + } + + public EmployeeBuilder constructName(String name) { + nameValue = name; + return this; + } + + public Employee createEmployee() { + return new Employee(idValue, nameValue); + } + } +} diff --git a/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/jackson/Fruit.java b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/jackson/Fruit.java new file mode 100644 index 0000000000..bfe547b076 --- /dev/null +++ b/lombok-modules/lombok-2/src/main/java/com/baeldung/lombok/jackson/Fruit.java @@ -0,0 +1,15 @@ +package com.baeldung.lombok.jackson; + +import lombok.Builder; +import lombok.Data; +import lombok.extern.jackson.Jacksonized; + +@Data +@Builder +@Jacksonized +public class Fruit { + + private String name; + private int id; + +} diff --git a/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/jackson/LombokWithJacksonEmployeeUnitTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/jackson/LombokWithJacksonEmployeeUnitTest.java new file mode 100644 index 0000000000..52a964c734 --- /dev/null +++ b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/jackson/LombokWithJacksonEmployeeUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.lombok.jackson; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import org.junit.jupiter.api.Test; +import com.fasterxml.jackson.databind.ObjectMapper; + +class LombokWithJacksonEmployeeUnitTest { + + @Test + void withEmployeeObject_thenSerializeSucessfully() throws IOException { + Employee employee = Employee.builder() + .identity(5) + .firstName("Bob") + .build(); + + String json = newObjectMapper().writeValueAsString(employee); + assertEquals("{\"identity\":5,\"firstName\":\"Bob\"}", json); + } + + @Test + public void withEmployeeJSON_thenDeserializeSucessfully() throws IOException { + String json = "{\"id\":5,\"name\":\"Bob\"}"; + Employee employee = newObjectMapper().readValue(json, Employee.class); + + assertEquals(5, employee.getIdentity()); + assertEquals("Bob", employee.getFirstName()); + } + + private ObjectMapper newObjectMapper() { + return new ObjectMapper(); + } + +} diff --git a/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/jackson/LombokWithJacksonFruitUnitTest.java b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/jackson/LombokWithJacksonFruitUnitTest.java new file mode 100644 index 0000000000..a8ecb05fbf --- /dev/null +++ b/lombok-modules/lombok-2/src/test/java/com/baeldung/lombok/jackson/LombokWithJacksonFruitUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.lombok.jackson; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import org.junit.jupiter.api.Test; +import com.fasterxml.jackson.databind.ObjectMapper; + +class LombokWithJacksonFruitUnitTest { + + @Test + void withFruitObject_thenSerializeSucessfully() throws IOException { + Fruit fruit = Fruit.builder() + .id(101) + .name("Apple") + .build(); + + String json = newObjectMapper().writeValueAsString(fruit); + assertEquals("{\"name\":\"Apple\",\"id\":101}", json); + } + + @Test + public void withFruitJSON_thenDeserializeSucessfully() throws IOException { + String json = "{\"name\":\"Apple\",\"id\":101}"; + Fruit fruit = newObjectMapper().readValue(json, Fruit.class); + assertEquals(new Fruit("Apple", 101), fruit); + } + + private ObjectMapper newObjectMapper() { + return new ObjectMapper(); + } + +} diff --git a/parent-boot-3/pom.xml b/parent-boot-3/pom.xml index 26d353f2ae..8f891ec788 100644 --- a/parent-boot-3/pom.xml +++ b/parent-boot-3/pom.xml @@ -1,7 +1,7 @@ + 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"> 4.0.0 parent-boot-3 0.0.1-SNAPSHOT @@ -34,6 +34,26 @@ + + ch.qos.logback + logback-classic + ${logback.version} + + + ch.qos.logback + logback-core + ${logback.version} + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + jcl-over-slf4j + ${slf4j.version} + org.springframework.boot spring-boot-starter-test @@ -44,26 +64,166 @@ + + org.apache.maven.plugins + maven-clean-plugin + ${maven-clean-plugin.version} + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + + org.apache.maven.plugins + maven-jar-plugin + ${maven-jar-plugin.version} + + + + ${start-class} + true + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + org.apache.maven.plugins + maven-resources-plugin + ${maven-resources-plugin.version} + + + org.graalvm.buildtools + native-maven-plugin + ${native-build-tools-plugin.version} + true + org.springframework.boot spring-boot-maven-plugin ${spring-boot.version} ${start-class} - - - - - repackage - - - + + + org.springframework.boot + spring-boot-maven-plugin + + + repackage + + repackage + + + + + + + + native + + + + org.springframework.boot + spring-boot-maven-plugin + + + paketobuildpacks/builder:tiny + + true + + + + + + process-aot + + process-aot + + + + + + org.graalvm.buildtools + native-maven-plugin + + ${project.build.outputDirectory} + + true + + 22.3 + + + + add-reachability-metadata + + add-reachability-metadata + + + + + + + + + nativeTest + + + org.junit.platform + junit-platform-launcher + test + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + process-test-aot + + process-test-aot + + + + + + org.graalvm.buildtools + native-maven-plugin + + ${project.build.outputDirectory} + + true + + 22.3 + + + + native-test + + test + + + + + + + + + + spring-milestones @@ -87,10 +247,21 @@ + 3.2.0 + 3.10.1 + 3.3.0 + 3.3.0 + 2.22.2 + 3.0.0-M3 5.8.2 3.0.0-M7 + 0.9.17 17 + ${java.version} + ${java.version} + 1.4.4 + 2.0.3 - \ No newline at end of file + diff --git a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/WebSecurityConfiguration.java b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/WebSecurityConfiguration.java index da99b7578e..12770c47ce 100644 --- a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/WebSecurityConfiguration.java +++ b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/WebSecurityConfiguration.java @@ -8,27 +8,30 @@ import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) -public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { +public class WebSecurityConfiguration { @Autowired private FaunaClient faunaClient; - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable(); + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http.csrf() + .disable(); http.authorizeRequests() - .antMatchers("/**").permitAll() - .and().httpBasic(); + .antMatchers("/**") + .permitAll() + .and() + .httpBasic(); + return http.build(); } @Bean - @Override public UserDetailsService userDetailsService() { return new FaunaUserDetailsService(faunaClient); } diff --git a/pom.xml b/pom.xml index feb9357bda..ba1f778614 100644 --- a/pom.xml +++ b/pom.xml @@ -326,7 +326,6 @@ parent-boot-1 parent-boot-2 - parent-boot-3 parent-spring-4 parent-spring-5 parent-java @@ -456,7 +455,6 @@ logging-modules lombok-modules lucene - mapstruct maven-modules @@ -534,7 +532,6 @@ parent-boot-1 parent-boot-2 - parent-boot-3 parent-spring-4 parent-spring-5 parent-java @@ -677,7 +674,6 @@ parent-boot-1 parent-boot-2 - parent-boot-3 parent-spring-4 parent-spring-5 parent-java @@ -732,7 +728,6 @@ parent-boot-1 parent-boot-2 - parent-boot-3 parent-spring-4 parent-spring-5 parent-java @@ -861,7 +856,6 @@ logging-modules lombok-modules lucene - mapstruct maven-modules @@ -930,7 +924,6 @@ parent-boot-1 parent-boot-2 - parent-boot-3 parent-spring-4 parent-spring-5 parent-java @@ -1066,7 +1059,6 @@ parent-boot-1 parent-boot-2 - parent-boot-3 parent-spring-4 parent-spring-5 parent-java @@ -1204,10 +1196,12 @@ spring-boot-modules/spring-boot-cassandre spring-boot-modules/spring-boot-camel spring-boot-modules/spring-boot-3 + spring-boot-modules/spring-boot-3-native spring-swagger-codegen/custom-validations-opeanpi-codegen testing-modules/testing-assertions persistence-modules/fauna lightrun + tablesaw @@ -1280,11 +1274,13 @@ spring-boot-modules/spring-boot-cassandre spring-boot-modules/spring-boot-camel spring-boot-modules/spring-boot-3 + spring-boot-modules/spring-boot-3-native spring-swagger-codegen/custom-validations-opeanpi-codegen testing-modules/testing-assertions persistence-modules/fauna lightrun spring-core-6 + tablesaw diff --git a/security-modules/apache-shiro/src/main/java/com/baeldung/comparison/springsecurity/config/SecurityConfig.java b/security-modules/apache-shiro/src/main/java/com/baeldung/comparison/springsecurity/config/SecurityConfig.java index d838eef9b3..a244af0294 100644 --- a/security-modules/apache-shiro/src/main/java/com/baeldung/comparison/springsecurity/config/SecurityConfig.java +++ b/security-modules/apache-shiro/src/main/java/com/baeldung/comparison/springsecurity/config/SecurityConfig.java @@ -1,40 +1,46 @@ package com.baeldung.comparison.springsecurity.config; import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 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.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.SecurityFilterChain; @EnableWebSecurity -public class SecurityConfig extends WebSecurityConfigurerAdapter { +public class SecurityConfig { - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable().authorizeRequests(authorize -> authorize.antMatchers("/index", "/login") - .permitAll() - .antMatchers("/home", "/logout") - .authenticated() - .antMatchers("/admin/**") - .hasRole("ADMIN")) + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http.csrf() + .disable() + .authorizeRequests(authorize -> authorize.antMatchers("/index", "/login") + .permitAll() + .antMatchers("/home", "/logout") + .authenticated() + .antMatchers("/admin/**") + .hasRole("ADMIN")) .formLogin(formLogin -> formLogin.loginPage("/login") .failureUrl("/login-error")); + return http.build(); } - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication() - .withUser("Jerry") + @Bean + public InMemoryUserDetailsManager userDetailsService() throws Exception { + UserDetails jerry = User.withUsername("Jerry") .password(passwordEncoder().encode("password")) .authorities("READ", "WRITE") .roles("ADMIN") - .and() - .withUser("Tom") + .build(); + UserDetails tom = User.withUsername("Tom") .password(passwordEncoder().encode("password")) .authorities("READ") - .roles("USER"); + .roles("USER") + .build(); + return new InMemoryUserDetailsManager(jerry, tom); } @Bean diff --git a/spring-boot-modules/spring-boot-3-native/pom.xml b/spring-boot-modules/spring-boot-3-native/pom.xml new file mode 100644 index 0000000000..9e664efc02 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-native/pom.xml @@ -0,0 +1,86 @@ + + + 4.0.0 + spring-boot-3-native + 0.0.1-SNAPSHOT + spring-boot-3-native + Demo project for Spring Boot + + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3/pom.xml + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + ${spring-doc.version} + + + org.springframework.boot + spring-boot-starter-graphql + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + org.graalvm.buildtools + native-maven-plugin + + + true + + + + + + + + + + + native + + + + org.graalvm.buildtools + native-maven-plugin + + + build-native + + compile-no-fork + + package + + + + + + + + + + 3.0.0-RC2 + 2.0.0-RC1 + 0.9.17 + com.baeldung.sample.TodoApplication + + + diff --git a/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/BoundaryConfiguration.java b/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/BoundaryConfiguration.java new file mode 100644 index 0000000000..1b7894abf9 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/BoundaryConfiguration.java @@ -0,0 +1,23 @@ +package com.baeldung.sample; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class BoundaryConfiguration { + + @Bean + public WebMvcConfigurer webMvcConfigurer() { + return new WebMvcConfigurer() { + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry + .addViewController("/") + .setViewName("redirect:/index.html"); + } + }; + } + +} diff --git a/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/GraphQlRuntimeHints.java b/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/GraphQlRuntimeHints.java new file mode 100644 index 0000000000..c20ff4cafa --- /dev/null +++ b/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/GraphQlRuntimeHints.java @@ -0,0 +1,22 @@ +package com.baeldung.sample; + +import org.springframework.aot.hint.RuntimeHints; +import org.springframework.aot.hint.RuntimeHintsRegistrar; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportRuntimeHints; + +@ImportRuntimeHints(GraphQlRuntimeHints.GraphQlResourcesRegistrar.class) +@Configuration +public class GraphQlRuntimeHints { + + static class GraphQlResourcesRegistrar implements RuntimeHintsRegistrar { + + @Override + public void registerHints(RuntimeHints hints, ClassLoader classLoader) { + hints.resources() + .registerPattern("graphql/**/") + .registerPattern("graphiql/index.html"); + } + } + +} diff --git a/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/JacksonRuntimeHints.java b/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/JacksonRuntimeHints.java new file mode 100644 index 0000000000..9c16ab0009 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/JacksonRuntimeHints.java @@ -0,0 +1,30 @@ +package com.baeldung.sample; + +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import org.springframework.aot.hint.RuntimeHints; +import org.springframework.aot.hint.RuntimeHintsRegistrar; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportRuntimeHints; + +@Configuration +@ImportRuntimeHints(JacksonRuntimeHints.PropertyNamingStrategyRegistrar.class) +public class JacksonRuntimeHints { + + private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(JacksonRuntimeHints.class); + + static class PropertyNamingStrategyRegistrar implements RuntimeHintsRegistrar { + + @Override + public void registerHints(RuntimeHints hints, ClassLoader classLoader) { + try { + hints + .reflection() + .registerField(PropertyNamingStrategies.class.getDeclaredField("SNAKE_CASE")); + log.info("Registered native hint for SNAKE_CASE!"); + } catch (NoSuchFieldException e) { + log.warn("Unable to register native hint for SNAKE_CASE!"); + } + } + } + +} diff --git a/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/TodoApplication.java b/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/TodoApplication.java new file mode 100644 index 0000000000..72c9c0e482 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/TodoApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.sample; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +@SpringBootApplication +public class TodoApplication { + public static void main(String[] args) { + SpringApplication.run(TodoApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/User.java b/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/User.java new file mode 100644 index 0000000000..fd5597e3d2 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/User.java @@ -0,0 +1,31 @@ +package com.baeldung.sample; + +public class User { + + private String firstName; + private String lastName; + + public User(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public User() { + } + + 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; + } +} diff --git a/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/UserController.java b/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/UserController.java new file mode 100644 index 0000000000..449bc09c46 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-native/src/main/java/com/baeldung/sample/UserController.java @@ -0,0 +1,19 @@ +package com.baeldung.sample; + +import org.springframework.graphql.data.method.annotation.QueryMapping; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/v1/user") +public class UserController { + + @QueryMapping("getUser") + @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) + public User getUser() { + return new User("John", "Doe"); + } + +} diff --git a/spring-boot-modules/spring-boot-3-native/src/main/resources/application.yml b/spring-boot-modules/spring-boot-3-native/src/main/resources/application.yml new file mode 100644 index 0000000000..0e206a6cd5 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-native/src/main/resources/application.yml @@ -0,0 +1,6 @@ +spring: + graphql: + graphiql: + enabled: true + jackson: + property-naming-strategy: SNAKE_CASE diff --git a/spring-boot-modules/spring-boot-3-native/src/main/resources/graphql/todo.graphqls b/spring-boot-modules/spring-boot-3-native/src/main/resources/graphql/todo.graphqls new file mode 100644 index 0000000000..c2dd5c1565 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-native/src/main/resources/graphql/todo.graphqls @@ -0,0 +1,8 @@ +type User { + firstName: String! + lastName: String! +} + +type Query { + getUser: User! +} diff --git a/spring-boot-modules/spring-boot-3-native/src/main/resources/static/index.html b/spring-boot-modules/spring-boot-3-native/src/main/resources/static/index.html new file mode 100644 index 0000000000..d8ab49c5ea --- /dev/null +++ b/spring-boot-modules/spring-boot-3-native/src/main/resources/static/index.html @@ -0,0 +1,17 @@ + + + + + Spring Native Demo Application + + +

Spring Native Demo Application

+

+ This is a sample application that can be built as native executable. +

+ + + diff --git a/spring-boot-modules/spring-boot-3-native/src/test/java/com/baeldung/sample/JacksonAutoConfigurationIntegrationTest.java b/spring-boot-modules/spring-boot-3-native/src/test/java/com/baeldung/sample/JacksonAutoConfigurationIntegrationTest.java new file mode 100644 index 0000000000..83ec6b3923 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-native/src/test/java/com/baeldung/sample/JacksonAutoConfigurationIntegrationTest.java @@ -0,0 +1,23 @@ +package com.baeldung.sample; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +class JacksonAutoConfigurationIntegrationTest { + + @Autowired + ObjectMapper mapper; + + @Test + void shouldUseSnakeCasePropertyNamingStrategy() { + assertThat(mapper.getPropertyNamingStrategy()) + .isSameAs(PropertyNamingStrategies.SNAKE_CASE); + } + +} diff --git a/spring-boot-modules/spring-boot-3-native/src/test/java/com/baeldung/sample/JacksonRuntimeHintsUnitTest.java b/spring-boot-modules/spring-boot-3-native/src/test/java/com/baeldung/sample/JacksonRuntimeHintsUnitTest.java new file mode 100644 index 0000000000..eb45db9407 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-native/src/test/java/com/baeldung/sample/JacksonRuntimeHintsUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.sample; + +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import org.junit.jupiter.api.Test; +import org.springframework.aot.hint.RuntimeHints; +import org.springframework.aot.hint.predicate.RuntimeHintsPredicates; + +import static org.assertj.core.api.Assertions.assertThat; + +class JacksonRuntimeHintsUnitTest { + + @Test + void shouldRegisterSnakeCasePropertyNamingStrategy() { + // arrange + final var hints = new RuntimeHints(); + final var expectSnakeCaseHint = RuntimeHintsPredicates + .reflection() + .onField(PropertyNamingStrategies.class, "SNAKE_CASE"); + // act + new JacksonRuntimeHints.PropertyNamingStrategyRegistrar() + .registerHints(hints, getClass().getClassLoader()); + // assert + assertThat(expectSnakeCaseHint).accepts(hints); + + } + +} diff --git a/spring-cloud-modules/spring-cloud-config/pom.xml b/spring-cloud-modules/spring-cloud-config/pom.xml index 8f4498e0c6..efbf30d0b2 100644 --- a/spring-cloud-modules/spring-cloud-config/pom.xml +++ b/spring-cloud-modules/spring-cloud-config/pom.xml @@ -18,6 +18,8 @@ spring-cloud-config-server spring-cloud-config-client + spring-cloud-config-overriding-properties-client + spring-cloud-config-overriding-properties-server @@ -36,4 +38,4 @@ 2021.0.3 - \ No newline at end of file + diff --git a/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/pom.xml b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/pom.xml new file mode 100644 index 0000000000..d297e5b44d --- /dev/null +++ b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + spring-cloud-config-overriding-properties-client + spring-cloud-config-overriding-properties-client + + + com.baeldung.spring.cloud + spring-cloud-config + 1.0-SNAPSHOT + + + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/src/main/java/com/baeldung/spring/cloud/config/overridingproperties/Client.java b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/src/main/java/com/baeldung/spring/cloud/config/overridingproperties/Client.java new file mode 100644 index 0000000000..c0c5f768bc --- /dev/null +++ b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/src/main/java/com/baeldung/spring/cloud/config/overridingproperties/Client.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.cloud.config.overridingproperties; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Client { + + public static void main(String[] args) { + SpringApplication.run(Client.class, args); + } +} + + diff --git a/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/src/main/java/com/baeldung/spring/cloud/config/overridingproperties/HelloController.java b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/src/main/java/com/baeldung/spring/cloud/config/overridingproperties/HelloController.java new file mode 100644 index 0000000000..c48b3d2b5c --- /dev/null +++ b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/src/main/java/com/baeldung/spring/cloud/config/overridingproperties/HelloController.java @@ -0,0 +1,33 @@ +package com.baeldung.spring.cloud.config.overridingproperties; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HelloController { + + @Value("${hello}") + private String hello; + + @Value("${welcome}") + private String welcome; + + @Value("${shared-property}") + private String shared; + + @GetMapping("hello") + public String hello() { + return this.hello; + } + + @GetMapping("welcome") + public String welcome() { + return this.welcome; + } + + @GetMapping("shared") + public String shared() { + return this.shared; + } +} diff --git a/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/src/main/resources/application-development.properties b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/src/main/resources/application-development.properties new file mode 100644 index 0000000000..0dd3e1bb91 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/src/main/resources/application-development.properties @@ -0,0 +1 @@ +hello=Hello local property! diff --git a/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/src/main/resources/application.properties b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/src/main/resources/application.properties new file mode 100644 index 0000000000..e4ff6e0550 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.cloud.config.name=baeldung +spring.config.import=optional:configserver:http://localhost:8081 +app.hello=Hello, overriden local property! diff --git a/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/src/test/java/com/baeldung/spring/cloud/config/client/SpringContextLiveTest.java b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/src/test/java/com/baeldung/spring/cloud/config/client/SpringContextLiveTest.java new file mode 100644 index 0000000000..ca029b2843 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-client/src/test/java/com/baeldung/spring/cloud/config/client/SpringContextLiveTest.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.cloud.config.client; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +@ExtendWith(SpringExtension.class) +@SpringBootTest +public class SpringContextLiveTest { + + @Test + public void contextLoads() { + } +} diff --git a/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/pom.xml b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/pom.xml new file mode 100644 index 0000000000..bcaa64e0d1 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/pom.xml @@ -0,0 +1,31 @@ + + + 4.0.0 + spring-cloud-config-overriding-properties-server + spring-cloud-config-overriding-properties-server + + + com.baeldung.spring.cloud + spring-cloud-config + 1.0-SNAPSHOT + + + + + org.springframework.cloud + spring-cloud-config-server + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/main/java/com/baeldung/spring/cloud/config/overridingproperties/ConfigServer.java b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/main/java/com/baeldung/spring/cloud/config/overridingproperties/ConfigServer.java new file mode 100644 index 0000000000..a8e2f80616 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/main/java/com/baeldung/spring/cloud/config/overridingproperties/ConfigServer.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.cloud.config.overridingproperties; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.config.server.EnableConfigServer; + +@SpringBootApplication +@EnableConfigServer +public class ConfigServer { + + public static void main(String[] args) { + SpringApplication.run(ConfigServer.class, args); + } +} diff --git a/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/main/resources/application.properties b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/main/resources/application.properties new file mode 100644 index 0000000000..84c63795d5 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/main/resources/application.properties @@ -0,0 +1,3 @@ +server.port=8081 +spring.cloud.config.server.native.search-locations=classpath:/config +#spring.cloud.config.server.overrides.hello=Hello Jane Doe - application.properties! diff --git a/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/main/resources/config/application.properties b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/main/resources/config/application.properties new file mode 100644 index 0000000000..0feac5bb17 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/main/resources/config/application.properties @@ -0,0 +1 @@ +shared-property=This property is shared accross all client applications diff --git a/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/main/resources/config/baeldung.properties b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/main/resources/config/baeldung.properties new file mode 100644 index 0000000000..471331b8bb --- /dev/null +++ b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/main/resources/config/baeldung.properties @@ -0,0 +1,2 @@ +hello=${app.hello:Hello Jane Doe!} +welcome=Welcome Jane Doe! diff --git a/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/test/java/com/baeldung/spring/cloud/config/server/SpringContextTest.java b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/test/java/com/baeldung/spring/cloud/config/server/SpringContextTest.java new file mode 100644 index 0000000000..bfa7e3639c --- /dev/null +++ b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/test/java/com/baeldung/spring/cloud/config/server/SpringContextTest.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.cloud.config.server; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.spring.cloud.config.overridingproperties.ConfigServer; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = ConfigServer.class) +@ActiveProfiles("native") +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/test/resources/application.properties b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/test/resources/application.properties new file mode 100644 index 0000000000..ded1724100 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-config/spring-cloud-config-overriding-properties-server/src/test/resources/application.properties @@ -0,0 +1 @@ +spring.cloud.config.server.native.search-locations=classpath:/config diff --git a/spring-native/pom-nativeimage.xml b/spring-native/pom-nativeimage.xml index 1b2cc3944a..6d42bedbe1 100644 --- a/spring-native/pom-nativeimage.xml +++ b/spring-native/pom-nativeimage.xml @@ -111,12 +111,12 @@ - 2.5.1 - 0.10.0 - 0.9.0 + 2.7.1 + 0.12.1 + 0.9.17 1.8 1.8 1.8 - \ No newline at end of file + diff --git a/spring-native/pom.xml b/spring-native/pom.xml index f54d7b5308..0cd502fbc1 100644 --- a/spring-native/pom.xml +++ b/spring-native/pom.xml @@ -70,12 +70,12 @@ paketobuildpacks/builder:tiny - 2.5.1 - 0.10.0 + 2.7.1 + 0.12.1 1.8 1.8 1.8 2.17.1 - \ No newline at end of file + diff --git a/spring-security-modules/spring-security-web-mvc/src/main/java/com/baeldung/clearsitedata/SpringSecurityConfig.java b/spring-security-modules/spring-security-web-mvc/src/main/java/com/baeldung/clearsitedata/SpringSecurityConfig.java index 13011da9e4..9138c6fd7b 100644 --- a/spring-security-modules/spring-security-web-mvc/src/main/java/com/baeldung/clearsitedata/SpringSecurityConfig.java +++ b/spring-security-modules/spring-security-web-mvc/src/main/java/com/baeldung/clearsitedata/SpringSecurityConfig.java @@ -1,26 +1,26 @@ package com.baeldung.clearsitedata; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.web.authentication.logout.HeaderWriterLogoutHandler; -import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter; - import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.CACHE; import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.COOKIES; import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.STORAGE; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.logout.HeaderWriterLogoutHandler; +import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter; + @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) -public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { +public class SpringSecurityConfig { + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf() .disable() .formLogin() @@ -28,8 +28,9 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { .loginProcessingUrl("/perform_login") .defaultSuccessUrl("/homepage.html", true) .and() - .logout().logoutUrl("/baeldung/logout") - .addLogoutHandler(new HeaderWriterLogoutHandler( - new ClearSiteDataHeaderWriter(CACHE, COOKIES, STORAGE))); + .logout() + .logoutUrl("/baeldung/logout") + .addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(CACHE, COOKIES, STORAGE))); + return http.build(); } } diff --git a/spring-security-modules/spring-security-web-mvc/src/main/java/com/baeldung/session/security/config/SecSecurityConfig.java b/spring-security-modules/spring-security-web-mvc/src/main/java/com/baeldung/session/security/config/SecSecurityConfig.java index 9a4978c27e..1dfb72eca9 100644 --- a/spring-security-modules/spring-security-web-mvc/src/main/java/com/baeldung/session/security/config/SecSecurityConfig.java +++ b/spring-security-modules/spring-security-web-mvc/src/main/java/com/baeldung/session/security/config/SecSecurityConfig.java @@ -2,12 +2,14 @@ package com.baeldung.session.security.config; 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.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.session.HttpSessionEventPublisher; @@ -15,50 +17,56 @@ import com.baeldung.security.MySimpleUrlAuthenticationSuccessHandler; @Configuration // @ImportResource({ "classpath:webSecurityConfig.xml" }) -public class SecSecurityConfig extends WebSecurityConfigurerAdapter { +public class SecSecurityConfig { - public SecSecurityConfig() { - super(); + @Bean + public InMemoryUserDetailsManager userDetailsService() { + UserDetails user1 = User.withUsername("user1") + .password(passwordEncoder().encode("user1Pass")) + .roles("USER") + .build(); + + UserDetails admin1 = User.withUsername("admin1") + .password(passwordEncoder().encode("admin1Pass")) + .roles("ADMIN") + .build(); + + return new InMemoryUserDetailsManager(user1, admin1); } - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - // @formatter:off - auth.inMemoryAuthentication() - .withUser("user1").password(passwordEncoder().encode("user1Pass")).roles("USER") - .and() - .withUser("admin1").password(passwordEncoder().encode("admin1Pass")).roles("ADMIN"); - // @formatter:on - } - - @Override - protected void configure(final HttpSecurity http) throws Exception { - // @formatter:off - http - .csrf().disable() - .authorizeRequests() - .antMatchers("/anonymous*").anonymous() - .antMatchers("/login*","/invalidSession*", "/sessionExpired*", "/foo/**").permitAll() - .anyRequest().authenticated() - .and() - .formLogin() - .loginPage("/login.html") - .loginProcessingUrl("/login") - .successHandler(successHandler()) - .failureUrl("/login.html?error=true") - .and() - .logout().deleteCookies("JSESSIONID") - .and() - .rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400) - .and() - .sessionManagement() - .sessionFixation().migrateSession() - .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) - .invalidSessionUrl("/invalidSession.html") - .maximumSessions(2) - .expiredUrl("/sessionExpired.html"); - - // @formatter:on + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http.csrf() + .disable() + .authorizeRequests() + .antMatchers("/anonymous*") + .anonymous() + .antMatchers("/login*", "/invalidSession*", "/sessionExpired*", "/foo/**") + .permitAll() + .anyRequest() + .authenticated() + .and() + .formLogin() + .loginPage("/login.html") + .loginProcessingUrl("/login") + .successHandler(successHandler()) + .failureUrl("/login.html?error=true") + .and() + .logout() + .deleteCookies("JSESSIONID") + .and() + .rememberMe() + .key("uniqueAndSecret") + .tokenValiditySeconds(86400) + .and() + .sessionManagement() + .sessionFixation() + .migrateSession() + .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) + .invalidSessionUrl("/invalidSession.html") + .maximumSessions(2) + .expiredUrl("/sessionExpired.html"); + return http.build(); } private AuthenticationSuccessHandler successHandler() { diff --git a/tablesaw/README.md b/tablesaw/README.md new file mode 100644 index 0000000000..e7409a0b6b --- /dev/null +++ b/tablesaw/README.md @@ -0,0 +1,5 @@ +This module contains tutorials related to the tablesaw java library. + +### Relevant Articles: + + diff --git a/tablesaw/pom.xml b/tablesaw/pom.xml new file mode 100644 index 0000000000..b54c9aa13e --- /dev/null +++ b/tablesaw/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + tablesaw + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + + tech.tablesaw + tablesaw-core + ${tablesaw.version} + + + + + 0.43.1 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.0 + + 17 + 17 + + + + + + diff --git a/tablesaw/src/test/java/com/baeldung/tablesaw/CSVUnitTest.java b/tablesaw/src/test/java/com/baeldung/tablesaw/CSVUnitTest.java new file mode 100644 index 0000000000..eb39b003e6 --- /dev/null +++ b/tablesaw/src/test/java/com/baeldung/tablesaw/CSVUnitTest.java @@ -0,0 +1,146 @@ +package com.baeldung.tablesaw; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import tech.tablesaw.api.DateColumn; +import tech.tablesaw.api.DoubleColumn; +import tech.tablesaw.api.StringColumn; +import tech.tablesaw.api.Table; +import tech.tablesaw.api.TimeColumn; +import tech.tablesaw.io.csv.CsvReadOptions; +import tech.tablesaw.selection.Selection; + +import java.io.File; +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static tech.tablesaw.aggregate.AggregateFunctions.max; +import static tech.tablesaw.aggregate.AggregateFunctions.mean; +import static tech.tablesaw.aggregate.AggregateFunctions.min; +import static tech.tablesaw.aggregate.AggregateFunctions.stdDev; + +class CSVUnitTest { + + private static Table table; + + @BeforeEach + void setup() { + URL resource = CSVUnitTest.class.getClassLoader().getResource("avocado.csv"); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + Path filePath = Paths.get(resource.getPath()); + File file = filePath.toFile(); + CsvReadOptions csvReadOptions = + CsvReadOptions.builder(file) + .separator(',') + .header(true) + .dateFormat(formatter) + .build(); + table = Table.read().usingOptions(csvReadOptions); + } + + @Test + void shouldReturnTheShapeStringOnAvocadoDataSet() { + assertThat(table.shape()).isEqualTo("avocado.csv: 18249 rows X 14 cols"); + } + + @Test + void shouldOrderTheTableByDateInAscendingOrder() { + Table ascendingDateSortedTable = table.sortAscendingOn("Date"); + assertThat(ascendingDateSortedTable.dateColumn("Date").get(0)).isEqualTo(LocalDate.parse("2015-01-04")); + } + + @Test + void shouldOrderTheTableByDateInDescendingOrder() { + Table descendingDateSortedTable = table.sortDescendingOn("Date"); + assertThat(descendingDateSortedTable.dateColumn("Date").get(0)).isEqualTo(LocalDate.parse("2018-03-25")); + } + + @Test + void shouldOrderTheTableByYearAndAveragePriceInAscendingOrder() { + Table ascendingYearAndAveragePriceSortedTable = table.sortOn("year", "-AveragePrice"); + assertThat(ascendingYearAndAveragePriceSortedTable.intColumn("year").get(0)).isEqualTo(2015); + assertThat(ascendingYearAndAveragePriceSortedTable.numberColumn("AveragePrice").get(0)).isEqualTo(2.79); + } + + @Test + void shouldRemoveTheValueWhenSettingAsMissing() { + DoubleColumn averagePrice = table.doubleColumn("AveragePrice").setMissing(0); + assertThat(averagePrice.get(0)).isNull(); + } + + @Test + void shouldAppendDataToTheColumn() { + DoubleColumn averagePrice = table.doubleColumn("AveragePrice"); + averagePrice.append(1.123); + assertThat(averagePrice.get(averagePrice.size() - 1)).isEqualTo(1.123); + } + + @Test + void shouldAppendDataToAveragePriceColumn() { + DoubleColumn averagePrice2 = table.doubleColumn("AveragePrice").copy(); + averagePrice2.setName("AveragePrice2"); + averagePrice2.append(1.123); + assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> table.addColumns(averagePrice2)); + } + + @Test + void shouldReturnTheTableContainingDataFrom2017andAveragePriceIsGreaterThan2Only() { + DateColumn dateTable = table.dateColumn("Date"); + DoubleColumn averagePrice = table.doubleColumn("AveragePrice"); + Selection selection = dateTable.isInYear(2017).and(averagePrice.isGreaterThan(2D)); + Table table2017 = table.where(selection); + assertThat(table2017.intColumn("year")).containsOnly(2017); + assertThat(table2017.doubleColumn("AveragePrice")).allMatch(avrgPrice -> avrgPrice > 2D); + } + + @Test + void shouldPrintToStandardOutputStatisticsOfAveragePriceByYearData() { + Table summary = table.summarize("AveragePrice", max, min, mean, stdDev).by("year"); + System.out.println(summary.print()); + Assertions.assertTrue(true); + } + + @Test + void shouldThrowIllegalArgumentExceptionWhenCreatingTableWithDifferentSizeColumns() { + StringColumn type = StringColumn.create("type"); + StringColumn region = StringColumn.create("region"); + type.addAll(List.of("Country", "City")); + region.append("USA"); + assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> Table.create(type, region)); + } + + @Test + void shouldNotThrowIllegalArgumentExceptionWhenCreatingTableWithDifferentSameSizeColumns() { + StringColumn type = StringColumn.create("type"); + StringColumn region = StringColumn.create("region"); + type.addAll(List.of("Country", "City")); + region.append("USA"); + region.appendMissing(); + assertThatNoException().isThrownBy(() -> Table.create(type, region)); + } + + @Test + void shouldAddColumnToTable() { + TimeColumn time = TimeColumn.create("time"); + Table table = Table.create("test"); + table.addColumns(time); + assertThat(table.columnNames()).contains("time"); + } + + @Test + void shouldBeEqualTwoValuesFromDifferentRowsOnTheTypeColumn() { + StringColumn type = table.stringColumn("type"); + List conventional = type.where(type.isEqualTo("conventional")).asList().stream() + .limit(2) + .toList(); + assertThat(conventional.get(0)).isSameAs(conventional.get(1)); + } +}