Merge branch 'eugenp:master' into danielmcnally285_string_to_long
This commit is contained in:
@@ -8,4 +8,5 @@ The code examples related to different libraries are each in their own module.
|
||||
Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases.
|
||||
|
||||
### Relevant articles
|
||||
- [Find Files by Extension in Specified Directory in Java](https://www.baeldung.com/java-recursive-search-directory-extension-match)
|
||||
- More articles [[<-- prev]](/libraries-6)
|
||||
|
||||
@@ -9,9 +9,9 @@
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<artifactId>parent-boot-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-boot-2</relativePath>
|
||||
<relativePath>../parent-boot-3</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
@@ -20,9 +20,8 @@
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security.oauth</groupId>
|
||||
<artifactId>spring-security-oauth2</artifactId>
|
||||
<version>${spring-security-oauth2.version}</version>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
@@ -68,6 +67,29 @@
|
||||
<artifactId>jsch</artifactId>
|
||||
<version>${jsch.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.xml.bind</groupId>
|
||||
<artifactId>jaxb-core</artifactId>
|
||||
<version>2.3.0.1</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
<version>2.3.1</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.xml.bind</groupId>
|
||||
<artifactId>jaxb-impl</artifactId>
|
||||
<version>2.3.1</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-oauth2-authorization-server</artifactId>
|
||||
<version>1.2.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.sshd</groupId>
|
||||
<artifactId>sshd-core</artifactId>
|
||||
@@ -125,7 +147,6 @@
|
||||
<bouncycastle.version>1.68</bouncycastle.version>
|
||||
<jsch.version>0.1.55</jsch.version>
|
||||
<apache-mina.version>2.5.1</apache-mina.version>
|
||||
<spring-security-oauth2.version>2.4.0.RELEASE</spring-security-oauth2.version>
|
||||
<xacml4j.version>1.4.0</xacml4j.version>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.web.servlet.ServletComponentScan;
|
||||
|
||||
|
||||
@SpringBootApplication
|
||||
@ServletComponentScan
|
||||
public class ScribejavaApplication {
|
||||
@@ -13,5 +12,4 @@ public class ScribejavaApplication {
|
||||
SpringApplication.run(ScribejavaApplication.class, args);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
@RestController
|
||||
public class GoogleController {
|
||||
|
||||
+8
-9
@@ -2,15 +2,14 @@ package com.baeldung.scribejava.controller;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.annotation.security.DeclareRoles;
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.HttpConstraint;
|
||||
import javax.servlet.annotation.ServletSecurity;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import jakarta.annotation.security.DeclareRoles;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.annotation.HttpConstraint;
|
||||
import jakarta.servlet.annotation.ServletSecurity;
|
||||
import jakarta.servlet.annotation.WebServlet;
|
||||
import jakarta.servlet.http.HttpServlet;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
@WebServlet(name="rbac", urlPatterns = {"/protected"})
|
||||
@DeclareRoles("USER")
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.Scanner;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.security.Principal;
|
||||
|
||||
@RestController(value = "/user")
|
||||
|
||||
+88
-30
@@ -1,45 +1,103 @@
|
||||
package com.baeldung.scribejava.oauth;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
|
||||
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
||||
import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository;
|
||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
|
||||
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
|
||||
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
|
||||
import org.springframework.security.oauth2.server.authorization.settings.ClientSettings;
|
||||
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
|
||||
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;
|
||||
|
||||
@Configuration
|
||||
@EnableAuthorizationServer
|
||||
public class AuthServiceConfig extends AuthorizationServerConfigurerAdapter {
|
||||
@EnableWebSecurity
|
||||
public class AuthServiceConfig {
|
||||
|
||||
@Autowired
|
||||
@Qualifier("authenticationManagerBean")
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
@Override
|
||||
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
|
||||
oauthServer.tokenKeyAccess("permitAll()")
|
||||
.checkTokenAccess("isAuthenticated()");
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilter(HttpSecurity http) throws Exception {
|
||||
http.headers( it -> it.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
|
||||
.csrf(AbstractHttpConfigurer::disable);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
|
||||
clients.inMemory()
|
||||
.withClient("baeldung_api_key")
|
||||
.secret("baeldung_api_secret")
|
||||
.authorizedGrantTypes("password","refresh_token")
|
||||
.scopes("read","write").autoApprove(true);
|
||||
@Bean
|
||||
public InMemoryUserDetailsManager userDetailsService() {
|
||||
UserDetails user = User.withUsername("baeldung")
|
||||
.password("scribejava")
|
||||
.roles("USER")
|
||||
.build();
|
||||
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
@Bean
|
||||
public RegisteredClientRepository registeredClientRepository() {
|
||||
RegisteredClient oidcClient = RegisteredClient.withId(UUID.randomUUID().toString())
|
||||
.clientId("baeldung_api_key")
|
||||
.clientSecret("baeldung_api_secret")
|
||||
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
|
||||
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
|
||||
.scope("read")
|
||||
.scope("write")
|
||||
.clientSettings(ClientSettings.builder().requireAuthorizationConsent(false).build())
|
||||
.build();
|
||||
|
||||
return new InMemoryRegisteredClientRepository(oidcClient);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
|
||||
endpoints
|
||||
.authenticationManager(authenticationManager)
|
||||
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
|
||||
@Bean
|
||||
@Order(1)
|
||||
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
|
||||
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
|
||||
http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
|
||||
.oidc(Customizer.withDefaults()); // Enable OpenID Connect 1.0
|
||||
http
|
||||
// Redirect to the login page when not authenticated from the
|
||||
// authorization endpoint
|
||||
.exceptionHandling((exceptions) -> exceptions
|
||||
.defaultAuthenticationEntryPointFor(
|
||||
new LoginUrlAuthenticationEntryPoint("/login"),
|
||||
new MediaTypeRequestMatcher(MediaType.TEXT_HTML)
|
||||
)
|
||||
)
|
||||
// Accept access tokens for User Info and/or Client Registration
|
||||
.oauth2ResourceServer((resourceServer) -> resourceServer
|
||||
.jwt(Customizer.withDefaults()));
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(2)
|
||||
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
|
||||
throws Exception {
|
||||
http
|
||||
.authorizeHttpRequests((authorize) -> authorize
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
// Form login handles the redirect to the login page from the
|
||||
// authorization server filter chain
|
||||
.formLogin(Customizer.withDefaults());
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
package com.baeldung.scribejava.oauth;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
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.oauth2.config.annotation.web.configuration.EnableResourceServer;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
|
||||
|
||||
@Configuration
|
||||
@EnableResourceServer
|
||||
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.headers().frameOptions().disable()
|
||||
.and()
|
||||
.csrf().disable();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.inMemoryAuthentication()
|
||||
.withUser("baeldung")
|
||||
.password("scribejava")
|
||||
.roles("USER");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManagerBean() throws Exception {
|
||||
return super.authenticationManagerBean();
|
||||
}
|
||||
|
||||
|
||||
@EnableResourceServer
|
||||
@Configuration
|
||||
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
public void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeRequests()
|
||||
.antMatchers("/user/me").authenticated()
|
||||
.and()
|
||||
.csrf().disable();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import com.github.scribejava.core.builder.ServiceBuilder;
|
||||
import com.github.scribejava.core.oauth.OAuth20Service;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
@Component
|
||||
public class GoogleService {
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import com.github.scribejava.core.builder.ServiceBuilder;
|
||||
import com.github.scribejava.core.oauth.OAuth20Service;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
|
||||
@Component
|
||||
public class MyService {
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import com.github.scribejava.core.builder.ServiceBuilder;
|
||||
import com.github.scribejava.core.oauth.OAuth10aService;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
|
||||
@Component
|
||||
public class TwitterService {
|
||||
|
||||
+9
@@ -1,5 +1,6 @@
|
||||
package com.baeldung.hibernate;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -74,5 +75,13 @@ public class CustomClassIntegrationTest {
|
||||
assertEquals("Sales", result.getDepartmentName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCastResultQueryToList_ThenListOfResultIsReturned() {
|
||||
Query<Result> query = session.createQuery("select new com.baeldung.hibernate.pojo.Result(m.name, m.department.name) "
|
||||
+ "from DeptEmployee m");
|
||||
List<Result> results = query.list();
|
||||
assertNotNull(results);
|
||||
assertEquals(1, results.size());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.spring.data.persistence.findvsget;
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class ApplicationConfig {
|
||||
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package com.baeldung.spring.data.persistence.findvsget.entity;
|
||||
|
||||
import java.util.Objects;
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@Column(name = "id")
|
||||
private Long id;
|
||||
@Column(name = "first_name")
|
||||
private String firstName;
|
||||
@Column(name = "second_name")
|
||||
private String secondName;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(final Long id, final String firstName, final String secondName) {
|
||||
this.id = id;
|
||||
this.firstName = firstName;
|
||||
this.secondName = secondName;
|
||||
}
|
||||
|
||||
public void setId(final Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(final String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getSecondName() {
|
||||
return secondName;
|
||||
}
|
||||
|
||||
public void setSecondName(final String secondName) {
|
||||
this.secondName = secondName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final User user = (User) o;
|
||||
|
||||
if (!Objects.equals(id, user.id)) {
|
||||
return false;
|
||||
}
|
||||
if (!Objects.equals(firstName, user.firstName)) {
|
||||
return false;
|
||||
}
|
||||
return Objects.equals(secondName, user.secondName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = id != null ? id.hashCode() : 0;
|
||||
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
|
||||
result = 31 * result + (secondName != null ? secondName.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" +
|
||||
"id=" + id +
|
||||
", firstName='" + firstName + '\'' +
|
||||
", secondName='" + secondName + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.spring.data.persistence.findvsget.repository;
|
||||
|
||||
import com.baeldung.spring.data.persistence.findvsget.entity.User;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Repository
|
||||
public interface NewTransactionUserRepository extends JpaRepository<User, Long> {
|
||||
|
||||
@Override
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
User getReferenceById(Long id);
|
||||
|
||||
@Override
|
||||
Optional<User> findById(Long id);
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.spring.data.persistence.findvsget.repository;
|
||||
|
||||
import com.baeldung.spring.data.persistence.findvsget.entity.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface SimpleUserRepository extends JpaRepository<User, Long> {
|
||||
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.spring.data.persistence.findvsget.service;
|
||||
|
||||
import com.baeldung.spring.data.persistence.findvsget.entity.User;
|
||||
import com.baeldung.spring.data.persistence.findvsget.repository.SimpleUserRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class NonTransactionalUserReferenceService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(NonTransactionalUserReferenceService.class);
|
||||
private SimpleUserRepository repository;
|
||||
|
||||
public User findUserReference(final long id) {
|
||||
log.info("Before requesting a user");
|
||||
final User user = repository.getReferenceById(id);
|
||||
log.info("After requesting a user");
|
||||
return user;
|
||||
}
|
||||
|
||||
public User findAndUseUserReference(final long id) {
|
||||
final User user = repository.getReferenceById(id);
|
||||
log.info("Before accessing a username");
|
||||
final String firstName = user.getFirstName();
|
||||
log.info("This message shouldn't be displayed because of the thrown exception: {}", firstName);
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setRepository(final SimpleUserRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.spring.data.persistence.findvsget.service;
|
||||
|
||||
import com.baeldung.spring.data.persistence.findvsget.entity.User;
|
||||
import com.baeldung.spring.data.persistence.findvsget.repository.SimpleUserRepository;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class SimpleUserService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SimpleUserService.class);
|
||||
private final SimpleUserRepository repository;
|
||||
|
||||
public SimpleUserService(final SimpleUserRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
public User findUser(final long id) {
|
||||
log.info("Before requesting a user in a findUser method");
|
||||
final Optional<User> optionalUser = repository.findById(id);
|
||||
log.info("After requesting a user in a findUser method");
|
||||
final User user = optionalUser.orElse(null);
|
||||
log.info("After unwrapping an optional in a findUser method");
|
||||
return user;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.spring.data.persistence.findvsget.service;
|
||||
|
||||
import com.baeldung.spring.data.persistence.findvsget.entity.User;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
public class TransactionalUserReferenceService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(TransactionalUserReferenceService.class);
|
||||
private JpaRepository<User, Long> repository;
|
||||
|
||||
@Transactional
|
||||
public User findUserReference(final long id) {
|
||||
log.info("Before requesting a user");
|
||||
final User user = repository.getReferenceById(id);
|
||||
log.info("After requesting a user");
|
||||
return user;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public User findAndUseUserReference(final long id) {
|
||||
final User user = repository.getReferenceById(id);
|
||||
log.info("Before accessing a username");
|
||||
final String firstName = user.getFirstName();
|
||||
log.info("After accessing a username: {}", firstName);
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setRepository(final JpaRepository<User, Long> repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.spring.data.persistence.findvsget;
|
||||
|
||||
import static com.baeldung.spring.data.persistence.findvsget.UserProvider.userSource;
|
||||
import static org.assertj.core.api.Assumptions.assumeThat;
|
||||
|
||||
import com.baeldung.spring.data.persistence.findvsget.entity.User;
|
||||
import com.baeldung.spring.data.persistence.findvsget.repository.SimpleUserRepository;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest(classes = ApplicationConfig.class, properties = {
|
||||
"spring.jpa.generate-ddl=true",
|
||||
"spring.jpa.show-sql=false"
|
||||
})
|
||||
abstract class DatabaseConfigurationBaseIntegrationTest {
|
||||
|
||||
private static final int NUMBER_OF_USERS = 10;
|
||||
|
||||
@Autowired
|
||||
private SimpleUserRepository repository;
|
||||
|
||||
@BeforeEach
|
||||
void populateDatabase() {
|
||||
final List<User> users = userSource()
|
||||
.map(Arguments::get)
|
||||
.map(s -> new User(((Long) s[0]), s[1].toString(), s[2].toString()))
|
||||
.collect(Collectors.toList());
|
||||
repository.saveAll(users);
|
||||
assumeThat(repository.findAll()).hasSize(NUMBER_OF_USERS);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void clearDatabase() {
|
||||
repository.deleteAll();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.spring.data.persistence.findvsget;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.baeldung.spring.data.persistence.findvsget.entity.User;
|
||||
import com.baeldung.spring.data.persistence.findvsget.service.SimpleUserService;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ArgumentsSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
@DisplayName("findBy test:")
|
||||
class FindUserIntegrationIntegrationTest extends DatabaseConfigurationBaseIntegrationTest {
|
||||
|
||||
|
||||
@Autowired
|
||||
private SimpleUserService service;
|
||||
|
||||
@ParameterizedTest
|
||||
@ArgumentsSource(UserProvider.class)
|
||||
@DisplayName("when looking for a user by an existing ID returns a user")
|
||||
void whenGettingUserByCorrectIdThenReturnUser(Long id, String firstName, String lastName) {
|
||||
final User expected = new User(id, firstName, lastName);
|
||||
final User actual = service.findUser(id);
|
||||
assertThat(actual).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@DisplayName("when looking for a user by a non-existing ID returns null")
|
||||
@ValueSource(longs = {11, 12, 13})
|
||||
void whenGettingUserByIncorrectIdThenReturnNull(Long id) {
|
||||
assertThat(service.findUser(id)).isNull();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
package com.baeldung.spring.data.persistence.findvsget;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
|
||||
import com.baeldung.spring.data.persistence.findvsget.entity.User;
|
||||
import com.baeldung.spring.data.persistence.findvsget.repository.NewTransactionUserRepository;
|
||||
import com.baeldung.spring.data.persistence.findvsget.repository.SimpleUserRepository;
|
||||
import com.baeldung.spring.data.persistence.findvsget.service.NonTransactionalUserReferenceService;
|
||||
import com.baeldung.spring.data.persistence.findvsget.service.TransactionalUserReferenceService;
|
||||
import org.hibernate.LazyInitializationException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ArgumentsSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
|
||||
@DisplayName("getReferenceBy test:")
|
||||
class GetReferenceIntegrationIntegrationTest extends DatabaseConfigurationBaseIntegrationTest {
|
||||
|
||||
private static final long EXISTING_ID = 1L;
|
||||
|
||||
@Nested
|
||||
@DisplayName("given non-transactional service, even if user exists")
|
||||
class GivenNonTransactionalService {
|
||||
|
||||
@Autowired
|
||||
private NonTransactionalUserReferenceService nonTransactionalService;
|
||||
|
||||
@BeforeEach
|
||||
void configureService(@Autowired SimpleUserRepository repository) {
|
||||
nonTransactionalService.setRepository(repository);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFindUserReferenceUsingOutsideServiceThenThrowsException() {
|
||||
final User user = nonTransactionalService.findUserReference(EXISTING_ID);
|
||||
assertThatExceptionOfType(LazyInitializationException.class)
|
||||
.isThrownBy(user::getFirstName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFindUserReferenceNotUsingOutsideServiceThenDontThrowException() {
|
||||
final User user = nonTransactionalService.findUserReference(EXISTING_ID);
|
||||
assertThat(user).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFindUserReferenceUsingInsideServiceThenThrowsException() {
|
||||
assertThatExceptionOfType(LazyInitializationException.class)
|
||||
.isThrownBy(() -> nonTransactionalService.findAndUseUserReference(EXISTING_ID));
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("given transactional service with simple repository, even if user exists")
|
||||
class GivenTransactionalService {
|
||||
|
||||
@Autowired
|
||||
private TransactionalUserReferenceService transactionalService;
|
||||
|
||||
@BeforeEach
|
||||
void configureService(@Autowired SimpleUserRepository repository) {
|
||||
transactionalService.setRepository(repository);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFindUserReferenceUsingOutsideServiceThenThrowsException() {
|
||||
final User user = transactionalService.findUserReference(EXISTING_ID);
|
||||
assertThatExceptionOfType(LazyInitializationException.class)
|
||||
.isThrownBy(user::getFirstName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFindUserReferenceNotUsingOutsideServiceThenDontThrowException() {
|
||||
final User user = transactionalService.findUserReference(EXISTING_ID);
|
||||
assertThat(user).isNotNull();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ArgumentsSource(UserProvider.class)
|
||||
void whenFindUserReferenceUsingInsideServiceThenReturnsUser(Long id, String firstName, String lastName) {
|
||||
final User expected = new User(id, firstName, lastName);
|
||||
final User actual = transactionalService.findAndUseUserReference(id);
|
||||
assertThat(actual).isEqualTo(expected);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("given transactional service with new transaction repository, even if user exists")
|
||||
class GivenTransactionalServiceWithNewTransactionRepository {
|
||||
|
||||
@Autowired
|
||||
private TransactionalUserReferenceService transactionalServiceWithNewTransactionRepository;
|
||||
|
||||
@BeforeEach
|
||||
void configureService(@Autowired NewTransactionUserRepository repository) {
|
||||
transactionalServiceWithNewTransactionRepository.setRepository(repository);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFindUserReferenceUsingOutsideServiceThenThrowsException() {
|
||||
final User user = transactionalServiceWithNewTransactionRepository
|
||||
.findUserReference(EXISTING_ID);
|
||||
assertThatExceptionOfType(LazyInitializationException.class)
|
||||
.isThrownBy(user::getFirstName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFindUserReferenceNotUsingOutsideServiceThenDontThrowException() {
|
||||
final User user = transactionalServiceWithNewTransactionRepository.findUserReference(EXISTING_ID);
|
||||
assertThat(user).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenFindUserReferenceUsingInsideServiceThenThrowsExceptionDueToSeparateTransactions() {
|
||||
assertThatExceptionOfType(LazyInitializationException.class)
|
||||
.isThrownBy(() -> transactionalServiceWithNewTransactionRepository
|
||||
.findAndUseUserReference(EXISTING_ID));
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.spring.data.persistence.findvsget;
|
||||
|
||||
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.ArgumentsProvider;
|
||||
|
||||
public class UserProvider implements ArgumentsProvider {
|
||||
|
||||
@Override
|
||||
public Stream<? extends Arguments> provideArguments(final ExtensionContext context) {
|
||||
return userSource();
|
||||
}
|
||||
|
||||
static Stream<Arguments> userSource() {
|
||||
return Stream.of(
|
||||
Arguments.of(1L, "Saundra", "Krystek"),
|
||||
Arguments.of(2L, "Korey", "Venners"),
|
||||
Arguments.of(3L, "Lory", "Daffey"),
|
||||
Arguments.of(4L, "Michail", "Spinella"),
|
||||
Arguments.of(5L, "Emanuel", "Geertje"),
|
||||
Arguments.of(6L, "Jervis", "Waugh"),
|
||||
Arguments.of(7L, "Chantal", "Soldan"),
|
||||
Arguments.of(8L, "Darnall", "Fanner"),
|
||||
Arguments.of(9L, "Cordelia", "Hindge"),
|
||||
Arguments.of(10L, "Lem", "Pitcock")
|
||||
);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.caseinsensitiveenum.converter;
|
||||
|
||||
import com.baeldung.caseinsensitiveenum.week.WeekDays;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
|
||||
public class CaseInsensitiveWeekDayConverter implements Converter<String, WeekDays> {
|
||||
|
||||
@Override
|
||||
public WeekDays convert(final String source) {
|
||||
try {
|
||||
return WeekDays.valueOf(source.trim());
|
||||
} catch (IllegalArgumentException exception) {
|
||||
return WeekDays.valueOf(source.trim().toUpperCase());
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.caseinsensitiveenum.converter;
|
||||
|
||||
import com.baeldung.caseinsensitiveenum.week.WeekDays;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
|
||||
public class StrictNullableWeekDayConverter implements Converter<String, WeekDays> {
|
||||
@Override
|
||||
public WeekDays convert(final String source) {
|
||||
try {
|
||||
return WeekDays.valueOf(source.trim());
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.caseinsensitiveenum.nonconventionalweek;
|
||||
|
||||
public enum NonConventionalWeekDays {
|
||||
Mon$Day, Tues$DAY_, Wednes$day, THURS$day_, Fri$Day$_$, Satur$DAY_, Sun$Day
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.caseinsensitiveenum.nonconventionalweek;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class NonConventionalWeekDaysHolder {
|
||||
|
||||
@Value("${monday}")
|
||||
private NonConventionalWeekDays monday;
|
||||
|
||||
@Value("${tuesday}")
|
||||
private NonConventionalWeekDays tuesday;
|
||||
|
||||
@Value("${wednesday}")
|
||||
private NonConventionalWeekDays wednesday;
|
||||
|
||||
@Value("${thursday}")
|
||||
private NonConventionalWeekDays thursday;
|
||||
|
||||
@Value("${friday}")
|
||||
private NonConventionalWeekDays friday;
|
||||
|
||||
@Value("${saturday}")
|
||||
private NonConventionalWeekDays saturday;
|
||||
|
||||
@Value("${sunday}")
|
||||
private NonConventionalWeekDays sunday;
|
||||
|
||||
public NonConventionalWeekDays getMonday() {
|
||||
return monday;
|
||||
}
|
||||
|
||||
public void setMonday(final NonConventionalWeekDays monday) {
|
||||
this.monday = monday;
|
||||
}
|
||||
|
||||
public NonConventionalWeekDays getTuesday() {
|
||||
return tuesday;
|
||||
}
|
||||
|
||||
public void setTuesday(final NonConventionalWeekDays tuesday) {
|
||||
this.tuesday = tuesday;
|
||||
}
|
||||
|
||||
public NonConventionalWeekDays getWednesday() {
|
||||
return wednesday;
|
||||
}
|
||||
|
||||
public void setWednesday(final NonConventionalWeekDays wednesday) {
|
||||
this.wednesday = wednesday;
|
||||
}
|
||||
|
||||
public NonConventionalWeekDays getThursday() {
|
||||
return thursday;
|
||||
}
|
||||
|
||||
public void setThursday(final NonConventionalWeekDays thursday) {
|
||||
this.thursday = thursday;
|
||||
}
|
||||
|
||||
public NonConventionalWeekDays getFriday() {
|
||||
return friday;
|
||||
}
|
||||
|
||||
public void setFriday(final NonConventionalWeekDays friday) {
|
||||
this.friday = friday;
|
||||
}
|
||||
|
||||
public NonConventionalWeekDays getSaturday() {
|
||||
return saturday;
|
||||
}
|
||||
|
||||
public void setSaturday(final NonConventionalWeekDays saturday) {
|
||||
this.saturday = saturday;
|
||||
}
|
||||
|
||||
public NonConventionalWeekDays getSunday() {
|
||||
return sunday;
|
||||
}
|
||||
|
||||
public void setSunday(final NonConventionalWeekDays sunday) {
|
||||
this.sunday = sunday;
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.caseinsensitiveenum.week;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class SpELWeekDaysHolder {
|
||||
|
||||
@Value("#{'${monday}'.toUpperCase()}")
|
||||
private WeekDays monday;
|
||||
|
||||
@Value("#{'${tuesday}'.toUpperCase()}")
|
||||
private WeekDays tuesday;
|
||||
|
||||
@Value("#{'${wednesday}'.toUpperCase()}")
|
||||
private WeekDays wednesday;
|
||||
|
||||
@Value("#{'${thursday}'.toUpperCase()}")
|
||||
private WeekDays thursday;
|
||||
|
||||
@Value("#{'${friday}'.toUpperCase()}")
|
||||
private WeekDays friday;
|
||||
|
||||
@Value("#{'${saturday}'.toUpperCase()}")
|
||||
private WeekDays saturday;
|
||||
|
||||
@Value("#{'${sunday}'.toUpperCase()}")
|
||||
private WeekDays sunday;
|
||||
|
||||
public WeekDays getMonday() {
|
||||
return monday;
|
||||
}
|
||||
|
||||
public void setMonday(final WeekDays monday) {
|
||||
this.monday = monday;
|
||||
}
|
||||
|
||||
public WeekDays getTuesday() {
|
||||
return tuesday;
|
||||
}
|
||||
|
||||
public void setTuesday(final WeekDays tuesday) {
|
||||
this.tuesday = tuesday;
|
||||
}
|
||||
|
||||
public WeekDays getWednesday() {
|
||||
return wednesday;
|
||||
}
|
||||
|
||||
public void setWednesday(final WeekDays wednesday) {
|
||||
this.wednesday = wednesday;
|
||||
}
|
||||
|
||||
public WeekDays getThursday() {
|
||||
return thursday;
|
||||
}
|
||||
|
||||
public void setThursday(final WeekDays thursday) {
|
||||
this.thursday = thursday;
|
||||
}
|
||||
|
||||
public WeekDays getFriday() {
|
||||
return friday;
|
||||
}
|
||||
|
||||
public void setFriday(final WeekDays friday) {
|
||||
this.friday = friday;
|
||||
}
|
||||
|
||||
public WeekDays getSaturday() {
|
||||
return saturday;
|
||||
}
|
||||
|
||||
public void setSaturday(final WeekDays saturday) {
|
||||
this.saturday = saturday;
|
||||
}
|
||||
|
||||
public WeekDays getSunday() {
|
||||
return sunday;
|
||||
}
|
||||
|
||||
public void setSunday(final WeekDays sunday) {
|
||||
this.sunday = sunday;
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.caseinsensitiveenum.week;
|
||||
|
||||
public enum WeekDays {
|
||||
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user