Merge remote-tracking branch 'origin/master'

This commit is contained in:
Philippe Sevestre 2024-02-25 19:33:50 -03:00
commit ab2d1768a2
40 changed files with 679 additions and 78 deletions

View File

@ -45,7 +45,6 @@
<properties>
<maven.compiler.source.version>11</maven.compiler.source.version>
<maven.compiler.target.version>11</maven.compiler.target.version>
<jackson.version>2.16.0</jackson.version>
<gson.version>2.10.1</gson.version>
</properties>

View File

@ -60,7 +60,6 @@
<properties>
<jmh.version>1.21</jmh.version>
<gson.version>2.10.1</gson.version>
<jackson.version>2.16.0</jackson.version>
<org.json.version>20230618</org.json.version>
</properties>
</project>

View File

@ -36,7 +36,6 @@
</build>
<properties>
<jackson.version>2.16.0</jackson.version>
<reflections.version>0.9.11</reflections.version>
</properties>

View File

@ -30,9 +30,5 @@
</resource>
</resources>
</build>
<properties>
<jackson.version>2.16.0</jackson.version>
</properties>
</project>

View File

@ -80,6 +80,7 @@
<!-- no longer available or maintained. Ref: https://spring.io/projects/spring-data-gemfire#overview -->
<module>spring-data-geode</module>
<module>spring-data-jpa-annotations</module>
<module>spring-data-jpa-annotations-2</module>
<module>spring-data-jpa-crud</module>
<module>spring-data-jpa-crud-2</module>
<module>spring-data-jpa-enterprise</module>

View File

@ -2,4 +2,5 @@
- [Patterns for Iterating Over Large Result Sets With Spring Data JPA](https://www.baeldung.com/spring-data-jpa-iterate-large-result-sets)
- [Count the Number of Rows in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-row-count)
- [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source)
- [How To Use findBy() With Multiple Columns in JPA](https://www.baeldung.com/spring-data-jpa-findby-multiple-columns)
- More articles: [[<-- prev]](../spring-boot-persistence-2)

View File

@ -55,7 +55,6 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
@ -91,7 +90,6 @@
<maven.compiler.target>17</maven.compiler.target>
<db.util.version>1.0.7</db.util.version>
<hypersistence-utils.version>3.7.0</hypersistence-utils.version>
<jackson.version>2.16.0</jackson.version>
<modelmapper.version>3.2.0</modelmapper.version>
<commons-codec.version>1.16.1</commons-codec.version>
<lombok.version>1.18.30</lombok.version>

View File

@ -60,7 +60,6 @@
<properties>
<spring-data-elasticsearch.version>5.1.2</spring-data-elasticsearch.version>
<elasticsearch.version>8.9.0</elasticsearch.version>
<jackson.version>2.16.0</jackson.version>
</properties>
</project>

View File

@ -0,0 +1,34 @@
<?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-data-jpa-annotations-2</artifactId>
<name>spring-data-jpa-annotations-2</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,42 @@
package com.baeldung.datajpatest;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "app_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.datajpatest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class);
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.datajpatest;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}

View File

@ -0,0 +1,68 @@
package com.baeldung.datajpatest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.After;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
@DataJpaTest
public class UserRepositoryIntegrationTest {
@Autowired
private UserRepository userRepository;
private User testUser;
@BeforeEach
public void setUp() {
// Initialize test data before each test method test
testUser = new User();
testUser.setUsername("testuser");
testUser.setPassword("password");
userRepository.save(testUser);
}
@After
public void tearDown() {
// Release test data after each test method
userRepository.delete(testUser);
}
@Test
void givenUser_whenSaved_thenCanBeFoundById() {
// Verify that the user has been saved successfully
User savedUser = userRepository.findById(testUser.getId())
.orElse(null);
assertNotNull(savedUser);
assertEquals(testUser.getUsername(), savedUser.getUsername());
assertEquals(testUser.getPassword(), savedUser.getPassword());
}
@Test
void givenUser_whenUpdated_thenCanBeFoundByIdWithUpdatedData() {
testUser.setUsername("updatedUsername");
userRepository.save(testUser);
User updatedUser = userRepository.findById(testUser.getId())
.orElse(null);
assertNotNull(updatedUser);
assertEquals("updatedUsername", updatedUser.getUsername());
}
@Test
void givenUser_whenFindByUsernameCalled_thenUserIsFound() {
User foundUser = userRepository.findByUsername("testuser");
assertNotNull(foundUser);
assertEquals("testuser", foundUser.getUsername());
}
}

View File

@ -1192,7 +1192,7 @@
<jstl-api.version>1.2</jstl-api.version>
<javax.servlet.jsp-api.version>2.3.3</javax.servlet.jsp-api.version>
<jstl.version>1.2</jstl.version>
<jackson.version>2.16.0</jackson.version>
<jackson.version>2.16.1</jackson.version>
<commons-fileupload.version>1.5</commons-fileupload.version>
<junit-platform.version>1.9.2</junit-platform.version>
<junit-jupiter.version>5.9.2</junit-jupiter.version>

View File

@ -8,9 +8,10 @@
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<dependencyManagement>
@ -29,13 +30,6 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
@ -67,8 +61,9 @@
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>${jakarta.validation-api.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -109,6 +104,7 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.springcloudgateway.introduction.IntroductionGatewayApplication</mainClass>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
@ -183,12 +179,12 @@
</profiles>
<properties>
<!-- <spring-cloud-dependencies.version>Hoxton.SR3</spring-cloud-dependencies.version> -->
<!-- <spring-boot.version>2.2.6.RELEASE</spring-boot.version> -->
<spring-cloud-dependencies.version>2023.0.0</spring-cloud-dependencies.version>
<hibernate-validator.version>8.0.1.Final</hibernate-validator.version>
<redis.version>0.7.2</redis.version>
<oauth2-oidc-sdk.version>9.19</oauth2-oidc-sdk.version>
<!-- <junit-bom.version>5.5.2</junit-bom.version> -->
<jakarta.validation-api.version>3.0.2</jakarta.validation-api.version>
</properties>
</project>

View File

@ -7,7 +7,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import javax.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotEmpty;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.http.HttpCookie;

View File

@ -1,6 +1,6 @@
package com.baeldung.springcloudgateway.oauth.backend.web;
import javax.annotation.PostConstruct;
import jakarta.annotation.PostConstruct;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

View File

@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec;

View File

@ -14,7 +14,7 @@ import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.cloud.gateway.filter.factory.SetPathGatewayFilterFactory;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;

View File

@ -14,7 +14,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;

View File

@ -13,7 +13,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;

View File

@ -11,7 +11,7 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
@ -51,9 +51,8 @@ public class RedisWebFilterFactoriesLiveTest {
ResponseEntity<String> r = restTemplate.getForEntity(url, String.class);
// assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
LOGGER.info("Received: status->{}, reason->{}, remaining->{}",
r.getStatusCodeValue(), r.getStatusCode().getReasonPhrase(),
r.getHeaders().get("X-RateLimit-Remaining"));
LOGGER.info("Received: status->{}, remaining->{}",
r.getStatusCodeValue(), r.getHeaders().get("X-RateLimit-Remaining"));
}
@After

View File

@ -14,7 +14,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;

View File

@ -1,3 +1,5 @@
## Relevant Articles
- [Spring Kafka Trusted Packages Feature](https://www.baeldung.com/spring-kafka-trusted-packages-feature)
- [How to Catch Deserialization Errors in Spring-Kafka?](https://www.baeldung.com/spring-kafka-deserialization-errors)
- [View Kafka Headers in Java](https://www.baeldung.com/java-kafka-view-headers)
- [Understanding Kafka InstanceAlreadyExistsException in Java](https://www.baeldung.com/kafka-instancealreadyexistsexception)

View File

@ -0,0 +1,47 @@
package com.baeldung.spring.kafka.groupId;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.CommonErrorHandler;
@EnableKafka
@Configuration
class KafkaConfig {
@Bean
ConsumerFactory<String, String> consumerFactory(@Value("${spring.kafka.bootstrap-servers:localhost:9092}") String bootstrapServers) {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ConsumerConfig.GROUP_ID_CONFIG, "${kafka.consumer.groupId:test-consumer-group}");
props.put(ConsumerConfig.CLIENT_ID_CONFIG, "rex");
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
return new DefaultKafkaConsumerFactory<>(props, new StringDeserializer(), new StringDeserializer());
}
@Bean
ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory(ConsumerFactory<String, String> consumerFactory,
CommonErrorHandler commonErrorHandler) {
var factory = new ConcurrentKafkaListenerContainerFactory<String, String>();
factory.setConsumerFactory(consumerFactory);
factory.setCommonErrorHandler(commonErrorHandler);
return factory;
}
@Bean
CommonErrorHandler kafkaErrorHandler() {
return new KafkaErrorHandler();
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.spring.kafka.groupId;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.common.errors.RecordDeserializationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.listener.CommonErrorHandler;
import org.springframework.kafka.listener.MessageListenerContainer;
import org.springframework.lang.NonNull;
class KafkaErrorHandler implements CommonErrorHandler {
private static final Logger log = LoggerFactory.getLogger(KafkaErrorHandler.class);
@Override
public void handleOtherException(@NonNull Exception exception, @NonNull Consumer<?, ?> consumer, @NonNull MessageListenerContainer container,
boolean batchListener) {
handle(exception, consumer);
}
private void handle(Exception exception, Consumer<?, ?> consumer) {
log.error("Exception thrown", exception);
if (exception instanceof RecordDeserializationException ex) {
consumer.seek(ex.topicPartition(), ex.offset() + 1L);
consumer.commitSync();
} else {
log.error("Exception not handled", exception);
}
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.spring.kafka.groupId;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = "com.baeldung.spring.kafka.groupId")
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.spring.kafka.groupId;
import java.util.concurrent.CountDownLatch;
import org.apache.kafka.clients.consumer.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;
@Service
public class MyKafkaConsumer {
private static final Logger LOGGER = LoggerFactory.getLogger(MyKafkaConsumer.class);
private CountDownLatch latch = new CountDownLatch(1);
private String payload;
@KafkaListener(topics = "${kafka.topic.name:test-topic}", clientIdPrefix = "neo", groupId = "${kafka.consumer.groupId:test-consumer-group}", concurrency = "4")
public void receive(@Payload String payload, Consumer<String, String> consumer) {
LOGGER.info("Consumer='{}' received payload='{}'", consumer.groupMetadata()
.memberId(), payload);
this.payload = payload;
latch.countDown();
}
public CountDownLatch getLatch() {
return latch;
}
public void resetLatch() {
latch = new CountDownLatch(1);
}
public String getPayload() {
return payload;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.spring.kafka.groupId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class MyKafkaProducer {
private static final Logger LOGGER = LoggerFactory.getLogger(MyKafkaProducer.class);
@Value("${kafka.topic.name:test-topic}")
private String topic;
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void send(String payload) {
LOGGER.info("Sending payload='{}' to topic='{}'", payload, topic);
kafkaTemplate.send(topic, payload);
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.spring.kafka.groupId;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.kafka.test.context.EmbeddedKafka;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
@SpringBootTest(classes = Main.class)
@ActiveProfiles("groupId")
@ComponentScan(basePackages = "com.baeldung.spring.kafka.groupId")
@DirtiesContext
@EmbeddedKafka(partitions = 4, topics = { "${kafka.topic.name:test-topic}" }, brokerProperties = { "listeners=PLAINTEXT://localhost:8000", "port=8000" })
public class MainLiveTest {
@Autowired
private MyKafkaConsumer consumer;
@Autowired
private MyKafkaProducer producer;
@BeforeEach
void setup() {
consumer.resetLatch();
}
@Test
public void givenEmbeddedKafkaBroker_whenSendingWithSimpleProducer_thenMessageReceived() throws Exception {
String data = "Test 123...";
producer.send(data);
boolean messageConsumed = consumer.getLatch()
.await(10, TimeUnit.SECONDS);
assertTrue(messageConsumed);
assertThat(consumer.getPayload(), containsString(data));
}
}

View File

@ -0,0 +1 @@
spring.kafka.bootstrap-servers=localhost:8000

View File

@ -10,8 +10,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>spring-security-modules</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<dependencies>
@ -64,6 +65,11 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.unboundid</groupId>
<artifactId>unboundid-ldapsdk</artifactId>
<version>${unboundid-ldapsdk.version}</version>
</dependency>
</dependencies>
<build>
@ -78,6 +84,8 @@
<properties>
<apacheds.version>1.5.5</apacheds.version>
<start-class>com.baeldung.SampleLDAPApplication</start-class>
<unboundid-ldapsdk.version>4.0.10</unboundid-ldapsdk.version>
</properties>
</project>

View File

@ -3,9 +3,6 @@ package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* Main Application Class - uses Spring Boot. Just run this as a normal Java

View File

@ -6,7 +6,7 @@ import org.springframework.ldap.core.support.BaseLdapPathContextSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.ldap.LdapBindAuthenticationManagerFactory;
import org.springframework.security.ldap.server.ApacheDSContainer;
import org.springframework.security.ldap.server.UnboundIdContainer;
import org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator;
import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;
import org.springframework.security.web.SecurityFilterChain;
@ -19,8 +19,8 @@ import org.springframework.security.web.SecurityFilterChain;
public class SecurityConfig {
@Bean
ApacheDSContainer ldapContainer() throws Exception {
return new ApacheDSContainer("dc=baeldung,dc=com", "classpath:users.ldif");
UnboundIdContainer ldapContainer() throws Exception {
return new UnboundIdContainer("dc=baeldung,dc=com", "classpath:users.ldif");
}
@Bean
@ -41,18 +41,13 @@ public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home", "/css/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/");
return http.build();
return http.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/home", "/css/**")
.permitAll()
.anyRequest()
.authenticated())
.formLogin(httpSecurityFormLoginConfigurer ->
httpSecurityFormLoginConfigurer.loginPage("/login").permitAll())
.logout(logout -> logout.logoutSuccessUrl("/")).build();
}
}

View File

@ -0,0 +1,172 @@
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.directory.server.core.avltree;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Comparator;
import org.apache.directory.shared.ldap.util.StringTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class to serialize the Array data.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
@SuppressWarnings("unchecked")
public class ArrayMarshaller<E> implements Marshaller<ArrayTree<E>> {
/** static logger */
private static final Logger LOG = LoggerFactory.getLogger(ArrayMarshaller.class);
/** used for serialized form of an empty AvlTree */
private static final byte[] EMPTY_TREE = new byte[1];
/** marshaller to be used for marshalling the keys */
private Marshaller<E> keyMarshaller;
/** key Comparator for the AvlTree */
private Comparator<E> comparator;
/**
* Creates a new instance of AvlTreeMarshaller with a custom key Marshaller.
* @param comparator Comparator to be used for key comparision
* @param keyMarshaller marshaller for keys
*/
public ArrayMarshaller(Comparator<E> comparator, Marshaller<E> keyMarshaller) {
this.comparator = comparator;
this.keyMarshaller = keyMarshaller;
}
/**
* Creates a new instance of AvlTreeMarshaller with the default key Marshaller which
* uses Java Serialization.
* @param comparator Comparator to be used for key comparision
*/
public ArrayMarshaller(Comparator<E> comparator) {
this.comparator = comparator;
this.keyMarshaller = (Marshaller<E>) DefaultMarshaller.INSTANCE;
}
/**
* Marshals the given tree to bytes
* @param tree the tree to be marshalled
*/
public byte[] serialize(ArrayTree<E> tree) {
if ((tree == null) || (tree.size() == 0)) {
return EMPTY_TREE;
}
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(byteStream);
byte[] data = null;
try {
out.writeByte(0); // represents the start of an Array byte stream
out.writeInt(tree.size());
for (int position = 0; position < tree.size(); position++) {
E value = tree.get(position);
byte[] bytes = this.keyMarshaller.serialize(value);
// Write the key length
out.writeInt(bytes.length);
// Write the key if its length is not null
if (bytes.length != 0) {
out.write(bytes);
}
}
out.flush();
data = byteStream.toByteArray();
// Try to deserialize, just to see
try {
deserialize(data);
}
catch (NullPointerException npe) {
System.out.println("Bad serialization, tree : [" + StringTools.dumpBytes(data) + "]");
throw npe;
}
out.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
return data;
}
/**
* Creates an Array from given bytes of data.
* @param data byte array to be converted into an array
*/
public ArrayTree<E> deserialize(byte[] data) throws IOException {
try {
if ((data == null) || (data.length == 0)) {
throw new IOException("Null or empty data array is invalid.");
}
if ((data.length == 1) && (data[0] == 0)) {
E[] array = (E[]) new Object[] {};
ArrayTree<E> tree = new ArrayTree<E>(this.comparator, array);
return tree;
}
ByteArrayInputStream bin = new ByteArrayInputStream(data);
DataInputStream din = new DataInputStream(bin);
byte startByte = din.readByte();
if (startByte != 0) {
throw new IOException("wrong array serialized data format");
}
int size = din.readInt();
E[] nodes = (E[]) new Object[size];
for (int i = 0; i < size; i++) {
// Read the object's size
int dataSize = din.readInt();
if (dataSize != 0) {
byte[] bytes = new byte[dataSize];
din.read(bytes);
E key = this.keyMarshaller.deserialize(bytes);
nodes[i] = key;
}
}
ArrayTree<E> arrayTree = new ArrayTree<E>(this.comparator, nodes);
return arrayTree;
}
catch (NullPointerException npe) {
System.out.println("Bad tree : [" + StringTools.dumpBytes(data) + "]");
throw npe;
}
}
}

View File

@ -52,7 +52,6 @@
<properties>
<instancio.version>2.9.0</instancio.version>
<jackson.version>2.14.1</jackson.version>
<junit-jupiter.version>5.9.2</junit-jupiter.version>
</properties>
</project>

View File

@ -33,7 +33,6 @@
<properties>
<datafaker.version>1.6.0</datafaker.version>
<jackson.version>2.16.0</jackson.version>
<spring-test.version>5.3.25</spring-test.version>
</properties>

View File

@ -3,18 +3,18 @@
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>
<groupId>com.baeldung</groupId>
<artifactId>spring-testing</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-testing</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.5.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
@ -23,29 +23,66 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<version>1.18.30</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>3.2.2</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<artifactId>spring-boot</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
@ -56,10 +93,6 @@
<artifactId>javax.persistence</artifactId>
<version>${javax.persistence.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
@ -67,9 +100,34 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-api.version}</version>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<version>3.2.2</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
</dependencies>

View File

@ -5,7 +5,7 @@ import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import javax.servlet.ServletContext;
import jakarta.servlet.ServletContext;
@EnableWebMvc
@Configuration

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<springProfile name="!dev">
<root level="INFO">
<!-- This is for the local environment -->
<appender-ref ref="CONSOLE"/>
</root>
</springProfile>
<springProfile name="dev">
<include resource="com/google/cloud/spring/logging/logback-json-appender.xml"/>
<root level="INFO">
<appender-ref ref="CONSOLE_JSON"/>
</root>
</springProfile>
</configuration>