Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
7cab9186b4
@ -21,6 +21,12 @@
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
|
@ -0,0 +1,96 @@
|
||||
package com.baeldung.list.difference;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class FindDifferencesBetweenListsUnitTest {
|
||||
|
||||
private static final List<String> listOne = Arrays.asList("Jack", "Tom", "Sam", "John", "James", "Jack");
|
||||
private static final List<String> listTwo = Arrays.asList("Jack", "Daniel", "Sam", "Alan", "James", "George");
|
||||
|
||||
@Test
|
||||
public void givenLists_whenUsingPlainJavaImpl_thenDifferencesAreFound() {
|
||||
List<String> differences = new ArrayList<>(listOne);
|
||||
differences.removeAll(listTwo);
|
||||
assertEquals(2, differences.size());
|
||||
assertThat(differences).containsExactly("Tom", "John");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenReverseLists_whenUsingPlainJavaImpl_thenDifferencesAreFound() {
|
||||
List<String> differences = new ArrayList<>(listTwo);
|
||||
differences.removeAll(listOne);
|
||||
assertEquals(3, differences.size());
|
||||
assertThat(differences).containsExactly("Daniel", "Alan", "George");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLists_whenUsingJavaStreams_thenDifferencesAreFound() {
|
||||
List<String> differences = listOne.stream()
|
||||
.filter(element -> !listTwo.contains(element))
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(2, differences.size());
|
||||
assertThat(differences).containsExactly("Tom", "John");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenReverseLists_whenUsingJavaStreams_thenDifferencesAreFound() {
|
||||
List<String> differences = listTwo.stream()
|
||||
.filter(element -> !listOne.contains(element))
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(3, differences.size());
|
||||
assertThat(differences).containsExactly("Daniel", "Alan", "George");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLists_whenUsingGoogleGuava_thenDifferencesAreFound() {
|
||||
List<String> differences = new ArrayList<>(Sets.difference(Sets.newHashSet(listOne), Sets.newHashSet(listTwo)));
|
||||
assertEquals(2, differences.size());
|
||||
assertThat(differences).containsExactlyInAnyOrder("Tom", "John");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenReverseLists_whenUsingGoogleGuava_thenDifferencesAreFound() {
|
||||
List<String> differences = new ArrayList<>(Sets.difference(Sets.newHashSet(listTwo), Sets.newHashSet(listOne)));
|
||||
assertEquals(3, differences.size());
|
||||
assertThat(differences).containsExactlyInAnyOrder("Daniel", "Alan", "George");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLists_whenUsingApacheCommons_thenDifferencesAreFound() {
|
||||
List<String> differences = new ArrayList<>((CollectionUtils.removeAll(listOne, listTwo)));
|
||||
assertEquals(2, differences.size());
|
||||
assertThat(differences).containsExactly("Tom", "John");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenReverseLists_whenUsingApacheCommons_thenDifferencesAreFound() {
|
||||
List<String> differences = new ArrayList<>((CollectionUtils.removeAll(listTwo, listOne)));
|
||||
assertEquals(3, differences.size());
|
||||
assertThat(differences).containsExactly("Daniel", "Alan", "George");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLists_whenUsingPlainJavaImpl_thenDifferencesWithDuplicatesAreFound() {
|
||||
List<String> differences = new ArrayList<>(listOne);
|
||||
listTwo.forEach(differences::remove);
|
||||
assertThat(differences).containsExactly("Tom", "John", "Jack");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLists_whenUsingApacheCommons_thenDifferencesWithDuplicatesAreFound() {
|
||||
List<String> differences = new ArrayList<>(CollectionUtils.subtract(listOne, listTwo));
|
||||
assertEquals(3, differences.size());
|
||||
assertThat(differences).containsExactly("Tom", "John", "Jack");
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.baeldung.threadlocal;
|
||||
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.RejectedExecutionHandler;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class ThreadLocalAwareThreadPool extends ThreadPoolExecutor {
|
||||
|
||||
public ThreadLocalAwareThreadPool(int corePoolSize,
|
||||
int maximumPoolSize,
|
||||
long keepAliveTime,
|
||||
TimeUnit unit,
|
||||
BlockingQueue<Runnable> workQueue,
|
||||
ThreadFactory threadFactory,
|
||||
RejectedExecutionHandler handler) {
|
||||
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void afterExecute(Runnable r, Throwable t) {
|
||||
// Call remove on each ThreadLocal
|
||||
}
|
||||
}
|
@ -0,0 +1,96 @@
|
||||
package com.baeldung.openoptions;
|
||||
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class OpenOptionsUnitTest {
|
||||
|
||||
private static final String HOME = System.getProperty("user.home");
|
||||
private static final String DUMMY_FILE_NAME = "sample.txt";
|
||||
private static final String EXISTING_FILE_NAME = "existingFile.txt";
|
||||
|
||||
private static final String DUMMY_TEXT = "This is a sample text.";
|
||||
private static final String ANOTHER_DUMMY_TEXT = "This is a another text.";
|
||||
|
||||
@BeforeClass
|
||||
public static void beforeAll() throws IOException {
|
||||
Path path = Paths.get(HOME, DUMMY_FILE_NAME);
|
||||
|
||||
try (OutputStream out = Files.newOutputStream(path)) {
|
||||
out.write(DUMMY_TEXT.getBytes());
|
||||
}
|
||||
|
||||
Files.createFile(Paths.get(HOME, EXISTING_FILE_NAME));
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void afterAll() throws IOException {
|
||||
Files.delete(Paths.get(HOME, "newfile.txt"));
|
||||
Files.delete(Paths.get(HOME, "sparse.txt"));
|
||||
Files.delete(Paths.get(HOME, DUMMY_FILE_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingPath_whenCreateNewFile_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(HOME, "newfile.txt");
|
||||
assertFalse(Files.exists(path));
|
||||
|
||||
Files.write(path, DUMMY_TEXT.getBytes(), StandardOpenOption.CREATE);
|
||||
assertTrue(Files.exists(path));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingPath_whenReadExistingFile_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(HOME, DUMMY_FILE_NAME);
|
||||
|
||||
try (InputStream in = Files.newInputStream(path); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
assertThat(line, CoreMatchers.containsString(DUMMY_TEXT));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingPath_whenWriteToExistingFile_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(HOME, DUMMY_FILE_NAME);
|
||||
|
||||
try (OutputStream out = Files.newOutputStream(path, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) {
|
||||
out.write(ANOTHER_DUMMY_TEXT.getBytes());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingPath_whenCreateSparseFile_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(HOME, "sparse.txt");
|
||||
Files.write(path, DUMMY_TEXT.getBytes(), StandardOpenOption.CREATE_NEW, StandardOpenOption.SPARSE);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingPath_whenDeleteOnClose_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(HOME, EXISTING_FILE_NAME);
|
||||
assertTrue(Files.exists(path)); // file was already created and exists
|
||||
|
||||
try (OutputStream out = Files.newOutputStream(path, StandardOpenOption.APPEND, StandardOpenOption.WRITE, StandardOpenOption.DELETE_ON_CLOSE)) {
|
||||
out.write(ANOTHER_DUMMY_TEXT.getBytes());
|
||||
}
|
||||
|
||||
assertFalse(Files.exists(path)); // file is deleted
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistingPath_whenWriteAndSync_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(HOME, DUMMY_FILE_NAME);
|
||||
Files.write(path, ANOTHER_DUMMY_TEXT.getBytes(), StandardOpenOption.APPEND, StandardOpenOption.WRITE, StandardOpenOption.SYNC);
|
||||
}
|
||||
}
|
@ -49,11 +49,11 @@ public class EchoServer {
|
||||
if (new String(buffer.array()).trim().equals(POISON_PILL)) {
|
||||
client.close();
|
||||
System.out.println("Not accepting client messages anymore");
|
||||
} else {
|
||||
buffer.flip();
|
||||
client.write(buffer);
|
||||
buffer.clear();
|
||||
}
|
||||
|
||||
buffer.flip();
|
||||
client.write(buffer);
|
||||
buffer.clear();
|
||||
}
|
||||
|
||||
private static void register(Selector selector, ServerSocketChannel serverSocket) throws IOException {
|
||||
|
@ -3,7 +3,7 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.baeldung.jhipster5</groupId>
|
||||
<artifactId>bookstore</artifactId>
|
||||
<artifactId>bookstore-monolith</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
<name>Bookstore</name>
|
||||
|
@ -40,6 +40,6 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<jib-maven-plugin.version>0.9.10</jib-maven-plugin.version>
|
||||
<jib-maven-plugin.version>2.5.0</jib-maven-plugin.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
@ -31,7 +31,7 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<spring.version>5.2.5.RELEASE</spring.version>
|
||||
<spring.version>5.2.8.RELEASE</spring.version>
|
||||
<spring-security.version>5.2.3.RELEASE</spring-security.version>
|
||||
<spring-boot-starter-test.version>1.5.10.RELEASE</spring-boot-starter-test.version>
|
||||
</properties>
|
||||
|
3
persistence-modules/java-jpa-3/README.md
Normal file
3
persistence-modules/java-jpa-3/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
## JPA in Java
|
||||
|
||||
This module contains articles about the Java Persistence API (JPA) in Java.
|
83
persistence-modules/java-jpa-3/pom.xml
Normal file
83
persistence-modules/java-jpa-3/pom.xml
Normal file
@ -0,0 +1,83 @@
|
||||
<?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>java-jpa-3</artifactId>
|
||||
<name>java-jpa-3</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>persistence-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-jpamodelgen</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--Compile time JPA API -->
|
||||
<dependency>
|
||||
<groupId>javax.persistence</groupId>
|
||||
<artifactId>javax.persistence-api</artifactId>
|
||||
<version>${javax.persistence-api.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!--Runtime JPA implementation -->
|
||||
<dependency>
|
||||
<groupId>org.eclipse.persistence</groupId>
|
||||
<artifactId>eclipselink</artifactId>
|
||||
<version>${eclipselink.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>${postgres.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<compilerArgument>-proc:none</compilerArgument>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<hibernate.version>5.4.14.Final</hibernate.version>
|
||||
<eclipselink.version>2.7.4</eclipselink.version>
|
||||
<postgres.version>42.2.5</postgres.version>
|
||||
<javax.persistence-api.version>2.2</javax.persistence-api.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
|
||||
<maven-processor-plugin.version>3.3.3</maven-processor-plugin.version>
|
||||
<build-helper-maven-plugin.version>3.0.0</build-helper-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,53 @@
|
||||
package com.baeldung.jpa.equality;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class EqualByBusinessKey {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String email;
|
||||
|
||||
public EqualByBusinessKey() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return java.util.Objects.hashCode(email);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (obj instanceof EqualByBusinessKey) {
|
||||
if (((EqualByBusinessKey) obj).getEmail() == getEmail()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
package com.baeldung.jpa.equality;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class EqualById {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String email;
|
||||
|
||||
public EqualById() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((id == null) ? 0 : id.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (obj instanceof EqualById) {
|
||||
return ((EqualById) obj).getId().equals(getId());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package com.baeldung.jpa.equality;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class EqualByJavaDefault implements Cloneable{
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String email;
|
||||
|
||||
public EqualByJavaDefault() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public Object clone() throws CloneNotSupportedException {
|
||||
return super.clone();
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
|
||||
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
|
||||
version="2.2">
|
||||
<persistence-unit name="jpa-h2-equality">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.equality.EqualByJavaDefault</class>
|
||||
<class>com.baeldung.jpa.equality.EqualById</class>
|
||||
<class>com.baeldung.jpa.equality.EqualByBusinessKey</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test" />
|
||||
<property name="javax.persistence.jdbc.user" value="sa" />
|
||||
<property name="javax.persistence.jdbc.password" value="" />
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
|
||||
<property name="show_sql" value="false" />
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
</persistence>
|
@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT"
|
||||
class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} -
|
||||
%msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
@ -0,0 +1,74 @@
|
||||
package com.baeldung.jpa.equality;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class EqualityUnitTest {
|
||||
|
||||
private static EntityManagerFactory factory;
|
||||
private static EntityManager entityManager;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
factory = Persistence.createEntityManagerFactory("jpa-h2-equality");
|
||||
entityManager = factory.createEntityManager();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenObjectBasedEquality_whenUsingEquals_thenEqualIsBasedOnInstance() throws CloneNotSupportedException {
|
||||
EqualByJavaDefault object1 = new EqualByJavaDefault();
|
||||
EqualByJavaDefault object2 = new EqualByJavaDefault();
|
||||
|
||||
object1.setEmail("test.user@domain.com");
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(object1);
|
||||
entityManager.getTransaction().commit();
|
||||
|
||||
object2 = (EqualByJavaDefault) object1.clone();
|
||||
|
||||
Assert.assertNotEquals(object1, object2);
|
||||
Assert.assertEquals(object1.getId(), object2.getId());
|
||||
Assert.assertEquals(object1.getEmail(), object2.getEmail());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIdBasedEquality_whenUsingEquals_thenEqualIsBasedOnId() {
|
||||
EqualById object1 = new EqualById();
|
||||
EqualById object2 = new EqualById();
|
||||
|
||||
object1.setEmail("test.user.1@domain.com");
|
||||
object2.setEmail("test.user.2@domain.com");
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(object1);
|
||||
entityManager.getTransaction().commit();
|
||||
|
||||
object2.setId(object1.getId());
|
||||
|
||||
Assert.assertEquals(object1, object2);
|
||||
Assert.assertEquals(object1.getId(), object2.getId());
|
||||
Assert.assertNotEquals(object1.getEmail(), object2.getEmail());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBusinessKeyBasedEquality_whenUsingEquals_thenEqualIsBasedOnBusinessKey() {
|
||||
EqualByBusinessKey object1 = new EqualByBusinessKey();
|
||||
EqualByBusinessKey object2 = new EqualByBusinessKey();
|
||||
|
||||
object1.setEmail("test.user@test-domain.com");
|
||||
object2.setEmail("test.user@test-domain.com");
|
||||
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(object1);
|
||||
entityManager.getTransaction().commit();
|
||||
|
||||
Assert.assertEquals(object1, object2);
|
||||
Assert.assertNotEquals(object1.getId(), object2.getId());
|
||||
}
|
||||
}
|
@ -6,8 +6,8 @@ import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableJpaRepositories("com.baeldung")
|
||||
@EntityScan("com.baeldung")
|
||||
@EnableJpaRepositories("com.baeldung.boot")
|
||||
@EntityScan("com.baeldung.boot")
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
@ -4,7 +4,7 @@ import javax.persistence.*;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
@Table(name = "basic_users")
|
||||
public class BasicUser {
|
||||
|
||||
@Id
|
||||
|
13
persistence-modules/spring-jpa-2/.gitignore
vendored
Normal file
13
persistence-modules/spring-jpa-2/.gitignore
vendored
Normal file
@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
19
persistence-modules/spring-jpa-2/README.md
Normal file
19
persistence-modules/spring-jpa-2/README.md
Normal file
@ -0,0 +1,19 @@
|
||||
=========
|
||||
|
||||
## Spring JPA Example Project
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
- [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many)
|
||||
- More articles: [[<-- prev]](/spring-jpa)
|
||||
|
||||
|
||||
### Eclipse Config
|
||||
After importing the project into Eclipse, you may see the following error:
|
||||
"No persistence xml file found in project"
|
||||
|
||||
This can be ignored:
|
||||
- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project"
|
||||
Or:
|
||||
- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator
|
||||
|
152
persistence-modules/spring-jpa-2/pom.xml
Normal file
152
persistence-modules/spring-jpa-2/pom.xml
Normal file
@ -0,0 +1,152 @@
|
||||
<?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-jpa</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>spring-jpa</name>
|
||||
<packaging>war</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>persistence-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- Spring -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-orm</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- persistence -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-entitymanager</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>xml-apis</groupId>
|
||||
<artifactId>xml-apis</artifactId>
|
||||
<version>${xml-apis.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.javassist</groupId>
|
||||
<artifactId>javassist</artifactId>
|
||||
<version>${javassist.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>${mysql-connector-java.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-jpa</artifactId>
|
||||
<version>${spring-data-jpa.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- validation -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
<version>${hibernate-validator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.el</groupId>
|
||||
<artifactId>javax.el-api</artifactId>
|
||||
<version>${javax.el-api.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- web -->
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
<version>${jstl.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>servlet-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
<version>${javax.servlet.servlet-api.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- utils -->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<!-- Spring -->
|
||||
<org.springframework.version>5.1.5.RELEASE</org.springframework.version>
|
||||
<javassist.version>3.21.0-GA</javassist.version>
|
||||
|
||||
<mysql-connector-java.version>6.0.6</mysql-connector-java.version>
|
||||
<spring-data-jpa.version>2.1.5.RELEASE</spring-data-jpa.version>
|
||||
|
||||
<!-- web -->
|
||||
<javax.servlet.servlet-api.version>2.5</javax.servlet.servlet-api.version>
|
||||
|
||||
<!-- various -->
|
||||
<hibernate-validator.version>6.0.15.Final</hibernate-validator.version>
|
||||
<xml-apis.version>1.4.01</xml-apis.version>
|
||||
<javax.el-api.version>2.2.5</javax.el-api.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>21.0</guava.version>
|
||||
<assertj.version>3.8.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,85 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Properties;
|
||||
|
||||
@Configuration
|
||||
@EnableTransactionManagement
|
||||
@PropertySource({ "classpath:persistence-h2.properties" })
|
||||
@ComponentScan({ "com.baeldung.persistence" })
|
||||
@EnableJpaRepositories(basePackages = "com.baeldung.persistence.dao")
|
||||
public class PersistenceJPAConfig {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
public PersistenceJPAConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
// beans
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(dataSource());
|
||||
em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
|
||||
|
||||
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||
em.setJpaVendorAdapter(vendorAdapter);
|
||||
em.setJpaProperties(additionalProperties());
|
||||
|
||||
return em;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
|
||||
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
|
||||
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
|
||||
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
|
||||
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
|
||||
final JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(emf);
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
|
||||
return new PersistenceExceptionTranslationPostProcessor();
|
||||
}
|
||||
|
||||
final Properties additionalProperties() {
|
||||
final Properties hibernateProperties = new Properties();
|
||||
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
|
||||
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
|
||||
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "false");
|
||||
|
||||
|
||||
return hibernateProperties;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.ImportResource;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
// @Configuration
|
||||
@EnableTransactionManagement
|
||||
@ComponentScan({ "com.baeldung.persistence" })
|
||||
@ImportResource({ "classpath:jpaConfig.xml" })
|
||||
public class PersistenceJPAConfigXml {
|
||||
|
||||
public PersistenceJPAConfigXml() {
|
||||
super();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||
import org.springframework.web.servlet.view.JstlView;
|
||||
|
||||
@EnableWebMvc
|
||||
@Configuration
|
||||
@ComponentScan({ "com.baeldung.web" })
|
||||
public class SpringWebConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
@Bean
|
||||
public InternalResourceViewResolver viewResolver() {
|
||||
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
|
||||
viewResolver.setViewClass(JstlView.class);
|
||||
viewResolver.setPrefix("/WEB-INF/views/jsp/");
|
||||
viewResolver.setSuffix(".jsp");
|
||||
return viewResolver;
|
||||
}
|
||||
}
|
@ -0,0 +1,67 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.orm.jpa.JpaTransactionManager;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Properties;
|
||||
|
||||
@Configuration
|
||||
@EnableJpaRepositories(basePackages = "com.baeldung.inmemory.persistence.dao")
|
||||
@PropertySource("persistence-student.properties")
|
||||
@EnableTransactionManagement
|
||||
public class StudentJpaConfig {
|
||||
|
||||
@Autowired
|
||||
private Environment env;
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
|
||||
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
|
||||
dataSource.setUrl(env.getProperty("jdbc.url"));
|
||||
dataSource.setUsername(env.getProperty("jdbc.user"));
|
||||
dataSource.setPassword(env.getProperty("jdbc.pass"));
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||
em.setDataSource(dataSource());
|
||||
em.setPackagesToScan(new String[] { "com.baeldung.inmemory.persistence.model" });
|
||||
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
|
||||
em.setJpaProperties(additionalProperties());
|
||||
return em;
|
||||
}
|
||||
|
||||
@Bean
|
||||
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
|
||||
JpaTransactionManager transactionManager = new JpaTransactionManager();
|
||||
transactionManager.setEntityManagerFactory(entityManagerFactory);
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
final Properties additionalProperties() {
|
||||
final Properties hibernateProperties = new Properties();
|
||||
|
||||
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
|
||||
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
|
||||
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
|
||||
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache"));
|
||||
hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache"));
|
||||
|
||||
return hibernateProperties;
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.config;
|
||||
|
||||
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
|
||||
|
||||
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
|
||||
@Override
|
||||
protected Class<?>[] getRootConfigClasses() {
|
||||
return new Class[] { PersistenceJPAConfig.class };
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getServletConfigClasses() {
|
||||
return new Class[] { SpringWebConfig.class };
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String[] getServletMappings() {
|
||||
return new String[] { "/" };
|
||||
}
|
||||
}
|
@ -0,0 +1 @@
|
||||
<ResourceLink name="jdbc/BaeldungDatabase" global="jdbc/BaeldungDatabase" type="javax.sql.DataSource"/>
|
@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
@ -0,0 +1,10 @@
|
||||
# jdbc.X
|
||||
jdbc.driverClassName=org.h2.Driver
|
||||
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
|
||||
jdbc.user=sa
|
||||
jdbc.pass=
|
||||
|
||||
# hibernate.X
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
hibernate.show_sql=true
|
||||
hibernate.hbm2ddl.auto=create-drop
|
@ -0,0 +1,11 @@
|
||||
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
|
||||
jdbc.url=jdbc:mysql://localhost:3306/myDb
|
||||
jdbc.user=tutorialuser
|
||||
jdbc.pass=tutorialpass
|
||||
|
||||
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
|
||||
hibernate.show_sql=true
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
|
||||
hibernate.cache.use_second_level_cache=false
|
||||
hibernate.cache.use_query_cache=false
|
@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
|
||||
xmlns:tx="http://www.springframework.org/schema/tx"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
|
||||
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
|
||||
>
|
||||
|
||||
<context:property-placeholder location="classpath:persistence-h2.properties"/>
|
||||
|
||||
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
<property name="packagesToScan" value="com.baeldung.persistence.model"/>
|
||||
<property name="jpaVendorAdapter">
|
||||
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
|
||||
<!-- <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" /> <property name="generateDdl" value="${jpa.generateDdl}" /> <property name="databasePlatform"
|
||||
value="${persistence.dialect}" /> </bean> -->
|
||||
</property>
|
||||
<property name="jpaProperties">
|
||||
<props>
|
||||
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
|
||||
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
|
||||
</props>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
|
||||
<property name="driverClassName" value="${jdbc.driverClassName}"/>
|
||||
<property name="url" value="${jdbc.url}"/>
|
||||
<property name="username" value="${jdbc.user}"/>
|
||||
<property name="password" value="${jdbc.pass}"/>
|
||||
</bean>
|
||||
|
||||
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
|
||||
<property name="entityManagerFactory" ref="myEmf"/>
|
||||
</bean>
|
||||
<tx:annotation-driven/>
|
||||
|
||||
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
|
||||
|
||||
</beans>
|
@ -0,0 +1,6 @@
|
||||
|
||||
|
||||
<Resource name="jdbc/BaeldungDatabase" auth="Container"
|
||||
type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
|
||||
url="jdbc:postgresql://localhost:5432/postgres"
|
||||
username="baeldung" password="pass1234" maxActive="20" maxIdle="10" maxWait="-1"/>
|
@ -0,0 +1 @@
|
||||
spring.jpa.hibernate.ddl-auto=none
|
@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
|
||||
<persistence-unit name="punit">
|
||||
<class>com.baeldung.persistence.model.Foo</class>
|
||||
<class>com.baeldung.persistence.model.Bar</class>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.user" value="root"/>
|
||||
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/HIBERTEST"/>
|
||||
<property name="javax.persistence.ddl-generation" value="drop-and-create-tables"/>
|
||||
<property name="javax.persistence.logging.level" value="INFO"/>
|
||||
<property name="hibernate.show_sql" value="true"/>
|
||||
<property name="hibernate.cache.use_second_level_cache" value="false"/>
|
||||
<property name="hibernate.cache.use_query_cache" value="false"/>
|
||||
</properties>
|
||||
|
||||
</persistence-unit>
|
||||
</persistence>
|
@ -0,0 +1,21 @@
|
||||
package com.baeldung;
|
||||
|
||||
import com.baeldung.config.PersistenceJPAConfig;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
@WebAppConfiguration
|
||||
@DirtiesContext
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
@ -16,7 +16,7 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
|
||||
|
||||
@Configuration
|
||||
@PropertySource("classpath:/manytomany/test.properties")
|
||||
@PropertySource("manytomany/test.properties")
|
||||
public class ManyToManyTestConfiguration {
|
||||
|
||||
@Bean
|
13
persistence-modules/spring-jpa-2/src/test/resources/.gitignore
vendored
Normal file
13
persistence-modules/spring-jpa-2/src/test/resources/.gitignore
vendored
Normal file
@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
@ -0,0 +1,9 @@
|
||||
jdbc.driverClassName=org.h2.Driver
|
||||
jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1
|
||||
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
hibernate.show_sql=true
|
||||
hibernate.hbm2ddl.auto=create
|
||||
|
||||
hibernate.cache.use_second_level_cache=false
|
||||
hibernate.cache.use_query_cache=false
|
@ -11,9 +11,7 @@
|
||||
- [A Guide to Spring AbstractRoutingDatasource](https://www.baeldung.com/spring-abstract-routing-data-source)
|
||||
- [Obtaining Auto-generated Keys in Spring JDBC](https://www.baeldung.com/spring-jdbc-autogenerated-keys)
|
||||
- [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries)
|
||||
- [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many)
|
||||
- [Spring Persistence (Hibernate and JPA) with a JNDI datasource](https://www.baeldung.com/spring-persistence-hibernate-and-jpa-with-a-jndi-datasource-2)
|
||||
|
||||
- More articles: [[next -->]](/spring-jpa-2)
|
||||
|
||||
### Eclipse Config
|
||||
After importing the project into Eclipse, you may see the following error:
|
||||
|
@ -37,7 +37,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.security.oauth.boot</groupId>
|
||||
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
|
||||
<version>${oauth-auto.version}</version>
|
||||
<version>${spring-boot.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
@ -65,8 +65,6 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<spring-boot.version>2.1.0.RELEASE</spring-boot.version>
|
||||
<oauth-auto.version>2.1.0.RELEASE</oauth-auto.version>
|
||||
<start-class>com.baeldung.oauth2.SpringOAuthApplication</start-class>
|
||||
</properties>
|
||||
|
||||
|
@ -60,8 +60,5 @@
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<properties>
|
||||
<spring-boot.version>2.2.1.RELEASE</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
@ -0,0 +1,13 @@
|
||||
package com.baeldung.logoutredirects;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class LogoutApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(LogoutApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.logoutredirects.securityconfig;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
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;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests(authz -> authz.mvcMatchers("/login")
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated())
|
||||
.logout(logout -> logout.permitAll()
|
||||
.logoutSuccessHandler((request, response, authentication) -> {
|
||||
response.setStatus(HttpServletResponse.SC_OK);
|
||||
}));
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -2,4 +2,6 @@ server.port=8081
|
||||
|
||||
logging.level.root=INFO
|
||||
|
||||
logging.level.com.baeldung.dsl.ClientErrorLoggingFilter=DEBUG
|
||||
logging.level.com.baeldung.dsl.ClientErrorLoggingFilter=DEBUG
|
||||
|
||||
logging.level.org.springframework.security=DEBUG
|
@ -0,0 +1,34 @@
|
||||
package com.baeldung.logoutredirects;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
|
||||
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@WebMvcTest()
|
||||
public class LogoutApplicationUnitTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@WithMockUser(value = "spring")
|
||||
@Test
|
||||
public void whenLogout_thenDisableRedirect() throws Exception {
|
||||
|
||||
this.mockMvc.perform(post("/logout").with(csrf()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").doesNotExist())
|
||||
.andExpect(unauthenticated())
|
||||
.andReturn();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.baeldung.exitcode.exceptionexitgen;
|
||||
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
@SpringBootApplication
|
||||
public class ExceptionExitCodeGeneratorApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ExceptionExitCodeGeneratorApplication.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
CommandLineRunner failApplication() {
|
||||
return args -> {
|
||||
throw new FailedToStartException();
|
||||
};
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.baeldung.exitcode.exceptionexitgen;
|
||||
|
||||
import org.springframework.boot.ExitCodeGenerator;
|
||||
|
||||
public class FailedToStartException extends RuntimeException implements ExitCodeGenerator {
|
||||
|
||||
@Override
|
||||
public int getExitCode() {
|
||||
return 127;
|
||||
}
|
||||
}
|
@ -1,30 +0,0 @@
|
||||
package com.baeldung.springbootsecurity.oauth2resource;
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@EnableResourceServer
|
||||
@SpringBootApplication(scanBasePackages = "com.baeldung.springbootsecurity.oauth2resource")
|
||||
public class SpringBootOAuth2ResourceApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
new SpringApplicationBuilder()
|
||||
.profiles("resource")
|
||||
.sources(SpringBootOAuth2ResourceApplication.class)
|
||||
.build()
|
||||
.run(args);
|
||||
}
|
||||
|
||||
@RestController
|
||||
class SecuredResourceController {
|
||||
|
||||
@GetMapping("/securedResource")
|
||||
public String securedResource() {
|
||||
return "Baeldung Secured Resource OK";
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -1,47 +0,0 @@
|
||||
package com.baeldung.springbootsecurity.oauth2server;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.annotation.CurrentSecurityContext;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
|
||||
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.security.Principal;
|
||||
|
||||
@EnableResourceServer
|
||||
@EnableAuthorizationServer
|
||||
@SpringBootApplication(scanBasePackages = "com.baeldung.springbootsecurity.oauth2server")
|
||||
public class SpringBootAuthorizationServerApplication {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SpringBootAuthorizationServerApplication.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringBootAuthorizationServerApplication.class, args);
|
||||
}
|
||||
|
||||
@RestController
|
||||
class UserController {
|
||||
|
||||
@GetMapping("/user")
|
||||
public Principal user(Principal user) {
|
||||
return user;
|
||||
}
|
||||
|
||||
@GetMapping("/authentication")
|
||||
public Object getAuthentication(@CurrentSecurityContext(expression = "authentication") Authentication authentication) {
|
||||
logger.info("authentication -> {}", authentication);
|
||||
return authentication.getDetails();
|
||||
}
|
||||
|
||||
@GetMapping("/principal")
|
||||
public String getPrincipal(@CurrentSecurityContext(expression = "authentication.principal") Principal principal) {
|
||||
logger.info("principal -> {}", principal);
|
||||
return principal.getName();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
package com.baeldung.springbootsecurity.oauth2server.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
|
||||
@Configuration
|
||||
@Profile("authz")
|
||||
public class AuthenticationMananagerConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Bean
|
||||
@Override
|
||||
public AuthenticationManager authenticationManagerBean() throws Exception {
|
||||
return super.authenticationManagerBean();
|
||||
}
|
||||
}
|
@ -1,46 +0,0 @@
|
||||
package com.baeldung.springbootsecurity.oauth2server.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
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.configurers.AuthorizationServerEndpointsConfigurer;
|
||||
|
||||
@Configuration
|
||||
@Profile("authz")
|
||||
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
|
||||
|
||||
@Autowired
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
@Override
|
||||
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
|
||||
endpoints.authenticationManager(authenticationManager);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
|
||||
clients
|
||||
.inMemory()
|
||||
.withClient("baeldung")
|
||||
.secret(passwordEncoder().encode("baeldung"))
|
||||
.authorizedGrantTypes("client_credentials", "password", "authorization_code")
|
||||
.scopes("openid", "read")
|
||||
.autoApprove(true)
|
||||
.and()
|
||||
.withClient("baeldung-admin")
|
||||
.secret(passwordEncoder().encode("baeldung"))
|
||||
.authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token")
|
||||
.scopes("read", "write")
|
||||
.autoApprove(true);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public BCryptPasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
@ -1,17 +0,0 @@
|
||||
package com.baeldung.springbootsecurity.oauth2server.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
|
||||
@Configuration
|
||||
@Profile("!authz")
|
||||
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager customAuthenticationManager() throws Exception {
|
||||
return authenticationManager();
|
||||
}
|
||||
}
|
@ -1,19 +0,0 @@
|
||||
package com.baeldung.springbootsecurity.oauth2sso;
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
|
||||
@EnableOAuth2Sso
|
||||
@SpringBootApplication(scanBasePackages = "com.baeldung.springbootsecurity.oauth2sso")
|
||||
public class SpringBootOAuth2SsoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
new SpringApplicationBuilder()
|
||||
.profiles("sso")
|
||||
.sources(SpringBootOAuth2SsoApplication.class)
|
||||
.build()
|
||||
.run(args);
|
||||
}
|
||||
}
|
@ -1,89 +0,0 @@
|
||||
package com.baeldung.springbootsecurity.oauth2server;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.web.server.LocalServerPort;
|
||||
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
|
||||
import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException;
|
||||
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static java.util.Collections.singletonList;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootAuthorizationServerApplication.class)
|
||||
@ActiveProfiles("authz")
|
||||
public class CustomConfigAuthorizationServerIntegrationTest extends OAuth2IntegrationTestSupport {
|
||||
|
||||
@LocalServerPort
|
||||
private int port;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
base = new URL("http://localhost:" + port);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOAuth2Context_whenAccessTokenIsRequested_ThenAccessTokenValueIsNotNull() {
|
||||
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read"));
|
||||
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
|
||||
|
||||
OAuth2AccessToken accessToken = restTemplate.getAccessToken();
|
||||
|
||||
assertNotNull(accessToken);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOAuth2Context_whenAccessingAuthentication_ThenRespondTokenDetails() {
|
||||
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read"));
|
||||
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
|
||||
|
||||
String authentication = executeGetRequest(restTemplate, "/authentication");
|
||||
|
||||
Pattern pattern = Pattern.compile("\\{\"remoteAddress\":\".*" +
|
||||
"\",\"sessionId\":null,\"tokenValue\":\".*" +
|
||||
"\",\"tokenType\":\"Bearer\",\"decodedDetails\":null}");
|
||||
assertTrue("authentication", pattern.matcher(authentication).matches());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOAuth2Context_whenAccessingPrincipal_ThenRespondBaeldung() {
|
||||
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read"));
|
||||
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
|
||||
|
||||
String principal = executeGetRequest(restTemplate, "/principal");
|
||||
|
||||
assertEquals("baeldung", principal);
|
||||
}
|
||||
|
||||
@Test(expected = OAuth2AccessDeniedException.class)
|
||||
public void givenOAuth2Context_whenAccessTokenIsRequestedWithInvalidException_ThenExceptionIsThrown() {
|
||||
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("write"));
|
||||
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
|
||||
|
||||
restTemplate.getAccessToken();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOAuth2Context_whenAccessTokenIsRequestedByClientWithWriteScope_ThenAccessTokenIsNotNull() {
|
||||
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung-admin", singletonList("write"));
|
||||
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
|
||||
|
||||
OAuth2AccessToken accessToken = restTemplate.getAccessToken();
|
||||
|
||||
assertNotNull(accessToken);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,32 +0,0 @@
|
||||
package com.baeldung.springbootsecurity.oauth2server;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
|
||||
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootAuthorizationServerApplication.class,
|
||||
properties = { "security.oauth2.client.client-id=client", "security.oauth2.client.client-secret=baeldung" })
|
||||
public class DefaultConfigAuthorizationServerIntegrationTest extends OAuth2IntegrationTestSupport {
|
||||
|
||||
@Test
|
||||
public void givenOAuth2Context_whenAccessTokenIsRequested_ThenAccessTokenValueIsNotNull() {
|
||||
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("client", asList("read", "write"));
|
||||
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
|
||||
|
||||
OAuth2AccessToken accessToken = restTemplate.getAccessToken();
|
||||
|
||||
assertNotNull(accessToken);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,53 +0,0 @@
|
||||
package com.baeldung.springbootsecurity.oauth2server;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
|
||||
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
|
||||
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
|
||||
import org.springframework.web.client.RequestCallback;
|
||||
import org.springframework.web.client.ResponseExtractor;
|
||||
|
||||
import java.net.URL;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.List;
|
||||
|
||||
import static java.lang.String.format;
|
||||
import static java.util.Collections.singletonList;
|
||||
import static org.springframework.http.HttpMethod.GET;
|
||||
|
||||
public class OAuth2IntegrationTestSupport {
|
||||
|
||||
public static final ResponseExtractor<String> EXTRACT_BODY_AS_STRING = clientHttpResponse ->
|
||||
IOUtils.toString(clientHttpResponse.getBody(), Charset.defaultCharset());
|
||||
private static final RequestCallback DO_NOTHING_CALLBACK = request -> {
|
||||
};
|
||||
|
||||
@Value("${local.server.port}")
|
||||
protected int port;
|
||||
|
||||
protected URL base;
|
||||
|
||||
protected ClientCredentialsResourceDetails getClientCredentialsResourceDetails(final String clientId, final List<String> scopes) {
|
||||
ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
|
||||
resourceDetails.setAccessTokenUri(format("http://localhost:%d/oauth/token", port));
|
||||
resourceDetails.setClientId(clientId);
|
||||
resourceDetails.setClientSecret("baeldung");
|
||||
resourceDetails.setScope(scopes);
|
||||
resourceDetails.setGrantType("client_credentials");
|
||||
return resourceDetails;
|
||||
}
|
||||
|
||||
protected OAuth2RestTemplate getOAuth2RestTemplate(final ClientCredentialsResourceDetails resourceDetails) {
|
||||
DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();
|
||||
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails, clientContext);
|
||||
restTemplate.setMessageConverters(singletonList(new MappingJackson2HttpMessageConverter()));
|
||||
return restTemplate;
|
||||
}
|
||||
|
||||
protected String executeGetRequest(OAuth2RestTemplate restTemplate, String path) {
|
||||
return restTemplate.execute(base.toString() + path, GET, DO_NOTHING_CALLBACK, EXTRACT_BODY_AS_STRING);
|
||||
}
|
||||
|
||||
}
|
@ -72,8 +72,7 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
|
||||
<spring-boot.version>2.2.2.RELEASE</spring-boot.version>
|
||||
<spring-cloud.version>Hoxton.SR4</spring-cloud.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
@ -18,8 +18,4 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<spring-cloud.version>Hoxton.SR1</spring-cloud.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -48,8 +48,6 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<spring-cloud.version>Finchley.SR1</spring-cloud.version>
|
||||
<spring-boot.version>2.0.6.RELEASE</spring-boot.version>
|
||||
<rate.limit.version>2.2.0.RELEASE</rate.limit.version>
|
||||
</properties>
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user