From e3bada67dd6bcabcdeb4c61304360aa78054abf7 Mon Sep 17 00:00:00 2001 From: Philippe Date: Thu, 24 Jan 2019 23:35:44 -0200 Subject: [PATCH 001/167] BAEL-1381 --- sql-injection-samples/.gitignore | 25 +++ sql-injection-samples/pom.xml | 61 +++++++ .../examples/security/sql/AccountDAO.java | 169 ++++++++++++++++++ .../examples/security/sql/AccountDTO.java | 16 ++ .../sql/SqlInjectionSamplesApplication.java | 14 ++ .../src/main/resources/application.properties | 0 .../resources/db/changelog/create-tables.xml | 19 ++ .../main/resources/db/master-changelog.xml | 8 + ...qlInjectionSamplesApplicationUnitTest.java | 60 +++++++ .../src/test/resources/application-test.yml | 6 + .../src/test/resources/data.sql | 4 + .../src/test/resources/schema.sql | 6 + 12 files changed, 388 insertions(+) create mode 100644 sql-injection-samples/.gitignore create mode 100644 sql-injection-samples/pom.xml create mode 100644 sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java create mode 100644 sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java create mode 100644 sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java create mode 100644 sql-injection-samples/src/main/resources/application.properties create mode 100644 sql-injection-samples/src/main/resources/db/changelog/create-tables.xml create mode 100644 sql-injection-samples/src/main/resources/db/master-changelog.xml create mode 100644 sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java create mode 100644 sql-injection-samples/src/test/resources/application-test.yml create mode 100644 sql-injection-samples/src/test/resources/data.sql create mode 100644 sql-injection-samples/src/test/resources/schema.sql diff --git a/sql-injection-samples/.gitignore b/sql-injection-samples/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/sql-injection-samples/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/sql-injection-samples/pom.xml b/sql-injection-samples/pom.xml new file mode 100644 index 0000000000..b6390ad387 --- /dev/null +++ b/sql-injection-samples/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + com.baeldung + sql-injection-samples + 0.0.1-SNAPSHOT + sql-injection-samples + Sample SQL Injection tests + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-jdbc + + + + org.apache.derby + derby + runtime + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.projectlombok + lombok + provided + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java b/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java new file mode 100644 index 0000000000..447dcc456d --- /dev/null +++ b/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java @@ -0,0 +1,169 @@ +/** + * + */ +package com.baeldung.examples.security.sql; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import javax.sql.DataSource; + +import org.springframework.stereotype.Component; + +/** + * @author Philippe + * + */ +@Component +public class AccountDAO { + + private final DataSource dataSource; + + public AccountDAO(DataSource dataSource) { + this.dataSource = dataSource; + } + + /** + * Return all accounts owned by a given customer,given his/her external id + * + * @param customerId + * @return + */ + public List unsafeFindAccountsByCustomerId(String customerId) { + + String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = '" + customerId + "'"; + + try (Connection c = dataSource.getConnection(); + ResultSet rs = c.createStatement() + .executeQuery(sql)) { + List accounts = new ArrayList<>(); + while (rs.next()) { + AccountDTO acc = AccountDTO.builder() + .customerId(rs.getString("customer_id")) + .branchId(rs.getString("branch_id")) + .accNumber(rs.getString("acc_number")) + .balance(rs.getBigDecimal("balance")) + .build(); + + accounts.add(acc); + } + + return accounts; + } catch (SQLException ex) { + throw new RuntimeException(ex); + } + } + + /** + * Return all accounts owned by a given customer,given his/her external id + * + * @param customerId + * @return + */ + public List safeFindAccountsByCustomerId(String customerId) { + + String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = ?"; + + try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement(sql)) { + p.setString(1, customerId); + ResultSet rs = p.executeQuery(); + List accounts = new ArrayList<>(); + while (rs.next()) { + AccountDTO acc = AccountDTO.builder() + .customerId(rs.getString("customerId")) + .branchId(rs.getString("branch_id")) + .accNumber(rs.getString("acc_number")) + .balance(rs.getBigDecimal("balance")) + .build(); + + accounts.add(acc); + } + return accounts; + } catch (SQLException ex) { + throw new RuntimeException(ex); + } + } + + private static final Set VALID_COLUMNS_FOR_ORDER_BY = Stream.of("acc_number", "branch_id", "balance") + .collect(Collectors.toCollection(HashSet::new)); + + /** + * Return all accounts owned by a given customer,given his/her external id + * + * @param customerId + * @return + */ + public List safeFindAccountsByCustomerId(String customerId, String orderBy) { + + String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = ? "; + + if (VALID_COLUMNS_FOR_ORDER_BY.contains(orderBy)) { + sql = sql + " order by " + orderBy; + } + else { + throw new IllegalArgumentException("Nice try!"); + } + + try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement(sql)) { + + p.setString(1, customerId); + ResultSet rs = p.executeQuery(); + List accounts = new ArrayList<>(); + while (rs.next()) { + AccountDTO acc = AccountDTO.builder() + .customerId(rs.getString("customerId")) + .branchId(rs.getString("branch_id")) + .accNumber(rs.getString("acc_number")) + .balance(rs.getBigDecimal("balance")) + .build(); + + accounts.add(acc); + } + + return accounts; + } catch (SQLException ex) { + throw new RuntimeException(ex); + } + } + + /** + * Invalid placeholder usage example + * + * @param tableName + * @return + */ + public List wrongCountRecordsByTableName(String tableName) { + + try (Connection c = dataSource.getConnection(); + PreparedStatement p = c.prepareStatement("select count(*) from ?")) { + + p.setString(1, tableName); + ResultSet rs = p.executeQuery(); + List accounts = new ArrayList<>(); + while (rs.next()) { + AccountDTO acc = AccountDTO.builder() + .customerId(rs.getString("customerId")) + .branchId(rs.getString("branch_id")) + .accNumber(rs.getString("acc_number")) + .balance(rs.getBigDecimal("balance")) + .build(); + + accounts.add(acc); + } + + return accounts; + } catch (SQLException ex) { + throw new RuntimeException(ex); + } + } + +} diff --git a/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java b/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java new file mode 100644 index 0000000000..2e6fa04af4 --- /dev/null +++ b/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java @@ -0,0 +1,16 @@ +package com.baeldung.examples.security.sql; + +import java.math.BigDecimal; + +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class AccountDTO { + + private String customerId; + private String accNumber; + private String branchId; + private BigDecimal balance; +} diff --git a/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java b/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java new file mode 100644 index 0000000000..c1083ae3de --- /dev/null +++ b/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.examples.security.sql; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SqlInjectionSamplesApplication { + + public static void main(String[] args) { + SpringApplication.run(SqlInjectionSamplesApplication.class, args); + } + +} + diff --git a/sql-injection-samples/src/main/resources/application.properties b/sql-injection-samples/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml b/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml new file mode 100644 index 0000000000..a405c02049 --- /dev/null +++ b/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sql-injection-samples/src/main/resources/db/master-changelog.xml b/sql-injection-samples/src/main/resources/db/master-changelog.xml new file mode 100644 index 0000000000..047ca2b314 --- /dev/null +++ b/sql-injection-samples/src/main/resources/db/master-changelog.xml @@ -0,0 +1,8 @@ + + + + \ No newline at end of file diff --git a/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java b/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java new file mode 100644 index 0000000000..1f37ba04b6 --- /dev/null +++ b/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.examples.security.sql; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.examples.security.sql.AccountDAO; +import com.baeldung.examples.security.sql.AccountDTO; + +@RunWith(SpringRunner.class) +@SpringBootTest +@ActiveProfiles({ "test" }) +public class SqlInjectionSamplesApplicationUnitTest { + + @Autowired + private AccountDAO target; + + @Test + public void givenAVulnerableMethod_whenValidCustomerId_thenReturnSingleAccount() { + + List accounts = target.unsafeFindAccountsByCustomerId("C1"); + assertThat(accounts).isNotNull(); + assertThat(accounts).isNotEmpty(); + assertThat(accounts).hasSize(1); + } + + @Test + public void givenAVulnerableMethod_whenHackedCustomerId_thenReturnAllAccounts() { + + List accounts = target.unsafeFindAccountsByCustomerId("C1' or '1'='1"); + assertThat(accounts).isNotNull(); + assertThat(accounts).isNotEmpty(); + assertThat(accounts).hasSize(3); + } + + @Test + public void givenASafeMethod_whenHackedCustomerId_thenReturnNoAccounts() { + + List accounts = target.safeFindAccountsByCustomerId("C1' or '1'='1"); + assertThat(accounts).isNotNull(); + assertThat(accounts).isEmpty(); + } + + @Test(expected = IllegalArgumentException.class) + public void givenASafeMethod_whenInvalidOrderBy_thenThroweException() { + target.safeFindAccountsByCustomerId("C1", "INVALID"); + } + + @Test(expected = RuntimeException.class) + public void givenWrongPlaceholderUsageMethod_whenNormalCall_thenThrowsException() { + target.wrongCountRecordsByTableName("Accounts"); + } +} diff --git a/sql-injection-samples/src/test/resources/application-test.yml b/sql-injection-samples/src/test/resources/application-test.yml new file mode 100644 index 0000000000..d07ee10aee --- /dev/null +++ b/sql-injection-samples/src/test/resources/application-test.yml @@ -0,0 +1,6 @@ +# +# Test profile configuration +# +spring: + datasource: + initialization-mode: always diff --git a/sql-injection-samples/src/test/resources/data.sql b/sql-injection-samples/src/test/resources/data.sql new file mode 100644 index 0000000000..586618a07f --- /dev/null +++ b/sql-injection-samples/src/test/resources/data.sql @@ -0,0 +1,4 @@ +insert into Accounts(customer_id,acc_number,branch_id,balance) values ('C1','0001',1,1000.00); +insert into Accounts(customer_id,acc_number,branch_id,balance) values ('C2','0002',1,500.00); +insert into Accounts(customer_id,acc_number,branch_id,balance) values ('C3','0003',1,501.00); + diff --git a/sql-injection-samples/src/test/resources/schema.sql b/sql-injection-samples/src/test/resources/schema.sql new file mode 100644 index 0000000000..bfb0ae8059 --- /dev/null +++ b/sql-injection-samples/src/test/resources/schema.sql @@ -0,0 +1,6 @@ +create table Accounts ( + customer_id varchar(16) not null, + acc_number varchar(16) not null, + branch_id decimal(8,0), + balance decimal(16,4) +); From 43d429e4151d5cf62ba7ce7ae69b13bb415be698 Mon Sep 17 00:00:00 2001 From: Philippe Date: Thu, 24 Jan 2019 23:48:22 -0200 Subject: [PATCH 002/167] [BAEL-1381] --- pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d084d0f7af..9306a1db2e 100644 --- a/pom.xml +++ b/pom.xml @@ -567,7 +567,8 @@ rule-engines/rulebook rsocket rxjava - rxjava-2 + rxjava-2 + sql-injection-samples From bc267aec07a0de7a79a7484cb60343f7a8067da3 Mon Sep 17 00:00:00 2001 From: Philippe Date: Tue, 29 Jan 2019 21:34:30 -0200 Subject: [PATCH 003/167] [BAEL-1381] New module name --- pom.xml | 2 +- .../sql-injection-samples}/.gitignore | 0 .../sql-injection-samples}/pom.xml | 2 +- .../java/com/baeldung/examples/security/sql/AccountDAO.java | 0 .../java/com/baeldung/examples/security/sql/AccountDTO.java | 0 .../examples/security/sql/SqlInjectionSamplesApplication.java | 0 .../src/main/resources/application.properties | 0 .../src/main/resources/db/changelog/create-tables.xml | 0 .../src/main/resources/db/master-changelog.xml | 0 .../security/sql/SqlInjectionSamplesApplicationUnitTest.java | 0 .../src/test/resources/application-test.yml | 0 .../sql-injection-samples}/src/test/resources/data.sql | 0 .../sql-injection-samples}/src/test/resources/schema.sql | 0 13 files changed, 2 insertions(+), 2 deletions(-) rename {sql-injection-samples => software-security/sql-injection-samples}/.gitignore (100%) rename {sql-injection-samples => software-security/sql-injection-samples}/pom.xml (96%) rename {sql-injection-samples => software-security/sql-injection-samples}/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java (100%) rename {sql-injection-samples => software-security/sql-injection-samples}/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java (100%) rename {sql-injection-samples => software-security/sql-injection-samples}/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java (100%) rename {sql-injection-samples => software-security/sql-injection-samples}/src/main/resources/application.properties (100%) rename {sql-injection-samples => software-security/sql-injection-samples}/src/main/resources/db/changelog/create-tables.xml (100%) rename {sql-injection-samples => software-security/sql-injection-samples}/src/main/resources/db/master-changelog.xml (100%) rename {sql-injection-samples => software-security/sql-injection-samples}/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java (100%) rename {sql-injection-samples => software-security/sql-injection-samples}/src/test/resources/application-test.yml (100%) rename {sql-injection-samples => software-security/sql-injection-samples}/src/test/resources/data.sql (100%) rename {sql-injection-samples => software-security/sql-injection-samples}/src/test/resources/schema.sql (100%) diff --git a/pom.xml b/pom.xml index 68a4a1f7ad..30d5e2ade8 100644 --- a/pom.xml +++ b/pom.xml @@ -568,7 +568,7 @@ rsocket rxjava rxjava-2 - sql-injection-samples + software-security diff --git a/sql-injection-samples/.gitignore b/software-security/sql-injection-samples/.gitignore similarity index 100% rename from sql-injection-samples/.gitignore rename to software-security/sql-injection-samples/.gitignore diff --git a/sql-injection-samples/pom.xml b/software-security/sql-injection-samples/pom.xml similarity index 96% rename from sql-injection-samples/pom.xml rename to software-security/sql-injection-samples/pom.xml index b6390ad387..d5e64db6b3 100644 --- a/sql-injection-samples/pom.xml +++ b/software-security/sql-injection-samples/pom.xml @@ -7,7 +7,7 @@ parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-2 + ../../parent-boot-2 com.baeldung diff --git a/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java similarity index 100% rename from sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java rename to software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java diff --git a/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java similarity index 100% rename from sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java rename to software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java diff --git a/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java similarity index 100% rename from sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java rename to software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java diff --git a/sql-injection-samples/src/main/resources/application.properties b/software-security/sql-injection-samples/src/main/resources/application.properties similarity index 100% rename from sql-injection-samples/src/main/resources/application.properties rename to software-security/sql-injection-samples/src/main/resources/application.properties diff --git a/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml b/software-security/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml similarity index 100% rename from sql-injection-samples/src/main/resources/db/changelog/create-tables.xml rename to software-security/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml diff --git a/sql-injection-samples/src/main/resources/db/master-changelog.xml b/software-security/sql-injection-samples/src/main/resources/db/master-changelog.xml similarity index 100% rename from sql-injection-samples/src/main/resources/db/master-changelog.xml rename to software-security/sql-injection-samples/src/main/resources/db/master-changelog.xml diff --git a/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java b/software-security/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java similarity index 100% rename from sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java rename to software-security/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java diff --git a/sql-injection-samples/src/test/resources/application-test.yml b/software-security/sql-injection-samples/src/test/resources/application-test.yml similarity index 100% rename from sql-injection-samples/src/test/resources/application-test.yml rename to software-security/sql-injection-samples/src/test/resources/application-test.yml diff --git a/sql-injection-samples/src/test/resources/data.sql b/software-security/sql-injection-samples/src/test/resources/data.sql similarity index 100% rename from sql-injection-samples/src/test/resources/data.sql rename to software-security/sql-injection-samples/src/test/resources/data.sql diff --git a/sql-injection-samples/src/test/resources/schema.sql b/software-security/sql-injection-samples/src/test/resources/schema.sql similarity index 100% rename from sql-injection-samples/src/test/resources/schema.sql rename to software-security/sql-injection-samples/src/test/resources/schema.sql From 35b89e5cbcd54032f7c80dca83fcca7b011a0cc9 Mon Sep 17 00:00:00 2001 From: Philippe Date: Tue, 29 Jan 2019 22:06:02 -0200 Subject: [PATCH 004/167] [BAEL-1381] software-security module --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 30d5e2ade8..787a03c2fb 100644 --- a/pom.xml +++ b/pom.xml @@ -568,7 +568,7 @@ rsocket rxjava rxjava-2 - software-security + software-security/sql-injection-samples From 9f61a81114fa31132c4764c22ae11f3bc4f51171 Mon Sep 17 00:00:00 2001 From: Philippe Date: Sun, 17 Feb 2019 20:56:09 -0300 Subject: [PATCH 005/167] [BAEL-1381] Add JPA examples --- .../CustomBaeldungQueueUnitTest.java | 0 .../PriorityQueueUnitTest.java | 0 .../sql-injection-samples/pom.xml | 13 ++ .../examples/security/sql/Account.java | 34 ++++ .../examples/security/sql/AccountDAO.java | 171 +++++++++++++++--- .../src/main/resources/application.properties | 1 + .../resources/db/changelog/create-tables.xml | 19 -- .../main/resources/db/master-changelog.xml | 8 - ...qlInjectionSamplesApplicationUnitTest.java | 34 +++- .../src/test/resources/application-test.yml | 14 +- .../src/test/resources/schema.sql | 1 + 11 files changed, 245 insertions(+), 50 deletions(-) rename core-java-collections/src/test/java/com/baeldung/{queueinterface => queueInterface}/CustomBaeldungQueueUnitTest.java (100%) rename core-java-collections/src/test/java/com/baeldung/{queueinterface => queueInterface}/PriorityQueueUnitTest.java (100%) create mode 100644 software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/Account.java delete mode 100644 software-security/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml delete mode 100644 software-security/sql-injection-samples/src/main/resources/db/master-changelog.xml diff --git a/core-java-collections/src/test/java/com/baeldung/queueinterface/CustomBaeldungQueueUnitTest.java b/core-java-collections/src/test/java/com/baeldung/queueInterface/CustomBaeldungQueueUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/queueinterface/CustomBaeldungQueueUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/queueInterface/CustomBaeldungQueueUnitTest.java diff --git a/core-java-collections/src/test/java/com/baeldung/queueinterface/PriorityQueueUnitTest.java b/core-java-collections/src/test/java/com/baeldung/queueInterface/PriorityQueueUnitTest.java similarity index 100% rename from core-java-collections/src/test/java/com/baeldung/queueinterface/PriorityQueueUnitTest.java rename to core-java-collections/src/test/java/com/baeldung/queueInterface/PriorityQueueUnitTest.java diff --git a/software-security/sql-injection-samples/pom.xml b/software-security/sql-injection-samples/pom.xml index e4510d9ef8..5b33c674d4 100644 --- a/software-security/sql-injection-samples/pom.xml +++ b/software-security/sql-injection-samples/pom.xml @@ -16,6 +16,8 @@ + + org.springframework.boot spring-boot-starter-jdbc @@ -42,6 +44,17 @@ provided + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.hibernate + hibernate-jpamodelgen + + + diff --git a/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/Account.java b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/Account.java new file mode 100644 index 0000000000..3f077d5592 --- /dev/null +++ b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/Account.java @@ -0,0 +1,34 @@ +/** + * + */ +package com.baeldung.examples.security.sql; + +import java.math.BigDecimal; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import lombok.Data; + +/** + * @author Philippe + * + */ +@Entity +@Table(name="Accounts") +@Data +public class Account { + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + private Long id; + + private String customerId; + private String accNumber; + private String branchId; + private BigDecimal balance; + +} diff --git a/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java index 447dcc456d..c7285e5fd3 100644 --- a/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java +++ b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java @@ -7,14 +7,24 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; +import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; +import javax.persistence.EntityManager; +import javax.persistence.Query; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Order; +import javax.persistence.criteria.Root; +import javax.persistence.metamodel.SingularAttribute; import javax.sql.DataSource; import org.springframework.stereotype.Component; @@ -27,9 +37,11 @@ import org.springframework.stereotype.Component; public class AccountDAO { private final DataSource dataSource; + private final EntityManager em; - public AccountDAO(DataSource dataSource) { + public AccountDAO(DataSource dataSource, EntityManager em) { this.dataSource = dataSource; + this.em = em; } /** @@ -63,6 +75,26 @@ public class AccountDAO { } } + /** + * Return all accounts owned by a given customer,given his/her external id - JPA version + * + * @param customerId + * @return + */ + public List unsafeJpaFindAccountsByCustomerId(String customerId) { + String jql = "from Account where customerId = '" + customerId + "'"; + TypedQuery q = em.createQuery(jql, Account.class); + return q.getResultList() + .stream() + .map(a -> AccountDTO.builder() + .accNumber(a.getAccNumber()) + .balance(a.getBalance()) + .branchId(a.getAccNumber()) + .customerId(a.getCustomerId()) + .build()) + .collect(Collectors.toList()); + } + /** * Return all accounts owned by a given customer,given his/her external id * @@ -71,7 +103,7 @@ public class AccountDAO { */ public List safeFindAccountsByCustomerId(String customerId) { - String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = ?"; + String sql = "select customer_id, branch_id,acc_number,balance from Accounts where customer_id = ?"; try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement(sql)) { p.setString(1, customerId); @@ -93,23 +125,73 @@ public class AccountDAO { } } + /** + * Return all accounts owned by a given customer,given his/her external id - JPA version + * + * @param customerId + * @return + */ + public List safeJpaFindAccountsByCustomerId(String customerId) { + + String jql = "from Account where customerId = :customerId"; + TypedQuery q = em.createQuery(jql, Account.class) + .setParameter("customerId", customerId); + + return q.getResultList() + .stream() + .map(a -> AccountDTO.builder() + .accNumber(a.getAccNumber()) + .balance(a.getBalance()) + .branchId(a.getAccNumber()) + .customerId(a.getCustomerId()) + .build()) + .collect(Collectors.toList()); + } + + /** + * Return all accounts owned by a given customer,given his/her external id - JPA version + * + * @param customerId + * @return + */ + public List safeJpaCriteriaFindAccountsByCustomerId(String customerId) { + + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(Account.class); + Root root = cq.from(Account.class); + cq.select(root) + .where(cb.equal(root.get(Account_.customerId), customerId)); + + TypedQuery q = em.createQuery(cq); + + return q.getResultList() + .stream() + .map(a -> AccountDTO.builder() + .accNumber(a.getAccNumber()) + .balance(a.getBalance()) + .branchId(a.getAccNumber()) + .customerId(a.getCustomerId()) + .build()) + .collect(Collectors.toList()); + } + private static final Set VALID_COLUMNS_FOR_ORDER_BY = Stream.of("acc_number", "branch_id", "balance") .collect(Collectors.toCollection(HashSet::new)); + /** * Return all accounts owned by a given customer,given his/her external id * * @param customerId * @return */ - public List safeFindAccountsByCustomerId(String customerId, String orderBy) { + public List safeFindAccountsByCustomerId(String customerId, String orderBy) { String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = ? "; if (VALID_COLUMNS_FOR_ORDER_BY.contains(orderBy)) { sql = sql + " order by " + orderBy; - } - else { + } else { throw new IllegalArgumentException("Nice try!"); } @@ -135,35 +217,82 @@ public class AccountDAO { } } + + private static final Map> VALID_JPA_COLUMNS_FOR_ORDER_BY = Stream.of( + new AbstractMap.SimpleEntry<>(Account_.ACC_NUMBER, Account_.accNumber), + new AbstractMap.SimpleEntry<>(Account_.BRANCH_ID, Account_.branchId), + new AbstractMap.SimpleEntry<>(Account_.BALANCE, Account_.balance) + ) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + + /** + * Return all accounts owned by a given customer,given his/her external id + * + * @param customerId + * @return + */ + public List safeJpaFindAccountsByCustomerId(String customerId, String orderBy) { + +SingularAttribute orderByAttribute = VALID_JPA_COLUMNS_FOR_ORDER_BY.get(orderBy); +if ( orderByAttribute == null) { + throw new IllegalArgumentException("Nice try!"); +} + +CriteriaBuilder cb = em.getCriteriaBuilder(); +CriteriaQuery cq = cb.createQuery(Account.class); +Root root = cq.from(Account.class); +cq.select(root) + .where(cb.equal(root.get(Account_.customerId), customerId)) + .orderBy(cb.asc(root.get(orderByAttribute))); + +TypedQuery q = em.createQuery(cq); + + return q.getResultList() + .stream() + .map(a -> AccountDTO.builder() + .accNumber(a.getAccNumber()) + .balance(a.getBalance()) + .branchId(a.getAccNumber()) + .customerId(a.getCustomerId()) + .build()) + .collect(Collectors.toList()); + + } + /** * Invalid placeholder usage example * * @param tableName * @return */ - public List wrongCountRecordsByTableName(String tableName) { + public Long wrongCountRecordsByTableName(String tableName) { + + try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement("select count(*) from ?")) { - try (Connection c = dataSource.getConnection(); - PreparedStatement p = c.prepareStatement("select count(*) from ?")) { - p.setString(1, tableName); ResultSet rs = p.executeQuery(); - List accounts = new ArrayList<>(); - while (rs.next()) { - AccountDTO acc = AccountDTO.builder() - .customerId(rs.getString("customerId")) - .branchId(rs.getString("branch_id")) - .accNumber(rs.getString("acc_number")) - .balance(rs.getBigDecimal("balance")) - .build(); + rs.next(); + return rs.getLong(1); - accounts.add(acc); - } - - return accounts; } catch (SQLException ex) { throw new RuntimeException(ex); } } + /** + * Invalid placeholder usage example - JPA + * + * @param tableName + * @return + */ + public Long wrongJpaCountRecordsByTableName(String tableName) { + + String jql = "select count(*) from :tableName"; + TypedQuery q = em.createQuery(jql, Long.class) + .setParameter("tableName", tableName); + + return q.getSingleResult(); + + } + } diff --git a/software-security/sql-injection-samples/src/main/resources/application.properties b/software-security/sql-injection-samples/src/main/resources/application.properties index e69de29bb2..8b13789179 100644 --- a/software-security/sql-injection-samples/src/main/resources/application.properties +++ b/software-security/sql-injection-samples/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/software-security/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml b/software-security/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml deleted file mode 100644 index a405c02049..0000000000 --- a/software-security/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/software-security/sql-injection-samples/src/main/resources/db/master-changelog.xml b/software-security/sql-injection-samples/src/main/resources/db/master-changelog.xml deleted file mode 100644 index 047ca2b314..0000000000 --- a/software-security/sql-injection-samples/src/main/resources/db/master-changelog.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - \ No newline at end of file diff --git a/software-security/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java b/software-security/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java index 1f37ba04b6..f61b738abc 100644 --- a/software-security/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java +++ b/software-security/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java @@ -40,6 +40,15 @@ public class SqlInjectionSamplesApplicationUnitTest { assertThat(accounts).hasSize(3); } + @Test + public void givenAVulnerableJpaMethod_whenHackedCustomerId_thenReturnAllAccounts() { + + List accounts = target.unsafeJpaFindAccountsByCustomerId("C1' or '1'='1"); + assertThat(accounts).isNotNull(); + assertThat(accounts).isNotEmpty(); + assertThat(accounts).hasSize(3); + } + @Test public void givenASafeMethod_whenHackedCustomerId_thenReturnNoAccounts() { @@ -48,13 +57,36 @@ public class SqlInjectionSamplesApplicationUnitTest { assertThat(accounts).isEmpty(); } + @Test + public void givenASafeJpaMethod_whenHackedCustomerId_thenReturnNoAccounts() { + + List accounts = target.safeJpaFindAccountsByCustomerId("C1' or '1'='1"); + assertThat(accounts).isNotNull(); + assertThat(accounts).isEmpty(); + } + + + @Test + public void givenASafeJpaCriteriaMethod_whenHackedCustomerId_thenReturnNoAccounts() { + + List accounts = target.safeJpaCriteriaFindAccountsByCustomerId("C1' or '1'='1"); + assertThat(accounts).isNotNull(); + assertThat(accounts).isEmpty(); + } + @Test(expected = IllegalArgumentException.class) public void givenASafeMethod_whenInvalidOrderBy_thenThroweException() { target.safeFindAccountsByCustomerId("C1", "INVALID"); } - @Test(expected = RuntimeException.class) + @Test(expected = Exception.class) public void givenWrongPlaceholderUsageMethod_whenNormalCall_thenThrowsException() { target.wrongCountRecordsByTableName("Accounts"); } + + @Test(expected = Exception.class) + public void givenWrongJpaPlaceholderUsageMethod_whenNormalCall_thenThrowsException() { + target.wrongJpaCountRecordsByTableName("Accounts"); + } + } diff --git a/software-security/sql-injection-samples/src/test/resources/application-test.yml b/software-security/sql-injection-samples/src/test/resources/application-test.yml index d07ee10aee..3af3f58bff 100644 --- a/software-security/sql-injection-samples/src/test/resources/application-test.yml +++ b/software-security/sql-injection-samples/src/test/resources/application-test.yml @@ -2,5 +2,17 @@ # Test profile configuration # spring: + liquibase: + change-log: db/changelog/db.changelog-master.xml + + jpa: + hibernate: + ddl-auto: none + datasource: - initialization-mode: always + initialization-mode: embedded + +logging: + level: + sql: DEBUG + \ No newline at end of file diff --git a/software-security/sql-injection-samples/src/test/resources/schema.sql b/software-security/sql-injection-samples/src/test/resources/schema.sql index bfb0ae8059..cfc4c44f98 100644 --- a/software-security/sql-injection-samples/src/test/resources/schema.sql +++ b/software-security/sql-injection-samples/src/test/resources/schema.sql @@ -1,4 +1,5 @@ create table Accounts ( + id BIGINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), customer_id varchar(16) not null, acc_number varchar(16) not null, branch_id decimal(8,0), From 33b60605d778d35ae48d0a177be3862e5d377393 Mon Sep 17 00:00:00 2001 From: Matt Zhang Date: Thu, 7 Mar 2019 23:44:32 +1100 Subject: [PATCH 006/167] BAEL-2569 : EnvironmentPostProcessor in Spring Boot --- .../PriceCalculationApplication.java | 59 +++++++++++++++ ...ceCalculationEnvironmentPostProcessor.java | 71 +++++++++++++++++++ .../PriceCalculationAutoConfig.java | 32 +++++++++ .../calculator/GrossPriceCalculator.java | 23 ++++++ .../calculator/NetPriceCalculator.java | 17 +++++ .../calculator/PriceCalculator.java | 5 ++ .../service/PriceCalculationService.java | 17 +++++ .../main/resources/META-INF/spring.factories | 8 ++- 8 files changed, 231 insertions(+), 1 deletion(-) create mode 100644 spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java create mode 100644 spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java create mode 100644 spring-boot/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java create mode 100644 spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java create mode 100644 spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java create mode 100644 spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java create mode 100644 spring-boot/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java new file mode 100644 index 0000000000..01be08d6ae --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java @@ -0,0 +1,59 @@ +package com.baeldung.environmentpostprocessor; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import com.baeldung.environmentpostprocessor.service.PriceCalculationService; + +@SpringBootApplication +public class PriceCalculationApplication implements CommandLineRunner { + + @Autowired + PriceCalculationService priceCalculationService; + + private static final Logger logger = LoggerFactory.getLogger(PriceCalculationApplication.class); + + public static void main(String[] args) { + SpringApplication.run(PriceCalculationApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + + List params = Arrays.stream(args) + .collect(Collectors.toList()); + if (verifyArguments(params)) { + double singlePrice = Double.valueOf(params.get(0)); + int quantity = Integer.valueOf(params.get(1)); + priceCalculationService.productTotalPrice(singlePrice, quantity); + } else { + logger.error("Invalid arguments " + params.toString()); + } + + } + + private boolean verifyArguments(List args) { + boolean successful = true; + if (args.size() != 2) { + successful = false; + return successful; + } + try { + double singlePrice = Double.valueOf(args.get(0)); + int quantity = Integer.valueOf(args.get(1)); + } catch (NumberFormatException e) { + successful = false; + } + return successful; + + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java new file mode 100644 index 0000000000..1b3099453e --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java @@ -0,0 +1,71 @@ +package com.baeldung.environmentpostprocessor; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.env.EnvironmentPostProcessor; +import org.springframework.core.Ordered; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.env.StandardEnvironment; + +public class PriceCalculationEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { + + private static final Logger logger = LoggerFactory.getLogger(PriceCalculationEnvironmentPostProcessor.class); + + public static final int DEFAULT_ORDER = Ordered.LOWEST_PRECEDENCE; + private int order = DEFAULT_ORDER; + private static final String PROPERTY_PREFIX = "com.baeldung.environmentpostprocessor."; + private static final String OS_ENV_PROPERTY_CALCUATION_MODE = "calculation_mode"; + private static final String OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE = "gross_calculation_tax_rate"; + private static final String OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE = "NET"; + private static final double OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE = 0; + + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + + PropertySource systemEnvironmentPropertySource = environment.getPropertySources() + .get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); + + Map priceCalculationConfiguration = new LinkedHashMap<>(); + if (isActive(systemEnvironmentPropertySource)) { + priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_CALCUATION_MODE), systemEnvironmentPropertySource.getProperty(OS_ENV_PROPERTY_CALCUATION_MODE)); + priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE), systemEnvironmentPropertySource.getProperty(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE)); + } else { + logger.warn("System environment variables [calculation_mode,gross_calculation_tax_rate] not detected, fallback to default value [calcuation_mode={},gross_calcuation_tax_rate={}]", OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE, + OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE); + priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_CALCUATION_MODE), OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE); + priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE), OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE); + } + + PropertySource priceCalcuationPropertySource = new MapPropertySource("priceCalcuationPS", priceCalculationConfiguration); + environment.getPropertySources() + .addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, priceCalcuationPropertySource); + + } + + private String key(String key) { + return PROPERTY_PREFIX + key.replaceAll("\\_", "."); + } + + private boolean isActive(PropertySource systemEnvpropertySource) { + if (systemEnvpropertySource.containsProperty(OS_ENV_PROPERTY_CALCUATION_MODE) && systemEnvpropertySource.containsProperty(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE)) { + return true; + } else + return false; + } + + public void setOrder(int order) { + this.order = order; + } + + @Override + public int getOrder() { + return order; + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java new file mode 100644 index 0000000000..c884f043a0 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java @@ -0,0 +1,32 @@ +package com.baeldung.environmentpostprocessor.autoconfig; + +import org.springframework.boot.autoconfigure.AutoConfigureOrder; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; + +import com.baeldung.environmentpostprocessor.calculator.GrossPriceCalculator; +import com.baeldung.environmentpostprocessor.calculator.NetPriceCalculator; +import com.baeldung.environmentpostprocessor.calculator.PriceCalculator; + +@Configuration +@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) +public class PriceCalculationAutoConfig { + + @Bean + @ConditionalOnProperty(name = "com.baeldung.environmentpostprocessor.calculation.mode", havingValue = "NET") + @ConditionalOnMissingBean + public PriceCalculator getNetPriceCalculator() { + return new NetPriceCalculator(); + } + + @Bean + @ConditionalOnProperty(name = "com.baeldung.environmentpostprocessor.calculation.mode", havingValue = "GROSS") + @ConditionalOnMissingBean + public PriceCalculator getGrossPriceCalculator() { + return new GrossPriceCalculator(); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java new file mode 100644 index 0000000000..f8f797bd66 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java @@ -0,0 +1,23 @@ +package com.baeldung.environmentpostprocessor.calculator; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; + +public class GrossPriceCalculator implements PriceCalculator { + + private static final Logger logger = LoggerFactory.getLogger(GrossPriceCalculator.class); + + @Value("${com.baeldung.environmentpostprocessor.gross.calculation.tax.rate}") + double taxRate; + + @Override + public double calculate(double singlePrice, int quantity) { + logger.info("Gross based price calculation with input parameters [singlePrice = {},quantity= {} ], {} percent tax applied.", singlePrice, quantity, taxRate * 100); + double netPrice = singlePrice * quantity; + double result = Math.round(netPrice * (1 + taxRate)); + logger.info("Calcuation result is {}", result); + return result; + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java new file mode 100644 index 0000000000..263dff6247 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java @@ -0,0 +1,17 @@ +package com.baeldung.environmentpostprocessor.calculator; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NetPriceCalculator implements PriceCalculator { + + private static final Logger logger = LoggerFactory.getLogger(GrossPriceCalculator.class); + + @Override + public double calculate(double singlePrice, int quantity) { + logger.info("Net based price calculation with input parameters [singlePrice = {},quantity= {} ], NO tax applied.", singlePrice, quantity); + double result = Math.round(singlePrice * quantity); + logger.info("Calcuation result is {}", result); + return result; + } +} diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java new file mode 100644 index 0000000000..9d7bef93a4 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java @@ -0,0 +1,5 @@ +package com.baeldung.environmentpostprocessor.calculator; + +public interface PriceCalculator { + public double calculate(double singlePrice, int quantity); +} diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java new file mode 100644 index 0000000000..0e4eb39506 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java @@ -0,0 +1,17 @@ +package com.baeldung.environmentpostprocessor.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.baeldung.environmentpostprocessor.calculator.PriceCalculator; + +@Service +public class PriceCalculationService { + + @Autowired + PriceCalculator priceCalculator; + + public double productTotalPrice(double singlePrice, int quantity) { + return priceCalculator.calculate(singlePrice, quantity); + } +} diff --git a/spring-boot/src/main/resources/META-INF/spring.factories b/spring-boot/src/main/resources/META-INF/spring.factories index e3d3aa4c8e..d8a01bbf82 100644 --- a/spring-boot/src/main/resources/META-INF/spring.factories +++ b/spring-boot/src/main/resources/META-INF/spring.factories @@ -1 +1,7 @@ -org.springframework.boot.diagnostics.FailureAnalyzer=com.baeldung.failureanalyzer.MyBeanNotOfRequiredTypeFailureAnalyzer \ No newline at end of file +org.springframework.boot.diagnostics.FailureAnalyzer=com.baeldung.failureanalyzer.MyBeanNotOfRequiredTypeFailureAnalyzer +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.baeldung.environmentpostprocessor.autoconfig.PriceCalculationAutoConfig + +org.springframework.boot.env.EnvironmentPostProcessor=\ +com.baeldung.environmentpostprocessor.PriceCalculationEnvironmentPostProcessor + From bbb98f7a91a91336fb47ae71651400b2b8516bab Mon Sep 17 00:00:00 2001 From: Matt Zhang Date: Mon, 11 Mar 2019 23:49:35 +1100 Subject: [PATCH 007/167] BAEL-2569 add test --- ...ationEnvironmentPostProcessorLiveTest.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 spring-boot/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java diff --git a/spring-boot/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java b/spring-boot/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java new file mode 100644 index 0000000000..352e7941fb --- /dev/null +++ b/spring-boot/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java @@ -0,0 +1,29 @@ +package com.baeldung.environmentpostprocessor; + +import static org.junit.Assert.assertTrue; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.environmentpostprocessor.service.PriceCalculationService; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PriceCalculationApplication.class) +public class PriceCalculationEnvironmentPostProcessorLiveTest { + + @Autowired + PriceCalculationService pcService; + + + @Test + public void WhenSetGrossEnvironmentVariable_ThenTaxApplied() { + double total = pcService.productTotalPrice(100, 4); + + Assert.assertEquals(400.0,total); + } + +} From a0227300bf92b3609a554916c8f70aa710d09900 Mon Sep 17 00:00:00 2001 From: "Matt Zhang (EXT)" Date: Wed, 13 Mar 2019 11:56:26 +1100 Subject: [PATCH 008/167] BAEL-2569 update test --- ...CalculationEnvironmentPostProcessorLiveTest.java | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/spring-boot/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java b/spring-boot/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java index 352e7941fb..54af217346 100644 --- a/spring-boot/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java +++ b/spring-boot/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java @@ -1,8 +1,7 @@ package com.baeldung.environmentpostprocessor; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -14,16 +13,14 @@ import com.baeldung.environmentpostprocessor.service.PriceCalculationService; @RunWith(SpringRunner.class) @SpringBootTest(classes = PriceCalculationApplication.class) public class PriceCalculationEnvironmentPostProcessorLiveTest { - + @Autowired PriceCalculationService pcService; - - + @Test - public void WhenSetGrossEnvironmentVariable_ThenTaxApplied() { + public void whenSetNetEnvironmentVariablebyDefault_thenNoTaxApplied() { double total = pcService.productTotalPrice(100, 4); - - Assert.assertEquals(400.0,total); + assertEquals(400.0, total, 0); } } From 9f8058a5603ced4177f5bc42ca7b8dbd408a5953 Mon Sep 17 00:00:00 2001 From: Matt Zhang Date: Fri, 29 Mar 2019 23:46:43 +1100 Subject: [PATCH 009/167] BAEL-2569 refactoring the class PriceCalculationEnvironmentPostProcessor --- ...ceCalculationEnvironmentPostProcessor.java | 39 +++++++++---------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java index 1b3099453e..42cbd1e90f 100644 --- a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java +++ b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java @@ -8,17 +8,17 @@ import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.PropertySource; import org.springframework.core.env.StandardEnvironment; -public class PriceCalculationEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { +@Order(Ordered.LOWEST_PRECEDENCE) +public class PriceCalculationEnvironmentPostProcessor implements EnvironmentPostProcessor { private static final Logger logger = LoggerFactory.getLogger(PriceCalculationEnvironmentPostProcessor.class); - public static final int DEFAULT_ORDER = Ordered.LOWEST_PRECEDENCE; - private int order = DEFAULT_ORDER; private static final String PROPERTY_PREFIX = "com.baeldung.environmentpostprocessor."; private static final String OS_ENV_PROPERTY_CALCUATION_MODE = "calculation_mode"; private static final String OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE = "gross_calculation_tax_rate"; @@ -28,26 +28,34 @@ public class PriceCalculationEnvironmentPostProcessor implements EnvironmentPost @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - PropertySource systemEnvironmentPropertySource = environment.getPropertySources() + PropertySource systemEnvPropertySource = environment.getPropertySources() .get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); - Map priceCalculationConfiguration = new LinkedHashMap<>(); - if (isActive(systemEnvironmentPropertySource)) { - priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_CALCUATION_MODE), systemEnvironmentPropertySource.getProperty(OS_ENV_PROPERTY_CALCUATION_MODE)); - priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE), systemEnvironmentPropertySource.getProperty(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE)); + Map mapPropertySource = new LinkedHashMap<>(); + if (isActive(systemEnvPropertySource)) { + populatePropertySource(systemEnvPropertySource, mapPropertySource); } else { logger.warn("System environment variables [calculation_mode,gross_calculation_tax_rate] not detected, fallback to default value [calcuation_mode={},gross_calcuation_tax_rate={}]", OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE, OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE); - priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_CALCUATION_MODE), OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE); - priceCalculationConfiguration.put(key(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE), OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE); + populateDefaultPropertySource(mapPropertySource); } - PropertySource priceCalcuationPropertySource = new MapPropertySource("priceCalcuationPS", priceCalculationConfiguration); + PropertySource priceCalcuationPropertySource = new MapPropertySource("priceCalcuationPS", mapPropertySource); environment.getPropertySources() .addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, priceCalcuationPropertySource); } + private void populatePropertySource(PropertySource source, Map target) { + target.put(key(OS_ENV_PROPERTY_CALCUATION_MODE), source.getProperty(OS_ENV_PROPERTY_CALCUATION_MODE)); + target.put(key(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE), source.getProperty(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE)); + } + + private void populateDefaultPropertySource(Map target) { + target.put(key(OS_ENV_PROPERTY_CALCUATION_MODE), OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE); + target.put(key(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE), OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE); + } + private String key(String key) { return PROPERTY_PREFIX + key.replaceAll("\\_", "."); } @@ -59,13 +67,4 @@ public class PriceCalculationEnvironmentPostProcessor implements EnvironmentPost return false; } - public void setOrder(int order) { - this.order = order; - } - - @Override - public int getOrder() { - return order; - } - } From 99a3aa5bab5e066bd8470ac2619160aaab19e788 Mon Sep 17 00:00:00 2001 From: Matt Zhang Date: Sun, 31 Mar 2019 22:42:32 +1100 Subject: [PATCH 010/167] BAEL-2569: changes to class PriceCalculationEnvironmentPostProcessor --- ...ceCalculationEnvironmentPostProcessor.java | 69 +++++++++++-------- 1 file changed, 40 insertions(+), 29 deletions(-) diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java index 42cbd1e90f..ca6d6cc28f 100644 --- a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java +++ b/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java @@ -1,7 +1,12 @@ package com.baeldung.environmentpostprocessor; +import static org.springframework.core.env.StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME; + +import java.util.Arrays; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -12,56 +17,62 @@ import org.springframework.core.annotation.Order; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.PropertySource; -import org.springframework.core.env.StandardEnvironment; @Order(Ordered.LOWEST_PRECEDENCE) public class PriceCalculationEnvironmentPostProcessor implements EnvironmentPostProcessor { private static final Logger logger = LoggerFactory.getLogger(PriceCalculationEnvironmentPostProcessor.class); - private static final String PROPERTY_PREFIX = "com.baeldung.environmentpostprocessor."; - private static final String OS_ENV_PROPERTY_CALCUATION_MODE = "calculation_mode"; - private static final String OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE = "gross_calculation_tax_rate"; - private static final String OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE = "NET"; - private static final double OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE = 0; + private static final String PREFIX = "com.baeldung.environmentpostprocessor."; + private static final String CALCUATION_MODE = "calculation_mode"; + private static final String GROSS_CALCULATION_TAX_RATE = "gross_calculation_tax_rate"; + private static final String CALCUATION_MODE_DEFAULT_VALUE = "NET"; + private static final double GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE = 0; + + List names = Arrays.asList(CALCUATION_MODE, GROSS_CALCULATION_TAX_RATE); + + private static Map defaults = new LinkedHashMap<>(); + static { + defaults.put(CALCUATION_MODE, CALCUATION_MODE_DEFAULT_VALUE); + defaults.put(GROSS_CALCULATION_TAX_RATE, GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE); + } @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - PropertySource systemEnvPropertySource = environment.getPropertySources() - .get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); + PropertySource system = environment.getPropertySources() + .get(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); - Map mapPropertySource = new LinkedHashMap<>(); - if (isActive(systemEnvPropertySource)) { - populatePropertySource(systemEnvPropertySource, mapPropertySource); - } else { - logger.warn("System environment variables [calculation_mode,gross_calculation_tax_rate] not detected, fallback to default value [calcuation_mode={},gross_calcuation_tax_rate={}]", OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE, - OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE); - populateDefaultPropertySource(mapPropertySource); + Map prefixed = new LinkedHashMap<>(); + + if (!hasOurPriceProperties(system)) { + // Baeldung-internal code so this doesn't break other examples + logger.warn("System environment variables [calculation_mode,gross_calculation_tax_rate] not detected, fallback to default value [calcuation_mode={},gross_calcuation_tax_rate={}]", CALCUATION_MODE_DEFAULT_VALUE, + GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE); + prefixed = names.stream() + .collect(Collectors.toMap(this::rename, this::getDefaultValue)); + environment.getPropertySources() + .addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed)); + return; } - PropertySource priceCalcuationPropertySource = new MapPropertySource("priceCalcuationPS", mapPropertySource); + prefixed = names.stream() + .collect(Collectors.toMap(this::rename, system::getProperty)); environment.getPropertySources() - .addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, priceCalcuationPropertySource); + .addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed)); } - private void populatePropertySource(PropertySource source, Map target) { - target.put(key(OS_ENV_PROPERTY_CALCUATION_MODE), source.getProperty(OS_ENV_PROPERTY_CALCUATION_MODE)); - target.put(key(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE), source.getProperty(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE)); + private Object getDefaultValue(String key) { + return defaults.get(key); } - private void populateDefaultPropertySource(Map target) { - target.put(key(OS_ENV_PROPERTY_CALCUATION_MODE), OS_ENV_PROPERTY_CALCUATION_MODE_DEFAULT_VALUE); - target.put(key(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE), OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE); + private String rename(String key) { + return PREFIX + key.replaceAll("\\_", "."); } - private String key(String key) { - return PROPERTY_PREFIX + key.replaceAll("\\_", "."); - } - - private boolean isActive(PropertySource systemEnvpropertySource) { - if (systemEnvpropertySource.containsProperty(OS_ENV_PROPERTY_CALCUATION_MODE) && systemEnvpropertySource.containsProperty(OS_ENV_PROPERTY_GROSS_CALCULATION_TAX_RATE)) { + private boolean hasOurPriceProperties(PropertySource system) { + if (system.containsProperty(CALCUATION_MODE) && system.containsProperty(GROSS_CALCULATION_TAX_RATE)) { return true; } else return false; From a86c69429bf8c99b56ed1b0f236db9a87043aab3 Mon Sep 17 00:00:00 2001 From: Philippe Date: Mon, 1 Apr 2019 22:22:02 -0300 Subject: [PATCH 011/167] Workaround for spring-framework#21094 --- spring-webflux-amqp/pom.xml | 116 ++++++++++-------- .../amqp/SpringWebfluxAmqpApplication.java | 21 ++++ .../src/main/resources/application.yml | 2 +- 3 files changed, 87 insertions(+), 52 deletions(-) diff --git a/spring-webflux-amqp/pom.xml b/spring-webflux-amqp/pom.xml index a8346458a0..88f5eff403 100755 --- a/spring-webflux-amqp/pom.xml +++ b/spring-webflux-amqp/pom.xml @@ -1,62 +1,76 @@ - 4.0.0 - org.baeldung.spring - spring-webflux-amqp - 1.0.0-SNAPSHOT - spring-webflux-amqp - jar - Spring WebFlux AMQP Sample + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + org.baeldung.spring + spring-webflux-amqp + 1.0.0-SNAPSHOT + spring-webflux-amqp + jar + Spring WebFlux AMQP Sample - - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 - + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + - - - org.springframework.boot - spring-boot-starter-amqp - - - org.springframework.boot - spring-boot-starter-webflux - + + + + + org.springframework.boot + spring-boot-dependencies + + 2.1.3.RELEASE + pom + import + + + - - org.springframework.boot - spring-boot-configuration-processor - true - + + + org.springframework.boot + spring-boot-starter-amqp + + + org.springframework.boot + spring-boot-starter-webflux + - - org.springframework.boot - spring-boot-starter-test - test - + + org.springframework.boot + spring-boot-configuration-processor + true + - - io.projectreactor - reactor-test - test - + + org.springframework.boot + spring-boot-starter-test + test + - - org.springframework.boot - spring-boot-starter-integration - - + + io.projectreactor + reactor-test + test + - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + org.springframework.boot + spring-boot-starter-integration + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + diff --git a/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java b/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java index 30614e7ee6..8a31299333 100755 --- a/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java +++ b/spring-webflux-amqp/src/main/java/org/baeldung/spring/amqp/SpringWebfluxAmqpApplication.java @@ -3,6 +3,12 @@ package org.baeldung.spring.amqp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.web.filter.reactive.HiddenHttpMethodFilter; +import org.springframework.web.server.ServerWebExchange; +import org.springframework.web.server.WebFilterChain; + +import reactor.core.publisher.Mono; @SpringBootApplication @EnableConfigurationProperties(DestinationsConfig.class) @@ -12,4 +18,19 @@ public class SpringWebfluxAmqpApplication { SpringApplication.run(SpringWebfluxAmqpApplication.class, args); } + + /** + * This is a workaround for https://github.com/spring-projects/spring-framework/issues/21094 + * @return + */ + @Bean + public HiddenHttpMethodFilter hiddenHttpMethodFilter() { + return new HiddenHttpMethodFilter() { + @Override + public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { + return chain.filter(exchange); + } + }; + } + } diff --git a/spring-webflux-amqp/src/main/resources/application.yml b/spring-webflux-amqp/src/main/resources/application.yml index 702aaba357..3f527ce4c5 100755 --- a/spring-webflux-amqp/src/main/resources/application.yml +++ b/spring-webflux-amqp/src/main/resources/application.yml @@ -1,6 +1,6 @@ spring: rabbitmq: - host: localhost + host: 192.168.99.100 port: 5672 username: guest password: guest From bac144389785c0a78ae398d5854b671fecccce41 Mon Sep 17 00:00:00 2001 From: Philippe Date: Tue, 2 Apr 2019 02:12:55 -0300 Subject: [PATCH 012/167] Initial import --- apache-olingo/olingo2/.gitignore | 29 +++++ apache-olingo/olingo2/pom.xml | 108 ++++++++++++++++++ .../olingo2/CarsODataApplication.java | 24 ++++ .../olingo2/CarsODataJPAServiceFactory.java | 38 ++++++ .../examples/olingo2/JerseyConfig.java | 49 ++++++++ .../olingo2/Olingo2SampleApplication.java | 15 +++ .../examples/olingo2/domain/CarMaker.java | 31 +++++ .../examples/olingo2/domain/CarModel.java | 30 +++++ .../src/main/resources/application.yml | 9 ++ .../olingo2/src/main/resources/data.sql | 3 + .../Olingo2SampleApplicationTests.java | 16 +++ .../sql-injection-samples/pom.xml | 4 + 12 files changed, 356 insertions(+) create mode 100644 apache-olingo/olingo2/.gitignore create mode 100644 apache-olingo/olingo2/pom.xml create mode 100644 apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataApplication.java create mode 100644 apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java create mode 100644 apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java create mode 100644 apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/Olingo2SampleApplication.java create mode 100644 apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java create mode 100644 apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java create mode 100644 apache-olingo/olingo2/src/main/resources/application.yml create mode 100644 apache-olingo/olingo2/src/main/resources/data.sql create mode 100644 apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationTests.java diff --git a/apache-olingo/olingo2/.gitignore b/apache-olingo/olingo2/.gitignore new file mode 100644 index 0000000000..153c9335eb --- /dev/null +++ b/apache-olingo/olingo2/.gitignore @@ -0,0 +1,29 @@ +HELP.md +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +/build/ + +### VS Code ### +.vscode/ diff --git a/apache-olingo/olingo2/pom.xml b/apache-olingo/olingo2/pom.xml new file mode 100644 index 0000000000..4fc81e5e49 --- /dev/null +++ b/apache-olingo/olingo2/pom.xml @@ -0,0 +1,108 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.3.RELEASE + + + org.baeldung.examples.olingo2 + olingo2-sample + 0.0.1-SNAPSHOT + olingo2-sample + Sample Olingo 2 Project + + + 1.8 + 2.0.11 + + + + + + org.springframework.boot + spring-boot-starter-jersey + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.apache.olingo + olingo-odata2-core + ${olingo2.version} + + + + javax.ws.rs + javax.ws.rs-api + + + + + org.apache.olingo + olingo-odata2-api + ${olingo2.version} + + + org.apache.olingo + olingo-odata2-jpa-processor-api + ${olingo2.version} + + + org.apache.olingo + olingo-odata2-jpa-processor-core + ${olingo2.version} + + + org.apache.olingo + olingo-odata2-jpa-processor-ref + ${olingo2.version} + + + org.eclipse.persistence + eclipselink + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataApplication.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataApplication.java new file mode 100644 index 0000000000..c7e3878f44 --- /dev/null +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataApplication.java @@ -0,0 +1,24 @@ +package org.baeldung.examples.olingo2; + + +import java.util.Set; + +import javax.ws.rs.ApplicationPath; + +import org.apache.olingo.odata2.core.rest.ODataRootLocator; +import org.apache.olingo.odata2.core.rest.app.ODataApplication; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class CarsODataApplication extends ODataApplication { + + private static final Logger log = LoggerFactory.getLogger(CarsODataApplication.class); + + public CarsODataApplication() { + super(); + log.info("[I17] Creating CarsODataApplication..."); + } + +} diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java new file mode 100644 index 0000000000..2d0ae14686 --- /dev/null +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java @@ -0,0 +1,38 @@ +package org.baeldung.examples.olingo2; + +import javax.persistence.EntityManager; + +import org.apache.olingo.odata2.jpa.processor.api.ODataJPAContext; +import org.apache.olingo.odata2.jpa.processor.api.ODataJPAServiceFactory; +import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +/** + * OData ServiceFactory that + * @author Philippe + * + */ +@Component +public class CarsODataJPAServiceFactory extends ODataJPAServiceFactory { + + private EntityManager em; + private static final Logger log = LoggerFactory.getLogger(CarsODataJPAServiceFactory.class); + + public CarsODataJPAServiceFactory(EntityManager em) { + this.em = em; + } + + @Override + public ODataJPAContext initializeODataJPAContext() throws ODataJPARuntimeException { + + ODataJPAContext oDataJPAContext = getODataJPAContext(); + oDataJPAContext.setEntityManagerFactory(em.getEntityManagerFactory()); + oDataJPAContext.setPersistenceUnitName("default"); + + return oDataJPAContext; + + } + +} diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java new file mode 100644 index 0000000000..33db629318 --- /dev/null +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java @@ -0,0 +1,49 @@ +package org.baeldung.examples.olingo2; + +import javax.servlet.ServletContext; +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.Path; + +import org.apache.olingo.odata2.api.ODataServiceFactory; +import org.apache.olingo.odata2.core.rest.ODataRootLocator; +import org.glassfish.jersey.server.ResourceConfig; +import org.springframework.stereotype.Component; + +@Component +@ApplicationPath("/odata") +public class JerseyConfig extends ResourceConfig { + + + public JerseyConfig(CarsODataApplication delegate,ServletContext servletContext,CarsODataJPAServiceFactory serviceFactory) { + + delegate + .getClasses() + .forEach( c -> { + // Avoid using the default Locator + if ( !ODataRootLocator.class.isAssignableFrom(c)) { + register(c); + } + }); + + register(new CustomLocator(serviceFactory)); + + } + + + @Path("/") + public static class CustomLocator extends ODataRootLocator { + + private CarsODataJPAServiceFactory serviceFactory; + + public CustomLocator(CarsODataJPAServiceFactory serviceFactory) { + this.serviceFactory = serviceFactory; + } + + @Override + public ODataServiceFactory getServiceFactory() { + return this.serviceFactory; + } + + } + +} diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/Olingo2SampleApplication.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/Olingo2SampleApplication.java new file mode 100644 index 0000000000..6cc4a45927 --- /dev/null +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/Olingo2SampleApplication.java @@ -0,0 +1,15 @@ +package org.baeldung.examples.olingo2; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +@SpringBootApplication +public class Olingo2SampleApplication extends SpringBootServletInitializer { + + public static void main(String[] args) { + new Olingo2SampleApplication() + .configure(new SpringApplicationBuilder(Olingo2SampleApplication.class)) + .run(args); + } +} diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java new file mode 100644 index 0000000000..1817a2dece --- /dev/null +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java @@ -0,0 +1,31 @@ +package org.baeldung.examples.olingo2.domain; + +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import javax.validation.constraints.NotNull; + +import lombok.Data; + +@Entity +@Data +@Table(name="car_maker") +public class CarMaker { + + @Id + private Long id; + + @NotNull + @Column(name="name") + private String name; + + @OneToMany(mappedBy="maker",cascade=CascadeType.ALL) + private List models; + + +} diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java new file mode 100644 index 0000000000..285e5ce379 --- /dev/null +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java @@ -0,0 +1,30 @@ +package org.baeldung.examples.olingo2.domain; + + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.validation.constraints.NotNull; + +import lombok.Data; + +@Entity +@Data +public class CarModel { + + @Id + private Long id; + + @NotNull + private String name; + + @NotNull + private Integer year; + + @NotNull + private String sku; + + @ManyToOne + private CarMaker maker; + +} diff --git a/apache-olingo/olingo2/src/main/resources/application.yml b/apache-olingo/olingo2/src/main/resources/application.yml new file mode 100644 index 0000000000..2af431eee1 --- /dev/null +++ b/apache-olingo/olingo2/src/main/resources/application.yml @@ -0,0 +1,9 @@ + +spring: + jersey: + application-path: /odata + + jpa: + show-sql: true + hibernate: + ddl-auto: update \ No newline at end of file diff --git a/apache-olingo/olingo2/src/main/resources/data.sql b/apache-olingo/olingo2/src/main/resources/data.sql new file mode 100644 index 0000000000..c1d32dc6ef --- /dev/null +++ b/apache-olingo/olingo2/src/main/resources/data.sql @@ -0,0 +1,3 @@ +insert into car_maker(id,name) values (1,'Special Motors'); +insert into car_maker(id,name) values (2,'BWM'); +insert into car_maker(id,name) values (3,'Dolores'); diff --git a/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationTests.java b/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationTests.java new file mode 100644 index 0000000000..687f6ab1ff --- /dev/null +++ b/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationTests.java @@ -0,0 +1,16 @@ +package org.baeldung.examples.olingo2; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class Olingo2SampleApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/software-security/sql-injection-samples/pom.xml b/software-security/sql-injection-samples/pom.xml index 5b33c674d4..b943151896 100644 --- a/software-security/sql-injection-samples/pom.xml +++ b/software-security/sql-injection-samples/pom.xml @@ -55,6 +55,10 @@ + + org.springframework.boot + spring-boot-devtools + From 881580f2fe9eac3464fafa0f7d4e9456a5deb441 Mon Sep 17 00:00:00 2001 From: Philippe Date: Thu, 4 Apr 2019 00:09:38 -0300 Subject: [PATCH 013/167] [BAEL-1219] OLingo2 code --- .../olingo2/CarsODataApplication.java | 24 -- .../olingo2/CarsODataJPAServiceFactory.java | 271 +++++++++++++++++- .../examples/olingo2/EntityManagerHolder.java | 18 ++ .../examples/olingo2/JerseyConfig.java | 82 +++++- .../olingo2/Olingo2SampleApplication.java | 7 +- .../examples/olingo2/domain/CarMaker.java | 7 +- .../examples/olingo2/domain/CarModel.java | 10 +- .../src/main/resources/application.yml | 1 + .../olingo2/src/main/resources/data.sql | 9 + .../src/test/resources/olingo2-queries.json | 256 +++++++++++++++++ 10 files changed, 641 insertions(+), 44 deletions(-) delete mode 100644 apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataApplication.java create mode 100644 apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/EntityManagerHolder.java create mode 100644 apache-olingo/olingo2/src/test/resources/olingo2-queries.json diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataApplication.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataApplication.java deleted file mode 100644 index c7e3878f44..0000000000 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataApplication.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.baeldung.examples.olingo2; - - -import java.util.Set; - -import javax.ws.rs.ApplicationPath; - -import org.apache.olingo.odata2.core.rest.ODataRootLocator; -import org.apache.olingo.odata2.core.rest.app.ODataApplication; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -@Component -public class CarsODataApplication extends ODataApplication { - - private static final Logger log = LoggerFactory.getLogger(CarsODataApplication.class); - - public CarsODataApplication() { - super(); - log.info("[I17] Creating CarsODataApplication..."); - } - -} diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java index 2d0ae14686..cf13bd0fc9 100644 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java @@ -1,37 +1,292 @@ package org.baeldung.examples.olingo2; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityGraph; import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.FlushModeType; +import javax.persistence.LockModeType; +import javax.persistence.Persistence; +import javax.persistence.Query; +import javax.persistence.StoredProcedureQuery; +import javax.persistence.SynchronizationType; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaDelete; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.CriteriaUpdate; +import javax.persistence.metamodel.Metamodel; import org.apache.olingo.odata2.jpa.processor.api.ODataJPAContext; import org.apache.olingo.odata2.jpa.processor.api.ODataJPAServiceFactory; import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.orm.jpa.EntityManagerFactoryUtils; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.stereotype.Component; /** - * OData ServiceFactory that + * ODataJPAServiceFactory implementation for our sample domain * @author Philippe * */ @Component public class CarsODataJPAServiceFactory extends ODataJPAServiceFactory { - private EntityManager em; private static final Logger log = LoggerFactory.getLogger(CarsODataJPAServiceFactory.class); - public CarsODataJPAServiceFactory(EntityManager em) { - this.em = em; + public CarsODataJPAServiceFactory() { + // Enable detailed error messages (useful for debugging) + setDetailErrors(true); } + + /** + * This method will be called by Olingo on every request to + * initialize the ODataJPAContext that will be used. + */ @Override public ODataJPAContext initializeODataJPAContext() throws ODataJPARuntimeException { - ODataJPAContext oDataJPAContext = getODataJPAContext(); - oDataJPAContext.setEntityManagerFactory(em.getEntityManagerFactory()); - oDataJPAContext.setPersistenceUnitName("default"); + log.info("[I32] >>> initializeODataJPAContext()"); + ODataJPAContext ctx = getODataJPAContext(); - return oDataJPAContext; + // Here we're passing the EM that was created by the EntityManagerFilter (see JerseyConfig) + ctx.setEntityManager(new EntityManagerWrapper(EntityManagerHolder.getCurrentEntityManager())); + ctx.setPersistenceUnitName("default"); + + // We're managing the EM's lifecycle, so we must inform Olingo that it should not + // try to manage transactions and/or persistence sessions + ctx.setContainerManaged(true); + + + return ctx; + + } + + static class EntityManagerWrapper implements EntityManager { + + private EntityManager delegate; + + public void persist(Object entity) { + log.info("[I68] persist: entity.class=" + entity.getClass().getSimpleName()); + delegate.persist(entity); + //delegate.flush(); + } + + public T merge(T entity) { + log.info("[I74] merge: entity.class=" + entity.getClass().getSimpleName()); + return delegate.merge(entity); + } + + public void remove(Object entity) { + log.info("[I78] remove: entity.class=" + entity.getClass().getSimpleName()); + delegate.remove(entity); + } + + public T find(Class entityClass, Object primaryKey) { + return delegate.find(entityClass, primaryKey); + } + + public T find(Class entityClass, Object primaryKey, Map properties) { + return delegate.find(entityClass, primaryKey, properties); + } + + public T find(Class entityClass, Object primaryKey, LockModeType lockMode) { + return delegate.find(entityClass, primaryKey, lockMode); + } + + public T find(Class entityClass, Object primaryKey, LockModeType lockMode, Map properties) { + return delegate.find(entityClass, primaryKey, lockMode, properties); + } + + public T getReference(Class entityClass, Object primaryKey) { + return delegate.getReference(entityClass, primaryKey); + } + + public void flush() { + delegate.flush(); + } + + public void setFlushMode(FlushModeType flushMode) { + delegate.setFlushMode(flushMode); + } + + public FlushModeType getFlushMode() { + return delegate.getFlushMode(); + } + + public void lock(Object entity, LockModeType lockMode) { + delegate.lock(entity, lockMode); + } + + public void lock(Object entity, LockModeType lockMode, Map properties) { + delegate.lock(entity, lockMode, properties); + } + + public void refresh(Object entity) { + delegate.refresh(entity); + } + + public void refresh(Object entity, Map properties) { + delegate.refresh(entity, properties); + } + + public void refresh(Object entity, LockModeType lockMode) { + delegate.refresh(entity, lockMode); + } + + public void refresh(Object entity, LockModeType lockMode, Map properties) { + delegate.refresh(entity, lockMode, properties); + } + + public void clear() { + delegate.clear(); + } + + public void detach(Object entity) { + delegate.detach(entity); + } + + public boolean contains(Object entity) { + return delegate.contains(entity); + } + + public LockModeType getLockMode(Object entity) { + return delegate.getLockMode(entity); + } + + public void setProperty(String propertyName, Object value) { + delegate.setProperty(propertyName, value); + } + + public Map getProperties() { + return delegate.getProperties(); + } + + public Query createQuery(String qlString) { + return delegate.createQuery(qlString); + } + + public TypedQuery createQuery(CriteriaQuery criteriaQuery) { + return delegate.createQuery(criteriaQuery); + } + + public Query createQuery(CriteriaUpdate updateQuery) { + return delegate.createQuery(updateQuery); + } + + public Query createQuery(CriteriaDelete deleteQuery) { + return delegate.createQuery(deleteQuery); + } + + public TypedQuery createQuery(String qlString, Class resultClass) { + return delegate.createQuery(qlString, resultClass); + } + + public Query createNamedQuery(String name) { + return delegate.createNamedQuery(name); + } + + public TypedQuery createNamedQuery(String name, Class resultClass) { + return delegate.createNamedQuery(name, resultClass); + } + + public Query createNativeQuery(String sqlString) { + return delegate.createNativeQuery(sqlString); + } + + public Query createNativeQuery(String sqlString, Class resultClass) { + return delegate.createNativeQuery(sqlString, resultClass); + } + + public Query createNativeQuery(String sqlString, String resultSetMapping) { + return delegate.createNativeQuery(sqlString, resultSetMapping); + } + + public StoredProcedureQuery createNamedStoredProcedureQuery(String name) { + return delegate.createNamedStoredProcedureQuery(name); + } + + public StoredProcedureQuery createStoredProcedureQuery(String procedureName) { + return delegate.createStoredProcedureQuery(procedureName); + } + + public StoredProcedureQuery createStoredProcedureQuery(String procedureName, Class... resultClasses) { + return delegate.createStoredProcedureQuery(procedureName, resultClasses); + } + + public StoredProcedureQuery createStoredProcedureQuery(String procedureName, String... resultSetMappings) { + return delegate.createStoredProcedureQuery(procedureName, resultSetMappings); + } + + public void joinTransaction() { + delegate.joinTransaction(); + } + + public boolean isJoinedToTransaction() { + return delegate.isJoinedToTransaction(); + } + + public T unwrap(Class cls) { + return delegate.unwrap(cls); + } + + public Object getDelegate() { + return delegate.getDelegate(); + } + + public void close() { + log.info("[I229] close"); + delegate.close(); + } + + public boolean isOpen() { + boolean isOpen = delegate.isOpen(); + log.info("[I236] isOpen: " + isOpen); + return isOpen; + } + + public EntityTransaction getTransaction() { + log.info("[I240] getTransaction()"); + return delegate.getTransaction(); + } + + public EntityManagerFactory getEntityManagerFactory() { + return delegate.getEntityManagerFactory(); + } + + public CriteriaBuilder getCriteriaBuilder() { + return delegate.getCriteriaBuilder(); + } + + public Metamodel getMetamodel() { + return delegate.getMetamodel(); + } + + public EntityGraph createEntityGraph(Class rootType) { + return delegate.createEntityGraph(rootType); + } + + public EntityGraph createEntityGraph(String graphName) { + return delegate.createEntityGraph(graphName); + } + + public EntityGraph getEntityGraph(String graphName) { + return delegate.getEntityGraph(graphName); + } + + public List> getEntityGraphs(Class entityClass) { + return delegate.getEntityGraphs(entityClass); + } + + public EntityManagerWrapper(EntityManager delegate) { + this.delegate = delegate; + } } diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/EntityManagerHolder.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/EntityManagerHolder.java new file mode 100644 index 0000000000..682621eb99 --- /dev/null +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/EntityManagerHolder.java @@ -0,0 +1,18 @@ +package org.baeldung.examples.olingo2; + +import javax.persistence.EntityManager; + +public class EntityManagerHolder { + + private static ThreadLocal currentEntityManager = new ThreadLocal<>(); + + + public static void setCurrentEntityManager(EntityManager em) { + currentEntityManager.set(em); + } + + public static EntityManager getCurrentEntityManager() { + return currentEntityManager.get(); + } + +} diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java index 33db629318..a82220e854 100644 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java @@ -1,41 +1,111 @@ package org.baeldung.examples.olingo2; +import java.io.IOException; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; import javax.servlet.ServletContext; import javax.ws.rs.ApplicationPath; import javax.ws.rs.Path; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.ext.Provider; import org.apache.olingo.odata2.api.ODataServiceFactory; import org.apache.olingo.odata2.core.rest.ODataRootLocator; +import org.apache.olingo.odata2.core.rest.app.ODataApplication; import org.glassfish.jersey.server.ResourceConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; +/** + * Jersey JAX-RS configuration + * @author Philippe + * + */ @Component @ApplicationPath("/odata") public class JerseyConfig extends ResourceConfig { - public JerseyConfig(CarsODataApplication delegate,ServletContext servletContext,CarsODataJPAServiceFactory serviceFactory) { + public JerseyConfig(CarsODataJPAServiceFactory serviceFactory, EntityManagerFactory emf) { - delegate + ODataApplication app = new ODataApplication(); + + app .getClasses() .forEach( c -> { - // Avoid using the default Locator + // Avoid using the default RootLocator, as we want + // a Spring Managed one if ( !ODataRootLocator.class.isAssignableFrom(c)) { register(c); } }); - register(new CustomLocator(serviceFactory)); + register(new CarsRootLocator(serviceFactory)); + register( new EntityManagerFilter(emf)); + } + + /** + * This filter handles the EntityManager transaction lifecycle. + * @author Philippe + * + */ + @Provider + public static class EntityManagerFilter implements ContainerRequestFilter, ContainerResponseFilter { + + private static final Logger log = LoggerFactory.getLogger(EntityManagerFilter.class); + + private final EntityManagerFactory emf; + + public EntityManagerFilter(EntityManagerFactory emf) { + this.emf = emf; + } + + @Override + public void filter(ContainerRequestContext ctx) throws IOException { + log.info("[I60] >>> filter"); + EntityManager em = this.emf.createEntityManager(); + EntityManagerHolder.setCurrentEntityManager(em); + + // Start a new transaction unless we have a simple GET + if ( !"GET".equalsIgnoreCase(ctx.getMethod())) { + em.getTransaction().begin(); + } + } + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { + + log.info("[I68] <<< filter"); + + EntityManager em = EntityManagerHolder.getCurrentEntityManager(); + if ( em != null && !"GET".equalsIgnoreCase(requestContext.getMethod())) { + EntityTransaction t = em.getTransaction(); + if ( t.isActive()) { + if ( !t.getRollbackOnly()) { + t.commit(); + } + } + } + + em.close(); + + } } @Path("/") - public static class CustomLocator extends ODataRootLocator { + public static class CarsRootLocator extends ODataRootLocator { private CarsODataJPAServiceFactory serviceFactory; - public CustomLocator(CarsODataJPAServiceFactory serviceFactory) { + public CarsRootLocator(CarsODataJPAServiceFactory serviceFactory) { this.serviceFactory = serviceFactory; } diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/Olingo2SampleApplication.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/Olingo2SampleApplication.java index 6cc4a45927..fa58612088 100644 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/Olingo2SampleApplication.java +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/Olingo2SampleApplication.java @@ -1,5 +1,6 @@ package org.baeldung.examples.olingo2; +import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @@ -7,9 +8,7 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer @SpringBootApplication public class Olingo2SampleApplication extends SpringBootServletInitializer { - public static void main(String[] args) { - new Olingo2SampleApplication() - .configure(new SpringApplicationBuilder(Olingo2SampleApplication.class)) - .run(args); + public static void main(String[] args) { + SpringApplication.run(Olingo2SampleApplication.class); } } diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java index 1817a2dece..42a3eaa59d 100644 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java @@ -5,6 +5,8 @@ import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @@ -18,13 +20,16 @@ import lombok.Data; public class CarMaker { @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @NotNull @Column(name="name") private String name; - @OneToMany(mappedBy="maker",cascade=CascadeType.ALL) + @OneToMany(mappedBy="maker", + orphanRemoval = true, + cascade=CascadeType.ALL) private List models; diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java index 285e5ce379..a4f2a04f6e 100644 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java @@ -2,17 +2,24 @@ package org.baeldung.examples.olingo2.domain; import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; +import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; +import javax.persistence.Table; import javax.validation.constraints.NotNull; import lombok.Data; @Entity @Data +@Table(name="car_model") public class CarModel { @Id + @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @NotNull @@ -24,7 +31,8 @@ public class CarModel { @NotNull private String sku; - @ManyToOne + @ManyToOne(optional=false, fetch= FetchType.LAZY) + @JoinColumn(name="maker_fk") private CarMaker maker; } diff --git a/apache-olingo/olingo2/src/main/resources/application.yml b/apache-olingo/olingo2/src/main/resources/application.yml index 2af431eee1..a29b572575 100644 --- a/apache-olingo/olingo2/src/main/resources/application.yml +++ b/apache-olingo/olingo2/src/main/resources/application.yml @@ -5,5 +5,6 @@ spring: jpa: show-sql: true + open-in-view: false hibernate: ddl-auto: update \ No newline at end of file diff --git a/apache-olingo/olingo2/src/main/resources/data.sql b/apache-olingo/olingo2/src/main/resources/data.sql index c1d32dc6ef..327f2688c5 100644 --- a/apache-olingo/olingo2/src/main/resources/data.sql +++ b/apache-olingo/olingo2/src/main/resources/data.sql @@ -1,3 +1,12 @@ insert into car_maker(id,name) values (1,'Special Motors'); insert into car_maker(id,name) values (2,'BWM'); insert into car_maker(id,name) values (3,'Dolores'); + +insert into car_model(id,maker_fk,name,sku,year) values(1,1,'Muze','SM001',2018); +insert into car_model(id,maker_fk,name,sku,year) values(2,1,'Empada','SM002',2008); + +insert into car_model(id,maker_fk,name,sku,year) values(4,2,'BWM-100','BWM100',2008); +insert into car_model(id,maker_fk,name,sku,year) values(5,2,'BWM-200','BWM200',2009); +insert into car_model(id,maker_fk,name,sku,year) values(6,2,'BWM-300','BWM300',2008); + +alter sequence hibernate_sequence restart with 100; \ No newline at end of file diff --git a/apache-olingo/olingo2/src/test/resources/olingo2-queries.json b/apache-olingo/olingo2/src/test/resources/olingo2-queries.json new file mode 100644 index 0000000000..9fdade6d10 --- /dev/null +++ b/apache-olingo/olingo2/src/test/resources/olingo2-queries.json @@ -0,0 +1,256 @@ +{ + "info": { + "_postman_id": "afa8e1e5-ab0e-4f1d-8b99-b7d1f091f975", + "name": "OLingo2 - Cars", + "schema": "https://schema.getpostman.com/json/collection/v2.0.0/collection.json" + }, + "item": [ + { + "name": "GET Metadata", + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": "http://localhost:8080/odata/$metadata" + }, + "response": [] + }, + { + "name": "GET All CarMakers", + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": "http://localhost:8080/odata/CarMakers" + }, + "response": [] + }, + { + "name": "GET Makers with Pagination", + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://localhost:8080/odata/CarMakers?$top=1&$orderby=Name&$skip=3", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "odata", + "CarMakers" + ], + "query": [ + { + "key": "$top", + "value": "1" + }, + { + "key": "$orderby", + "value": "Name" + }, + { + "key": "$skip", + "value": "3" + } + ] + } + }, + "response": [] + }, + { + "name": "GET Makers and Models", + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://localhost:8080/odata/CarMakers?$expand=CarModelDetails", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "odata", + "CarMakers" + ], + "query": [ + { + "key": "$expand", + "value": "CarModelDetails" + } + ] + } + }, + "response": [] + }, + { + "name": "GET Makers with filter", + "request": { + "method": "GET", + "header": [ + { + "key": "Accept", + "value": "application/json", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://localhost:8080/odata/CarMakers?$filter=Name eq 'BWM'&$expand=CarModelDetails", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "odata", + "CarMakers" + ], + "query": [ + { + "key": "$filter", + "value": "Name eq 'BWM'" + }, + { + "key": "$expand", + "value": "CarModelDetails" + } + ] + } + }, + "response": [] + }, + { + "name": "Create CarMaker", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "name": "Content-Type", + "value": "application/atom+xml", + "type": "text" + }, + { + "key": "Accept", + "value": "application/atom+xml", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": " \r\n\r\n \r\n 2019-04-02T21:36:47Z\r\n \r\n \r\n \r\n \r\n \r\n \r\n Lucien\r\n \r\n \r\n" + }, + "url": "http://localhost:8080/odata/CarMakers" + }, + "response": [] + }, + { + "name": "Create CarModel", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "name": "Content-Type", + "type": "text", + "value": "application/atom+xml" + }, + { + "key": "Accept", + "type": "text", + "value": "application/atom+xml" + } + ], + "body": { + "mode": "raw", + "raw": " \r\n\r\n \r\n 2019-04-02T21:36:47Z\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\t Tata\r\n\t TT101\r\n\t 2018\r\n \r\n \r\n" + }, + "url": "http://localhost:8080/odata/CarModels" + }, + "response": [] + }, + { + "name": "Update CarMaker", + "request": { + "method": "PUT", + "header": [ + { + "key": "Content-Type", + "name": "Content-Type", + "type": "text", + "value": "application/atom+xml" + }, + { + "key": "Accept", + "type": "text", + "value": "application/atom+xml" + } + ], + "body": { + "mode": "raw", + "raw": " \r\n\r\n \r\n 2019-04-02T21:36:47Z\r\n \r\n \r\n \r\n \r\n \r\n \r\n 5\r\n KaiserWagen\r\n \r\n \r\n" + }, + "url": "http://localhost:8080/odata/CarMakers(5L)" + }, + "response": [] + }, + { + "name": "All CarModels", + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": "http://localhost:8080/odata/CarModels" + }, + "response": [] + }, + { + "name": "Delete CarModel", + "request": { + "method": "DELETE", + "header": [ + { + "key": "Content-Type", + "name": "Content-Type", + "type": "text", + "value": "application/atom+xml" + }, + { + "key": "Accept", + "type": "text", + "value": "application/atom+xml" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": "http://localhost:8080/odata/CarModels(100L)" + }, + "response": [] + } + ] +} \ No newline at end of file From f5ac80e332dca0488c81bf7ee86fce2114aaa068 Mon Sep 17 00:00:00 2001 From: Matt Zhang Date: Sun, 7 Apr 2019 22:42:15 +1000 Subject: [PATCH 014/167] BAEL-2569 move code to spring-boot-ops module --- .../PriceCalculationApplication.java | 2 +- .../PriceCalculationEnvironmentPostProcessor.java | 0 .../autoconfig/PriceCalculationAutoConfig.java | 0 .../calculator/GrossPriceCalculator.java | 0 .../calculator/NetPriceCalculator.java | 0 .../calculator/PriceCalculator.java | 0 .../service/PriceCalculationService.java | 0 .../src/main/resources/META-INF/spring.factories | 6 ++++++ .../PriceCalculationEnvironmentPostProcessorLiveTest.java | 0 spring-boot/src/main/resources/META-INF/spring.factories | 5 ----- 10 files changed, 7 insertions(+), 6 deletions(-) rename {spring-boot => spring-boot-ops}/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java (96%) rename {spring-boot => spring-boot-ops}/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java (100%) rename {spring-boot => spring-boot-ops}/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java (100%) rename {spring-boot => spring-boot-ops}/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java (100%) rename {spring-boot => spring-boot-ops}/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java (100%) rename {spring-boot => spring-boot-ops}/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java (100%) rename {spring-boot => spring-boot-ops}/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java (100%) create mode 100644 spring-boot-ops/src/main/resources/META-INF/spring.factories rename {spring-boot => spring-boot-ops}/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java (100%) diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java b/spring-boot-ops/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java similarity index 96% rename from spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java rename to spring-boot-ops/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java index 01be08d6ae..ed912d8c0a 100644 --- a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java +++ b/spring-boot-ops/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationApplication.java @@ -35,7 +35,7 @@ public class PriceCalculationApplication implements CommandLineRunner { int quantity = Integer.valueOf(params.get(1)); priceCalculationService.productTotalPrice(singlePrice, quantity); } else { - logger.error("Invalid arguments " + params.toString()); + logger.warn("Invalid arguments " + params.toString()); } } diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java b/spring-boot-ops/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java rename to spring-boot-ops/src/main/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessor.java diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java b/spring-boot-ops/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java rename to spring-boot-ops/src/main/java/com/baeldung/environmentpostprocessor/autoconfig/PriceCalculationAutoConfig.java diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java b/spring-boot-ops/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java rename to spring-boot-ops/src/main/java/com/baeldung/environmentpostprocessor/calculator/GrossPriceCalculator.java diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java b/spring-boot-ops/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java rename to spring-boot-ops/src/main/java/com/baeldung/environmentpostprocessor/calculator/NetPriceCalculator.java diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java b/spring-boot-ops/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java rename to spring-boot-ops/src/main/java/com/baeldung/environmentpostprocessor/calculator/PriceCalculator.java diff --git a/spring-boot/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java b/spring-boot-ops/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java rename to spring-boot-ops/src/main/java/com/baeldung/environmentpostprocessor/service/PriceCalculationService.java diff --git a/spring-boot-ops/src/main/resources/META-INF/spring.factories b/spring-boot-ops/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..c36b67f8d7 --- /dev/null +++ b/spring-boot-ops/src/main/resources/META-INF/spring.factories @@ -0,0 +1,6 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.baeldung.environmentpostprocessor.autoconfig.PriceCalculationAutoConfig + +org.springframework.boot.env.EnvironmentPostProcessor=\ +com.baeldung.environmentpostprocessor.PriceCalculationEnvironmentPostProcessor + diff --git a/spring-boot/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java b/spring-boot-ops/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java rename to spring-boot-ops/src/test/java/com/baeldung/environmentpostprocessor/PriceCalculationEnvironmentPostProcessorLiveTest.java diff --git a/spring-boot/src/main/resources/META-INF/spring.factories b/spring-boot/src/main/resources/META-INF/spring.factories index d8a01bbf82..336477df96 100644 --- a/spring-boot/src/main/resources/META-INF/spring.factories +++ b/spring-boot/src/main/resources/META-INF/spring.factories @@ -1,7 +1,2 @@ org.springframework.boot.diagnostics.FailureAnalyzer=com.baeldung.failureanalyzer.MyBeanNotOfRequiredTypeFailureAnalyzer -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.baeldung.environmentpostprocessor.autoconfig.PriceCalculationAutoConfig - -org.springframework.boot.env.EnvironmentPostProcessor=\ -com.baeldung.environmentpostprocessor.PriceCalculationEnvironmentPostProcessor From 6ac9c01d3d996ec716e4386b945815acdcbe3b4c Mon Sep 17 00:00:00 2001 From: Philippe Date: Mon, 8 Apr 2019 10:23:31 -0300 Subject: [PATCH 015/167] Initial import --- .../olingo2/CarsODataJPAServiceFactory.java | 39 +-- .../examples/olingo2/EntityManagerHolder.java | 18 -- .../examples/olingo2/JerseyConfig.java | 40 +-- .../src/main/resources/application.yml | 4 +- apache-olingo/olingo4/.gitignore | 29 +++ apache-olingo/olingo4/pom.xml | 95 +++++++ .../examples/olingo4/DefaultODataFactory.java | 20 ++ .../examples/olingo4/ODataFactory.java | 8 + .../olingo4/ODataHttpHandlerFactory.java | 8 + .../olingo4/ODataHttpHandlerFactoryImpl.java | 42 ++++ .../olingo4/ODataServiceConfiguration.java | 46 ++++ .../examples/olingo4/ODataServlet.java | 38 +++ .../olingo4/Olingo4SampleApplication.java | 13 + .../examples/olingo4/domain/CarMaker.java | 36 +++ .../examples/olingo4/domain/CarModel.java | 38 +++ .../examples/olingo4/edm/EdmTypeMapper.java | 46 ++++ .../examples/olingo4/edm/JpaEdmProvider.java | 237 ++++++++++++++++++ .../JpaEntityCollectionProcessor.java | 185 ++++++++++++++ .../repository/CarMakerRepository.java | 12 + .../repository/CarModelRepository.java | 13 + .../repository/EdmEntityRepository.java | 15 ++ .../repository/RepositoryRegistry.java | 28 +++ .../src/main/resources/application.properties | 6 + .../olingo4/src/main/resources/data.sql | 12 + .../Olingo4SampleApplicationTests.java | 16 ++ 25 files changed, 991 insertions(+), 53 deletions(-) delete mode 100644 apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/EntityManagerHolder.java create mode 100644 apache-olingo/olingo4/.gitignore create mode 100644 apache-olingo/olingo4/pom.xml create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/DefaultODataFactory.java create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataFactory.java create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactory.java create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactoryImpl.java create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServiceConfiguration.java create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServlet.java create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/Olingo4SampleApplication.java create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarMaker.java create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/EdmTypeMapper.java create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarMakerRepository.java create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarModelRepository.java create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/EdmEntityRepository.java create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java create mode 100644 apache-olingo/olingo4/src/main/resources/application.properties create mode 100644 apache-olingo/olingo4/src/main/resources/data.sql create mode 100644 apache-olingo/olingo4/src/test/java/org/baeldung/examples/olingo4/Olingo4SampleApplicationTests.java diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java index cf13bd0fc9..65a0428154 100644 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java @@ -19,10 +19,13 @@ import javax.persistence.criteria.CriteriaDelete; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaUpdate; import javax.persistence.metamodel.Metamodel; +import javax.servlet.http.HttpServletRequest; +import org.apache.olingo.odata2.api.processor.ODataContext; import org.apache.olingo.odata2.jpa.processor.api.ODataJPAContext; import org.apache.olingo.odata2.jpa.processor.api.ODataJPAServiceFactory; import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException; +import org.baeldung.examples.olingo2.JerseyConfig.EntityManagerFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.orm.jpa.EntityManagerFactoryUtils; @@ -36,15 +39,14 @@ import org.springframework.stereotype.Component; */ @Component public class CarsODataJPAServiceFactory extends ODataJPAServiceFactory { - + private static final Logger log = LoggerFactory.getLogger(CarsODataJPAServiceFactory.class); - + public CarsODataJPAServiceFactory() { // Enable detailed error messages (useful for debugging) setDetailErrors(true); } - /** * This method will be called by Olingo on every request to * initialize the ODataJPAContext that will be used. @@ -54,37 +56,40 @@ public class CarsODataJPAServiceFactory extends ODataJPAServiceFactory { log.info("[I32] >>> initializeODataJPAContext()"); ODataJPAContext ctx = getODataJPAContext(); - + ODataContext octx = ctx.getODataContext(); + HttpServletRequest request = (HttpServletRequest)octx.getParameter(ODataContext.HTTP_SERVLET_REQUEST_OBJECT); + EntityManager em = (EntityManager)request.getAttribute(EntityManagerFilter.EM_REQUEST_ATTRIBUTE); + // Here we're passing the EM that was created by the EntityManagerFilter (see JerseyConfig) - ctx.setEntityManager(new EntityManagerWrapper(EntityManagerHolder.getCurrentEntityManager())); + ctx.setEntityManager(new EntityManagerWrapper(em)); ctx.setPersistenceUnitName("default"); // We're managing the EM's lifecycle, so we must inform Olingo that it should not // try to manage transactions and/or persistence sessions - ctx.setContainerManaged(true); - - + ctx.setContainerManaged(true); return ctx; - } - + static class EntityManagerWrapper implements EntityManager { - + private EntityManager delegate; - + public void persist(Object entity) { - log.info("[I68] persist: entity.class=" + entity.getClass().getSimpleName()); + log.info("[I68] persist: entity.class=" + entity.getClass() + .getSimpleName()); delegate.persist(entity); - //delegate.flush(); + // delegate.flush(); } public T merge(T entity) { - log.info("[I74] merge: entity.class=" + entity.getClass().getSimpleName()); + log.info("[I74] merge: entity.class=" + entity.getClass() + .getSimpleName()); return delegate.merge(entity); } public void remove(Object entity) { - log.info("[I78] remove: entity.class=" + entity.getClass().getSimpleName()); + log.info("[I78] remove: entity.class=" + entity.getClass() + .getSimpleName()); delegate.remove(entity); } @@ -287,7 +292,7 @@ public class CarsODataJPAServiceFactory extends ODataJPAServiceFactory { public EntityManagerWrapper(EntityManager delegate) { this.delegate = delegate; } - + } } diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/EntityManagerHolder.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/EntityManagerHolder.java deleted file mode 100644 index 682621eb99..0000000000 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/EntityManagerHolder.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung.examples.olingo2; - -import javax.persistence.EntityManager; - -public class EntityManagerHolder { - - private static ThreadLocal currentEntityManager = new ThreadLocal<>(); - - - public static void setCurrentEntityManager(EntityManager em) { - currentEntityManager.set(em); - } - - public static EntityManager getCurrentEntityManager() { - return currentEntityManager.get(); - } - -} diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java index a82220e854..78caf99861 100644 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.examples.olingo2; + package org.baeldung.examples.olingo2; import java.io.IOException; @@ -6,12 +6,14 @@ import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; import javax.ws.rs.ApplicationPath; import javax.ws.rs.Path; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.core.Context; import javax.ws.rs.ext.Provider; import org.apache.olingo.odata2.api.ODataServiceFactory; @@ -57,11 +59,15 @@ public class JerseyConfig extends ResourceConfig { */ @Provider public static class EntityManagerFilter implements ContainerRequestFilter, ContainerResponseFilter { - + private static final Logger log = LoggerFactory.getLogger(EntityManagerFilter.class); - + public static final String EM_REQUEST_ATTRIBUTE = EntityManagerFilter.class.getName() + "_ENTITY_MANAGER"; + private final EntityManagerFactory emf; + @Context + private HttpServletRequest httpRequest; + public EntityManagerFilter(EntityManagerFactory emf) { this.emf = emf; } @@ -70,11 +76,12 @@ public class JerseyConfig extends ResourceConfig { public void filter(ContainerRequestContext ctx) throws IOException { log.info("[I60] >>> filter"); EntityManager em = this.emf.createEntityManager(); - EntityManagerHolder.setCurrentEntityManager(em); - + httpRequest.setAttribute(EM_REQUEST_ATTRIBUTE, em); + // Start a new transaction unless we have a simple GET - if ( !"GET".equalsIgnoreCase(ctx.getMethod())) { - em.getTransaction().begin(); + if (!"GET".equalsIgnoreCase(ctx.getMethod())) { + em.getTransaction() + .begin(); } } @@ -82,24 +89,23 @@ public class JerseyConfig extends ResourceConfig { public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { log.info("[I68] <<< filter"); + EntityManager em = (EntityManager) httpRequest.getAttribute(EM_REQUEST_ATTRIBUTE); - EntityManager em = EntityManagerHolder.getCurrentEntityManager(); - if ( em != null && !"GET".equalsIgnoreCase(requestContext.getMethod())) { + if (!"GET".equalsIgnoreCase(requestContext.getMethod())) { EntityTransaction t = em.getTransaction(); - if ( t.isActive()) { - if ( !t.getRollbackOnly()) { + if (t.isActive()) { + if (!t.getRollbackOnly()) { t.commit(); } } } - + em.close(); - + } - + } - - + @Path("/") public static class CarsRootLocator extends ODataRootLocator { @@ -113,7 +119,7 @@ public class JerseyConfig extends ResourceConfig { public ODataServiceFactory getServiceFactory() { return this.serviceFactory; } - + } } diff --git a/apache-olingo/olingo2/src/main/resources/application.yml b/apache-olingo/olingo2/src/main/resources/application.yml index a29b572575..21563a94fe 100644 --- a/apache-olingo/olingo2/src/main/resources/application.yml +++ b/apache-olingo/olingo2/src/main/resources/application.yml @@ -1,4 +1,6 @@ - +server: + port: 8180 + spring: jersey: application-path: /odata diff --git a/apache-olingo/olingo4/.gitignore b/apache-olingo/olingo4/.gitignore new file mode 100644 index 0000000000..153c9335eb --- /dev/null +++ b/apache-olingo/olingo4/.gitignore @@ -0,0 +1,29 @@ +HELP.md +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +/build/ + +### VS Code ### +.vscode/ diff --git a/apache-olingo/olingo4/pom.xml b/apache-olingo/olingo4/pom.xml new file mode 100644 index 0000000000..a6f1fcdb7b --- /dev/null +++ b/apache-olingo/olingo4/pom.xml @@ -0,0 +1,95 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.3.RELEASE + + + org.baeldung.examples.olingo4 + olingo4-sample + 0.0.1-SNAPSHOT + olingo4-sample + Sample Olingo 4 Project + + + 1.8 + 4.5.0 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + com.h2database + h2 + runtime + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-web + + + + org.apache.olingo + odata-server-api + ${odata.version} + + + org.apache.olingo + odata-server-core + ${odata.version} + runtime + + + + org.apache.olingo + odata-commons-api + ${odata.version} + + + org.apache.olingo + odata-commons-core + ${odata.version} + + + + commons-beanutils + commons-beanutils + 1.9.3 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/DefaultODataFactory.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/DefaultODataFactory.java new file mode 100644 index 0000000000..18f7f8ba24 --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/DefaultODataFactory.java @@ -0,0 +1,20 @@ +package org.baeldung.examples.olingo4; + +import org.apache.olingo.server.api.OData; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.stereotype.Component; + +/** + * Default implementation for ODataFactory + * @author Philippe + * + */ +@Component +public class DefaultODataFactory implements ODataFactory { + + @Override + public OData newInstance() { + return OData.newInstance(); + } + +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataFactory.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataFactory.java new file mode 100644 index 0000000000..9acb4b8c5e --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataFactory.java @@ -0,0 +1,8 @@ +package org.baeldung.examples.olingo4; + +import org.apache.olingo.server.api.OData; + +public interface ODataFactory { + + public OData newInstance(); +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactory.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactory.java new file mode 100644 index 0000000000..27d0737c24 --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactory.java @@ -0,0 +1,8 @@ +package org.baeldung.examples.olingo4; + +import org.apache.olingo.server.api.ODataHttpHandler; + +public interface ODataHttpHandlerFactory { + + ODataHttpHandler newInstance(); +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactoryImpl.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactoryImpl.java new file mode 100644 index 0000000000..68d39dc052 --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactoryImpl.java @@ -0,0 +1,42 @@ +package org.baeldung.examples.olingo4; + +import java.util.Collections; +import java.util.List; + +import org.apache.olingo.commons.api.edm.provider.CsdlEdmProvider; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataHttpHandler; +import org.apache.olingo.server.api.ServiceMetadata; +import org.apache.olingo.server.api.processor.Processor; + +import lombok.Builder; + +@Builder +public class ODataHttpHandlerFactoryImpl implements ODataHttpHandlerFactory { + + + private final ODataFactory odataFactory; + private final CsdlEdmProvider edmProvider; + private final List processors; + + public ODataHttpHandlerFactoryImpl(ODataFactory odataFactory,CsdlEdmProvider edmProvider, List processors) { + this.odataFactory = odataFactory; + this.edmProvider = edmProvider; + this.processors = processors; + } + + @Override + public ODataHttpHandler newInstance() { + + OData odata = odataFactory.newInstance(); + ServiceMetadata metadata = odata.createServiceMetadata(edmProvider, Collections.emptyList()); + ODataHttpHandler handler = odata.createHandler(metadata); + + // Register all available processors + processors.forEach(p -> handler.register(p)); + + + return handler; + } + +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServiceConfiguration.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServiceConfiguration.java new file mode 100644 index 0000000000..bbac0ceac7 --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServiceConfiguration.java @@ -0,0 +1,46 @@ +package org.baeldung.examples.olingo4; + +import java.util.List; + +import javax.persistence.EntityManagerFactory; +import javax.servlet.http.HttpServlet; + +import org.apache.olingo.commons.api.edm.provider.CsdlEdmProvider; +import org.apache.olingo.server.api.processor.Processor; +import org.baeldung.examples.olingo4.ODataHttpHandlerFactoryImpl.ODataHttpHandlerFactoryImplBuilder; +import org.springframework.boot.web.servlet.ServletRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ODataServiceConfiguration { + + + @Bean + public ServletRegistrationBean odataServletRegistration(ODataHttpHandlerFactory factory, EntityManagerFactory emf) { + + ServletRegistrationBean bean = new ServletRegistrationBean( + odataServlet(factory,emf), + "/odata/*"); + bean.setLoadOnStartup(1); + return bean; + } + + + @Bean + public HttpServlet odataServlet(ODataHttpHandlerFactory factory, EntityManagerFactory emf ) { + + return new ODataServlet(factory,emf); + } + + + @Bean + public ODataHttpHandlerFactory httpHandlerFactory(CsdlEdmProvider edmProvider, ODataFactory odataFactory, List processors) { + return new ODataHttpHandlerFactoryImplBuilder() + .edmProvider(edmProvider) + .odataFactory(odataFactory) + .processors(processors) + .build(); + } + +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServlet.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServlet.java new file mode 100644 index 0000000000..c2adf2c1ae --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServlet.java @@ -0,0 +1,38 @@ +/** + * + */ +package org.baeldung.examples.olingo4; + +import java.io.IOException; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.olingo.server.api.ODataHttpHandler; + +/** + * @author Philippe + * + */ +public class ODataServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + private final ODataHttpHandlerFactory odataHttpHandlerFactory; + + + public ODataServlet(ODataHttpHandlerFactory factory, EntityManagerFactory emf) { + this.odataHttpHandlerFactory = factory; + } + + @Override + protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + + ODataHttpHandler handler = odataHttpHandlerFactory.newInstance(); + handler.process(req, resp); + } +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/Olingo4SampleApplication.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/Olingo4SampleApplication.java new file mode 100644 index 0000000000..1ac872ea0f --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/Olingo4SampleApplication.java @@ -0,0 +1,13 @@ +package org.baeldung.examples.olingo4; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Olingo4SampleApplication { + + public static void main(String[] args) { + SpringApplication.run(Olingo4SampleApplication.class, args); + } + +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarMaker.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarMaker.java new file mode 100644 index 0000000000..79825b4556 --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarMaker.java @@ -0,0 +1,36 @@ +package org.baeldung.examples.olingo4.domain; + +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import javax.validation.constraints.NotNull; + +import lombok.Data; + +@Entity +@Data +@Table(name="car_maker") +public class CarMaker { + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + private Long id; + + @NotNull + @Column(name="name") + private String name; + + @OneToMany(mappedBy="maker", + orphanRemoval = true, + cascade=CascadeType.ALL) + private List models; + + +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java new file mode 100644 index 0000000000..e6cd80ebf1 --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java @@ -0,0 +1,38 @@ +package org.baeldung.examples.olingo4.domain; + + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; +import javax.validation.constraints.NotNull; + +import lombok.Data; + +@Entity +@Data +@Table(name="car_model") +public class CarModel { + + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + private Long id; + + @NotNull + private String name; + + @NotNull + private Integer year; + + @NotNull + private String sku; + + @ManyToOne(optional=false, fetch= FetchType.LAZY) + @JoinColumn(name="maker_fk") + private CarMaker maker; + +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/EdmTypeMapper.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/EdmTypeMapper.java new file mode 100644 index 0000000000..95797752a2 --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/EdmTypeMapper.java @@ -0,0 +1,46 @@ +package org.baeldung.examples.olingo4.edm; + +import java.util.Collections; +import java.util.Date; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.sql.Time; +import java.util.AbstractMap.SimpleEntry; + +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; +import org.springframework.stereotype.Component; + +@Component +public class EdmTypeMapper { + + public EdmPrimitiveTypeKind java2edm(Class clazz) { + EdmPrimitiveTypeKind result = java2edm.get(clazz); + if ( result == null ) { + throw new IllegalArgumentException("[E19] Unsupported class mapping: class=" + clazz); + } + else { + return result; + } + } + + // Static map used generate attribute metadada based on Java types + static Map,EdmPrimitiveTypeKind> java2edm = Collections + .unmodifiableMap(Stream.of( + new SimpleEntry<>(Boolean.class,EdmPrimitiveTypeKind.Boolean), + new SimpleEntry<>(Byte.class,EdmPrimitiveTypeKind.SByte), + new SimpleEntry<>(Date.class,EdmPrimitiveTypeKind.Date), + new SimpleEntry<>(Time.class,EdmPrimitiveTypeKind.TimeOfDay), + new SimpleEntry<>(Number.class,EdmPrimitiveTypeKind.Decimal), + new SimpleEntry<>(Float.class,EdmPrimitiveTypeKind.Single), + new SimpleEntry<>(Double.class,EdmPrimitiveTypeKind.Double), + new SimpleEntry<>(UUID.class,EdmPrimitiveTypeKind.Guid), + new SimpleEntry<>(Short.class,EdmPrimitiveTypeKind.Int16), + new SimpleEntry<>(Integer.class,EdmPrimitiveTypeKind.Int32), + new SimpleEntry<>(Long.class,EdmPrimitiveTypeKind.Int64), + new SimpleEntry<>(String.class,EdmPrimitiveTypeKind.String) + + ).collect(Collectors.toMap((e)-> e.getKey(),(e)-> e.getValue()))); + +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java new file mode 100644 index 0000000000..3e490cdf58 --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java @@ -0,0 +1,237 @@ +package org.baeldung.examples.olingo4.edm; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import javax.persistence.EntityManagerFactory; +import javax.persistence.metamodel.Attribute.PersistentAttributeType; +import javax.persistence.metamodel.EntityType; +import javax.persistence.metamodel.Metamodel; +import javax.persistence.metamodel.PluralAttribute; +import javax.persistence.metamodel.SingularAttribute; + +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmProvider; +import org.apache.olingo.commons.api.edm.provider.CsdlEntityContainer; +import org.apache.olingo.commons.api.edm.provider.CsdlEntityContainerInfo; +import org.apache.olingo.commons.api.edm.provider.CsdlEntitySet; +import org.apache.olingo.commons.api.edm.provider.CsdlEntityType; +import org.apache.olingo.commons.api.edm.provider.CsdlNavigationProperty; +import org.apache.olingo.commons.api.edm.provider.CsdlProperty; +import org.apache.olingo.commons.api.edm.provider.CsdlPropertyRef; +import org.apache.olingo.commons.api.edm.provider.CsdlSchema; +import org.apache.olingo.commons.api.ex.ODataException; +import org.springframework.stereotype.Component; + +@Component +public class JpaEdmProvider extends CsdlAbstractEdmProvider { + + EntityManagerFactory emf; + + // + private EdmTypeMapper typeMapper; + + // Service Namespace + public static final String NAMESPACE = "OData.Demo"; + + // EDM Container + public static final String CONTAINER_NAME = "Cars"; + public static final FullQualifiedName CONTAINER = new FullQualifiedName(NAMESPACE, CONTAINER_NAME); + + public JpaEdmProvider(EntityManagerFactory emf, EdmTypeMapper mapper) { + this.emf = emf; + this.typeMapper = mapper; + } + + /* (non-Javadoc) + * @see org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmProvider#getEntitySet(org.apache.olingo.commons.api.edm.FullQualifiedName, java.lang.String) + */ + @Override + public CsdlEntitySet getEntitySet(FullQualifiedName entityContainer, String entitySetName) throws ODataException { + + if (entityContainer.equals(CONTAINER)) { + + EntityType e = emf.getMetamodel() + .getEntities() + .stream() + .filter((ent) -> (ent.getName() + "s") + .equals(entitySetName)) + .findFirst() + .orElse(null); + + if (e != null) { + CsdlEntitySet entitySet = new CsdlEntitySet(); + entitySet.setName(entitySetName); + entitySet.setType(new FullQualifiedName(NAMESPACE, e.getName())); + return entitySet; + } + } + + return null; + } + + /* (non-Javadoc) + * @see org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmProvider#getEntityContainerInfo(org.apache.olingo.commons.api.edm.FullQualifiedName) + */ + @Override + public CsdlEntityContainerInfo getEntityContainerInfo(FullQualifiedName entityContainerName) throws ODataException { + + // This method is invoked when displaying the Service Document at e.g. http://localhost:8080/DemoService/DemoService.svc + if (entityContainerName == null || entityContainerName.equals(CONTAINER)) { + CsdlEntityContainerInfo entityContainerInfo = new CsdlEntityContainerInfo(); + entityContainerInfo.setContainerName(CONTAINER); + return entityContainerInfo; + } + + return null; + } + + /* (non-Javadoc) + * @see org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmProvider#getSchemas() + */ + @Override + public List getSchemas() throws ODataException { + // create Schema + CsdlSchema schema = new CsdlSchema(); + schema.setNamespace(NAMESPACE); + + // add EntityTypes + List entityTypes = emf.getMetamodel() + .getEntities() + .stream() + .map((e) -> { + try { + return getEntityType(new FullQualifiedName(NAMESPACE, e.getName())); + } catch (ODataException oe) { + throw new RuntimeException(oe); + } + }) + .collect(Collectors.toList()); + + schema.setEntityTypes(entityTypes); + + // add EntityContainer + schema.setEntityContainer(getEntityContainer()); + + // finally + List schemas = new ArrayList(); + schemas.add(schema); + + return schemas; + } + + /* (non-Javadoc) + * @see org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmProvider#getEntityContainer() + */ + @Override + public CsdlEntityContainer getEntityContainer() throws ODataException { + + + // add EntityTypes + List entitySets = emf.getMetamodel() + .getEntities() + .stream() + .map((e) -> { + try { + // Here we use a simple mapping strategy to map entity types to entity set names: + // + return getEntitySet(CONTAINER, e.getName() + "s"); + } catch (ODataException oe) { + throw new RuntimeException(oe); + } + }) + .collect(Collectors.toList()); + + // create EntityContainer + CsdlEntityContainer entityContainer = new CsdlEntityContainer(); + entityContainer.setName(CONTAINER_NAME); + entityContainer.setEntitySets(entitySets); + + return entityContainer; + } + + @Override + public CsdlEntityType getEntityType(FullQualifiedName entityTypeName) throws ODataException { + + Metamodel mm = emf.getMetamodel(); + + CsdlEntityType result = null; + + result = mm.getEntities() + .stream() + .filter(et -> entityTypeName.equals(new FullQualifiedName(NAMESPACE, et.getName()))) + .map(et -> buildODataType(et)) + .findFirst() + .orElse(null); + + return result; + + } + + /** + * Maps a JPA type to its OData counterpart. + * @param et + * @return + */ + protected CsdlEntityType buildODataType(EntityType et) { + + CsdlEntityType result = new CsdlEntityType(); + result.setName(et.getName()); + + // Process simple properties + List properties = et.getDeclaredSingularAttributes() + .stream() + .filter(attr -> attr.getPersistentAttributeType() == PersistentAttributeType.BASIC) + .map(attr -> buildBasicAttribute(et, attr)) + .collect(Collectors.toList()); + + result.setProperties(properties); + + // Process Ids + List ids = et.getDeclaredSingularAttributes() + .stream() + .filter(attr -> attr.getPersistentAttributeType() == PersistentAttributeType.BASIC && attr.isId()) + .map(attr -> buildRefAttribute(et, attr)) + .collect(Collectors.toList()); + + result.setKey(ids); + + // Process navs + List navs = et.getDeclaredPluralAttributes() + .stream() + .map(attr -> buildNavAttribute(et, attr)) + .collect(Collectors.toList()); + result.setNavigationProperties(navs); + + return result; + } + + private CsdlProperty buildBasicAttribute(EntityType et, SingularAttribute attr) { + + CsdlProperty p = new CsdlProperty().setName(attr.getName()) + .setType(typeMapper.java2edm(attr.getJavaType()) + .getFullQualifiedName()) + .setNullable(et.getDeclaredSingularAttribute(attr.getName()) + .isOptional()); + + return p; + } + + private CsdlPropertyRef buildRefAttribute(EntityType et, SingularAttribute attr) { + + CsdlPropertyRef p = new CsdlPropertyRef().setName(attr.getName()); + + return p; + } + + private CsdlNavigationProperty buildNavAttribute(EntityType et, PluralAttribute attr) { + + CsdlNavigationProperty p = new CsdlNavigationProperty().setName(attr.getName()) + .setType(new FullQualifiedName(NAMESPACE, attr.getBindableJavaType().getSimpleName())) + .setNullable(false); // for now + + return p; + } + +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java new file mode 100644 index 0000000000..ed921484c1 --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java @@ -0,0 +1,185 @@ +package org.baeldung.examples.olingo4.processor; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; + +import javax.persistence.EntityManagerFactory; +import javax.persistence.metamodel.EntityType; +import javax.persistence.metamodel.SingularAttribute; + +import org.apache.commons.beanutils.PropertyUtils; +import org.apache.olingo.commons.api.data.ContextURL; +import org.apache.olingo.commons.api.data.Entity; +import org.apache.olingo.commons.api.data.EntityCollection; +import org.apache.olingo.commons.api.data.Property; +import org.apache.olingo.commons.api.data.ValueType; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.ex.ODataRuntimeException; +import org.apache.olingo.commons.api.format.ContentType; +import org.apache.olingo.commons.api.http.HttpHeader; +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataLibraryException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.ServiceMetadata; +import org.apache.olingo.server.api.processor.CountEntityCollectionProcessor; +import org.apache.olingo.server.api.processor.EntityCollectionProcessor; +import org.apache.olingo.server.api.serializer.EntityCollectionSerializerOptions; +import org.apache.olingo.server.api.serializer.ODataSerializer; +import org.apache.olingo.server.api.serializer.SerializerResult; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.baeldung.examples.olingo4.repository.RepositoryRegistry; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Component; + +@Component +public class JpaEntityCollectionProcessor implements CountEntityCollectionProcessor { + + private OData odata; + private ServiceMetadata serviceMetadata; + private EntityManagerFactory emf; + private RepositoryRegistry repositoryRegistry; + + public JpaEntityCollectionProcessor(EntityManagerFactory emf, RepositoryRegistry repositoryRegistry) { + this.emf = emf; + this.repositoryRegistry = repositoryRegistry; + } + + @Override + public void init(OData odata, ServiceMetadata serviceMetadata) { + this.odata = odata; + this.serviceMetadata = serviceMetadata; + } + + @Override + public void readEntityCollection(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { + + // 1st we have retrieve the requested EntitySet from the uriInfo object (representation of the parsed service URI) + List resourcePaths = uriInfo.getUriResourceParts(); + UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0); // in our example, the first segment is the EntitySet + EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet(); + + // 2nd: fetch the data from backend for this requested EntitySetName + // it has to be delivered as EntitySet object + EntityCollection entitySet = getData(edmEntitySet, uriInfo); + + // 3rd: create a serializer based on the requested format (json) + ODataSerializer serializer = odata.createSerializer(responseFormat); + + // 4th: Now serialize the content: transform from the EntitySet object to InputStream + EdmEntityType edmEntityType = edmEntitySet.getEntityType(); + ContextURL contextUrl = ContextURL.with() + .entitySet(edmEntitySet) + .build(); + + final String id = request.getRawBaseUri() + "/" + edmEntitySet.getName(); + EntityCollectionSerializerOptions opts = EntityCollectionSerializerOptions.with() + .id(id) + .contextURL(contextUrl) + .build(); + SerializerResult serializerResult = serializer.entityCollection(serviceMetadata, edmEntityType, entitySet, opts); + InputStream serializedContent = serializerResult.getContent(); + + // Finally: configure the response object: set the body, headers and status code + response.setContent(serializedContent); + response.setStatusCode(HttpStatusCode.OK.getStatusCode()); + response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString()); + + } + + @Override + public void countEntityCollection(ODataRequest request, ODataResponse response, UriInfo uriInfo) throws ODataApplicationException, ODataLibraryException { + + // 1st we have retrieve the requested EntitySet from the uriInfo object (representation of the parsed service URI) + List resourcePaths = uriInfo.getUriResourceParts(); + UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0); // in our example, the first segment is the EntitySet + EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet(); + + // 2nd: fetch the data from backend for this requested EntitySetName + Long count = getCount(edmEntitySet, uriInfo); + + // Finally: configure the response object: set the body, headers and status code + response.setContent(new ByteArrayInputStream(count.toString() + .getBytes())); + response.setStatusCode(HttpStatusCode.OK.getStatusCode()); + response.setHeader(HttpHeader.CONTENT_TYPE, "text/plain"); + + } + + private EntityCollection getData(EdmEntitySet edmEntitySet, UriInfo uriInfo) { + + EdmEntityType type = edmEntitySet.getEntityType(); + JpaRepository repo = repositoryRegistry.getRepositoryForEntity(type); + EntityCollection result = new EntityCollection(); + + repo.findAll() + .stream() + .forEach((it) -> result.getEntities() + .add(map2entity(edmEntitySet, it))); + + return result; + } + + private Entity map2entity(EdmEntitySet edmEntitySet, Object entry) { + + EntityType et = emf.getMetamodel() + .entity(entry.getClass()); + + + Entity e = new Entity(); + try { + // First, we set the entity's primary key + + // Now map all properties + et.getDeclaredSingularAttributes().stream() + .forEach( (attr) -> { + if ( !attr.isAssociation()) { + Object v = getPropertyValue(entry,attr.getName()); + Property p = new Property(null, attr.getName(),ValueType.PRIMITIVE,v); + e.addProperty(p); + + if ( attr.isId()) { + e.setId(createId(edmEntitySet.getName(),v)); + } + } + + }); + + } catch (Exception ex) { + throw new ODataRuntimeException("[E141] Unable to create OData entity", ex); + } + + return e; + } + + private Object getPropertyValue(Object entry, String name) { + try { + return PropertyUtils.getProperty(entry,name); + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + throw new ODataRuntimeException("[E141] Unable to read property from entity, property=" + name, e); + } + } + + private URI createId(String entitySetName, Object id) { + try { + return new URI(entitySetName + "(" + String.valueOf(id) + ")"); + } catch (URISyntaxException e) { + throw new ODataRuntimeException("[E177] Unable to create URI", e); + } + } + + private Long getCount(EdmEntitySet edmEntitySet, UriInfo uriInfo) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarMakerRepository.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarMakerRepository.java new file mode 100644 index 0000000000..70664bcf86 --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarMakerRepository.java @@ -0,0 +1,12 @@ +package org.baeldung.examples.olingo4.repository; + +import org.baeldung.examples.olingo4.domain.CarMaker; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; +import org.springframework.stereotype.Repository; + +@Repository +public interface CarMakerRepository extends JpaRepository, JpaSpecificationExecutor, EdmEntityRepository { + + public default String getEdmEntityName() { return CarMaker.class.getSimpleName();} +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarModelRepository.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarModelRepository.java new file mode 100644 index 0000000000..40590b15e1 --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarModelRepository.java @@ -0,0 +1,13 @@ +package org.baeldung.examples.olingo4.repository; + +import org.baeldung.examples.olingo4.domain.CarModel; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; +import org.springframework.stereotype.Repository; + +@Repository +public interface CarModelRepository extends JpaRepository, JpaSpecificationExecutor,EdmEntityRepository { + + public default String getEdmEntityName() { return CarModel.class.getSimpleName();} + +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/EdmEntityRepository.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/EdmEntityRepository.java new file mode 100644 index 0000000000..105925c958 --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/EdmEntityRepository.java @@ -0,0 +1,15 @@ +/** + * + */ +package org.baeldung.examples.olingo4.repository; + + +/** + * @author Philippe + * + */ +public interface EdmEntityRepository { + + public String getEdmEntityName(); + +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java new file mode 100644 index 0000000000..991eb21fc2 --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java @@ -0,0 +1,28 @@ +package org.baeldung.examples.olingo4.repository; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Component; + +@Component +public class RepositoryRegistry { + + private Map> repositoriesByClassName = new HashMap<>(); + + public RepositoryRegistry(List allRepositories) { + + allRepositories.stream().forEach((r) -> + repositoriesByClassName.put(r.getEdmEntityName(),(JpaRepository)r)); + + } + + + public JpaRepository getRepositoryForEntity(EdmEntityType entityType) { + JpaRepository repo = repositoriesByClassName.get(entityType.getName()); + return repo; + } +} diff --git a/apache-olingo/olingo4/src/main/resources/application.properties b/apache-olingo/olingo4/src/main/resources/application.properties new file mode 100644 index 0000000000..6f115b5ae4 --- /dev/null +++ b/apache-olingo/olingo4/src/main/resources/application.properties @@ -0,0 +1,6 @@ +spring: + jpa: + show-sql: true + open-in-view: false + hibernate: + ddl-auto: update diff --git a/apache-olingo/olingo4/src/main/resources/data.sql b/apache-olingo/olingo4/src/main/resources/data.sql new file mode 100644 index 0000000000..327f2688c5 --- /dev/null +++ b/apache-olingo/olingo4/src/main/resources/data.sql @@ -0,0 +1,12 @@ +insert into car_maker(id,name) values (1,'Special Motors'); +insert into car_maker(id,name) values (2,'BWM'); +insert into car_maker(id,name) values (3,'Dolores'); + +insert into car_model(id,maker_fk,name,sku,year) values(1,1,'Muze','SM001',2018); +insert into car_model(id,maker_fk,name,sku,year) values(2,1,'Empada','SM002',2008); + +insert into car_model(id,maker_fk,name,sku,year) values(4,2,'BWM-100','BWM100',2008); +insert into car_model(id,maker_fk,name,sku,year) values(5,2,'BWM-200','BWM200',2009); +insert into car_model(id,maker_fk,name,sku,year) values(6,2,'BWM-300','BWM300',2008); + +alter sequence hibernate_sequence restart with 100; \ No newline at end of file diff --git a/apache-olingo/olingo4/src/test/java/org/baeldung/examples/olingo4/Olingo4SampleApplicationTests.java b/apache-olingo/olingo4/src/test/java/org/baeldung/examples/olingo4/Olingo4SampleApplicationTests.java new file mode 100644 index 0000000000..5d23a4148e --- /dev/null +++ b/apache-olingo/olingo4/src/test/java/org/baeldung/examples/olingo4/Olingo4SampleApplicationTests.java @@ -0,0 +1,16 @@ +package org.baeldung.examples.olingo4; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class Olingo4SampleApplicationTests { + + @Test + public void contextLoads() { + } + +} From 270582b25aac5b27b87281f9bdeaecf9e155c87f Mon Sep 17 00:00:00 2001 From: Philippe Date: Fri, 12 Apr 2019 00:16:38 -0300 Subject: [PATCH 016/167] [BAEL-1219] Code for Olingo V4 sample --- apache-olingo/olingo4/pom.xml | 2 +- .../olingo4/ODataServiceConfiguration.java | 31 +- .../examples/olingo4/ODataServlet.java | 2 +- .../examples/olingo4/edm/JpaEdmProvider.java | 33 +- .../JpaEntityCollectionProcessor.java | 77 ++-- .../olingo4/processor/JpaEntityMapper.java | 84 ++++ .../olingo4/processor/JpaEntityProcessor.java | 378 ++++++++++++++++++ .../repository/CarMakerRepository.java | 6 +- .../repository/CarModelRepository.java | 11 +- .../repository/EdmEntityRepository.java | 4 +- .../repository/RepositoryRegistry.java | 11 +- .../src/main/resources/application.properties | 3 + 12 files changed, 552 insertions(+), 90 deletions(-) create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityMapper.java create mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityProcessor.java diff --git a/apache-olingo/olingo4/pom.xml b/apache-olingo/olingo4/pom.xml index a6f1fcdb7b..794aee0711 100644 --- a/apache-olingo/olingo4/pom.xml +++ b/apache-olingo/olingo4/pom.xml @@ -52,7 +52,7 @@ org.springframework.boot spring-boot-starter-web - + org.apache.olingo odata-server-api diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServiceConfiguration.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServiceConfiguration.java index bbac0ceac7..0cde665359 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServiceConfiguration.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServiceConfiguration.java @@ -14,33 +14,22 @@ import org.springframework.context.annotation.Configuration; @Configuration public class ODataServiceConfiguration { - - - @Bean - public ServletRegistrationBean odataServletRegistration(ODataHttpHandlerFactory factory, EntityManagerFactory emf) { - - ServletRegistrationBean bean = new ServletRegistrationBean( - odataServlet(factory,emf), - "/odata/*"); - bean.setLoadOnStartup(1); - return bean; - } - @Bean - public HttpServlet odataServlet(ODataHttpHandlerFactory factory, EntityManagerFactory emf ) { - - return new ODataServlet(factory,emf); + public ServletRegistrationBean odataServletRegistration(ODataHttpHandlerFactory factory) { + ServletRegistrationBean srb = + new ServletRegistrationBean<>(new ODataServlet(factory), "/odata/*"); + srb.setLoadOnStartup(1); + return srb; } - - + @Bean public ODataHttpHandlerFactory httpHandlerFactory(CsdlEdmProvider edmProvider, ODataFactory odataFactory, List processors) { return new ODataHttpHandlerFactoryImplBuilder() - .edmProvider(edmProvider) - .odataFactory(odataFactory) - .processors(processors) - .build(); + .edmProvider(edmProvider) + .odataFactory(odataFactory) + .processors(processors) + .build(); } } diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServlet.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServlet.java index c2adf2c1ae..c379124541 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServlet.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServlet.java @@ -25,7 +25,7 @@ public class ODataServlet extends HttpServlet { private final ODataHttpHandlerFactory odataHttpHandlerFactory; - public ODataServlet(ODataHttpHandlerFactory factory, EntityManagerFactory emf) { + public ODataServlet(ODataHttpHandlerFactory factory) { this.odataHttpHandlerFactory = factory; } diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java index 3e490cdf58..68edb58e12 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java @@ -62,8 +62,9 @@ public class JpaEdmProvider extends CsdlAbstractEdmProvider { if (e != null) { CsdlEntitySet entitySet = new CsdlEntitySet(); - entitySet.setName(entitySetName); - entitySet.setType(new FullQualifiedName(NAMESPACE, e.getName())); + entitySet + .setName(entitySetName) + .setType(new FullQualifiedName(NAMESPACE, e.getName())); return entitySet; } } @@ -135,7 +136,6 @@ public class JpaEdmProvider extends CsdlAbstractEdmProvider { .map((e) -> { try { // Here we use a simple mapping strategy to map entity types to entity set names: - // return getEntitySet(CONTAINER, e.getName() + "s"); } catch (ODataException oe) { throw new RuntimeException(oe); @@ -197,12 +197,22 @@ public class JpaEdmProvider extends CsdlAbstractEdmProvider { result.setKey(ids); - // Process navs + // Process 1:N navs List navs = et.getDeclaredPluralAttributes() .stream() .map(attr -> buildNavAttribute(et, attr)) .collect(Collectors.toList()); result.setNavigationProperties(navs); + + // Process N:1 navs + List navs2 = et.getDeclaredSingularAttributes() + .stream() + .filter(attr -> attr.getPersistentAttributeType() == PersistentAttributeType.MANY_TO_ONE) + .map(attr -> buildNavAttribute(et, attr)) + .collect(Collectors.toList()); + + result.getNavigationProperties().addAll(navs2); + return result; } @@ -225,13 +235,26 @@ public class JpaEdmProvider extends CsdlAbstractEdmProvider { return p; } + // Build NavProperty for 1:N or M:N associations private CsdlNavigationProperty buildNavAttribute(EntityType et, PluralAttribute attr) { CsdlNavigationProperty p = new CsdlNavigationProperty().setName(attr.getName()) .setType(new FullQualifiedName(NAMESPACE, attr.getBindableJavaType().getSimpleName())) - .setNullable(false); // for now + .setCollection(true) + .setNullable(false); return p; } + // Build NavProperty for N:1 associations + private CsdlNavigationProperty buildNavAttribute(EntityType et, SingularAttribute attr) { + + CsdlNavigationProperty p = new CsdlNavigationProperty().setName(attr.getName()) + .setType(new FullQualifiedName(NAMESPACE, attr.getBindableJavaType().getSimpleName())) + .setCollection(false) + .setNullable(attr.isOptional()); + + return p; + } + } diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java index ed921484c1..6bca0e9896 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java @@ -48,10 +48,12 @@ public class JpaEntityCollectionProcessor implements CountEntityCollectionProces private ServiceMetadata serviceMetadata; private EntityManagerFactory emf; private RepositoryRegistry repositoryRegistry; + private JpaEntityMapper entityMapper; - public JpaEntityCollectionProcessor(EntityManagerFactory emf, RepositoryRegistry repositoryRegistry) { + public JpaEntityCollectionProcessor(EntityManagerFactory emf, RepositoryRegistry repositoryRegistry, JpaEntityMapper entityMapper) { this.emf = emf; this.repositoryRegistry = repositoryRegistry; + this.entityMapper = entityMapper; } @Override @@ -115,71 +117,40 @@ public class JpaEntityCollectionProcessor implements CountEntityCollectionProces } - private EntityCollection getData(EdmEntitySet edmEntitySet, UriInfo uriInfo) { + /** + * Helper method to retrieve all entities of an entity set from an the backend database + * @param edmEntitySet + * @param uriInfo + * @return + */ + protected EntityCollection getData(EdmEntitySet edmEntitySet, UriInfo uriInfo) { EdmEntityType type = edmEntitySet.getEntityType(); - JpaRepository repo = repositoryRegistry.getRepositoryForEntity(type); + JpaRepository repo = (JpaRepository)repositoryRegistry.getRepositoryForEntity(type); EntityCollection result = new EntityCollection(); repo.findAll() .stream() .forEach((it) -> result.getEntities() - .add(map2entity(edmEntitySet, it))); + .add(entityMapper.map2entity(edmEntitySet, it))); return result; } - private Entity map2entity(EdmEntitySet edmEntitySet, Object entry) { - - EntityType et = emf.getMetamodel() - .entity(entry.getClass()); - - - Entity e = new Entity(); - try { - // First, we set the entity's primary key - - // Now map all properties - et.getDeclaredSingularAttributes().stream() - .forEach( (attr) -> { - if ( !attr.isAssociation()) { - Object v = getPropertyValue(entry,attr.getName()); - Property p = new Property(null, attr.getName(),ValueType.PRIMITIVE,v); - e.addProperty(p); - - if ( attr.isId()) { - e.setId(createId(edmEntitySet.getName(),v)); - } - } - - }); - - } catch (Exception ex) { - throw new ODataRuntimeException("[E141] Unable to create OData entity", ex); - } - - return e; - } - - private Object getPropertyValue(Object entry, String name) { - try { - return PropertyUtils.getProperty(entry,name); - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new ODataRuntimeException("[E141] Unable to read property from entity, property=" + name, e); - } - } - - private URI createId(String entitySetName, Object id) { - try { - return new URI(entitySetName + "(" + String.valueOf(id) + ")"); - } catch (URISyntaxException e) { - throw new ODataRuntimeException("[E177] Unable to create URI", e); - } - } + /** + * Helper method to get the total size of an entity set + * @param edmEntitySet + * @param uriInfo + * @return + */ private Long getCount(EdmEntitySet edmEntitySet, UriInfo uriInfo) { - // TODO Auto-generated method stub - return null; + + EdmEntityType type = edmEntitySet.getEntityType(); + JpaRepository repo = (JpaRepository)repositoryRegistry.getRepositoryForEntity(type); + EntityCollection result = new EntityCollection(); + + return repo.count(); } } diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityMapper.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityMapper.java new file mode 100644 index 0000000000..5fd863124f --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityMapper.java @@ -0,0 +1,84 @@ +/** + * + */ +package org.baeldung.examples.olingo4.processor; + +import java.lang.reflect.InvocationTargetException; +import java.net.URI; +import java.net.URISyntaxException; + +import javax.persistence.EntityManagerFactory; +import javax.persistence.metamodel.EntityType; + +import org.apache.commons.beanutils.PropertyUtils; +import org.apache.olingo.commons.api.data.Entity; +import org.apache.olingo.commons.api.data.Property; +import org.apache.olingo.commons.api.data.ValueType; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.ex.ODataRuntimeException; +import org.springframework.stereotype.Component; + +/** + *

Helper class that converts a JPA entity into an OData entity using + * available metadata from the JPA's EntityManagerFactory.

+ * + * @author Philippe + * + */ +@Component +public class JpaEntityMapper { + + private EntityManagerFactory emf; + + public JpaEntityMapper(EntityManagerFactory emf) { + this.emf = emf; + } + + + public Entity map2entity(EdmEntitySet edmEntitySet, Object entry) { + + EntityType et = emf.getMetamodel() + .entity(entry.getClass()); + + + Entity e = new Entity(); + try { + et.getDeclaredSingularAttributes().stream() + .forEach( (attr) -> { + if ( !attr.isAssociation()) { + Object v = getPropertyValue(entry,attr.getName()); + Property p = new Property(null, attr.getName(),ValueType.PRIMITIVE,v); + e.addProperty(p); + + if ( attr.isId()) { + e.setId(createId(edmEntitySet.getName(),v)); + } + } + }); + } catch (Exception ex) { + throw new ODataRuntimeException("[E141] Unable to create OData entity", ex); + } + + return e; + } + + + private Object getPropertyValue(Object entry, String name) { + try { + return PropertyUtils.getProperty(entry,name); + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + throw new ODataRuntimeException("[E141] Unable to read property from entity, property=" + name, e); + } + } + + private URI createId(String entitySetName, Object id) { + try { + return new URI(entitySetName + "(" + String.valueOf(id) + ")"); + } catch (URISyntaxException e) { + throw new ODataRuntimeException("[E177] Unable to create URI", e); + } + } + + + +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityProcessor.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityProcessor.java new file mode 100644 index 0000000000..23a5a7ac4b --- /dev/null +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityProcessor.java @@ -0,0 +1,378 @@ +/** + * + */ +package org.baeldung.examples.olingo4.processor; + +import java.io.InputStream; +import java.lang.reflect.Member; +import java.util.Collection; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; + +import javax.persistence.EntityManagerFactory; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import javax.persistence.metamodel.SingularAttribute; + +import org.apache.commons.beanutils.PropertyUtils; +import org.apache.olingo.commons.api.data.ContextURL; +import org.apache.olingo.commons.api.data.Entity; +import org.apache.olingo.commons.api.data.EntityCollection; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmNavigationProperty; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.ex.ODataRuntimeException; +import org.apache.olingo.commons.api.format.ContentType; +import org.apache.olingo.commons.api.http.HttpHeader; +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataLibraryException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.ServiceMetadata; +import org.apache.olingo.server.api.processor.EntityProcessor; +import org.apache.olingo.server.api.serializer.EntityCollectionSerializerOptions; +import org.apache.olingo.server.api.serializer.EntitySerializerOptions; +import org.apache.olingo.server.api.serializer.ODataSerializer; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.apache.olingo.server.api.serializer.SerializerResult; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceNavigation; +import org.baeldung.examples.olingo4.repository.EdmEntityRepository; +import org.baeldung.examples.olingo4.repository.RepositoryRegistry; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; +import org.springframework.stereotype.Component; + +/** + * JpaEntityProcessor adapter. + *

This implementation is heavily based on the Tutorial available + * at Olingo's site. It is meant to be an starting point for an actual implementation.

+ *

Please note that many features from a full-fledged are missing + * @author Philippe + * + */ +@Component +public class JpaEntityProcessor implements EntityProcessor { + + private EntityManagerFactory emf; + private OData odata; + private ServiceMetadata serviceMetadata; + private RepositoryRegistry registry; + private JpaEntityMapper entityMapper; + + public JpaEntityProcessor(EntityManagerFactory emf, RepositoryRegistry registry, JpaEntityMapper entityMapper) { + this.emf = emf; + this.registry = registry; + this.entityMapper = entityMapper; + } + + /* (non-Javadoc) + * @see org.apache.olingo.server.api.processor.Processor#init(org.apache.olingo.server.api.OData, org.apache.olingo.server.api.ServiceMetadata) + */ + @Override + public void init(OData odata, ServiceMetadata serviceMetadata) { + this.odata = odata; + this.serviceMetadata = serviceMetadata; + + } + + /* (non-Javadoc) + * @see org.apache.olingo.server.api.processor.EntityProcessor#readEntity(org.apache.olingo.server.api.ODataRequest, org.apache.olingo.server.api.ODataResponse, org.apache.olingo.server.api.uri.UriInfo, org.apache.olingo.commons.api.format.ContentType) + */ + @Override + public void readEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { + + // First, we have to figure out which entity is requested + List resourceParts = uriInfo.getUriResourceParts(); + InputStream entityStream; + + UriResourceEntitySet rootResourceEntitySet = (UriResourceEntitySet) resourceParts.get(0); + EdmEntitySet rootEntitySet = rootResourceEntitySet.getEntitySet(); + List rootPredicates = rootResourceEntitySet.getKeyPredicates(); + EdmEntityType rootEntityType = rootEntitySet.getEntityType(); + + + if ( resourceParts.size() == 1 ) { + entityStream = readEntity(rootEntitySet,rootPredicates,responseFormat); + } + else if ( resourceParts.size() == 2 ) { + UriResource part = resourceParts.get(1); + if ( !(part instanceof UriResourceNavigation)) { + throw new ODataRuntimeException("[E103] part type not supported: class=" + part.getClass().getName()); + } + + UriResourceNavigation navSegment = (UriResourceNavigation)part; + + // We have three scenarios we must handle: + // Entity(x)/Related, where Related is a 1:N or M:N relationship => result is a collection + // Entity(x)/Related, where Related is a N:1 or 1:1 relationship => result is a single entity + // Entity(x)/Related(z), where Related is a 1:N or M:N relationship => result is a single entity + if (navSegment.getKeyPredicates().isEmpty()) { + if ( isOne2ManyProperty(rootEntityType,navSegment.getProperty())) { + entityStream = readRelatedEntities(rootEntitySet,rootPredicates,navSegment.getProperty(),responseFormat); + } + else { + // The relation must point to another entity type, so casting should be safe here + EdmEntityType resultType = (EdmEntityType)rootEntityType.getNavigationProperty(navSegment.getProperty().getName()).getType(); + EdmEntitySet resultEntitySet = entitySetFromType(resultType); + + entityStream = readEntity(resultEntitySet, navSegment.getKeyPredicates(), responseFormat); + } + } + else { + entityStream = readRelatedEntity(request, rootEntitySet,rootPredicates,navSegment.getProperty(),navSegment.getKeyPredicates(),responseFormat); + } + + } + else { + // For now, we'll only allow navigation just to directly linked navs + throw new ODataApplicationException("[E109] Multi-level navigation not supported", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ROOT); + } + + //4. configure the response object + response.setContent(entityStream); + response.setStatusCode(HttpStatusCode.OK.getStatusCode()); + response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString()); + + } + + + // Lookup the EntitySet associated with an EntityType + // In our example, we assume we have only one entityset for each entity type + private EdmEntitySet entitySetFromType(EdmEntityType type) { + return serviceMetadata + .getEdm() + .getEntityContainer() + .getEntitySets() + .stream() + .filter((s) -> s.getEntityType().getName().equals(type.getName())) + .findFirst() + .orElseThrow(() -> new ODataRuntimeException("[E144] No entity set found for type " + type.getFullQualifiedName())); + } + + // + private boolean isOne2ManyProperty(EdmEntityType entityType, EdmNavigationProperty property) { + return entityType.getProperty(property.getName()) != null && property.isCollection(); + } + + private InputStream readEntity(EdmEntitySet entitySet, List keyPredicates,ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { + + Entity entity = readEntityData(entitySet,keyPredicates); + + ContextURL contextUrl = ContextURL.with().entitySet(entitySet).build(); + // expand and select currently not supported + EntitySerializerOptions options = EntitySerializerOptions + .with() + .contextURL(contextUrl) + .build(); + + ODataSerializer serializer = odata.createSerializer(responseFormat); + + SerializerResult serializerResult = serializer.entity(serviceMetadata, entitySet.getEntityType(), entity, options); + return serializerResult.getContent(); + } + + private InputStream readRelatedEntities(EdmEntitySet rootEntitySet, List rootPredicates, EdmNavigationProperty property, ContentType responseFormat) throws ODataApplicationException { + + Object jpaEntity = readJPAEntity(rootEntitySet, rootPredicates); + try { + Object set = PropertyUtils.getProperty(jpaEntity, property.getName()); + EdmEntitySet entitySet = entitySetFromType(property.getType()); + ContextURL contextUrl = ContextURL + .with() + .entitySet(entitySet) + .build(); + + EntityCollectionSerializerOptions options = EntityCollectionSerializerOptions + .with() + .contextURL(contextUrl) + .build(); + + EntityCollection result = new EntityCollection(); + + ((Collection)set) + .stream() + .map((o) -> this.entityMapper.map2entity(entitySet, o)) + .forEach((e) -> result.getEntities().add(e)); + + ODataSerializer serializer = odata.createSerializer(responseFormat); + SerializerResult serializerResult = serializer.entityCollection(serviceMetadata, property.getType(), result, options); + return serializerResult.getContent(); + } + catch(Exception ex) { + throw new ODataRuntimeException("[E181] Error accessing database", ex); + } + } + + @SuppressWarnings({ "rawtypes", "serial", "unchecked" }) + private InputStream readRelatedEntity(ODataRequest request, EdmEntitySet rootEntitySet, List rootPredicates, EdmNavigationProperty property, List predicates, ContentType responseFormat) throws ODataApplicationException, SerializerException { + + + JpaSpecificationExecutor rootRepo = (JpaSpecificationExecutor)registry.getRepositoryForEntity(rootEntitySet.getEntityType()); + JpaSpecificationExecutor repo = (JpaSpecificationExecutor)registry.getRepositoryForEntity(property.getType()); + + // We assume here that we have a bi-directional 1:N relationship, so we'll + // always have a property in the child entity that points to the parent + Class rootClass = ((EdmEntityRepository)rootRepo).getEntityClass(); + Class childClass = ((EdmEntityRepository)repo).getEntityClass(); + SingularAttribute fk = emf.getMetamodel() + .entity(childClass) + .getSingularAttributes() + .stream() + .filter((attr) -> attr.isAssociation() && attr.getJavaType().isAssignableFrom(rootClass)) + .findFirst() + .orElse(null); + + SingularAttribute pk = emf.getMetamodel() + .entity(childClass) + .getId(Long.class); + + SingularAttribute rootPk = emf.getMetamodel() + .entity(rootClass) + .getId(Long.class); + + if ( fk == null ) { + throw new ODataRuntimeException("[E230] No singular attribute of child class '" + childClass.getName() + "' found" ); + } + + + Specification spec = new Specification() { + @Override + public Predicate toPredicate(Root root, CriteriaQuery q, CriteriaBuilder cb) { + + try { + Object rootInstance = rootClass.newInstance(); + PropertyUtils.setProperty(rootInstance, rootPk.getName(), getEntityKey(rootEntitySet.getEntityType(),rootPredicates)); + + final Predicate p = cb.and( + cb.equal( + root.get(pk), + getEntityKey(property.getType(),predicates)), + cb.equal( + root.get(fk), + rootInstance)); + + return p; + } + catch(Exception ex) { + throw new ODataRuntimeException(ex); + } + + } + }; + + // Read data from DB + EdmEntitySet relatedEntitySet = entitySetFromType(property.getType()); + EntityCollection data = new EntityCollection(); + + repo.findAll(spec) + .stream() + .forEach((entry) -> data.getEntities().add(entityMapper.map2entity(relatedEntitySet, entry))); + + // + + ODataSerializer serializer = odata.createSerializer(responseFormat); + + // 4th: Now serialize the content: transform from the EntitySet object to InputStream + EdmEntityType edmEntityType = relatedEntitySet.getEntityType(); + ContextURL contextUrl = ContextURL.with() + .entitySet(relatedEntitySet) + .build(); + + final String id = request.getRawBaseUri() + "/" + relatedEntitySet.getName(); + EntityCollectionSerializerOptions opts = EntityCollectionSerializerOptions.with() + .id(id) + .contextURL(contextUrl) + .build(); + SerializerResult serializerResult = serializer.entityCollection(serviceMetadata, edmEntityType, data, opts); + InputStream serializedContent = serializerResult.getContent(); + + + return serializedContent; + } + + + /** + * This method returns a speficic entity given its primary key + * @param edmEntitySet + * @param keyPredicates + * @return + */ + protected Entity readEntityData(EdmEntitySet edmEntitySet, List keyPredicates) throws ODataApplicationException { + + Object jpaEntry = readJPAEntity(edmEntitySet, keyPredicates); + Entity e = entityMapper.map2entity(edmEntitySet, jpaEntry); + return e; + } + + private Object readJPAEntity(EdmEntitySet edmEntitySet, List keyPredicates) throws ODataApplicationException { + EdmEntityType type = edmEntitySet.getEntityType(); + JpaRepository repo = (JpaRepository)registry.getRepositoryForEntity(type); + + // Get key value + Object keyValue = getEntityKey(type,keyPredicates); + Object entry = repo + .findById(keyValue) + .orElseThrow( + () -> new ODataApplicationException("[E116] NO entity found for the given key", + HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH)); + + return entry; + } + + private Object getEntityKey(EdmEntityType type, List keyPredicates) { + + if ( keyPredicates.size() > 1 ) { + throw new ODataRuntimeException("[E131] Composite keys are not supported"); + } + + // For now, we'll assume we only have numeric keys. + UriParameter keyParam = keyPredicates.get(0); + try { + return Long.parseLong(keyParam.getText()); + } + catch(NumberFormatException nfe) { + throw new ODataRuntimeException("[E140] Invalid key value. Only numeric keys are supported by this service"); + } + + + } + + /* (non-Javadoc) + * @see org.apache.olingo.server.api.processor.EntityProcessor#createEntity(org.apache.olingo.server.api.ODataRequest, org.apache.olingo.server.api.ODataResponse, org.apache.olingo.server.api.uri.UriInfo, org.apache.olingo.commons.api.format.ContentType, org.apache.olingo.commons.api.format.ContentType) + */ + @Override + public void createEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType requestFormat, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.apache.olingo.server.api.processor.EntityProcessor#updateEntity(org.apache.olingo.server.api.ODataRequest, org.apache.olingo.server.api.ODataResponse, org.apache.olingo.server.api.uri.UriInfo, org.apache.olingo.commons.api.format.ContentType, org.apache.olingo.commons.api.format.ContentType) + */ + @Override + public void updateEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType requestFormat, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see org.apache.olingo.server.api.processor.EntityProcessor#deleteEntity(org.apache.olingo.server.api.ODataRequest, org.apache.olingo.server.api.ODataResponse, org.apache.olingo.server.api.uri.UriInfo) + */ + @Override + public void deleteEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo) throws ODataApplicationException, ODataLibraryException { + // TODO Auto-generated method stub + + } + +} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarMakerRepository.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarMakerRepository.java index 70664bcf86..1bde9f148c 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarMakerRepository.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarMakerRepository.java @@ -6,7 +6,11 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; @Repository -public interface CarMakerRepository extends JpaRepository, JpaSpecificationExecutor, EdmEntityRepository { +public interface CarMakerRepository extends EdmEntityRepository, JpaRepository, JpaSpecificationExecutor { public default String getEdmEntityName() { return CarMaker.class.getSimpleName();} + @Override + default Class getEntityClass() { + return CarMaker.class; + } } diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarModelRepository.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarModelRepository.java index 40590b15e1..247bf6e77b 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarModelRepository.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarModelRepository.java @@ -1,13 +1,22 @@ package org.baeldung.examples.olingo4.repository; +import java.util.List; + import org.baeldung.examples.olingo4.domain.CarModel; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; @Repository -public interface CarModelRepository extends JpaRepository, JpaSpecificationExecutor,EdmEntityRepository { +public interface CarModelRepository extends EdmEntityRepository, JpaRepository, JpaSpecificationExecutor { + public List findByMakerId(Long makerId); + public default String getEdmEntityName() { return CarModel.class.getSimpleName();} + + @Override + default Class getEntityClass() { + return CarModel.class; + } } diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/EdmEntityRepository.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/EdmEntityRepository.java index 105925c958..dbfd0e6f93 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/EdmEntityRepository.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/EdmEntityRepository.java @@ -8,8 +8,10 @@ package org.baeldung.examples.olingo4.repository; * @author Philippe * */ -public interface EdmEntityRepository { +public interface EdmEntityRepository { public String getEdmEntityName(); + public Class getEntityClass(); + } diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java index 991eb21fc2..20981fdfef 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java @@ -5,24 +5,23 @@ import java.util.List; import java.util.Map; import org.apache.olingo.commons.api.edm.EdmEntityType; -import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Component; @Component public class RepositoryRegistry { - private Map> repositoriesByClassName = new HashMap<>(); + private Map> repositoriesByClassName = new HashMap<>(); - public RepositoryRegistry(List allRepositories) { + public RepositoryRegistry(List> allRepositories) { allRepositories.stream().forEach((r) -> - repositoriesByClassName.put(r.getEdmEntityName(),(JpaRepository)r)); + repositoriesByClassName.put(r.getEdmEntityName(),(EdmEntityRepository)r)); } - public JpaRepository getRepositoryForEntity(EdmEntityType entityType) { - JpaRepository repo = repositoriesByClassName.get(entityType.getName()); + public EdmEntityRepository getRepositoryForEntity(EdmEntityType entityType) { + EdmEntityRepository repo = repositoriesByClassName.get(entityType.getName()); return repo; } } diff --git a/apache-olingo/olingo4/src/main/resources/application.properties b/apache-olingo/olingo4/src/main/resources/application.properties index 6f115b5ae4..e4742b4fbb 100644 --- a/apache-olingo/olingo4/src/main/resources/application.properties +++ b/apache-olingo/olingo4/src/main/resources/application.properties @@ -1,3 +1,6 @@ +server: + port: 8080 + spring: jpa: show-sql: true From 5f30277f9e8af356288061502bc180a425d314be Mon Sep 17 00:00:00 2001 From: Philippe Date: Sun, 14 Apr 2019 13:17:38 -0300 Subject: [PATCH 017/167] [BAEL-1219] Code polishing --- .../examples/olingo4/domain/CarModel.java | 2 +- .../examples/olingo4/edm/JpaEdmProvider.java | 17 +- .../JpaEntityCollectionProcessor.java | 17 +- .../olingo4/processor/JpaEntityMapper.java | 11 +- .../olingo4/processor/JpaEntityProcessor.java | 276 +++++++----------- .../repository/RepositoryRegistry.java | 12 +- .../src/main/resources/application.properties | 2 +- 7 files changed, 144 insertions(+), 193 deletions(-) diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java index e6cd80ebf1..a9254e48b9 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java @@ -31,7 +31,7 @@ public class CarModel { @NotNull private String sku; - @ManyToOne(optional=false, fetch= FetchType.LAZY) + @ManyToOne(optional=false, fetch= FetchType.EAGER ) @JoinColumn(name="maker_fk") private CarMaker maker; diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java index 68edb58e12..4cd979e931 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java @@ -1,7 +1,9 @@ package org.baeldung.examples.olingo4.edm; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import javax.persistence.EntityManagerFactory; @@ -33,11 +35,14 @@ public class JpaEdmProvider extends CsdlAbstractEdmProvider { private EdmTypeMapper typeMapper; // Service Namespace - public static final String NAMESPACE = "OData.Demo"; + public static final String NAMESPACE = "Baeldung.OData"; // EDM Container public static final String CONTAINER_NAME = "Cars"; public static final FullQualifiedName CONTAINER = new FullQualifiedName(NAMESPACE, CONTAINER_NAME); + + // Caches of OData types by it fully qualified name + private Map cdslName2Type = new HashMap<>(); public JpaEdmProvider(EntityManagerFactory emf, EdmTypeMapper mapper) { this.emf = emf; @@ -153,11 +158,13 @@ public class JpaEdmProvider extends CsdlAbstractEdmProvider { @Override public CsdlEntityType getEntityType(FullQualifiedName entityTypeName) throws ODataException { + + CsdlEntityType result = cdslName2Type.get(entityTypeName); + if ( result != null ) { + return result; + } Metamodel mm = emf.getMetamodel(); - - CsdlEntityType result = null; - result = mm.getEntities() .stream() .filter(et -> entityTypeName.equals(new FullQualifiedName(NAMESPACE, et.getName()))) @@ -165,6 +172,8 @@ public class JpaEdmProvider extends CsdlAbstractEdmProvider { .findFirst() .orElse(null); + // save for future use + cdslName2Type.put(entityTypeName, result); return result; } diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java index 6bca0e9896..4a4e5026f3 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java @@ -5,6 +5,7 @@ import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.net.URISyntaxException; +import java.util.Collection; import java.util.List; import javax.persistence.EntityManagerFactory; @@ -19,6 +20,7 @@ import org.apache.olingo.commons.api.data.Property; import org.apache.olingo.commons.api.data.ValueType; import org.apache.olingo.commons.api.edm.EdmEntitySet; import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmNavigationProperty; import org.apache.olingo.commons.api.ex.ODataRuntimeException; import org.apache.olingo.commons.api.format.ContentType; import org.apache.olingo.commons.api.http.HttpHeader; @@ -35,6 +37,7 @@ import org.apache.olingo.server.api.serializer.EntityCollectionSerializerOptions import org.apache.olingo.server.api.serializer.ODataSerializer; import org.apache.olingo.server.api.serializer.SerializerResult; import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriParameter; import org.apache.olingo.server.api.uri.UriResource; import org.apache.olingo.server.api.uri.UriResourceEntitySet; import org.baeldung.examples.olingo4.repository.RepositoryRegistry; @@ -110,8 +113,7 @@ public class JpaEntityCollectionProcessor implements CountEntityCollectionProces Long count = getCount(edmEntitySet, uriInfo); // Finally: configure the response object: set the body, headers and status code - response.setContent(new ByteArrayInputStream(count.toString() - .getBytes())); + response.setContent(new ByteArrayInputStream(count.toString().getBytes())); response.setStatusCode(HttpStatusCode.OK.getStatusCode()); response.setHeader(HttpHeader.CONTENT_TYPE, "text/plain"); @@ -130,9 +132,9 @@ public class JpaEntityCollectionProcessor implements CountEntityCollectionProces EntityCollection result = new EntityCollection(); repo.findAll() - .stream() - .forEach((it) -> result.getEntities() - .add(entityMapper.map2entity(edmEntitySet, it))); + .stream() + .forEach((it) -> result.getEntities() + .add(entityMapper.map2entity(edmEntitySet, it))); return result; } @@ -144,7 +146,7 @@ public class JpaEntityCollectionProcessor implements CountEntityCollectionProces * @param uriInfo * @return */ - private Long getCount(EdmEntitySet edmEntitySet, UriInfo uriInfo) { + protected Long getCount(EdmEntitySet edmEntitySet, UriInfo uriInfo) { EdmEntityType type = edmEntitySet.getEntityType(); JpaRepository repo = (JpaRepository)repositoryRegistry.getRepositoryForEntity(type); @@ -152,5 +154,8 @@ public class JpaEntityCollectionProcessor implements CountEntityCollectionProces return repo.count(); } + + + } diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityMapper.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityMapper.java index 5fd863124f..1978aa4fd6 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityMapper.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityMapper.java @@ -63,13 +63,22 @@ public class JpaEntityMapper { } - private Object getPropertyValue(Object entry, String name) { + public Object getPropertyValue(Object entry, String name) { try { return PropertyUtils.getProperty(entry,name); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new ODataRuntimeException("[E141] Unable to read property from entity, property=" + name, e); } } + + public void setPropertyValue(Object entry, String name,Object value) { + try { + PropertyUtils.setProperty(entry,name,value); + } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + throw new ODataRuntimeException("[E141] Unable to read property from entity, property=" + name, e); + } + } + private URI createId(String entitySetName, Object id) { try { diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityProcessor.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityProcessor.java index 23a5a7ac4b..719e5de160 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityProcessor.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityProcessor.java @@ -4,27 +4,19 @@ package org.baeldung.examples.olingo4.processor; import java.io.InputStream; -import java.lang.reflect.Member; -import java.util.Collection; import java.util.List; import java.util.Locale; -import java.util.stream.Collectors; +import java.util.Optional; +import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; import javax.persistence.metamodel.SingularAttribute; -import org.apache.commons.beanutils.PropertyUtils; import org.apache.olingo.commons.api.data.ContextURL; import org.apache.olingo.commons.api.data.Entity; -import org.apache.olingo.commons.api.data.EntityCollection; import org.apache.olingo.commons.api.edm.EdmEntitySet; import org.apache.olingo.commons.api.edm.EdmEntityType; import org.apache.olingo.commons.api.edm.EdmNavigationProperty; -import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.api.ex.ODataRuntimeException; import org.apache.olingo.commons.api.format.ContentType; import org.apache.olingo.commons.api.http.HttpHeader; @@ -36,10 +28,8 @@ import org.apache.olingo.server.api.ODataRequest; import org.apache.olingo.server.api.ODataResponse; import org.apache.olingo.server.api.ServiceMetadata; import org.apache.olingo.server.api.processor.EntityProcessor; -import org.apache.olingo.server.api.serializer.EntityCollectionSerializerOptions; import org.apache.olingo.server.api.serializer.EntitySerializerOptions; import org.apache.olingo.server.api.serializer.ODataSerializer; -import org.apache.olingo.server.api.serializer.SerializerException; import org.apache.olingo.server.api.serializer.SerializerResult; import org.apache.olingo.server.api.uri.UriInfo; import org.apache.olingo.server.api.uri.UriParameter; @@ -48,9 +38,7 @@ import org.apache.olingo.server.api.uri.UriResourceEntitySet; import org.apache.olingo.server.api.uri.UriResourceNavigation; import org.baeldung.examples.olingo4.repository.EdmEntityRepository; import org.baeldung.examples.olingo4.repository.RepositoryRegistry; -import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Component; /** @@ -99,11 +87,9 @@ public class JpaEntityProcessor implements EntityProcessor { UriResourceEntitySet rootResourceEntitySet = (UriResourceEntitySet) resourceParts.get(0); EdmEntitySet rootEntitySet = rootResourceEntitySet.getEntitySet(); List rootPredicates = rootResourceEntitySet.getKeyPredicates(); - EdmEntityType rootEntityType = rootEntitySet.getEntityType(); - if ( resourceParts.size() == 1 ) { - entityStream = readEntity(rootEntitySet,rootPredicates,responseFormat); + entityStream = readRootEntity(rootEntitySet,rootPredicates,responseFormat); } else if ( resourceParts.size() == 2 ) { UriResource part = resourceParts.get(1); @@ -112,27 +98,7 @@ public class JpaEntityProcessor implements EntityProcessor { } UriResourceNavigation navSegment = (UriResourceNavigation)part; - - // We have three scenarios we must handle: - // Entity(x)/Related, where Related is a 1:N or M:N relationship => result is a collection - // Entity(x)/Related, where Related is a N:1 or 1:1 relationship => result is a single entity - // Entity(x)/Related(z), where Related is a 1:N or M:N relationship => result is a single entity - if (navSegment.getKeyPredicates().isEmpty()) { - if ( isOne2ManyProperty(rootEntityType,navSegment.getProperty())) { - entityStream = readRelatedEntities(rootEntitySet,rootPredicates,navSegment.getProperty(),responseFormat); - } - else { - // The relation must point to another entity type, so casting should be safe here - EdmEntityType resultType = (EdmEntityType)rootEntityType.getNavigationProperty(navSegment.getProperty().getName()).getType(); - EdmEntitySet resultEntitySet = entitySetFromType(resultType); - - entityStream = readEntity(resultEntitySet, navSegment.getKeyPredicates(), responseFormat); - } - } - else { - entityStream = readRelatedEntity(request, rootEntitySet,rootPredicates,navSegment.getProperty(),navSegment.getKeyPredicates(),responseFormat); - } - + entityStream = readRelatedEntity(request, rootEntitySet,rootPredicates,navSegment.getProperty(),navSegment.getKeyPredicates(),responseFormat); } else { // For now, we'll only allow navigation just to directly linked navs @@ -161,14 +127,30 @@ public class JpaEntityProcessor implements EntityProcessor { } // - private boolean isOne2ManyProperty(EdmEntityType entityType, EdmNavigationProperty property) { - return entityType.getProperty(property.getName()) != null && property.isCollection(); - } + // private boolean isOne2ManyProperty(EdmEntityType entityType, EdmNavigationProperty property) { + // return entityType.getProperty(property.getName()) != null && property.isCollection(); + //} - private InputStream readEntity(EdmEntitySet entitySet, List keyPredicates,ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { - - Entity entity = readEntityData(entitySet,keyPredicates); + @SuppressWarnings({ "rawtypes", "unchecked" }) + private InputStream readRootEntity(EdmEntitySet entitySet, List keyPredicates,ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { + EdmEntityType type = entitySet.getEntityType(); + JpaRepository repo = registry.getRepositoryForEntity(type); + // Get key value + Long keyValue = getEntityKey(keyPredicates); + Optional entry = repo.findById(keyValue); + if ( !entry.isPresent()) { + throw new ODataApplicationException( + "[E116] NO entity found for the given key", + HttpStatusCode.NOT_FOUND.getStatusCode(), + Locale.ENGLISH); + } + + Entity e = entityMapper.map2entity(entitySet, entry.get()); + return serializeEntity(entitySet,e,responseFormat); + } + + private InputStream serializeEntity(EdmEntitySet entitySet, Entity entity,ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { ContextURL contextUrl = ContextURL.with().entitySet(entitySet).build(); // expand and select currently not supported EntitySerializerOptions options = EntitySerializerOptions @@ -180,157 +162,101 @@ public class JpaEntityProcessor implements EntityProcessor { SerializerResult serializerResult = serializer.entity(serviceMetadata, entitySet.getEntityType(), entity, options); return serializerResult.getContent(); + } - private InputStream readRelatedEntities(EdmEntitySet rootEntitySet, List rootPredicates, EdmNavigationProperty property, ContentType responseFormat) throws ODataApplicationException { - - Object jpaEntity = readJPAEntity(rootEntitySet, rootPredicates); - try { - Object set = PropertyUtils.getProperty(jpaEntity, property.getName()); - EdmEntitySet entitySet = entitySetFromType(property.getType()); - ContextURL contextUrl = ContextURL - .with() - .entitySet(entitySet) - .build(); - - EntityCollectionSerializerOptions options = EntityCollectionSerializerOptions - .with() - .contextURL(contextUrl) - .build(); - - EntityCollection result = new EntityCollection(); - - ((Collection)set) - .stream() - .map((o) -> this.entityMapper.map2entity(entitySet, o)) - .forEach((e) -> result.getEntities().add(e)); - - ODataSerializer serializer = odata.createSerializer(responseFormat); - SerializerResult serializerResult = serializer.entityCollection(serviceMetadata, property.getType(), result, options); - return serializerResult.getContent(); - } - catch(Exception ex) { - throw new ODataRuntimeException("[E181] Error accessing database", ex); - } - } +// @SuppressWarnings("unchecked") +// protected InputStream readRelatedEntities(EdmEntitySet rootEntitySet, List rootPredicates, EdmNavigationProperty property, ContentType responseFormat) throws ODataApplicationException { +// +// Object jpaEntity = readJPAEntity(rootEntitySet, rootPredicates); +// try { +// Collection set = (Collection)PropertyUtils.getProperty(jpaEntity, property.getName()); +// EdmEntitySet entitySet = entitySetFromType(property.getType()); +// ContextURL contextUrl = ContextURL +// .with() +// .entitySet(entitySet) +// .build(); +// +// EntityCollectionSerializerOptions options = EntityCollectionSerializerOptions +// .with() +// .contextURL(contextUrl) +// .build(); +// +// EntityCollection result = new EntityCollection(); +// +// set.stream() +// .map((o) -> this.entityMapper.map2entity(entitySet, o)) +// .forEach((e) -> result.getEntities().add(e)); +// +// ODataSerializer serializer = odata.createSerializer(responseFormat); +// SerializerResult serializerResult = serializer.entityCollection(serviceMetadata, property.getType(), result, options); +// return serializerResult.getContent(); +// } +// catch(Exception ex) { +// throw new ODataRuntimeException("[E181] Error accessing database", ex); +// } +// } - @SuppressWarnings({ "rawtypes", "serial", "unchecked" }) - private InputStream readRelatedEntity(ODataRequest request, EdmEntitySet rootEntitySet, List rootPredicates, EdmNavigationProperty property, List predicates, ContentType responseFormat) throws ODataApplicationException, SerializerException { + @SuppressWarnings({ "rawtypes", "unchecked" }) + private InputStream readRelatedEntity(ODataRequest request, EdmEntitySet entitySet, List rootPredicates, EdmNavigationProperty property, List parentPredicates, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { - JpaSpecificationExecutor rootRepo = (JpaSpecificationExecutor)registry.getRepositoryForEntity(rootEntitySet.getEntityType()); - JpaSpecificationExecutor repo = (JpaSpecificationExecutor)registry.getRepositoryForEntity(property.getType()); + JpaRepository repo = (JpaRepository)registry.getRepositoryForEntity(entitySet.getEntityType()); + EdmEntityRepository relatedRepo = (EdmEntityRepository)registry.getRepositoryForEntity(property.getType()); // We assume here that we have a bi-directional 1:N relationship, so we'll // always have a property in the child entity that points to the parent - Class rootClass = ((EdmEntityRepository)rootRepo).getEntityClass(); - Class childClass = ((EdmEntityRepository)repo).getEntityClass(); + Class rootClass = ((EdmEntityRepository)repo).getEntityClass(); + Class relatedClass = ((EdmEntityRepository)relatedRepo).getEntityClass(); + SingularAttribute fk = emf.getMetamodel() - .entity(childClass) + .entity(rootClass) .getSingularAttributes() .stream() - .filter((attr) -> attr.isAssociation() && attr.getJavaType().isAssignableFrom(rootClass)) + .filter((attr) -> { + boolean b = attr.isAssociation() && attr.getJavaType().isAssignableFrom(relatedClass); + return b; + }) .findFirst() .orElse(null); - SingularAttribute pk = emf.getMetamodel() - .entity(childClass) - .getId(Long.class); - - SingularAttribute rootPk = emf.getMetamodel() - .entity(rootClass) - .getId(Long.class); - if ( fk == null ) { - throw new ODataRuntimeException("[E230] No singular attribute of child class '" + childClass.getName() + "' found" ); + throw new ODataRuntimeException("[E230] No singular attribute of child class '" + relatedClass.getName() + "' found" ); } - - Specification spec = new Specification() { - @Override - public Predicate toPredicate(Root root, CriteriaQuery q, CriteriaBuilder cb) { + Long pkValue = getEntityKey(rootPredicates); + EntityManager em = this.emf.createEntityManager(); + try { + // Read data from DB + Object root = em.find(rootClass, pkValue); + Object related = this.entityMapper.getPropertyValue(root, fk.getName()); - try { - Object rootInstance = rootClass.newInstance(); - PropertyUtils.setProperty(rootInstance, rootPk.getName(), getEntityKey(rootEntitySet.getEntityType(),rootPredicates)); - - final Predicate p = cb.and( - cb.equal( - root.get(pk), - getEntityKey(property.getType(),predicates)), - cb.equal( - root.get(fk), - rootInstance)); - - return p; - } - catch(Exception ex) { - throw new ODataRuntimeException(ex); - } - - } - }; - - // Read data from DB - EdmEntitySet relatedEntitySet = entitySetFromType(property.getType()); - EntityCollection data = new EntityCollection(); - - repo.findAll(spec) - .stream() - .forEach((entry) -> data.getEntities().add(entityMapper.map2entity(relatedEntitySet, entry))); - - // - - ODataSerializer serializer = odata.createSerializer(responseFormat); - - // 4th: Now serialize the content: transform from the EntitySet object to InputStream - EdmEntityType edmEntityType = relatedEntitySet.getEntityType(); - ContextURL contextUrl = ContextURL.with() - .entitySet(relatedEntitySet) - .build(); - - final String id = request.getRawBaseUri() + "/" + relatedEntitySet.getName(); - EntityCollectionSerializerOptions opts = EntityCollectionSerializerOptions.with() - .id(id) - .contextURL(contextUrl) - .build(); - SerializerResult serializerResult = serializer.entityCollection(serviceMetadata, edmEntityType, data, opts); - InputStream serializedContent = serializerResult.getContent(); - - - return serializedContent; - } - - - /** - * This method returns a speficic entity given its primary key - * @param edmEntitySet - * @param keyPredicates - * @return - */ - protected Entity readEntityData(EdmEntitySet edmEntitySet, List keyPredicates) throws ODataApplicationException { - - Object jpaEntry = readJPAEntity(edmEntitySet, keyPredicates); - Entity e = entityMapper.map2entity(edmEntitySet, jpaEntry); - return e; - } - - private Object readJPAEntity(EdmEntitySet edmEntitySet, List keyPredicates) throws ODataApplicationException { - EdmEntityType type = edmEntitySet.getEntityType(); - JpaRepository repo = (JpaRepository)registry.getRepositoryForEntity(type); - - // Get key value - Object keyValue = getEntityKey(type,keyPredicates); - Object entry = repo - .findById(keyValue) - .orElseThrow( - () -> new ODataApplicationException("[E116] NO entity found for the given key", - HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH)); - - return entry; + EdmEntitySet relatedEntitySet = entitySetFromType(property.getType()); + Entity e = entityMapper.map2entity(relatedEntitySet, related); + return serializeEntity(relatedEntitySet,e,responseFormat); + } + finally { + em.close(); + } } - private Object getEntityKey(EdmEntityType type, List keyPredicates) { +// @SuppressWarnings("unchecked") +// private Object readJPAEntity(EdmEntitySet edmEntitySet, List keyPredicates) throws ODataApplicationException { +// EdmEntityType type = edmEntitySet.getEntityType(); +// JpaRepository repo = (JpaRepository)registry.getRepositoryForEntity(type); +// +// // Get key value +// Object keyValue = getEntityKey(type,keyPredicates); +// Object entry = repo +// .findById(keyValue) +// .orElseThrow( +// () -> new ODataApplicationException("[E116] NO entity found for the given key", +// HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH)); +// +// return entry; +// } + + private Long getEntityKey(List keyPredicates) { if ( keyPredicates.size() > 1 ) { throw new ODataRuntimeException("[E131] Composite keys are not supported"); diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java index 20981fdfef..e3bb172e3a 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java @@ -5,23 +5,25 @@ import java.util.List; import java.util.Map; import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Component; @Component public class RepositoryRegistry { - private Map> repositoriesByClassName = new HashMap<>(); + private Map> repositoriesByClassName = new HashMap<>(); public RepositoryRegistry(List> allRepositories) { - allRepositories.stream().forEach((r) -> - repositoriesByClassName.put(r.getEdmEntityName(),(EdmEntityRepository)r)); + allRepositories.stream() + .forEach((r) -> + repositoriesByClassName.put(r.getEdmEntityName(),(JpaRepository)r)); } - public EdmEntityRepository getRepositoryForEntity(EdmEntityType entityType) { - EdmEntityRepository repo = repositoriesByClassName.get(entityType.getName()); + public JpaRepository getRepositoryForEntity(EdmEntityType entityType) { + JpaRepository repo = repositoriesByClassName.get(entityType.getName()); return repo; } } diff --git a/apache-olingo/olingo4/src/main/resources/application.properties b/apache-olingo/olingo4/src/main/resources/application.properties index e4742b4fbb..02c7fe5c4d 100644 --- a/apache-olingo/olingo4/src/main/resources/application.properties +++ b/apache-olingo/olingo4/src/main/resources/application.properties @@ -4,6 +4,6 @@ server: spring: jpa: show-sql: true - open-in-view: false + open-in-view: true hibernate: ddl-auto: update From 8372ad4a379d45eb9f0f0f6e44efc443bee1cde7 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Fri, 26 Apr 2019 00:39:53 +0530 Subject: [PATCH 018/167] [BAEL-14118] - Make sure the tutorials build doesn't generate any un-committed or un-ignored artifacts --- .gitignore | 3 +- core-groovy/.gitignore | 1 + .../src/main/resources/ioSerializedObject.txt | Bin 199 -> 0 bytes .../baeldung/io/DataAndObjectsUnitTest.groovy | 4 +- jackson-2/.gitignore | 5 +- .../jhipster-microservice/car-app/pom.xml | 166 ++++++++--------- .../jhipster-microservice/dealer-app/pom.xml | 164 ++++++++--------- .../jhipster-microservice/gateway-app/pom.xml | 172 +++++++++--------- testing-modules/groovy-spock/.gitignore | 1 + 9 files changed, 262 insertions(+), 254 deletions(-) create mode 100644 core-groovy/.gitignore delete mode 100644 core-groovy/src/main/resources/ioSerializedObject.txt create mode 100644 testing-modules/groovy-spock/.gitignore diff --git a/.gitignore b/.gitignore index b981a473f6..50cb889e5b 100644 --- a/.gitignore +++ b/.gitignore @@ -76,4 +76,5 @@ persistence-modules/hibernate5/transaction.log apache-avro/src/main/java/com/baeldung/avro/model/ jta/transaction-logs/ software-security/sql-injection-samples/derby.log -spring-soap/src/main/java/com/baeldung/springsoap/gen/ \ No newline at end of file +spring-soap/src/main/java/com/baeldung/springsoap/gen/ +/report-*.json \ No newline at end of file diff --git a/core-groovy/.gitignore b/core-groovy/.gitignore new file mode 100644 index 0000000000..09220fdf52 --- /dev/null +++ b/core-groovy/.gitignore @@ -0,0 +1 @@ +/src/main/resources/ioSerializedObject.txt \ No newline at end of file diff --git a/core-groovy/src/main/resources/ioSerializedObject.txt b/core-groovy/src/main/resources/ioSerializedObject.txt deleted file mode 100644 index 833ed32bf128ecf8d2d6b6893b3959bc3c4bf8a9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 199 zcmZ4UmVvdnh(RPdKUXg)F*PTpG%sB*GhZ(xu{itSp^g0yHl1)~Vqo!PU@I<3EGaGa zVc + def serializedDataFile = new File('src/main/resources/ioSerializedObject.txt') + serializedDataFile.createNewFile() + serializedDataFile.withObjectOutputStream { out -> out.writeObject(task) } diff --git a/jackson-2/.gitignore b/jackson-2/.gitignore index 83c05e60c8..4b1cfaf098 100644 --- a/jackson-2/.gitignore +++ b/jackson-2/.gitignore @@ -10,4 +10,7 @@ # Packaged files # *.jar *.war -*.ear \ No newline at end of file +*.ear + +# Files +/src/main/resources/orderOutput.yaml \ No newline at end of file diff --git a/jhipster/jhipster-microservice/car-app/pom.xml b/jhipster/jhipster-microservice/car-app/pom.xml index 529877d448..86d94d0a44 100644 --- a/jhipster/jhipster-microservice/car-app/pom.xml +++ b/jhipster/jhipster-microservice/car-app/pom.xml @@ -1,21 +1,100 @@ 4.0.0 - com.car.app - car-app - car-app - war jhipster-microservice com.baeldung.jhipster 1.0.0-SNAPSHOT + com.car.app + car-app + war + car-app ${maven.version} + + -Djava.security.egd=file:/dev/./urandom -Xmx256m + 3.6.2 + 2.0.0 + 2.5 + 3.5 + 0.4.13 + 1.2 + 5.2.8.Final + 2.6.0 + 0.7.9 + 1.8 + 3.21.0-GA + 1.0.0 + 1.1.0 + 0.7.0 + 3.6 + 2.0.0 + 3.6.2 + 4.8 + jdt_apt + 1.1.0.Final + 2.10 + 1.4.1 + 3.0.1 + yyyyMMddHHmmss + 3.0.0 + 3.1.3 + v6.10.0 + + + + + ${project.build.directory}/test-results + 0.0.20 + false + 3.2.2 + 2.12.1 + 3.2 + + src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + + S3437,UndocumentedApi,BoldAndItalicTagsCheck + + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + + ${project.testresult.directory}/karma + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + 2.5.0 + + Camden.SR5 + 2.6.1 + 1.4.10.Final + 1.1.0.Final + v0.21.3 + + @@ -819,83 +898,4 @@ - - -Djava.security.egd=file:/dev/./urandom -Xmx256m - 3.6.2 - 2.0.0 - 2.5 - 3.5 - 0.4.13 - 1.2 - 5.2.8.Final - 2.6.0 - 0.7.9 - 1.8 - 3.21.0-GA - 1.0.0 - 1.1.0 - 0.7.0 - 3.6 - 2.0.0 - 3.6.2 - 4.8 - jdt_apt - 1.1.0.Final - 2.10 - 1.4.1 - 3.0.1 - yyyyMMddHHmmss - 3.0.0 - 3.1.3 - v6.10.0 - - - - - ${project.build.directory}/test-results - 0.0.20 - false - 3.2.2 - 2.12.1 - 3.2 - - src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - - S3437,UndocumentedApi,BoldAndItalicTagsCheck - - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - - ${project.testresult.directory}/karma - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - 2.5.0 - - Camden.SR5 - 2.6.1 - 1.4.10.Final - 1.1.0.Final - v0.21.3 - - diff --git a/jhipster/jhipster-microservice/dealer-app/pom.xml b/jhipster/jhipster-microservice/dealer-app/pom.xml index 1eac8a930e..3051399ae6 100644 --- a/jhipster/jhipster-microservice/dealer-app/pom.xml +++ b/jhipster/jhipster-microservice/dealer-app/pom.xml @@ -1,21 +1,99 @@ 4.0.0 - com.dealer.app - dealer-app - dealer-app - war jhipster-microservice com.baeldung.jhipster 1.0.0-SNAPSHOT + com.dealer.app + dealer-app + war + dealer-app ${maven.version} + + -Djava.security.egd=file:/dev/./urandom -Xmx256m + 3.6.2 + 2.0.0 + 2.5 + 3.5 + 0.4.13 + 1.2 + 5.2.8.Final + 2.6.0 + 0.7.9 + 3.21.0-GA + 1.0.0 + 1.1.0 + 0.7.0 + 3.6 + 2.0.0 + 3.6.2 + 4.8 + jdt_apt + 1.1.0.Final + 2.10 + 1.4.1 + 3.0.1 + yyyyMMddHHmmss + 3.0.0 + 3.1.3 + v6.10.0 + + + + + ${project.build.directory}/test-results + 0.0.20 + false + 3.2.2 + 2.12.1 + 3.2 + + src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + + S3437,UndocumentedApi,BoldAndItalicTagsCheck + + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + + ${project.testresult.directory}/karma + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + 2.5.0 + + Camden.SR5 + 2.6.1 + 1.4.10.Final + 1.1.0.Final + v0.21.3 + + @@ -813,83 +891,5 @@ - - - -Djava.security.egd=file:/dev/./urandom -Xmx256m - 3.6.2 - 2.0.0 - 2.5 - 3.5 - 0.4.13 - 1.2 - 5.2.8.Final - 2.6.0 - 0.7.9 - 3.21.0-GA - 1.0.0 - 1.1.0 - 0.7.0 - 3.6 - 2.0.0 - 3.6.2 - 4.8 - jdt_apt - 1.1.0.Final - 2.10 - 1.4.1 - 3.0.1 - yyyyMMddHHmmss - 3.0.0 - 3.1.3 - v6.10.0 - - - - - ${project.build.directory}/test-results - 0.0.20 - false - 3.2.2 - 2.12.1 - 3.2 - src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - - S3437,UndocumentedApi,BoldAndItalicTagsCheck - - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - - ${project.testresult.directory}/karma - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - 2.5.0 - - Camden.SR5 - 2.6.1 - 1.4.10.Final - 1.1.0.Final - v0.21.3 - - diff --git a/jhipster/jhipster-microservice/gateway-app/pom.xml b/jhipster/jhipster-microservice/gateway-app/pom.xml index babc9e4f24..4e2c19ed2d 100644 --- a/jhipster/jhipster-microservice/gateway-app/pom.xml +++ b/jhipster/jhipster-microservice/gateway-app/pom.xml @@ -1,21 +1,103 @@ 4.0.0 - com.gateway - gateway-app - gateway-app - war jhipster-microservice com.baeldung.jhipster 1.0.0-SNAPSHOT + com.gateway + gateway-app + war + gateway-app ${maven.version} + + -Djava.security.egd=file:/dev/./urandom -Xmx256m + 3.6.2 + 2.0.0 + 3.6.0 + 1.10 + 2.5 + 3.5 + 0.4.13 + 1.3 + 1.2 + 5.2.8.Final + 2.6.0 + 0.7.9 + 3.21.0-GA + 1.0.0 + 1.1.0 + 0.7.0 + 3.6 + 2.0.0 + 3.6.2 + 4.8 + 1.3.0 + jdt_apt + 1.1.0.Final + 2.10 + 1.4.1 + 3.0.1 + yyyyMMddHHmmss + 3.0.0 + 3.1.3 + v6.10.0 + + + + + ${project.build.directory}/test-results + 0.0.20 + false + 3.2.2 + 2.12.1 + 3.2 + + src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* + + S3437,UndocumentedApi,BoldAndItalicTagsCheck + + + src/main/webapp/app/**/*.* + Web:BoldAndItalicTagsCheck + + src/main/java/**/* + squid:S3437 + + src/main/java/**/* + squid:UndocumentedApi + + ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec + ${project.testresult.directory}/coverage/jacoco/jacoco.exec + jacoco + + ${project.testresult.directory}/karma + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.testresult.directory}/coverage/report-lcov/lcov.info + + ${project.basedir}/src/main/ + ${project.testresult.directory}/surefire-reports + ${project.basedir}/src/test/ + + 2.5.0 + + Camden.SR5 + 2.6.1 + 1.4.10.Final + 1.1.0.Final + v0.21.3 + + @@ -925,87 +1007,5 @@ - - - -Djava.security.egd=file:/dev/./urandom -Xmx256m - 3.6.2 - 2.0.0 - 3.6.0 - 1.10 - 2.5 - 3.5 - 0.4.13 - 1.3 - 1.2 - 5.2.8.Final - 2.6.0 - 0.7.9 - 3.21.0-GA - 1.0.0 - 1.1.0 - 0.7.0 - 3.6 - 2.0.0 - 3.6.2 - 4.8 - 1.3.0 - jdt_apt - 1.1.0.Final - 2.10 - 1.4.1 - 3.0.1 - yyyyMMddHHmmss - 3.0.0 - 3.1.3 - v6.10.0 - - - - - ${project.build.directory}/test-results - 0.0.20 - false - 3.2.2 - 2.12.1 - 3.2 - - src/main/webapp/content/**/*.*, src/main/webapp/bower_components/**/*.*, src/main/webapp/i18n/*.js, target/www/**/*.* - - S3437,UndocumentedApi,BoldAndItalicTagsCheck - - - src/main/webapp/app/**/*.* - Web:BoldAndItalicTagsCheck - - src/main/java/**/* - squid:S3437 - - src/main/java/**/* - squid:UndocumentedApi - - ${project.testresult.directory}/coverage/jacoco/jacoco-it.exec - ${project.testresult.directory}/coverage/jacoco/jacoco.exec - jacoco - - ${project.testresult.directory}/karma - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.testresult.directory}/coverage/report-lcov/lcov.info - - ${project.basedir}/src/main/ - ${project.testresult.directory}/surefire-reports - ${project.basedir}/src/test/ - - 2.5.0 - - Camden.SR5 - 2.6.1 - 1.4.10.Final - 1.1.0.Final - v0.21.3 - diff --git a/testing-modules/groovy-spock/.gitignore b/testing-modules/groovy-spock/.gitignore new file mode 100644 index 0000000000..37118ef42c --- /dev/null +++ b/testing-modules/groovy-spock/.gitignore @@ -0,0 +1 @@ +/report-*.json \ No newline at end of file From 21b43b0f1184a9d463bcf810c421e0654bd5b604 Mon Sep 17 00:00:00 2001 From: mikr Date: Mon, 6 May 2019 00:12:00 +0200 Subject: [PATCH 019/167] BAEL-2580 JVM Platform Annotations in Kotlin - added Unit Test --- .../com/baeldung/jvmannotations/Document.kt | 8 ++------ .../kotlin/com/baeldung/range/DocumentTest.kt | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 6 deletions(-) create mode 100644 core-kotlin-2/src/test/kotlin/com/baeldung/range/DocumentTest.kt diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/Document.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/Document.kt index 3f9922b88b..f66f8fbae0 100644 --- a/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/Document.kt +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/Document.kt @@ -5,6 +5,8 @@ import java.util.* interface Document { @JvmDefault + fun getTypeDefault() = "document" + fun getType() = "document" } @@ -23,9 +25,3 @@ class TextDocument : Document { } class XmlDocument(d : Document) : Document by d - -fun main() { - val myDocument = TextDocument() - val myTextDocument = XmlDocument(myDocument) - println("${myDocument.getType()} ${myTextDocument.getType()}") -} diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/DocumentTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/range/DocumentTest.kt new file mode 100644 index 0000000000..449e009104 --- /dev/null +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/range/DocumentTest.kt @@ -0,0 +1,18 @@ +package com.baeldung.range + +import org.junit.Test +import kotlin.test.assertEquals + +class DocumentTest { + + @Test + fun testDefaultMethod() { + + val myDocument = TextDocument() + val myTextDocument = XmlDocument(myDocument) + + assertEquals("text", myDocument.getType()) + assertEquals("text", myTextDocument.getType()) + assertEquals("document", myTextDocument.getTypeDefault()) + } +} \ No newline at end of file From 4d85678e968074b6b52870cf6553c5ac3f52e582 Mon Sep 17 00:00:00 2001 From: Hamed Mirzaei Date: Tue, 7 May 2019 10:22:42 +0430 Subject: [PATCH 020/167] To enable multiple execution of a job with the same parameters --- spring-batch/src/main/java/org/baeldung/batch/App.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/spring-batch/src/main/java/org/baeldung/batch/App.java b/spring-batch/src/main/java/org/baeldung/batch/App.java index cea4e8d486..8bf58e65d2 100644 --- a/spring-batch/src/main/java/org/baeldung/batch/App.java +++ b/spring-batch/src/main/java/org/baeldung/batch/App.java @@ -3,6 +3,7 @@ package org.baeldung.batch; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; +import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -21,7 +22,11 @@ public class App { final Job job = (Job) context.getBean("firstBatchJob"); System.out.println("Starting the batch job"); try { - final JobExecution execution = jobLauncher.run(job, new JobParameters()); + // To enable multiple execution of a job with the same parameters + JobParameters jobParameters = new JobParametersBuilder() + .addString("jobID", String.valueOf(System.currentTimeMillis())) + .toJobParameters(); + final JobExecution execution = jobLauncher.run(job, jobParameters); System.out.println("Job Status : " + execution.getStatus()); System.out.println("Job succeeded"); } catch (final Exception e) { From 26f6585a19db17f9709ca028fc288093c7db9c8e Mon Sep 17 00:00:00 2001 From: Philippe Date: Tue, 7 May 2019 23:57:54 -0300 Subject: [PATCH 021/167] [BAEL-1219] Add Sample URLs --- apache-olingo/Samples.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 apache-olingo/Samples.md diff --git a/apache-olingo/Samples.md b/apache-olingo/Samples.md new file mode 100644 index 0000000000..def8971d64 --- /dev/null +++ b/apache-olingo/Samples.md @@ -0,0 +1,21 @@ +## OData test URLs + +This following table contains test URLs that can be used with the Olingo V2 demo project. + +| URL | Description | +|------------------------------------------|-------------------------------------------------| +| `http://localhost:8180/odata/$metadata` | fetch OData metadata document | +| `http://localhost:8180/odata/CarMakers?$top=10&$skip=10` | Get 10 entities starting at offset 10 | +| `http://localhost:8180/odata/CarMakers?$count` | Return total count of entities in this set | +| `http://localhost:8180/odata/CarMakers?$filter=startswith(Name,'B')` | Return entities where the *Name* property starts with 'B' | +| `http://localhost:8180/odata/CarModels?$filter=Year eq 2008 and CarMakerDetails/Name eq 'BWM'` | Return *CarModel* entities where the *Name* property of its maker starts with 'B' | +| `http://localhost:8180/odata/CarModels(1L)?$expand=CarMakerDetails` | Return the *CarModel* with primary key '1', along with its maker| +| `http://localhost:8180/odata/CarModels(1L)?$select=Name,Sku` | Return the *CarModel* with primary key '1', returing only its *Name* and *Sku* properties | +| `http://localhost:8180/odata/CarModels?$orderBy=Name asc,Sku desc` | Return *CarModel* entities, ordered by the their *Name* and *Sku* properties | +| `http://localhost:8180/odata/CarModels?$format=json` | Return *CarModel* entities, using a JSON representation| + + + + + + From 6824bfa4972fca771393acd3cd2174219256ec3f Mon Sep 17 00:00:00 2001 From: Guilherme Lima Date: Thu, 9 May 2019 14:34:03 -0300 Subject: [PATCH 022/167] Updating javadoc --- .../java/org/baeldung/web/util/RestPreconditions.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/spring-rest-full/src/main/java/org/baeldung/web/util/RestPreconditions.java b/spring-rest-full/src/main/java/org/baeldung/web/util/RestPreconditions.java index 4e211ccb10..4f2dedcfa0 100644 --- a/spring-rest-full/src/main/java/org/baeldung/web/util/RestPreconditions.java +++ b/spring-rest-full/src/main/java/org/baeldung/web/util/RestPreconditions.java @@ -31,11 +31,11 @@ public final class RestPreconditions { /** * Check if some value was found, otherwise throw exception. - * - * @param expression - * has value true if found, otherwise false + * + * @param resource + * has value not null to be returned, otherwise throw exception * @throws MyResourceNotFoundException - * if expression is false, means value not found. + * if resource is null, means value not found. */ public static T checkFound(final T resource) { if (resource == null) { From f833bc18d161b6b737488d6b375c29a467833835 Mon Sep 17 00:00:00 2001 From: Philippe Date: Sat, 11 May 2019 21:21:18 -0300 Subject: [PATCH 023/167] [BAEL-2894] Minor formatting --- apache-olingo/olingo2/pom.xml | 10 ---- apache-olingo/olingo4/pom.xml | 14 +++--- .../examples/olingo4/edm/JpaEdmProvider.java | 47 +++++++++---------- 3 files changed, 30 insertions(+), 41 deletions(-) diff --git a/apache-olingo/olingo2/pom.xml b/apache-olingo/olingo2/pom.xml index 4fc81e5e49..493d34119e 100644 --- a/apache-olingo/olingo2/pom.xml +++ b/apache-olingo/olingo2/pom.xml @@ -68,16 +68,6 @@ - - org.apache.olingo - olingo-odata2-api - ${olingo2.version} - - - org.apache.olingo - olingo-odata2-jpa-processor-api - ${olingo2.version} - org.apache.olingo olingo-odata2-jpa-processor-core diff --git a/apache-olingo/olingo4/pom.xml b/apache-olingo/olingo4/pom.xml index 794aee0711..6323db413a 100644 --- a/apache-olingo/olingo4/pom.xml +++ b/apache-olingo/olingo4/pom.xml @@ -53,16 +53,16 @@ spring-boot-starter-web - - org.apache.olingo - odata-server-api - ${odata.version} - org.apache.olingo odata-server-core ${odata.version} - runtime + + commons-beanutils commons-beanutils diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java index 4cd979e931..585aecfa84 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java @@ -192,7 +192,7 @@ public class JpaEdmProvider extends CsdlAbstractEdmProvider { List properties = et.getDeclaredSingularAttributes() .stream() .filter(attr -> attr.getPersistentAttributeType() == PersistentAttributeType.BASIC) - .map(attr -> buildBasicAttribute(et, attr)) + .map(attr -> buildBasicAttribute(attr)) .collect(Collectors.toList()); result.setProperties(properties); @@ -201,24 +201,25 @@ public class JpaEdmProvider extends CsdlAbstractEdmProvider { List ids = et.getDeclaredSingularAttributes() .stream() .filter(attr -> attr.getPersistentAttributeType() == PersistentAttributeType.BASIC && attr.isId()) - .map(attr -> buildRefAttribute(et, attr)) + .map(attr -> buildRefAttribute(attr)) .collect(Collectors.toList()); result.setKey(ids); // Process 1:N navs List navs = et.getDeclaredPluralAttributes() - .stream() - .map(attr -> buildNavAttribute(et, attr)) - .collect(Collectors.toList()); + .stream() + .filter(attr -> attr.isAssociation()) + .map(attr -> buildNavAttribute(attr)) + .collect(Collectors.toList()); result.setNavigationProperties(navs); // Process N:1 navs List navs2 = et.getDeclaredSingularAttributes() - .stream() - .filter(attr -> attr.getPersistentAttributeType() == PersistentAttributeType.MANY_TO_ONE) - .map(attr -> buildNavAttribute(et, attr)) - .collect(Collectors.toList()); + .stream() + .filter(attr -> attr.getPersistentAttributeType() == PersistentAttributeType.MANY_TO_ONE) + .map(attr -> buildMany2OneNavAttribute(attr)) + .collect(Collectors.toList()); result.getNavigationProperties().addAll(navs2); @@ -226,42 +227,40 @@ public class JpaEdmProvider extends CsdlAbstractEdmProvider { return result; } - private CsdlProperty buildBasicAttribute(EntityType et, SingularAttribute attr) { + private CsdlProperty buildBasicAttribute(SingularAttribute attr) { CsdlProperty p = new CsdlProperty().setName(attr.getName()) - .setType(typeMapper.java2edm(attr.getJavaType()) - .getFullQualifiedName()) - .setNullable(et.getDeclaredSingularAttribute(attr.getName()) - .isOptional()); + .setType(typeMapper.java2edm(attr.getJavaType()) + .getFullQualifiedName()) + .setNullable(attr.isOptional()); return p; } - private CsdlPropertyRef buildRefAttribute(EntityType et, SingularAttribute attr) { + private CsdlPropertyRef buildRefAttribute(SingularAttribute attr) { CsdlPropertyRef p = new CsdlPropertyRef().setName(attr.getName()); - return p; } // Build NavProperty for 1:N or M:N associations - private CsdlNavigationProperty buildNavAttribute(EntityType et, PluralAttribute attr) { + private CsdlNavigationProperty buildNavAttribute(PluralAttribute attr) { CsdlNavigationProperty p = new CsdlNavigationProperty().setName(attr.getName()) - .setType(new FullQualifiedName(NAMESPACE, attr.getBindableJavaType().getSimpleName())) - .setCollection(true) - .setNullable(false); + .setType(new FullQualifiedName(NAMESPACE, attr.getBindableJavaType().getSimpleName())) + .setCollection(true) + .setNullable(false); return p; } // Build NavProperty for N:1 associations - private CsdlNavigationProperty buildNavAttribute(EntityType et, SingularAttribute attr) { + private CsdlNavigationProperty buildMany2OneNavAttribute(SingularAttribute attr) { CsdlNavigationProperty p = new CsdlNavigationProperty().setName(attr.getName()) - .setType(new FullQualifiedName(NAMESPACE, attr.getBindableJavaType().getSimpleName())) - .setCollection(false) - .setNullable(attr.isOptional()); + .setType(new FullQualifiedName(NAMESPACE, attr.getBindableJavaType().getSimpleName())) + .setCollection(false) + .setNullable(attr.isOptional()); return p; } From b83362799dbda6d758ba7277f0c8c37883b3fcee Mon Sep 17 00:00:00 2001 From: Philippe Date: Sun, 12 May 2019 17:09:09 -0300 Subject: [PATCH 024/167] [BAEL-2894] remove Lombok --- apache-olingo/olingo2/pom.xml | 5 - .../examples/olingo2/domain/CarMaker.java | 105 +++++++++++-- .../examples/olingo2/domain/CarModel.java | 145 ++++++++++++++++-- apache-olingo/olingo4/pom.xml | 5 - .../olingo4/ODataHttpHandlerFactoryImpl.java | 42 +++-- .../examples/olingo4/domain/CarMaker.java | 105 +++++++++++-- .../examples/olingo4/domain/CarModel.java | 145 ++++++++++++++++-- 7 files changed, 482 insertions(+), 70 deletions(-) diff --git a/apache-olingo/olingo2/pom.xml b/apache-olingo/olingo2/pom.xml index 493d34119e..1efd4ea602 100644 --- a/apache-olingo/olingo2/pom.xml +++ b/apache-olingo/olingo2/pom.xml @@ -44,11 +44,6 @@ spring-boot-configuration-processor true - - org.projectlombok - lombok - true - org.springframework.boot spring-boot-starter-test diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java index 42a3eaa59d..e66d266062 100644 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java @@ -12,25 +12,104 @@ import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; -import lombok.Data; - @Entity -@Data -@Table(name="car_maker") +@Table(name = "car_maker") public class CarMaker { - + @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - + @NotNull - @Column(name="name") + @Column(name = "name") private String name; - - @OneToMany(mappedBy="maker", - orphanRemoval = true, - cascade=CascadeType.ALL) + + @OneToMany(mappedBy = "maker", orphanRemoval = true, cascade = CascadeType.ALL) private List models; - + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the models + */ + public List getModels() { + return models; + } + + /** + * @param models the models to set + */ + public void setModels(List models) { + this.models = models; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((models == null) ? 0 : models.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + CarMaker other = (CarMaker) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (models == null) { + if (other.models != null) + return false; + } else if (!models.equals(other.models)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } } diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java index a4f2a04f6e..f9f563e01e 100644 --- a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java +++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java @@ -1,6 +1,5 @@ package org.baeldung.examples.olingo2.domain; - import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; @@ -11,28 +10,150 @@ import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull; -import lombok.Data; - @Entity -@Data -@Table(name="car_model") +@Table(name = "car_model") public class CarModel { @Id - @GeneratedValue(strategy=GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.AUTO) private Long id; - + @NotNull private String name; - + @NotNull private Integer year; - + @NotNull private String sku; - - @ManyToOne(optional=false, fetch= FetchType.LAZY) - @JoinColumn(name="maker_fk") + + @ManyToOne(optional = false, fetch = FetchType.LAZY) + @JoinColumn(name = "maker_fk") private CarMaker maker; + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the year + */ + public Integer getYear() { + return year; + } + + /** + * @param year the year to set + */ + public void setYear(Integer year) { + this.year = year; + } + + /** + * @return the sku + */ + public String getSku() { + return sku; + } + + /** + * @param sku the sku to set + */ + public void setSku(String sku) { + this.sku = sku; + } + + /** + * @return the maker + */ + public CarMaker getMaker() { + return maker; + } + + /** + * @param maker the maker to set + */ + public void setMaker(CarMaker maker) { + this.maker = maker; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((maker == null) ? 0 : maker.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((sku == null) ? 0 : sku.hashCode()); + result = prime * result + ((year == null) ? 0 : year.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + CarModel other = (CarModel) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (maker == null) { + if (other.maker != null) + return false; + } else if (!maker.equals(other.maker)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (sku == null) { + if (other.sku != null) + return false; + } else if (!sku.equals(other.sku)) + return false; + if (year == null) { + if (other.year != null) + return false; + } else if (!year.equals(other.year)) + return false; + return true; + } + } diff --git a/apache-olingo/olingo4/pom.xml b/apache-olingo/olingo4/pom.xml index 6323db413a..3a93a6fa45 100644 --- a/apache-olingo/olingo4/pom.xml +++ b/apache-olingo/olingo4/pom.xml @@ -38,11 +38,6 @@ runtime - - org.projectlombok - lombok - true - org.springframework.boot spring-boot-starter-test diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactoryImpl.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactoryImpl.java index 68d39dc052..e5d4d06a95 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactoryImpl.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactoryImpl.java @@ -9,17 +9,13 @@ import org.apache.olingo.server.api.ODataHttpHandler; import org.apache.olingo.server.api.ServiceMetadata; import org.apache.olingo.server.api.processor.Processor; -import lombok.Builder; - -@Builder public class ODataHttpHandlerFactoryImpl implements ODataHttpHandlerFactory { - - + private final ODataFactory odataFactory; private final CsdlEdmProvider edmProvider; private final List processors; - public ODataHttpHandlerFactoryImpl(ODataFactory odataFactory,CsdlEdmProvider edmProvider, List processors) { + public ODataHttpHandlerFactoryImpl(ODataFactory odataFactory, CsdlEdmProvider edmProvider, List processors) { this.odataFactory = odataFactory; this.edmProvider = edmProvider; this.processors = processors; @@ -27,16 +23,42 @@ public class ODataHttpHandlerFactoryImpl implements ODataHttpHandlerFactory { @Override public ODataHttpHandler newInstance() { - + OData odata = odataFactory.newInstance(); ServiceMetadata metadata = odata.createServiceMetadata(edmProvider, Collections.emptyList()); ODataHttpHandler handler = odata.createHandler(metadata); - + // Register all available processors processors.forEach(p -> handler.register(p)); - - + return handler; } + public static class ODataHttpHandlerFactoryImplBuilder { + + private ODataFactory odataFactory; + private CsdlEdmProvider edmProvider; + private List processors; + + public ODataHttpHandlerFactoryImplBuilder odataFactory(ODataFactory odataFactory) { + this.odataFactory = odataFactory; + return this; + } + + public ODataHttpHandlerFactoryImplBuilder edmProvider(CsdlEdmProvider edmProvider) { + this.edmProvider = edmProvider; + return this; + } + + public ODataHttpHandlerFactoryImplBuilder processors(List processors) { + this.processors = processors; + return this; + } + + public ODataHttpHandlerFactoryImpl build() { + return new ODataHttpHandlerFactoryImpl(odataFactory, edmProvider, processors); + } + + } + } diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarMaker.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarMaker.java index 79825b4556..f1b793cbe9 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarMaker.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarMaker.java @@ -12,25 +12,104 @@ import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; -import lombok.Data; - @Entity -@Data -@Table(name="car_maker") +@Table(name = "car_maker") public class CarMaker { - + @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - + @NotNull - @Column(name="name") + @Column(name = "name") private String name; - - @OneToMany(mappedBy="maker", - orphanRemoval = true, - cascade=CascadeType.ALL) + + @OneToMany(mappedBy = "maker", orphanRemoval = true, cascade = CascadeType.ALL) private List models; - + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the models + */ + public List getModels() { + return models; + } + + /** + * @param models the models to set + */ + public void setModels(List models) { + this.models = models; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((models == null) ? 0 : models.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + CarMaker other = (CarMaker) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (models == null) { + if (other.models != null) + return false; + } else if (!models.equals(other.models)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } } diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java index a9254e48b9..7652641d7e 100644 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java +++ b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java @@ -1,6 +1,5 @@ package org.baeldung.examples.olingo4.domain; - import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; @@ -11,28 +10,150 @@ import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull; -import lombok.Data; - @Entity -@Data -@Table(name="car_model") +@Table(name = "car_model") public class CarModel { @Id - @GeneratedValue(strategy=GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.AUTO) private Long id; - + @NotNull private String name; - + @NotNull private Integer year; - + @NotNull private String sku; - - @ManyToOne(optional=false, fetch= FetchType.EAGER ) - @JoinColumn(name="maker_fk") + + @ManyToOne(optional = false, fetch = FetchType.EAGER) + @JoinColumn(name = "maker_fk") private CarMaker maker; + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the year + */ + public Integer getYear() { + return year; + } + + /** + * @param year the year to set + */ + public void setYear(Integer year) { + this.year = year; + } + + /** + * @return the sku + */ + public String getSku() { + return sku; + } + + /** + * @param sku the sku to set + */ + public void setSku(String sku) { + this.sku = sku; + } + + /** + * @return the maker + */ + public CarMaker getMaker() { + return maker; + } + + /** + * @param maker the maker to set + */ + public void setMaker(CarMaker maker) { + this.maker = maker; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((maker == null) ? 0 : maker.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((sku == null) ? 0 : sku.hashCode()); + result = prime * result + ((year == null) ? 0 : year.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + CarModel other = (CarModel) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (maker == null) { + if (other.maker != null) + return false; + } else if (!maker.equals(other.maker)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (sku == null) { + if (other.sku != null) + return false; + } else if (!sku.equals(other.sku)) + return false; + if (year == null) { + if (other.year != null) + return false; + } else if (!year.equals(other.year)) + return false; + return true; + } + } From 608db42334c844b1b503bde30d9423423ec840b2 Mon Sep 17 00:00:00 2001 From: Matt Zhang Date: Sat, 18 May 2019 19:24:25 +1000 Subject: [PATCH 025/167] BAEL-2878 Guide to Spring's ApplicationContextRunner --- .../service/CustomService.java | 10 +++ .../service/DefaultService.java | 10 +++ .../service/SimpleService.java | 7 ++ .../ConditionalOnBeanTest.java | 77 +++++++++++++++++++ .../ConditionalOnClassTest.java | 76 ++++++++++++++++++ .../ConditionalOnPropertyTest.java | 64 +++++++++++++++ .../ConditionalOnPropertyTest.properties | 1 + 7 files changed, 245 insertions(+) create mode 100644 spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/CustomService.java create mode 100644 spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/DefaultService.java create mode 100644 spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/SimpleService.java create mode 100644 spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanTest.java create mode 100644 spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnClassTest.java create mode 100644 spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnPropertyTest.java create mode 100644 spring-boot-autoconfiguration/src/test/resources/ConditionalOnPropertyTest.properties diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/CustomService.java b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/CustomService.java new file mode 100644 index 0000000000..634e49fed3 --- /dev/null +++ b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/CustomService.java @@ -0,0 +1,10 @@ +package com.baeldung.autoconfiguration.service; + +public class CustomService implements SimpleService { + + @Override + public String serve() { + return "Custom Service"; + } + +} diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/DefaultService.java b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/DefaultService.java new file mode 100644 index 0000000000..ee91bcb051 --- /dev/null +++ b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/DefaultService.java @@ -0,0 +1,10 @@ +package com.baeldung.autoconfiguration.service; + +public class DefaultService implements SimpleService { + + @Override + public String serve() { + return "Default Service"; + } + +} diff --git a/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/SimpleService.java b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/SimpleService.java new file mode 100644 index 0000000000..b6c72d7159 --- /dev/null +++ b/spring-boot-autoconfiguration/src/main/java/com/baeldung/autoconfiguration/service/SimpleService.java @@ -0,0 +1,7 @@ +package com.baeldung.autoconfiguration.service; + +public interface SimpleService { + + public String serve(); + +} diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanTest.java b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanTest.java new file mode 100644 index 0000000000..313d1253c5 --- /dev/null +++ b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanTest.java @@ -0,0 +1,77 @@ +package com.baeldung.autoconfiguration; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +public class ConditionalOnBeanTest { + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); + + @Test + public void whenDependentBeanIsPresent_thenConditionalBeanCreated() { + this.contextRunner.withUserConfiguration(basicConfiguration.class, ConditionalOnBeanConfiguration.class) + .run((context) -> { + assertThat(context).hasBean("created"); + assertThat(context).getBean("created") + .isEqualTo("This is always created"); + assertThat(context).hasBean("createOnBean"); + assertThat(context).getBean("createOnBean") + .isEqualTo("This is created when bean (name=created) is present"); + }); + } + + @Test + public void whenDependentBeanIsPresent_thenConditionalMissingBeanIgnored() { + this.contextRunner.withUserConfiguration(basicConfiguration.class, ConditionalOnMissingBeanConfiguration.class) + .run((context) -> { + assertThat(context).hasBean("created"); + assertThat(context).getBean("created") + .isEqualTo("This is always created"); + assertThat(context).doesNotHaveBean("createOnMissingBean"); + }); + } + + @Test + public void whenDependentBeanIsNotPresent_thenConditionalMissingBeanCreated() { + this.contextRunner.withUserConfiguration(ConditionalOnMissingBeanConfiguration.class) + .run((context) -> { + assertThat(context).hasBean("createOnMissingBean"); + assertThat(context).getBean("createOnMissingBean") + .isEqualTo("This is created when bean (name=created) is missing"); + assertThat(context).doesNotHaveBean("created"); + }); + } + + @Configuration + protected static class basicConfiguration { + @Bean + public String created() { + return "This is always created"; + } + } + + @Configuration + @ConditionalOnBean(name = "created") + protected static class ConditionalOnBeanConfiguration { + @Bean + public String createOnBean() { + return "This is created when bean (name=created) is present"; + } + } + + @Configuration + @ConditionalOnMissingBean(name = "created") + protected static class ConditionalOnMissingBeanConfiguration { + @Bean + public String createOnMissingBean() { + return "This is created when bean (name=created) is missing"; + } + } + +} diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnClassTest.java b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnClassTest.java new file mode 100644 index 0000000000..7f01ea85d4 --- /dev/null +++ b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnClassTest.java @@ -0,0 +1,76 @@ +package com.baeldung.autoconfiguration; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; +import org.springframework.boot.test.context.FilteredClassLoader; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +public class ConditionalOnClassTest { + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); + + @Test + public void whenDependentClassIsPresent_thenBeanCreated() { + this.contextRunner.withUserConfiguration(ConditionalOnClassConfiguration.class) + .run(context -> { + assertThat(context).hasBean("created"); + assertThat(context.getBean("created")).isEqualTo("This is created when ConditionalOnClassTest is present on the classpath"); + }); + } + + @Test + public void whenDependentClassIsPresent_thenBeanMissing() { + this.contextRunner.withUserConfiguration(ConditionalOnMissingClassConfiguration.class) + .run(context -> { + assertThat(context).doesNotHaveBean("missed"); + }); + } + + @Test + public void whenDependentClassIsNotPresent_thenBeanMissing() { + this.contextRunner.withUserConfiguration(ConditionalOnClassConfiguration.class) + .withClassLoader(new FilteredClassLoader(ConditionalOnClassTest.class)) + .run((context) -> { + assertThat(context).doesNotHaveBean("created"); + assertThat(context).doesNotHaveBean(ConditionalOnClassTest.class); + + }); + } + + @Test + public void whenDependentClassIsNotPresent_thenBeanCreated() { + this.contextRunner.withUserConfiguration(ConditionalOnMissingClassConfiguration.class) + .withClassLoader(new FilteredClassLoader(ConditionalOnClassTest.class)) + .run((context) -> { + assertThat(context).hasBean("missed"); + assertThat(context).getBean("missed") + .isEqualTo("This is missed when ConditionalOnClassTest is present on the classpath"); + assertThat(context).doesNotHaveBean(ConditionalOnClassTest.class); + + }); + } + + @Configuration + @ConditionalOnClass(ConditionalOnClassTest.class) + protected static class ConditionalOnClassConfiguration { + @Bean + public String created() { + return "This is created when ConditionalOnClassTest is present on the classpath"; + } + } + + @Configuration + @ConditionalOnMissingClass("com.baeldung.autoconfiguration.ConditionalOnClassTest") + protected static class ConditionalOnMissingClassConfiguration { + @Bean + public String missed() { + return "This is missed when ConditionalOnClassTest is present on the classpath"; + } + } + +} diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnPropertyTest.java b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnPropertyTest.java new file mode 100644 index 0000000000..2c09b72dda --- /dev/null +++ b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnPropertyTest.java @@ -0,0 +1,64 @@ +package com.baeldung.autoconfiguration; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.TestPropertySource; + +import com.baeldung.autoconfiguration.service.CustomService; +import com.baeldung.autoconfiguration.service.DefaultService; +import com.baeldung.autoconfiguration.service.SimpleService; + +public class ConditionalOnPropertyTest { + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); + + @Test + public void whenGivenCustomPropertyValue_thenCustomServiceCreated() { + this.contextRunner.withPropertyValues("com.baeldung.service=custom") + .withUserConfiguration(SimpleServiceConfiguration.class) + .run(context -> { + assertThat(context).hasBean("customService"); + SimpleService simpleService = context.getBean(CustomService.class); + assertThat(simpleService.serve()).isEqualTo("Custom Service"); + assertThat(context).doesNotHaveBean("defaultService"); + }); + } + + @Test + public void whenGivenDefaultPropertyValue_thenDefaultServiceCreated() { + this.contextRunner.withPropertyValues("com.baeldung.service=default") + .withUserConfiguration(SimpleServiceConfiguration.class) + .run(context -> { + assertThat(context).hasBean("defaultService"); + SimpleService simpleService = context.getBean(DefaultService.class); + assertThat(simpleService.serve()).isEqualTo("Default Service"); + assertThat(context).doesNotHaveBean("customService"); + }); + } + + @Configuration + @TestPropertySource("classpath:ConditionalOnPropertyTest.properties") + protected static class SimpleServiceConfiguration { + + @Bean + @ConditionalOnProperty(name = "com.baeldung.service", havingValue = "default") + @ConditionalOnMissingBean + public DefaultService defaultService() { + return new DefaultService(); + } + + @Bean + @ConditionalOnProperty(name = "com.baeldung.service", havingValue = "custom") + @ConditionalOnMissingBean + public CustomService customService() { + return new CustomService(); + } + } + +} diff --git a/spring-boot-autoconfiguration/src/test/resources/ConditionalOnPropertyTest.properties b/spring-boot-autoconfiguration/src/test/resources/ConditionalOnPropertyTest.properties new file mode 100644 index 0000000000..b6334bc1ce --- /dev/null +++ b/spring-boot-autoconfiguration/src/test/resources/ConditionalOnPropertyTest.properties @@ -0,0 +1 @@ +com.baeldung.service=custom \ No newline at end of file From 567fe3151ce7c232314dc7b8a8dcabffdf08ad2e Mon Sep 17 00:00:00 2001 From: Chirag Dewan Date: Sat, 18 May 2019 19:20:02 +0530 Subject: [PATCH 026/167] BAEL2941: Using JUnit SpringJUnit4ClassRunner with Parametrized --- testing-modules/spring-testing/pom.xml | 12 +++ .../java/com/baeldung/config/WebConfig.java | 17 +++++ .../parameterized/EmployeeRoleController.java | 32 ++++++++ .../RoleControllerIntegrationTest.java | 49 +++++++++++++ ...ParameterizedClassRuleIntegrationTest.java | 73 +++++++++++++++++++ ...ontrollerParameterizedIntegrationTest.java | 69 ++++++++++++++++++ 6 files changed, 252 insertions(+) create mode 100644 testing-modules/spring-testing/src/main/java/com/baeldung/config/WebConfig.java create mode 100644 testing-modules/spring-testing/src/main/java/com/baeldung/controller/parameterized/EmployeeRoleController.java create mode 100644 testing-modules/spring-testing/src/test/java/com/baeldung/controller/parameterized/RoleControllerIntegrationTest.java create mode 100644 testing-modules/spring-testing/src/test/java/com/baeldung/controller/parameterized/RoleControllerParameterizedClassRuleIntegrationTest.java create mode 100644 testing-modules/spring-testing/src/test/java/com/baeldung/controller/parameterized/RoleControllerParameterizedIntegrationTest.java diff --git a/testing-modules/spring-testing/pom.xml b/testing-modules/spring-testing/pom.xml index 630aed0c81..10d34f169b 100644 --- a/testing-modules/spring-testing/pom.xml +++ b/testing-modules/spring-testing/pom.xml @@ -44,6 +44,11 @@ spring-context LATEST + + org.springframework + spring-webmvc + ${spring.version} + org.eclipse.persistence javax.persistence @@ -66,6 +71,11 @@ ${awaitility.version} test + + javax.servlet + javax.servlet-api + ${servlet.api.version} + @@ -84,6 +94,8 @@ 2.0.0.0 3.1.6 5.4.0 + 5.1.4.RELEASE + 4.0.1 \ No newline at end of file diff --git a/testing-modules/spring-testing/src/main/java/com/baeldung/config/WebConfig.java b/testing-modules/spring-testing/src/main/java/com/baeldung/config/WebConfig.java new file mode 100644 index 0000000000..eca0aed57f --- /dev/null +++ b/testing-modules/spring-testing/src/main/java/com/baeldung/config/WebConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +import javax.servlet.ServletContext; + +@EnableWebMvc +@Configuration +@ComponentScan(basePackages = {"com.baeldung.controller.parameterized"}) +public class WebConfig { + + @Autowired + private ServletContext ctx; +} diff --git a/testing-modules/spring-testing/src/main/java/com/baeldung/controller/parameterized/EmployeeRoleController.java b/testing-modules/spring-testing/src/main/java/com/baeldung/controller/parameterized/EmployeeRoleController.java new file mode 100644 index 0000000000..0f1ed9e61d --- /dev/null +++ b/testing-modules/spring-testing/src/main/java/com/baeldung/controller/parameterized/EmployeeRoleController.java @@ -0,0 +1,32 @@ +package com.baeldung.controller.parameterized; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +import java.util.HashMap; +import java.util.Map; + +@Controller +public class EmployeeRoleController { + + private static Map userRoleCache = new HashMap<>(); + + static { + userRoleCache.put("John", Role.ADMIN); + userRoleCache.put("Doe", Role.EMPLOYEE); + } + + @RequestMapping(value = "/role/{name}", method = RequestMethod.GET, produces = "application/text") + @ResponseBody + public String getEmployeeRole(@PathVariable("name") String employeeName) { + + return userRoleCache.get(employeeName).toString(); + } + + private enum Role { + ADMIN, EMPLOYEE + } +} diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/controller/parameterized/RoleControllerIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/controller/parameterized/RoleControllerIntegrationTest.java new file mode 100644 index 0000000000..c362067cc0 --- /dev/null +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/controller/parameterized/RoleControllerIntegrationTest.java @@ -0,0 +1,49 @@ +package com.baeldung.controller.parameterized; + +import com.baeldung.config.WebConfig; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultHandlers; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = WebConfig.class) +public class RoleControllerIntegrationTest { + + @Autowired + private WebApplicationContext wac; + + private MockMvc mockMvc; + + private static final String CONTENT_TYPE = "application/text;charset=ISO-8859-1"; + + @Before + public void setup() throws Exception { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + } + + @Test + public void givenEmployeeNameJohnWhenInvokeRoleThenReturnAdmin() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/role/John")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)) + .andExpect(MockMvcResultMatchers.content().string("ADMIN")); + } + + @Test + public void givenEmployeeNameDoeWhenInvokeRoleThenReturnEmployee() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/role/Doe")).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)) + .andExpect(MockMvcResultMatchers.content().string("EMPLOYEE")); + } + +} \ No newline at end of file diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/controller/parameterized/RoleControllerParameterizedClassRuleIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/controller/parameterized/RoleControllerParameterizedClassRuleIntegrationTest.java new file mode 100644 index 0000000000..eca294a742 --- /dev/null +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/controller/parameterized/RoleControllerParameterizedClassRuleIntegrationTest.java @@ -0,0 +1,73 @@ +package com.baeldung.controller.parameterized; + +import com.baeldung.config.WebConfig; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestContextManager; +import org.springframework.test.context.junit4.rules.SpringClassRule; +import org.springframework.test.context.junit4.rules.SpringMethodRule; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.util.ArrayList; +import java.util.Collection; + +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; + +@RunWith(Parameterized.class) +@WebAppConfiguration +@ContextConfiguration(classes = WebConfig.class) +public class RoleControllerParameterizedClassRuleIntegrationTest { + + private static final String CONTENT_TYPE = "application/text;charset=ISO-8859-1"; + + @ClassRule + public static final SpringClassRule scr = new SpringClassRule(); + + @Rule + public final SpringMethodRule smr = new SpringMethodRule(); + + @Autowired + private WebApplicationContext wac; + + private MockMvc mockMvc; + + @Parameter(value = 0) + public String name; + + @Parameter(value = 1) + public String role; + + @Parameters + public static Collection data() { + Collection params = new ArrayList(); + params.add(new Object[]{"John", "ADMIN"}); + params.add(new Object[]{"Doe", "EMPLOYEE"}); + + return params; + } + + @Before + public void setup() throws Exception { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + } + + @Test + public void givenEmployeeNameWhenInvokeRoleThenReturnRole() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/role/" + name)).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)) + .andExpect(MockMvcResultMatchers.content().string(role)); + } + +} \ No newline at end of file diff --git a/testing-modules/spring-testing/src/test/java/com/baeldung/controller/parameterized/RoleControllerParameterizedIntegrationTest.java b/testing-modules/spring-testing/src/test/java/com/baeldung/controller/parameterized/RoleControllerParameterizedIntegrationTest.java new file mode 100644 index 0000000000..1458b24b06 --- /dev/null +++ b/testing-modules/spring-testing/src/test/java/com/baeldung/controller/parameterized/RoleControllerParameterizedIntegrationTest.java @@ -0,0 +1,69 @@ +package com.baeldung.controller.parameterized; + +import com.baeldung.config.WebConfig; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestContextManager; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.util.ArrayList; +import java.util.Collection; + +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; + +@RunWith(Parameterized.class) +@WebAppConfiguration +@ContextConfiguration(classes = WebConfig.class) +public class RoleControllerParameterizedIntegrationTest { + + private static final String CONTENT_TYPE = "application/text;charset=ISO-8859-1"; + + @Autowired + private WebApplicationContext wac; + + private MockMvc mockMvc; + + private TestContextManager testContextManager; + + @Parameter(value = 0) + public String name; + + @Parameter(value = 1) + public String role; + + @Parameters + public static Collection data() { + Collection params = new ArrayList(); + params.add(new Object[]{"John", "ADMIN"}); + params.add(new Object[]{"Doe", "EMPLOYEE"}); + + return params; + } + + @Before + public void setup() throws Exception { + this.testContextManager = new TestContextManager(getClass()); + this.testContextManager.prepareTestInstance(this); + + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + } + + @Test + public void givenEmployeeNameWhenInvokeRoleThenReturnRole() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/role/" + name)).andDo(print()).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(CONTENT_TYPE)) + .andExpect(MockMvcResultMatchers.content().string(role)); + } + +} \ No newline at end of file From 552b2b2fa941f313d38ae44588dec44d3b0d82df Mon Sep 17 00:00:00 2001 From: Liesheng Long Date: Mon, 20 May 2019 02:24:51 -0400 Subject: [PATCH 027/167] sample code for article "Java Optional As Return Type" --- core-java-modules/core-java-8-2/pom.xml | 16 ++++++- .../HandleOptionalTypeExample.java | 41 ++++++++++++++++++ .../OptionalToJsonExample.java | 20 +++++++++ .../PersistOptionalTypeExample.java | 24 +++++++++++ .../PersistOptionalTypeExample2.java | 22 ++++++++++ .../PersistUserNoOptionalExample.java | 22 ++++++++++ .../SerializeOptionalTypeExample.java | 42 +++++++++++++++++++ .../com/baeldung/optionalReturnType/User.java | 31 ++++++++++++++ .../optionalReturnType/UserOptional.java | 35 ++++++++++++++++ .../optionalReturnType/UserOptionalField.java | 31 ++++++++++++++ .../main/resources/META-INF/persistence.xml | 32 ++++++++++++++ 11 files changed, 315 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java create mode 100644 core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java create mode 100644 core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java create mode 100644 core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java create mode 100644 core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserNoOptionalExample.java create mode 100644 core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java create mode 100644 core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/User.java create mode 100644 core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptional.java create mode 100644 core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java create mode 100644 core-java-modules/core-java-8-2/src/main/resources/META-INF/persistence.xml diff --git a/core-java-modules/core-java-8-2/pom.xml b/core-java-modules/core-java-8-2/pom.xml index fbaf795b95..862b739530 100644 --- a/core-java-modules/core-java-8-2/pom.xml +++ b/core-java-modules/core-java-8-2/pom.xml @@ -30,7 +30,21 @@ icu4j ${icu.version} - + + org.hibernate + hibernate-core + 5.4.0.Final + + + com.h2database + h2 + 1.4.197 + + + com.fasterxml.jackson.core + jackson-databind + 2.9.8 + diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java new file mode 100644 index 0000000000..a49909901b --- /dev/null +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java @@ -0,0 +1,41 @@ +package com.baeldung.optionalReturnType; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +public class HandleOptionalTypeExample { + static Map usersByName = new HashMap(); + static { + User user1 = new User(); + user1.setUserId(1l); + user1.setFirstName("baeldung"); + usersByName.put("baeldung", user1); + } + + public static void main(String[] args) { + changeUserName("baeldung", "baeldung-new"); + changeUserName("user", "user-new"); + } + + public static void changeUserName(String oldFirstName, String newFirstName) { + Optional userOpt = findUserByName(oldFirstName); + if(userOpt.isPresent()){ + User user = userOpt.get(); + user.setFirstName(newFirstName); + + System.out.println("user with name "+oldFirstName+" is changed to "+ user.getFirstName()); + } else { + //user is missing + System.out.println("user with name "+oldFirstName+" is not found."); + } + } + + public static Optional findUserByName(String name){ + //look up the user in the database, the user object below could be null + User user=usersByName.get(name); + Optional opt = Optional.ofNullable(user); + + return opt; + } +} diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java new file mode 100644 index 0000000000..cec5ba5ce1 --- /dev/null +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java @@ -0,0 +1,20 @@ +package com.baeldung.optionalReturnType; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class OptionalToJsonExample { + public static void main(String[] args) { + UserOptional user = new UserOptional(); + user.setUserId(1l); + user.setFirstName("Bael Dung"); + + ObjectMapper om = new ObjectMapper(); + try { + System.out.print("user in json is:"+om.writeValueAsString(user)); + } catch (JsonProcessingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } +} diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java new file mode 100644 index 0000000000..afe46ca7eb --- /dev/null +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java @@ -0,0 +1,24 @@ +package com.baeldung.optionalReturnType; + +import java.util.Optional; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +public class PersistOptionalTypeExample { + static String persistenceUnit = "com.baeldung.optionalReturnType"; + static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit); + + static EntityManager entityManager = emf.createEntityManager(); + + public static void main(String[] args) { + UserOptionalField user1 = new UserOptionalField(); + user1.setUserId(1l); + user1.setFirstName(Optional.of("Bael Dung")); + entityManager.persist(user1); + + UserOptional user2 = entityManager.find(UserOptional.class, 1l); + System.out.print("User2.firstName:"+user2.getFirstName()); + } +} diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java new file mode 100644 index 0000000000..0662b692a8 --- /dev/null +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java @@ -0,0 +1,22 @@ +package com.baeldung.optionalReturnType; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +public class PersistOptionalTypeExample2 { + static String persistenceUnit = "com.baeldung.optionalReturnType"; + static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit); + + static EntityManager em = emf.createEntityManager(); + + public static void main(String[] args) { + UserOptional user1 = new UserOptional(); + user1.setUserId(1l); + user1.setFirstName("Bael Dung"); + em.persist(user1); + + UserOptional user2 = em.find(UserOptional.class, 1l); + System.out.print("User2.firstName:"+user2.getFirstName()); + } +} diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserNoOptionalExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserNoOptionalExample.java new file mode 100644 index 0000000000..dba67feecd --- /dev/null +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserNoOptionalExample.java @@ -0,0 +1,22 @@ +package com.baeldung.optionalReturnType; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +public class PersistUserNoOptionalExample { + static String persistenceUnit = "com.baeldung.optionalReturnType"; + static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit); + + static EntityManager em = emf.createEntityManager(); + + public static void main(String[] args) { + User user1 = new User(); + user1.setUserId(1l); + user1.setFirstName("Bael Dung"); + em.persist(user1); + + User user2 = em.find(User.class, 1l); + System.out.print("User2.firstName:"+user2.getFirstName()); + } +} diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java new file mode 100644 index 0000000000..7ad4a5325e --- /dev/null +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java @@ -0,0 +1,42 @@ +package com.baeldung.optionalReturnType; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.util.Optional; + +public class SerializeOptionalTypeExample { + public static void main(String[] args) { + User user1 = new User(); + user1.setUserId(1l); + user1.setFirstName("baeldung"); + + serializeObject(user1, "user1.ser"); + + + UserOptionalField user2 = new UserOptionalField(); + user2.setUserId(1l); + user2.setFirstName(Optional.of("baeldung")); + + serializeObject(user2, "user2.ser"); + + } + + public static void serializeObject(Object object, String fileName) { + // Serialization + try { + FileOutputStream file = new FileOutputStream(fileName); + ObjectOutputStream out = new ObjectOutputStream(file); + + out.writeObject(object); + + out.close(); + file.close(); + + System.out.println("Object "+object.toString()+ " has been serialized to file "+fileName); + + } catch(IOException e) { + e.printStackTrace(); + } + } +} diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/User.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/User.java new file mode 100644 index 0000000000..42bedb4817 --- /dev/null +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/User.java @@ -0,0 +1,31 @@ +package com.baeldung.optionalReturnType; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class User implements Serializable { + @Id + private long userId; + + private String firstName; + + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + +} diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptional.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptional.java new file mode 100644 index 0000000000..c48781ea80 --- /dev/null +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptional.java @@ -0,0 +1,35 @@ +package com.baeldung.optionalReturnType; + +import java.io.Serializable; +import java.util.Optional; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class UserOptional implements Serializable { + @Id + private long userId; + + @Column(nullable = true) + private String firstName; + + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + + public Optional getFirstName() { + return Optional.ofNullable(firstName); + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + Optional.ofNullable(firstName); + } + +} diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java new file mode 100644 index 0000000000..0778a8bb99 --- /dev/null +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java @@ -0,0 +1,31 @@ +package com.baeldung.optionalReturnType; + +import java.io.Serializable; +import java.util.Optional; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class UserOptionalField implements Serializable { + @Id + private long userId; + + private Optional firstName; + + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + + public Optional getFirstName() { + return firstName; + } + + public void setFirstName(Optional firstName) { + this.firstName = firstName; + } +} diff --git a/core-java-modules/core-java-8-2/src/main/resources/META-INF/persistence.xml b/core-java-modules/core-java-8-2/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000000..3a05c733ee --- /dev/null +++ b/core-java-modules/core-java-8-2/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,32 @@ + + + + + Persist Optional Return Type Demo + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.optionalReturnType.UserNoOptional + com.baeldung.optionalReturnType.UserOptional + com.baeldung.optionalReturnType.UserOptionalField + true + + + + + + + + + + + + + \ No newline at end of file From 6754e4cd218f2ba032ef798e48c9a26410a159a7 Mon Sep 17 00:00:00 2001 From: Matt Zhang Date: Mon, 20 May 2019 21:37:55 +1000 Subject: [PATCH 028/167] BAEL-2878 rename the test --- ... => ConditionalOnBeanIntegrationTest.java} | 2 +- ...=> ConditionalOnClassIntegrationTest.java} | 22 +++++++++---------- ...ConditionalOnPropertyIntegrationTest.java} | 2 +- 3 files changed, 13 insertions(+), 13 deletions(-) rename spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/{ConditionalOnBeanTest.java => ConditionalOnBeanIntegrationTest.java} (98%) rename spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/{ConditionalOnClassTest.java => ConditionalOnClassIntegrationTest.java} (80%) rename spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/{ConditionalOnPropertyTest.java => ConditionalOnPropertyIntegrationTest.java} (98%) diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanTest.java b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanIntegrationTest.java similarity index 98% rename from spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanTest.java rename to spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanIntegrationTest.java index 313d1253c5..c94b432b9d 100644 --- a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanTest.java +++ b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -public class ConditionalOnBeanTest { +public class ConditionalOnBeanIntegrationTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnClassTest.java b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnClassIntegrationTest.java similarity index 80% rename from spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnClassTest.java rename to spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnClassIntegrationTest.java index 7f01ea85d4..f2866867f2 100644 --- a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnClassTest.java +++ b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnClassIntegrationTest.java @@ -10,7 +10,7 @@ import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -public class ConditionalOnClassTest { +public class ConditionalOnClassIntegrationTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); @@ -19,7 +19,7 @@ public class ConditionalOnClassTest { this.contextRunner.withUserConfiguration(ConditionalOnClassConfiguration.class) .run(context -> { assertThat(context).hasBean("created"); - assertThat(context.getBean("created")).isEqualTo("This is created when ConditionalOnClassTest is present on the classpath"); + assertThat(context.getBean("created")).isEqualTo("This is created when ConditionalOnClassIntegrationTest is present on the classpath"); }); } @@ -34,10 +34,10 @@ public class ConditionalOnClassTest { @Test public void whenDependentClassIsNotPresent_thenBeanMissing() { this.contextRunner.withUserConfiguration(ConditionalOnClassConfiguration.class) - .withClassLoader(new FilteredClassLoader(ConditionalOnClassTest.class)) + .withClassLoader(new FilteredClassLoader(ConditionalOnClassIntegrationTest.class)) .run((context) -> { assertThat(context).doesNotHaveBean("created"); - assertThat(context).doesNotHaveBean(ConditionalOnClassTest.class); + assertThat(context).doesNotHaveBean(ConditionalOnClassIntegrationTest.class); }); } @@ -45,31 +45,31 @@ public class ConditionalOnClassTest { @Test public void whenDependentClassIsNotPresent_thenBeanCreated() { this.contextRunner.withUserConfiguration(ConditionalOnMissingClassConfiguration.class) - .withClassLoader(new FilteredClassLoader(ConditionalOnClassTest.class)) + .withClassLoader(new FilteredClassLoader(ConditionalOnClassIntegrationTest.class)) .run((context) -> { assertThat(context).hasBean("missed"); assertThat(context).getBean("missed") - .isEqualTo("This is missed when ConditionalOnClassTest is present on the classpath"); - assertThat(context).doesNotHaveBean(ConditionalOnClassTest.class); + .isEqualTo("This is missed when ConditionalOnClassIntegrationTest is present on the classpath"); + assertThat(context).doesNotHaveBean(ConditionalOnClassIntegrationTest.class); }); } @Configuration - @ConditionalOnClass(ConditionalOnClassTest.class) + @ConditionalOnClass(ConditionalOnClassIntegrationTest.class) protected static class ConditionalOnClassConfiguration { @Bean public String created() { - return "This is created when ConditionalOnClassTest is present on the classpath"; + return "This is created when ConditionalOnClassIntegrationTest is present on the classpath"; } } @Configuration - @ConditionalOnMissingClass("com.baeldung.autoconfiguration.ConditionalOnClassTest") + @ConditionalOnMissingClass("com.baeldung.autoconfiguration.ConditionalOnClassIntegrationTest") protected static class ConditionalOnMissingClassConfiguration { @Bean public String missed() { - return "This is missed when ConditionalOnClassTest is present on the classpath"; + return "This is missed when ConditionalOnClassIntegrationTest is present on the classpath"; } } diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnPropertyTest.java b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnPropertyIntegrationTest.java similarity index 98% rename from spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnPropertyTest.java rename to spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnPropertyIntegrationTest.java index 2c09b72dda..c0733722dc 100644 --- a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnPropertyTest.java +++ b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnPropertyIntegrationTest.java @@ -14,7 +14,7 @@ import com.baeldung.autoconfiguration.service.CustomService; import com.baeldung.autoconfiguration.service.DefaultService; import com.baeldung.autoconfiguration.service.SimpleService; -public class ConditionalOnPropertyTest { +public class ConditionalOnPropertyIntegrationTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); From 2c9c96a811f2cd1ebf90af4f2f042e795c598eb6 Mon Sep 17 00:00:00 2001 From: Liesheng Long Date: Mon, 20 May 2019 21:59:47 -0400 Subject: [PATCH 029/167] fixed some code --- .../optionalReturnType/PersistOptionalTypeExample.java | 2 ++ ...sistUserNoOptionalExample.java => PersistUserExample.java} | 2 +- .../core-java-8-2/src/main/resources/META-INF/persistence.xml | 4 +++- 3 files changed, 6 insertions(+), 2 deletions(-) rename core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/{PersistUserNoOptionalExample.java => PersistUserExample.java} (93%) diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java index afe46ca7eb..681fae565b 100644 --- a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java @@ -12,6 +12,8 @@ public class PersistOptionalTypeExample { static EntityManager entityManager = emf.createEntityManager(); + //to run this app, uncomment the follow line in META-INF/persistence.xml + //com.baeldung.optionalReturnType.UserOptionalField public static void main(String[] args) { UserOptionalField user1 = new UserOptionalField(); user1.setUserId(1l); diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserNoOptionalExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserExample.java similarity index 93% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserNoOptionalExample.java rename to core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserExample.java index dba67feecd..af17f83c6e 100644 --- a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserNoOptionalExample.java +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserExample.java @@ -4,7 +4,7 @@ import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; -public class PersistUserNoOptionalExample { +public class PersistUserExample { static String persistenceUnit = "com.baeldung.optionalReturnType"; static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit); diff --git a/core-java-modules/core-java-8-2/src/main/resources/META-INF/persistence.xml b/core-java-modules/core-java-8-2/src/main/resources/META-INF/persistence.xml index 3a05c733ee..e8cd723ec2 100644 --- a/core-java-modules/core-java-8-2/src/main/resources/META-INF/persistence.xml +++ b/core-java-modules/core-java-8-2/src/main/resources/META-INF/persistence.xml @@ -9,9 +9,11 @@ transaction-type="RESOURCE_LOCAL"> Persist Optional Return Type Demo org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.optionalReturnType.UserNoOptional + com.baeldung.optionalReturnType.User com.baeldung.optionalReturnType.UserOptional + true From 350a93ea9d5570425ef9fa086777e9cacf265408 Mon Sep 17 00:00:00 2001 From: Philippe Date: Tue, 21 May 2019 01:03:22 -0300 Subject: [PATCH 030/167] [BAEL-2894] Use standard port --- apache-olingo/olingo2/src/main/resources/application.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-olingo/olingo2/src/main/resources/application.yml b/apache-olingo/olingo2/src/main/resources/application.yml index 21563a94fe..71df0c4166 100644 --- a/apache-olingo/olingo2/src/main/resources/application.yml +++ b/apache-olingo/olingo2/src/main/resources/application.yml @@ -1,5 +1,5 @@ server: - port: 8180 + port: 8080 spring: jersey: From b1c95c27163704af483a0d354393bbed6843997f Mon Sep 17 00:00:00 2001 From: Philippe Date: Tue, 21 May 2019 01:06:09 -0300 Subject: [PATCH 031/167] [BAEL-2894] Remove olingo4 module --- apache-olingo/olingo4/.gitignore | 29 -- apache-olingo/olingo4/pom.xml | 90 ------ .../examples/olingo4/DefaultODataFactory.java | 20 -- .../examples/olingo4/ODataFactory.java | 8 - .../olingo4/ODataHttpHandlerFactory.java | 8 - .../olingo4/ODataHttpHandlerFactoryImpl.java | 64 ---- .../olingo4/ODataServiceConfiguration.java | 35 -- .../examples/olingo4/ODataServlet.java | 38 --- .../olingo4/Olingo4SampleApplication.java | 13 - .../examples/olingo4/domain/CarMaker.java | 115 ------- .../examples/olingo4/domain/CarModel.java | 159 --------- .../examples/olingo4/edm/EdmTypeMapper.java | 46 --- .../examples/olingo4/edm/JpaEdmProvider.java | 268 --------------- .../JpaEntityCollectionProcessor.java | 161 ---------- .../olingo4/processor/JpaEntityMapper.java | 93 ------ .../olingo4/processor/JpaEntityProcessor.java | 304 ------------------ .../repository/CarMakerRepository.java | 16 - .../repository/CarModelRepository.java | 22 -- .../repository/EdmEntityRepository.java | 17 - .../repository/RepositoryRegistry.java | 29 -- .../src/main/resources/application.properties | 9 - .../olingo4/src/main/resources/data.sql | 12 - .../Olingo4SampleApplicationTests.java | 16 - 23 files changed, 1572 deletions(-) delete mode 100644 apache-olingo/olingo4/.gitignore delete mode 100644 apache-olingo/olingo4/pom.xml delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/DefaultODataFactory.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataFactory.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactory.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactoryImpl.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServiceConfiguration.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServlet.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/Olingo4SampleApplication.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarMaker.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/EdmTypeMapper.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityMapper.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityProcessor.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarMakerRepository.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarModelRepository.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/EdmEntityRepository.java delete mode 100644 apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java delete mode 100644 apache-olingo/olingo4/src/main/resources/application.properties delete mode 100644 apache-olingo/olingo4/src/main/resources/data.sql delete mode 100644 apache-olingo/olingo4/src/test/java/org/baeldung/examples/olingo4/Olingo4SampleApplicationTests.java diff --git a/apache-olingo/olingo4/.gitignore b/apache-olingo/olingo4/.gitignore deleted file mode 100644 index 153c9335eb..0000000000 --- a/apache-olingo/olingo4/.gitignore +++ /dev/null @@ -1,29 +0,0 @@ -HELP.md -/target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -/build/ - -### VS Code ### -.vscode/ diff --git a/apache-olingo/olingo4/pom.xml b/apache-olingo/olingo4/pom.xml deleted file mode 100644 index 3a93a6fa45..0000000000 --- a/apache-olingo/olingo4/pom.xml +++ /dev/null @@ -1,90 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.1.3.RELEASE - - - org.baeldung.examples.olingo4 - olingo4-sample - 0.0.1-SNAPSHOT - olingo4-sample - Sample Olingo 4 Project - - - 1.8 - 4.5.0 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - - com.h2database - h2 - runtime - - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.boot - spring-boot-starter-web - - - - org.apache.olingo - odata-server-core - ${odata.version} - - - - commons-beanutils - commons-beanutils - 1.9.3 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/DefaultODataFactory.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/DefaultODataFactory.java deleted file mode 100644 index 18f7f8ba24..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/DefaultODataFactory.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung.examples.olingo4; - -import org.apache.olingo.server.api.OData; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.stereotype.Component; - -/** - * Default implementation for ODataFactory - * @author Philippe - * - */ -@Component -public class DefaultODataFactory implements ODataFactory { - - @Override - public OData newInstance() { - return OData.newInstance(); - } - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataFactory.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataFactory.java deleted file mode 100644 index 9acb4b8c5e..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataFactory.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.examples.olingo4; - -import org.apache.olingo.server.api.OData; - -public interface ODataFactory { - - public OData newInstance(); -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactory.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactory.java deleted file mode 100644 index 27d0737c24..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactory.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.examples.olingo4; - -import org.apache.olingo.server.api.ODataHttpHandler; - -public interface ODataHttpHandlerFactory { - - ODataHttpHandler newInstance(); -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactoryImpl.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactoryImpl.java deleted file mode 100644 index e5d4d06a95..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataHttpHandlerFactoryImpl.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.baeldung.examples.olingo4; - -import java.util.Collections; -import java.util.List; - -import org.apache.olingo.commons.api.edm.provider.CsdlEdmProvider; -import org.apache.olingo.server.api.OData; -import org.apache.olingo.server.api.ODataHttpHandler; -import org.apache.olingo.server.api.ServiceMetadata; -import org.apache.olingo.server.api.processor.Processor; - -public class ODataHttpHandlerFactoryImpl implements ODataHttpHandlerFactory { - - private final ODataFactory odataFactory; - private final CsdlEdmProvider edmProvider; - private final List processors; - - public ODataHttpHandlerFactoryImpl(ODataFactory odataFactory, CsdlEdmProvider edmProvider, List processors) { - this.odataFactory = odataFactory; - this.edmProvider = edmProvider; - this.processors = processors; - } - - @Override - public ODataHttpHandler newInstance() { - - OData odata = odataFactory.newInstance(); - ServiceMetadata metadata = odata.createServiceMetadata(edmProvider, Collections.emptyList()); - ODataHttpHandler handler = odata.createHandler(metadata); - - // Register all available processors - processors.forEach(p -> handler.register(p)); - - return handler; - } - - public static class ODataHttpHandlerFactoryImplBuilder { - - private ODataFactory odataFactory; - private CsdlEdmProvider edmProvider; - private List processors; - - public ODataHttpHandlerFactoryImplBuilder odataFactory(ODataFactory odataFactory) { - this.odataFactory = odataFactory; - return this; - } - - public ODataHttpHandlerFactoryImplBuilder edmProvider(CsdlEdmProvider edmProvider) { - this.edmProvider = edmProvider; - return this; - } - - public ODataHttpHandlerFactoryImplBuilder processors(List processors) { - this.processors = processors; - return this; - } - - public ODataHttpHandlerFactoryImpl build() { - return new ODataHttpHandlerFactoryImpl(odataFactory, edmProvider, processors); - } - - } - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServiceConfiguration.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServiceConfiguration.java deleted file mode 100644 index 0cde665359..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServiceConfiguration.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.examples.olingo4; - -import java.util.List; - -import javax.persistence.EntityManagerFactory; -import javax.servlet.http.HttpServlet; - -import org.apache.olingo.commons.api.edm.provider.CsdlEdmProvider; -import org.apache.olingo.server.api.processor.Processor; -import org.baeldung.examples.olingo4.ODataHttpHandlerFactoryImpl.ODataHttpHandlerFactoryImplBuilder; -import org.springframework.boot.web.servlet.ServletRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class ODataServiceConfiguration { - - @Bean - public ServletRegistrationBean odataServletRegistration(ODataHttpHandlerFactory factory) { - ServletRegistrationBean srb = - new ServletRegistrationBean<>(new ODataServlet(factory), "/odata/*"); - srb.setLoadOnStartup(1); - return srb; - } - - @Bean - public ODataHttpHandlerFactory httpHandlerFactory(CsdlEdmProvider edmProvider, ODataFactory odataFactory, List processors) { - return new ODataHttpHandlerFactoryImplBuilder() - .edmProvider(edmProvider) - .odataFactory(odataFactory) - .processors(processors) - .build(); - } - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServlet.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServlet.java deleted file mode 100644 index c379124541..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/ODataServlet.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * - */ -package org.baeldung.examples.olingo4; - -import java.io.IOException; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.olingo.server.api.ODataHttpHandler; - -/** - * @author Philippe - * - */ -public class ODataServlet extends HttpServlet { - - private static final long serialVersionUID = 1L; - private final ODataHttpHandlerFactory odataHttpHandlerFactory; - - - public ODataServlet(ODataHttpHandlerFactory factory) { - this.odataHttpHandlerFactory = factory; - } - - @Override - protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - - ODataHttpHandler handler = odataHttpHandlerFactory.newInstance(); - handler.process(req, resp); - } -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/Olingo4SampleApplication.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/Olingo4SampleApplication.java deleted file mode 100644 index 1ac872ea0f..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/Olingo4SampleApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung.examples.olingo4; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class Olingo4SampleApplication { - - public static void main(String[] args) { - SpringApplication.run(Olingo4SampleApplication.class, args); - } - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarMaker.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarMaker.java deleted file mode 100644 index f1b793cbe9..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarMaker.java +++ /dev/null @@ -1,115 +0,0 @@ -package org.baeldung.examples.olingo4.domain; - -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.Table; -import javax.validation.constraints.NotNull; - -@Entity -@Table(name = "car_maker") -public class CarMaker { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @NotNull - @Column(name = "name") - private String name; - - @OneToMany(mappedBy = "maker", orphanRemoval = true, cascade = CascadeType.ALL) - private List models; - - /** - * @return the id - */ - public Long getId() { - return id; - } - - /** - * @param id the id to set - */ - public void setId(Long id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the models - */ - public List getModels() { - return models; - } - - /** - * @param models the models to set - */ - public void setModels(List models) { - this.models = models; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((models == null) ? 0 : models.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - CarMaker other = (CarMaker) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (models == null) { - if (other.models != null) - return false; - } else if (!models.equals(other.models)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java deleted file mode 100644 index 7652641d7e..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/domain/CarModel.java +++ /dev/null @@ -1,159 +0,0 @@ -package org.baeldung.examples.olingo4.domain; - -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import javax.validation.constraints.NotNull; - -@Entity -@Table(name = "car_model") -public class CarModel { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - @NotNull - private String name; - - @NotNull - private Integer year; - - @NotNull - private String sku; - - @ManyToOne(optional = false, fetch = FetchType.EAGER) - @JoinColumn(name = "maker_fk") - private CarMaker maker; - - /** - * @return the id - */ - public Long getId() { - return id; - } - - /** - * @param id the id to set - */ - public void setId(Long id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the year - */ - public Integer getYear() { - return year; - } - - /** - * @param year the year to set - */ - public void setYear(Integer year) { - this.year = year; - } - - /** - * @return the sku - */ - public String getSku() { - return sku; - } - - /** - * @param sku the sku to set - */ - public void setSku(String sku) { - this.sku = sku; - } - - /** - * @return the maker - */ - public CarMaker getMaker() { - return maker; - } - - /** - * @param maker the maker to set - */ - public void setMaker(CarMaker maker) { - this.maker = maker; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((maker == null) ? 0 : maker.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((sku == null) ? 0 : sku.hashCode()); - result = prime * result + ((year == null) ? 0 : year.hashCode()); - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - CarModel other = (CarModel) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (maker == null) { - if (other.maker != null) - return false; - } else if (!maker.equals(other.maker)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (sku == null) { - if (other.sku != null) - return false; - } else if (!sku.equals(other.sku)) - return false; - if (year == null) { - if (other.year != null) - return false; - } else if (!year.equals(other.year)) - return false; - return true; - } - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/EdmTypeMapper.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/EdmTypeMapper.java deleted file mode 100644 index 95797752a2..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/EdmTypeMapper.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.baeldung.examples.olingo4.edm; - -import java.util.Collections; -import java.util.Date; -import java.util.Map; -import java.util.UUID; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import java.sql.Time; -import java.util.AbstractMap.SimpleEntry; - -import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; -import org.springframework.stereotype.Component; - -@Component -public class EdmTypeMapper { - - public EdmPrimitiveTypeKind java2edm(Class clazz) { - EdmPrimitiveTypeKind result = java2edm.get(clazz); - if ( result == null ) { - throw new IllegalArgumentException("[E19] Unsupported class mapping: class=" + clazz); - } - else { - return result; - } - } - - // Static map used generate attribute metadada based on Java types - static Map,EdmPrimitiveTypeKind> java2edm = Collections - .unmodifiableMap(Stream.of( - new SimpleEntry<>(Boolean.class,EdmPrimitiveTypeKind.Boolean), - new SimpleEntry<>(Byte.class,EdmPrimitiveTypeKind.SByte), - new SimpleEntry<>(Date.class,EdmPrimitiveTypeKind.Date), - new SimpleEntry<>(Time.class,EdmPrimitiveTypeKind.TimeOfDay), - new SimpleEntry<>(Number.class,EdmPrimitiveTypeKind.Decimal), - new SimpleEntry<>(Float.class,EdmPrimitiveTypeKind.Single), - new SimpleEntry<>(Double.class,EdmPrimitiveTypeKind.Double), - new SimpleEntry<>(UUID.class,EdmPrimitiveTypeKind.Guid), - new SimpleEntry<>(Short.class,EdmPrimitiveTypeKind.Int16), - new SimpleEntry<>(Integer.class,EdmPrimitiveTypeKind.Int32), - new SimpleEntry<>(Long.class,EdmPrimitiveTypeKind.Int64), - new SimpleEntry<>(String.class,EdmPrimitiveTypeKind.String) - - ).collect(Collectors.toMap((e)-> e.getKey(),(e)-> e.getValue()))); - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java deleted file mode 100644 index 585aecfa84..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/edm/JpaEdmProvider.java +++ /dev/null @@ -1,268 +0,0 @@ -package org.baeldung.examples.olingo4.edm; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.persistence.EntityManagerFactory; -import javax.persistence.metamodel.Attribute.PersistentAttributeType; -import javax.persistence.metamodel.EntityType; -import javax.persistence.metamodel.Metamodel; -import javax.persistence.metamodel.PluralAttribute; -import javax.persistence.metamodel.SingularAttribute; - -import org.apache.olingo.commons.api.edm.FullQualifiedName; -import org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmProvider; -import org.apache.olingo.commons.api.edm.provider.CsdlEntityContainer; -import org.apache.olingo.commons.api.edm.provider.CsdlEntityContainerInfo; -import org.apache.olingo.commons.api.edm.provider.CsdlEntitySet; -import org.apache.olingo.commons.api.edm.provider.CsdlEntityType; -import org.apache.olingo.commons.api.edm.provider.CsdlNavigationProperty; -import org.apache.olingo.commons.api.edm.provider.CsdlProperty; -import org.apache.olingo.commons.api.edm.provider.CsdlPropertyRef; -import org.apache.olingo.commons.api.edm.provider.CsdlSchema; -import org.apache.olingo.commons.api.ex.ODataException; -import org.springframework.stereotype.Component; - -@Component -public class JpaEdmProvider extends CsdlAbstractEdmProvider { - - EntityManagerFactory emf; - - // - private EdmTypeMapper typeMapper; - - // Service Namespace - public static final String NAMESPACE = "Baeldung.OData"; - - // EDM Container - public static final String CONTAINER_NAME = "Cars"; - public static final FullQualifiedName CONTAINER = new FullQualifiedName(NAMESPACE, CONTAINER_NAME); - - // Caches of OData types by it fully qualified name - private Map cdslName2Type = new HashMap<>(); - - public JpaEdmProvider(EntityManagerFactory emf, EdmTypeMapper mapper) { - this.emf = emf; - this.typeMapper = mapper; - } - - /* (non-Javadoc) - * @see org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmProvider#getEntitySet(org.apache.olingo.commons.api.edm.FullQualifiedName, java.lang.String) - */ - @Override - public CsdlEntitySet getEntitySet(FullQualifiedName entityContainer, String entitySetName) throws ODataException { - - if (entityContainer.equals(CONTAINER)) { - - EntityType e = emf.getMetamodel() - .getEntities() - .stream() - .filter((ent) -> (ent.getName() + "s") - .equals(entitySetName)) - .findFirst() - .orElse(null); - - if (e != null) { - CsdlEntitySet entitySet = new CsdlEntitySet(); - entitySet - .setName(entitySetName) - .setType(new FullQualifiedName(NAMESPACE, e.getName())); - return entitySet; - } - } - - return null; - } - - /* (non-Javadoc) - * @see org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmProvider#getEntityContainerInfo(org.apache.olingo.commons.api.edm.FullQualifiedName) - */ - @Override - public CsdlEntityContainerInfo getEntityContainerInfo(FullQualifiedName entityContainerName) throws ODataException { - - // This method is invoked when displaying the Service Document at e.g. http://localhost:8080/DemoService/DemoService.svc - if (entityContainerName == null || entityContainerName.equals(CONTAINER)) { - CsdlEntityContainerInfo entityContainerInfo = new CsdlEntityContainerInfo(); - entityContainerInfo.setContainerName(CONTAINER); - return entityContainerInfo; - } - - return null; - } - - /* (non-Javadoc) - * @see org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmProvider#getSchemas() - */ - @Override - public List getSchemas() throws ODataException { - // create Schema - CsdlSchema schema = new CsdlSchema(); - schema.setNamespace(NAMESPACE); - - // add EntityTypes - List entityTypes = emf.getMetamodel() - .getEntities() - .stream() - .map((e) -> { - try { - return getEntityType(new FullQualifiedName(NAMESPACE, e.getName())); - } catch (ODataException oe) { - throw new RuntimeException(oe); - } - }) - .collect(Collectors.toList()); - - schema.setEntityTypes(entityTypes); - - // add EntityContainer - schema.setEntityContainer(getEntityContainer()); - - // finally - List schemas = new ArrayList(); - schemas.add(schema); - - return schemas; - } - - /* (non-Javadoc) - * @see org.apache.olingo.commons.api.edm.provider.CsdlAbstractEdmProvider#getEntityContainer() - */ - @Override - public CsdlEntityContainer getEntityContainer() throws ODataException { - - - // add EntityTypes - List entitySets = emf.getMetamodel() - .getEntities() - .stream() - .map((e) -> { - try { - // Here we use a simple mapping strategy to map entity types to entity set names: - return getEntitySet(CONTAINER, e.getName() + "s"); - } catch (ODataException oe) { - throw new RuntimeException(oe); - } - }) - .collect(Collectors.toList()); - - // create EntityContainer - CsdlEntityContainer entityContainer = new CsdlEntityContainer(); - entityContainer.setName(CONTAINER_NAME); - entityContainer.setEntitySets(entitySets); - - return entityContainer; - } - - @Override - public CsdlEntityType getEntityType(FullQualifiedName entityTypeName) throws ODataException { - - CsdlEntityType result = cdslName2Type.get(entityTypeName); - if ( result != null ) { - return result; - } - - Metamodel mm = emf.getMetamodel(); - result = mm.getEntities() - .stream() - .filter(et -> entityTypeName.equals(new FullQualifiedName(NAMESPACE, et.getName()))) - .map(et -> buildODataType(et)) - .findFirst() - .orElse(null); - - // save for future use - cdslName2Type.put(entityTypeName, result); - return result; - - } - - /** - * Maps a JPA type to its OData counterpart. - * @param et - * @return - */ - protected CsdlEntityType buildODataType(EntityType et) { - - CsdlEntityType result = new CsdlEntityType(); - result.setName(et.getName()); - - // Process simple properties - List properties = et.getDeclaredSingularAttributes() - .stream() - .filter(attr -> attr.getPersistentAttributeType() == PersistentAttributeType.BASIC) - .map(attr -> buildBasicAttribute(attr)) - .collect(Collectors.toList()); - - result.setProperties(properties); - - // Process Ids - List ids = et.getDeclaredSingularAttributes() - .stream() - .filter(attr -> attr.getPersistentAttributeType() == PersistentAttributeType.BASIC && attr.isId()) - .map(attr -> buildRefAttribute(attr)) - .collect(Collectors.toList()); - - result.setKey(ids); - - // Process 1:N navs - List navs = et.getDeclaredPluralAttributes() - .stream() - .filter(attr -> attr.isAssociation()) - .map(attr -> buildNavAttribute(attr)) - .collect(Collectors.toList()); - result.setNavigationProperties(navs); - - // Process N:1 navs - List navs2 = et.getDeclaredSingularAttributes() - .stream() - .filter(attr -> attr.getPersistentAttributeType() == PersistentAttributeType.MANY_TO_ONE) - .map(attr -> buildMany2OneNavAttribute(attr)) - .collect(Collectors.toList()); - - result.getNavigationProperties().addAll(navs2); - - - return result; - } - - private CsdlProperty buildBasicAttribute(SingularAttribute attr) { - - CsdlProperty p = new CsdlProperty().setName(attr.getName()) - .setType(typeMapper.java2edm(attr.getJavaType()) - .getFullQualifiedName()) - .setNullable(attr.isOptional()); - - return p; - } - - private CsdlPropertyRef buildRefAttribute(SingularAttribute attr) { - - CsdlPropertyRef p = new CsdlPropertyRef().setName(attr.getName()); - return p; - } - - // Build NavProperty for 1:N or M:N associations - private CsdlNavigationProperty buildNavAttribute(PluralAttribute attr) { - - CsdlNavigationProperty p = new CsdlNavigationProperty().setName(attr.getName()) - .setType(new FullQualifiedName(NAMESPACE, attr.getBindableJavaType().getSimpleName())) - .setCollection(true) - .setNullable(false); - - return p; - } - - // Build NavProperty for N:1 associations - private CsdlNavigationProperty buildMany2OneNavAttribute(SingularAttribute attr) { - - CsdlNavigationProperty p = new CsdlNavigationProperty().setName(attr.getName()) - .setType(new FullQualifiedName(NAMESPACE, attr.getBindableJavaType().getSimpleName())) - .setCollection(false) - .setNullable(attr.isOptional()); - - return p; - } - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java deleted file mode 100644 index 4a4e5026f3..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityCollectionProcessor.java +++ /dev/null @@ -1,161 +0,0 @@ -package org.baeldung.examples.olingo4.processor; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Collection; -import java.util.List; - -import javax.persistence.EntityManagerFactory; -import javax.persistence.metamodel.EntityType; -import javax.persistence.metamodel.SingularAttribute; - -import org.apache.commons.beanutils.PropertyUtils; -import org.apache.olingo.commons.api.data.ContextURL; -import org.apache.olingo.commons.api.data.Entity; -import org.apache.olingo.commons.api.data.EntityCollection; -import org.apache.olingo.commons.api.data.Property; -import org.apache.olingo.commons.api.data.ValueType; -import org.apache.olingo.commons.api.edm.EdmEntitySet; -import org.apache.olingo.commons.api.edm.EdmEntityType; -import org.apache.olingo.commons.api.edm.EdmNavigationProperty; -import org.apache.olingo.commons.api.ex.ODataRuntimeException; -import org.apache.olingo.commons.api.format.ContentType; -import org.apache.olingo.commons.api.http.HttpHeader; -import org.apache.olingo.commons.api.http.HttpStatusCode; -import org.apache.olingo.server.api.OData; -import org.apache.olingo.server.api.ODataApplicationException; -import org.apache.olingo.server.api.ODataLibraryException; -import org.apache.olingo.server.api.ODataRequest; -import org.apache.olingo.server.api.ODataResponse; -import org.apache.olingo.server.api.ServiceMetadata; -import org.apache.olingo.server.api.processor.CountEntityCollectionProcessor; -import org.apache.olingo.server.api.processor.EntityCollectionProcessor; -import org.apache.olingo.server.api.serializer.EntityCollectionSerializerOptions; -import org.apache.olingo.server.api.serializer.ODataSerializer; -import org.apache.olingo.server.api.serializer.SerializerResult; -import org.apache.olingo.server.api.uri.UriInfo; -import org.apache.olingo.server.api.uri.UriParameter; -import org.apache.olingo.server.api.uri.UriResource; -import org.apache.olingo.server.api.uri.UriResourceEntitySet; -import org.baeldung.examples.olingo4.repository.RepositoryRegistry; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Component; - -@Component -public class JpaEntityCollectionProcessor implements CountEntityCollectionProcessor { - - private OData odata; - private ServiceMetadata serviceMetadata; - private EntityManagerFactory emf; - private RepositoryRegistry repositoryRegistry; - private JpaEntityMapper entityMapper; - - public JpaEntityCollectionProcessor(EntityManagerFactory emf, RepositoryRegistry repositoryRegistry, JpaEntityMapper entityMapper) { - this.emf = emf; - this.repositoryRegistry = repositoryRegistry; - this.entityMapper = entityMapper; - } - - @Override - public void init(OData odata, ServiceMetadata serviceMetadata) { - this.odata = odata; - this.serviceMetadata = serviceMetadata; - } - - @Override - public void readEntityCollection(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { - - // 1st we have retrieve the requested EntitySet from the uriInfo object (representation of the parsed service URI) - List resourcePaths = uriInfo.getUriResourceParts(); - UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0); // in our example, the first segment is the EntitySet - EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet(); - - // 2nd: fetch the data from backend for this requested EntitySetName - // it has to be delivered as EntitySet object - EntityCollection entitySet = getData(edmEntitySet, uriInfo); - - // 3rd: create a serializer based on the requested format (json) - ODataSerializer serializer = odata.createSerializer(responseFormat); - - // 4th: Now serialize the content: transform from the EntitySet object to InputStream - EdmEntityType edmEntityType = edmEntitySet.getEntityType(); - ContextURL contextUrl = ContextURL.with() - .entitySet(edmEntitySet) - .build(); - - final String id = request.getRawBaseUri() + "/" + edmEntitySet.getName(); - EntityCollectionSerializerOptions opts = EntityCollectionSerializerOptions.with() - .id(id) - .contextURL(contextUrl) - .build(); - SerializerResult serializerResult = serializer.entityCollection(serviceMetadata, edmEntityType, entitySet, opts); - InputStream serializedContent = serializerResult.getContent(); - - // Finally: configure the response object: set the body, headers and status code - response.setContent(serializedContent); - response.setStatusCode(HttpStatusCode.OK.getStatusCode()); - response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString()); - - } - - @Override - public void countEntityCollection(ODataRequest request, ODataResponse response, UriInfo uriInfo) throws ODataApplicationException, ODataLibraryException { - - // 1st we have retrieve the requested EntitySet from the uriInfo object (representation of the parsed service URI) - List resourcePaths = uriInfo.getUriResourceParts(); - UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0); // in our example, the first segment is the EntitySet - EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet(); - - // 2nd: fetch the data from backend for this requested EntitySetName - Long count = getCount(edmEntitySet, uriInfo); - - // Finally: configure the response object: set the body, headers and status code - response.setContent(new ByteArrayInputStream(count.toString().getBytes())); - response.setStatusCode(HttpStatusCode.OK.getStatusCode()); - response.setHeader(HttpHeader.CONTENT_TYPE, "text/plain"); - - } - - /** - * Helper method to retrieve all entities of an entity set from an the backend database - * @param edmEntitySet - * @param uriInfo - * @return - */ - protected EntityCollection getData(EdmEntitySet edmEntitySet, UriInfo uriInfo) { - - EdmEntityType type = edmEntitySet.getEntityType(); - JpaRepository repo = (JpaRepository)repositoryRegistry.getRepositoryForEntity(type); - EntityCollection result = new EntityCollection(); - - repo.findAll() - .stream() - .forEach((it) -> result.getEntities() - .add(entityMapper.map2entity(edmEntitySet, it))); - - return result; - } - - - /** - * Helper method to get the total size of an entity set - * @param edmEntitySet - * @param uriInfo - * @return - */ - protected Long getCount(EdmEntitySet edmEntitySet, UriInfo uriInfo) { - - EdmEntityType type = edmEntitySet.getEntityType(); - JpaRepository repo = (JpaRepository)repositoryRegistry.getRepositoryForEntity(type); - EntityCollection result = new EntityCollection(); - - return repo.count(); - } - - - - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityMapper.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityMapper.java deleted file mode 100644 index 1978aa4fd6..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityMapper.java +++ /dev/null @@ -1,93 +0,0 @@ -/** - * - */ -package org.baeldung.examples.olingo4.processor; - -import java.lang.reflect.InvocationTargetException; -import java.net.URI; -import java.net.URISyntaxException; - -import javax.persistence.EntityManagerFactory; -import javax.persistence.metamodel.EntityType; - -import org.apache.commons.beanutils.PropertyUtils; -import org.apache.olingo.commons.api.data.Entity; -import org.apache.olingo.commons.api.data.Property; -import org.apache.olingo.commons.api.data.ValueType; -import org.apache.olingo.commons.api.edm.EdmEntitySet; -import org.apache.olingo.commons.api.ex.ODataRuntimeException; -import org.springframework.stereotype.Component; - -/** - *

Helper class that converts a JPA entity into an OData entity using - * available metadata from the JPA's EntityManagerFactory.

- * - * @author Philippe - * - */ -@Component -public class JpaEntityMapper { - - private EntityManagerFactory emf; - - public JpaEntityMapper(EntityManagerFactory emf) { - this.emf = emf; - } - - - public Entity map2entity(EdmEntitySet edmEntitySet, Object entry) { - - EntityType et = emf.getMetamodel() - .entity(entry.getClass()); - - - Entity e = new Entity(); - try { - et.getDeclaredSingularAttributes().stream() - .forEach( (attr) -> { - if ( !attr.isAssociation()) { - Object v = getPropertyValue(entry,attr.getName()); - Property p = new Property(null, attr.getName(),ValueType.PRIMITIVE,v); - e.addProperty(p); - - if ( attr.isId()) { - e.setId(createId(edmEntitySet.getName(),v)); - } - } - }); - } catch (Exception ex) { - throw new ODataRuntimeException("[E141] Unable to create OData entity", ex); - } - - return e; - } - - - public Object getPropertyValue(Object entry, String name) { - try { - return PropertyUtils.getProperty(entry,name); - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new ODataRuntimeException("[E141] Unable to read property from entity, property=" + name, e); - } - } - - public void setPropertyValue(Object entry, String name,Object value) { - try { - PropertyUtils.setProperty(entry,name,value); - } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new ODataRuntimeException("[E141] Unable to read property from entity, property=" + name, e); - } - } - - - private URI createId(String entitySetName, Object id) { - try { - return new URI(entitySetName + "(" + String.valueOf(id) + ")"); - } catch (URISyntaxException e) { - throw new ODataRuntimeException("[E177] Unable to create URI", e); - } - } - - - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityProcessor.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityProcessor.java deleted file mode 100644 index 719e5de160..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/processor/JpaEntityProcessor.java +++ /dev/null @@ -1,304 +0,0 @@ -/** - * - */ -package org.baeldung.examples.olingo4.processor; - -import java.io.InputStream; -import java.util.List; -import java.util.Locale; -import java.util.Optional; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.metamodel.SingularAttribute; - -import org.apache.olingo.commons.api.data.ContextURL; -import org.apache.olingo.commons.api.data.Entity; -import org.apache.olingo.commons.api.edm.EdmEntitySet; -import org.apache.olingo.commons.api.edm.EdmEntityType; -import org.apache.olingo.commons.api.edm.EdmNavigationProperty; -import org.apache.olingo.commons.api.ex.ODataRuntimeException; -import org.apache.olingo.commons.api.format.ContentType; -import org.apache.olingo.commons.api.http.HttpHeader; -import org.apache.olingo.commons.api.http.HttpStatusCode; -import org.apache.olingo.server.api.OData; -import org.apache.olingo.server.api.ODataApplicationException; -import org.apache.olingo.server.api.ODataLibraryException; -import org.apache.olingo.server.api.ODataRequest; -import org.apache.olingo.server.api.ODataResponse; -import org.apache.olingo.server.api.ServiceMetadata; -import org.apache.olingo.server.api.processor.EntityProcessor; -import org.apache.olingo.server.api.serializer.EntitySerializerOptions; -import org.apache.olingo.server.api.serializer.ODataSerializer; -import org.apache.olingo.server.api.serializer.SerializerResult; -import org.apache.olingo.server.api.uri.UriInfo; -import org.apache.olingo.server.api.uri.UriParameter; -import org.apache.olingo.server.api.uri.UriResource; -import org.apache.olingo.server.api.uri.UriResourceEntitySet; -import org.apache.olingo.server.api.uri.UriResourceNavigation; -import org.baeldung.examples.olingo4.repository.EdmEntityRepository; -import org.baeldung.examples.olingo4.repository.RepositoryRegistry; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Component; - -/** - * JpaEntityProcessor adapter. - *

This implementation is heavily based on the Tutorial available - * at Olingo's site. It is meant to be an starting point for an actual implementation.

- *

Please note that many features from a full-fledged are missing - * @author Philippe - * - */ -@Component -public class JpaEntityProcessor implements EntityProcessor { - - private EntityManagerFactory emf; - private OData odata; - private ServiceMetadata serviceMetadata; - private RepositoryRegistry registry; - private JpaEntityMapper entityMapper; - - public JpaEntityProcessor(EntityManagerFactory emf, RepositoryRegistry registry, JpaEntityMapper entityMapper) { - this.emf = emf; - this.registry = registry; - this.entityMapper = entityMapper; - } - - /* (non-Javadoc) - * @see org.apache.olingo.server.api.processor.Processor#init(org.apache.olingo.server.api.OData, org.apache.olingo.server.api.ServiceMetadata) - */ - @Override - public void init(OData odata, ServiceMetadata serviceMetadata) { - this.odata = odata; - this.serviceMetadata = serviceMetadata; - - } - - /* (non-Javadoc) - * @see org.apache.olingo.server.api.processor.EntityProcessor#readEntity(org.apache.olingo.server.api.ODataRequest, org.apache.olingo.server.api.ODataResponse, org.apache.olingo.server.api.uri.UriInfo, org.apache.olingo.commons.api.format.ContentType) - */ - @Override - public void readEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { - - // First, we have to figure out which entity is requested - List resourceParts = uriInfo.getUriResourceParts(); - InputStream entityStream; - - UriResourceEntitySet rootResourceEntitySet = (UriResourceEntitySet) resourceParts.get(0); - EdmEntitySet rootEntitySet = rootResourceEntitySet.getEntitySet(); - List rootPredicates = rootResourceEntitySet.getKeyPredicates(); - - if ( resourceParts.size() == 1 ) { - entityStream = readRootEntity(rootEntitySet,rootPredicates,responseFormat); - } - else if ( resourceParts.size() == 2 ) { - UriResource part = resourceParts.get(1); - if ( !(part instanceof UriResourceNavigation)) { - throw new ODataRuntimeException("[E103] part type not supported: class=" + part.getClass().getName()); - } - - UriResourceNavigation navSegment = (UriResourceNavigation)part; - entityStream = readRelatedEntity(request, rootEntitySet,rootPredicates,navSegment.getProperty(),navSegment.getKeyPredicates(),responseFormat); - } - else { - // For now, we'll only allow navigation just to directly linked navs - throw new ODataApplicationException("[E109] Multi-level navigation not supported", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ROOT); - } - - //4. configure the response object - response.setContent(entityStream); - response.setStatusCode(HttpStatusCode.OK.getStatusCode()); - response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString()); - - } - - - // Lookup the EntitySet associated with an EntityType - // In our example, we assume we have only one entityset for each entity type - private EdmEntitySet entitySetFromType(EdmEntityType type) { - return serviceMetadata - .getEdm() - .getEntityContainer() - .getEntitySets() - .stream() - .filter((s) -> s.getEntityType().getName().equals(type.getName())) - .findFirst() - .orElseThrow(() -> new ODataRuntimeException("[E144] No entity set found for type " + type.getFullQualifiedName())); - } - - // - // private boolean isOne2ManyProperty(EdmEntityType entityType, EdmNavigationProperty property) { - // return entityType.getProperty(property.getName()) != null && property.isCollection(); - //} - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private InputStream readRootEntity(EdmEntitySet entitySet, List keyPredicates,ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { - EdmEntityType type = entitySet.getEntityType(); - JpaRepository repo = registry.getRepositoryForEntity(type); - - // Get key value - Long keyValue = getEntityKey(keyPredicates); - Optional entry = repo.findById(keyValue); - if ( !entry.isPresent()) { - throw new ODataApplicationException( - "[E116] NO entity found for the given key", - HttpStatusCode.NOT_FOUND.getStatusCode(), - Locale.ENGLISH); - } - - Entity e = entityMapper.map2entity(entitySet, entry.get()); - return serializeEntity(entitySet,e,responseFormat); - } - - private InputStream serializeEntity(EdmEntitySet entitySet, Entity entity,ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { - ContextURL contextUrl = ContextURL.with().entitySet(entitySet).build(); - // expand and select currently not supported - EntitySerializerOptions options = EntitySerializerOptions - .with() - .contextURL(contextUrl) - .build(); - - ODataSerializer serializer = odata.createSerializer(responseFormat); - - SerializerResult serializerResult = serializer.entity(serviceMetadata, entitySet.getEntityType(), entity, options); - return serializerResult.getContent(); - - } - -// @SuppressWarnings("unchecked") -// protected InputStream readRelatedEntities(EdmEntitySet rootEntitySet, List rootPredicates, EdmNavigationProperty property, ContentType responseFormat) throws ODataApplicationException { -// -// Object jpaEntity = readJPAEntity(rootEntitySet, rootPredicates); -// try { -// Collection set = (Collection)PropertyUtils.getProperty(jpaEntity, property.getName()); -// EdmEntitySet entitySet = entitySetFromType(property.getType()); -// ContextURL contextUrl = ContextURL -// .with() -// .entitySet(entitySet) -// .build(); -// -// EntityCollectionSerializerOptions options = EntityCollectionSerializerOptions -// .with() -// .contextURL(contextUrl) -// .build(); -// -// EntityCollection result = new EntityCollection(); -// -// set.stream() -// .map((o) -> this.entityMapper.map2entity(entitySet, o)) -// .forEach((e) -> result.getEntities().add(e)); -// -// ODataSerializer serializer = odata.createSerializer(responseFormat); -// SerializerResult serializerResult = serializer.entityCollection(serviceMetadata, property.getType(), result, options); -// return serializerResult.getContent(); -// } -// catch(Exception ex) { -// throw new ODataRuntimeException("[E181] Error accessing database", ex); -// } -// } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private InputStream readRelatedEntity(ODataRequest request, EdmEntitySet entitySet, List rootPredicates, EdmNavigationProperty property, List parentPredicates, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { - - - JpaRepository repo = (JpaRepository)registry.getRepositoryForEntity(entitySet.getEntityType()); - EdmEntityRepository relatedRepo = (EdmEntityRepository)registry.getRepositoryForEntity(property.getType()); - - // We assume here that we have a bi-directional 1:N relationship, so we'll - // always have a property in the child entity that points to the parent - Class rootClass = ((EdmEntityRepository)repo).getEntityClass(); - Class relatedClass = ((EdmEntityRepository)relatedRepo).getEntityClass(); - - SingularAttribute fk = emf.getMetamodel() - .entity(rootClass) - .getSingularAttributes() - .stream() - .filter((attr) -> { - boolean b = attr.isAssociation() && attr.getJavaType().isAssignableFrom(relatedClass); - return b; - }) - .findFirst() - .orElse(null); - - if ( fk == null ) { - throw new ODataRuntimeException("[E230] No singular attribute of child class '" + relatedClass.getName() + "' found" ); - } - - Long pkValue = getEntityKey(rootPredicates); - EntityManager em = this.emf.createEntityManager(); - try { - // Read data from DB - Object root = em.find(rootClass, pkValue); - Object related = this.entityMapper.getPropertyValue(root, fk.getName()); - - EdmEntitySet relatedEntitySet = entitySetFromType(property.getType()); - Entity e = entityMapper.map2entity(relatedEntitySet, related); - return serializeEntity(relatedEntitySet,e,responseFormat); - } - finally { - em.close(); - } - } - -// @SuppressWarnings("unchecked") -// private Object readJPAEntity(EdmEntitySet edmEntitySet, List keyPredicates) throws ODataApplicationException { -// EdmEntityType type = edmEntitySet.getEntityType(); -// JpaRepository repo = (JpaRepository)registry.getRepositoryForEntity(type); -// -// // Get key value -// Object keyValue = getEntityKey(type,keyPredicates); -// Object entry = repo -// .findById(keyValue) -// .orElseThrow( -// () -> new ODataApplicationException("[E116] NO entity found for the given key", -// HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH)); -// -// return entry; -// } - - private Long getEntityKey(List keyPredicates) { - - if ( keyPredicates.size() > 1 ) { - throw new ODataRuntimeException("[E131] Composite keys are not supported"); - } - - // For now, we'll assume we only have numeric keys. - UriParameter keyParam = keyPredicates.get(0); - try { - return Long.parseLong(keyParam.getText()); - } - catch(NumberFormatException nfe) { - throw new ODataRuntimeException("[E140] Invalid key value. Only numeric keys are supported by this service"); - } - - - } - - /* (non-Javadoc) - * @see org.apache.olingo.server.api.processor.EntityProcessor#createEntity(org.apache.olingo.server.api.ODataRequest, org.apache.olingo.server.api.ODataResponse, org.apache.olingo.server.api.uri.UriInfo, org.apache.olingo.commons.api.format.ContentType, org.apache.olingo.commons.api.format.ContentType) - */ - @Override - public void createEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType requestFormat, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { - // TODO Auto-generated method stub - - } - - /* (non-Javadoc) - * @see org.apache.olingo.server.api.processor.EntityProcessor#updateEntity(org.apache.olingo.server.api.ODataRequest, org.apache.olingo.server.api.ODataResponse, org.apache.olingo.server.api.uri.UriInfo, org.apache.olingo.commons.api.format.ContentType, org.apache.olingo.commons.api.format.ContentType) - */ - @Override - public void updateEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType requestFormat, ContentType responseFormat) throws ODataApplicationException, ODataLibraryException { - // TODO Auto-generated method stub - - } - - /* (non-Javadoc) - * @see org.apache.olingo.server.api.processor.EntityProcessor#deleteEntity(org.apache.olingo.server.api.ODataRequest, org.apache.olingo.server.api.ODataResponse, org.apache.olingo.server.api.uri.UriInfo) - */ - @Override - public void deleteEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo) throws ODataApplicationException, ODataLibraryException { - // TODO Auto-generated method stub - - } - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarMakerRepository.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarMakerRepository.java deleted file mode 100644 index 1bde9f148c..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarMakerRepository.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.examples.olingo4.repository; - -import org.baeldung.examples.olingo4.domain.CarMaker; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -import org.springframework.stereotype.Repository; - -@Repository -public interface CarMakerRepository extends EdmEntityRepository, JpaRepository, JpaSpecificationExecutor { - - public default String getEdmEntityName() { return CarMaker.class.getSimpleName();} - @Override - default Class getEntityClass() { - return CarMaker.class; - } -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarModelRepository.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarModelRepository.java deleted file mode 100644 index 247bf6e77b..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/CarModelRepository.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.examples.olingo4.repository; - -import java.util.List; - -import org.baeldung.examples.olingo4.domain.CarModel; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -import org.springframework.stereotype.Repository; - -@Repository -public interface CarModelRepository extends EdmEntityRepository, JpaRepository, JpaSpecificationExecutor { - - public List findByMakerId(Long makerId); - - public default String getEdmEntityName() { return CarModel.class.getSimpleName();} - - @Override - default Class getEntityClass() { - return CarModel.class; - } - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/EdmEntityRepository.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/EdmEntityRepository.java deleted file mode 100644 index dbfd0e6f93..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/EdmEntityRepository.java +++ /dev/null @@ -1,17 +0,0 @@ -/** - * - */ -package org.baeldung.examples.olingo4.repository; - - -/** - * @author Philippe - * - */ -public interface EdmEntityRepository { - - public String getEdmEntityName(); - public Class getEntityClass(); - - -} diff --git a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java b/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java deleted file mode 100644 index e3bb172e3a..0000000000 --- a/apache-olingo/olingo4/src/main/java/org/baeldung/examples/olingo4/repository/RepositoryRegistry.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.examples.olingo4.repository; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.olingo.commons.api.edm.EdmEntityType; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Component; - -@Component -public class RepositoryRegistry { - - private Map> repositoriesByClassName = new HashMap<>(); - - public RepositoryRegistry(List> allRepositories) { - - allRepositories.stream() - .forEach((r) -> - repositoriesByClassName.put(r.getEdmEntityName(),(JpaRepository)r)); - - } - - - public JpaRepository getRepositoryForEntity(EdmEntityType entityType) { - JpaRepository repo = repositoriesByClassName.get(entityType.getName()); - return repo; - } -} diff --git a/apache-olingo/olingo4/src/main/resources/application.properties b/apache-olingo/olingo4/src/main/resources/application.properties deleted file mode 100644 index 02c7fe5c4d..0000000000 --- a/apache-olingo/olingo4/src/main/resources/application.properties +++ /dev/null @@ -1,9 +0,0 @@ -server: - port: 8080 - -spring: - jpa: - show-sql: true - open-in-view: true - hibernate: - ddl-auto: update diff --git a/apache-olingo/olingo4/src/main/resources/data.sql b/apache-olingo/olingo4/src/main/resources/data.sql deleted file mode 100644 index 327f2688c5..0000000000 --- a/apache-olingo/olingo4/src/main/resources/data.sql +++ /dev/null @@ -1,12 +0,0 @@ -insert into car_maker(id,name) values (1,'Special Motors'); -insert into car_maker(id,name) values (2,'BWM'); -insert into car_maker(id,name) values (3,'Dolores'); - -insert into car_model(id,maker_fk,name,sku,year) values(1,1,'Muze','SM001',2018); -insert into car_model(id,maker_fk,name,sku,year) values(2,1,'Empada','SM002',2008); - -insert into car_model(id,maker_fk,name,sku,year) values(4,2,'BWM-100','BWM100',2008); -insert into car_model(id,maker_fk,name,sku,year) values(5,2,'BWM-200','BWM200',2009); -insert into car_model(id,maker_fk,name,sku,year) values(6,2,'BWM-300','BWM300',2008); - -alter sequence hibernate_sequence restart with 100; \ No newline at end of file diff --git a/apache-olingo/olingo4/src/test/java/org/baeldung/examples/olingo4/Olingo4SampleApplicationTests.java b/apache-olingo/olingo4/src/test/java/org/baeldung/examples/olingo4/Olingo4SampleApplicationTests.java deleted file mode 100644 index 5d23a4148e..0000000000 --- a/apache-olingo/olingo4/src/test/java/org/baeldung/examples/olingo4/Olingo4SampleApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.examples.olingo4; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class Olingo4SampleApplicationTests { - - @Test - public void contextLoads() { - } - -} From 2c79a4a97f841a1335a031a041f78631b95b0003 Mon Sep 17 00:00:00 2001 From: Alessio Stalla Date: Tue, 21 May 2019 19:05:11 +0200 Subject: [PATCH 032/167] First Hibernate Validator specific constraints tests. --- persistence-modules/hibernate-mapping/pom.xml | 20 ++---- .../hibernate/persistmaps/mapkey/User.java | 22 ++++++ .../UserAdditionalValidationUnitTest.java | 72 +++++++++++++++++++ 3 files changed, 101 insertions(+), 13 deletions(-) create mode 100644 persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index 6bab3c5b1f..67eda5bf72 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -5,9 +5,9 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT - ../../ + .. hibernate-mapping @@ -31,17 +31,12 @@ h2 ${h2.version} - + org.hibernate hibernate-validator ${hibernate-validator.version} - - javax.el - javax.el-api - ${javax.el-api.version} - org.glassfish javax.el @@ -60,11 +55,10 @@ - 5.3.7.Final + 5.3.10.Final 3.8.0 - 5.3.3.Final - 2.2.5 - 3.0.1-b08 + 6.0.16.Final + 3.0.1-b11 - \ No newline at end of file + diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java index f6e8f1cdd6..961fc944a4 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java @@ -6,6 +6,7 @@ import javax.persistence.Id; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.CreditCardNumber; @Entity public class User { @@ -23,6 +24,12 @@ public class User { @Size(min = 3, max = 5) private String city; + @CreditCardNumber + private String creditCardNumber; + + @CreditCardNumber(ignoreNonDigitCharacters = true) + private String lenientCreditCardNumber; + public User(String firstName, String middleName, String lastName, String city) { super(); this.firstName = firstName; @@ -63,4 +70,19 @@ public class User { this.city = city; } + public String getCreditCardNumber() { + return creditCardNumber; + } + + public void setCreditCardNumber(String creditCardNumber) { + this.creditCardNumber = creditCardNumber; + } + + public String getLenientCreditCardNumber() { + return lenientCreditCardNumber; + } + + public void setLenientCreditCardNumber(String lenientCreditCardNumber) { + this.lenientCreditCardNumber = lenientCreditCardNumber; + } } diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java new file mode 100644 index 0000000000..aaf52fe765 --- /dev/null +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.hibernate.validation; + +import com.baeldung.hibernate.HibernateUtil; +import com.baeldung.hibernate.Strategy; +import com.baeldung.hibernate.persistmaps.mapkey.User; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import javax.persistence.PersistenceException; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class UserAdditionalValidationUnitTest { + + private static Validator validator; + private static SessionFactory sessionFactory; + private Session session; + private Set> constraintViolations; + + @BeforeClass + public static void before() { + ValidatorFactory config = Validation.buildDefaultValidatorFactory(); + validator = config.getValidator(); + sessionFactory = HibernateUtil.getSessionFactory(Strategy.MAP_KEY_BASED); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @Test + public void whenValidationWithCCNAndNullCCN_thenNoConstraintViolation() { + User user = new User("John", "Paul", "Butler", "York"); + constraintViolations = validator.validateProperty(user, "creditCardNumber"); + assertTrue(constraintViolations.isEmpty()); + } + + @Test + public void whenValidationWithCCNAndValidCCN_thenNoConstraintViolation() { + User user = new User("John", "Paul", "Butler", "York"); + user.setCreditCardNumber("79927398713"); + constraintViolations = validator.validateProperty(user, "creditCardNumber"); + assertTrue(constraintViolations.isEmpty()); + } + + @Test + public void whenValidationWithCCNAndInvalidCCN_thenConstraintViolation() { + User user = new User("John", "Paul", "Butler", "York"); + user.setCreditCardNumber("79927398714"); + constraintViolations = validator.validateProperty(user, "creditCardNumber"); + assertEquals(constraintViolations.size(), 1); + } + + @Test + public void whenValidationWithLenientCCNAndValidCCNWithDashes_thenNoConstraintViolation() { + User user = new User("John", "Paul", "Butler", "York"); + user.setLenientCreditCardNumber("7992-7398-713"); + constraintViolations = validator.validateProperty(user, "lenientCreditCardNumber"); + assertTrue(constraintViolations.isEmpty()); + } +} From a2e90642333c01f2547d1be9b5975d6a3053a34b Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Tue, 21 May 2019 21:24:57 +0300 Subject: [PATCH 033/167] Create README.MD --- core-java-modules/core-java-lambdas/README.MD | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/core-java-lambdas/README.MD diff --git a/core-java-modules/core-java-lambdas/README.MD b/core-java-modules/core-java-lambdas/README.MD new file mode 100644 index 0000000000..31790ffbb1 --- /dev/null +++ b/core-java-modules/core-java-lambdas/README.MD @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](https://www.baeldung.com/java-lambda-effectively-final-local-variables) From a59168b67fe9fd0e8e46236104d19b671dcecd01 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Thu, 23 May 2019 12:37:11 +0530 Subject: [PATCH 034/167] [BAEL-14777] - Removed old spring 4 and xml related settings --- .../org/baeldung/config/child/WebConfig.java | 2 - .../config/parent/SecurityConfig.java | 1 - .../src/main/resources/prop.xml | 13 ----- .../src/main/resources/webSecurityConfig.xml | 21 -------- .../src/main/webapp/WEB-INF/web_old.xml | 51 ------------------- 5 files changed, 88 deletions(-) delete mode 100644 spring-security-rest-custom/src/main/resources/prop.xml delete mode 100644 spring-security-rest-custom/src/main/resources/webSecurityConfig.xml delete mode 100644 spring-security-rest-custom/src/main/webapp/WEB-INF/web_old.xml diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/config/child/WebConfig.java b/spring-security-rest-custom/src/main/java/org/baeldung/config/child/WebConfig.java index d7b2da6fe7..6688d41ffa 100644 --- a/spring-security-rest-custom/src/main/java/org/baeldung/config/child/WebConfig.java +++ b/spring-security-rest-custom/src/main/java/org/baeldung/config/child/WebConfig.java @@ -14,8 +14,6 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc @ComponentScan("org.baeldung.web") -// @ImportResource({ "classpath:prop.xml" }) -// @PropertySource("classpath:foo.properties") public class WebConfig implements WebMvcConfigurer { public WebConfig() { diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java index 616c2a7684..74e2df2174 100644 --- a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java +++ b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java @@ -10,7 +10,6 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration -// @ImportResource({ "classpath:webSecurityConfig.xml" }) @EnableWebSecurity @ComponentScan("org.baeldung.security") public class SecurityConfig extends WebSecurityConfigurerAdapter { diff --git a/spring-security-rest-custom/src/main/resources/prop.xml b/spring-security-rest-custom/src/main/resources/prop.xml deleted file mode 100644 index b853d939d6..0000000000 --- a/spring-security-rest-custom/src/main/resources/prop.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml b/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml deleted file mode 100644 index fa5dc894bf..0000000000 --- a/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-security-rest-custom/src/main/webapp/WEB-INF/web_old.xml b/spring-security-rest-custom/src/main/webapp/WEB-INF/web_old.xml deleted file mode 100644 index 0fa9abd258..0000000000 --- a/spring-security-rest-custom/src/main/webapp/WEB-INF/web_old.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - Spring Security Custom Application - - - - contextClass - - org.springframework.web.context.support.AnnotationConfigWebApplicationContext - - - - contextConfigLocation - org.baeldung.config.parent - - - - org.springframework.web.context.ContextLoaderListener - - - - - api - org.springframework.web.servlet.DispatcherServlet - - - - - 1 - - - api - /api/* - - - - - springSecurityFilterChain - org.springframework.web.filter.DelegatingFilterProxy - - - springSecurityFilterChain - /* - - - \ No newline at end of file From d4a51e7ac883bb426d1c344a5e0ad4e5bf28b7ce Mon Sep 17 00:00:00 2001 From: amit2103 Date: Thu, 23 May 2019 21:06:21 +0530 Subject: [PATCH 035/167] [BAEL-14777] - Added wrongly deleted web security config xml --- .../src/main/resources/webSecurityConfig.xml | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 spring-security-rest-custom/src/main/resources/webSecurityConfig.xml diff --git a/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml b/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml new file mode 100644 index 0000000000..fa5dc894bf --- /dev/null +++ b/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + \ No newline at end of file From 3946260278b43d6e2ae4e359747d721c3ceca61d Mon Sep 17 00:00:00 2001 From: Loredana Date: Thu, 23 May 2019 20:23:14 +0300 Subject: [PATCH 036/167] fix conflict --- .../com/baeldung/logging/slf4j/Slf4jLogger.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java b/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java index df41e071fd..aaa2d83ca6 100644 --- a/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java +++ b/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java @@ -75,6 +75,8 @@ public class Slf4jLogger implements System.Logger { return; } + String message = MessageFormat.format(format, params); + switch (level) { case TRACE: logger.trace(format, params); From a5a99c28b1e5c3229cb6d2765a85c64bb35fdef6 Mon Sep 17 00:00:00 2001 From: Liesheng Long Date: Thu, 23 May 2019 20:09:03 -0400 Subject: [PATCH 037/167] formatting the source code --- .../HandleOptionalTypeExample.java | 64 +++++++++---------- .../OptionalToJsonExample.java | 25 ++++---- .../PersistOptionalTypeExample.java | 32 +++++----- .../PersistOptionalTypeExample2.java | 28 ++++---- .../PersistUserExample.java | 28 ++++---- .../SerializeOptionalTypeExample.java | 61 +++++++++--------- .../com/baeldung/optionalReturnType/User.java | 36 +++++------ .../optionalReturnType/UserOptional.java | 40 ++++++------ .../optionalReturnType/UserOptionalField.java | 34 +++++----- 9 files changed, 173 insertions(+), 175 deletions(-) diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java index a49909901b..c472bab077 100644 --- a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java @@ -5,37 +5,37 @@ import java.util.Map; import java.util.Optional; public class HandleOptionalTypeExample { - static Map usersByName = new HashMap(); - static { - User user1 = new User(); - user1.setUserId(1l); - user1.setFirstName("baeldung"); - usersByName.put("baeldung", user1); - } - - public static void main(String[] args) { - changeUserName("baeldung", "baeldung-new"); - changeUserName("user", "user-new"); - } - - public static void changeUserName(String oldFirstName, String newFirstName) { - Optional userOpt = findUserByName(oldFirstName); - if(userOpt.isPresent()){ - User user = userOpt.get(); - user.setFirstName(newFirstName); - - System.out.println("user with name "+oldFirstName+" is changed to "+ user.getFirstName()); - } else { - //user is missing - System.out.println("user with name "+oldFirstName+" is not found."); - } - } - - public static Optional findUserByName(String name){ - //look up the user in the database, the user object below could be null - User user=usersByName.get(name); - Optional opt = Optional.ofNullable(user); + static Map usersByName = new HashMap(); + static { + User user1 = new User(); + user1.setUserId(1l); + user1.setFirstName("baeldung"); + usersByName.put("baeldung", user1); + } - return opt; - } + public static void main(String[] args) { + changeUserName("baeldung", "baeldung-new"); + changeUserName("user", "user-new"); + } + + public static void changeUserName(String oldFirstName, String newFirstName) { + Optional userOpt = findUserByName(oldFirstName); + if (userOpt.isPresent()) { + User user = userOpt.get(); + user.setFirstName(newFirstName); + + System.out.println("user with name " + oldFirstName + " is changed to " + user.getFirstName()); + } else { + // user is missing + System.out.println("user with name " + oldFirstName + " is not found."); + } + } + + public static Optional findUserByName(String name) { + // look up the user in the database, the user object below could be null + User user = usersByName.get(name); + Optional opt = Optional.ofNullable(user); + + return opt; + } } diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java index cec5ba5ce1..b44a35fae1 100644 --- a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java @@ -4,17 +4,16 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class OptionalToJsonExample { - public static void main(String[] args) { - UserOptional user = new UserOptional(); - user.setUserId(1l); - user.setFirstName("Bael Dung"); - - ObjectMapper om = new ObjectMapper(); - try { - System.out.print("user in json is:"+om.writeValueAsString(user)); - } catch (JsonProcessingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + public static void main(String[] args) { + UserOptional user = new UserOptional(); + user.setUserId(1l); + user.setFirstName("Bael Dung"); + + ObjectMapper om = new ObjectMapper(); + try { + System.out.print("user in json is:" + om.writeValueAsString(user)); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + } } diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java index 681fae565b..85c96b9bc3 100644 --- a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java @@ -7,20 +7,20 @@ import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class PersistOptionalTypeExample { - static String persistenceUnit = "com.baeldung.optionalReturnType"; - static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit); - - static EntityManager entityManager = emf.createEntityManager(); - - //to run this app, uncomment the follow line in META-INF/persistence.xml - //com.baeldung.optionalReturnType.UserOptionalField - public static void main(String[] args) { - UserOptionalField user1 = new UserOptionalField(); - user1.setUserId(1l); - user1.setFirstName(Optional.of("Bael Dung")); - entityManager.persist(user1); - - UserOptional user2 = entityManager.find(UserOptional.class, 1l); - System.out.print("User2.firstName:"+user2.getFirstName()); - } + static String persistenceUnit = "com.baeldung.optionalReturnType"; + static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit); + + static EntityManager entityManager = emf.createEntityManager(); + + // to run this app, uncomment the follow line in META-INF/persistence.xml + // com.baeldung.optionalReturnType.UserOptionalField + public static void main(String[] args) { + UserOptionalField user1 = new UserOptionalField(); + user1.setUserId(1l); + user1.setFirstName(Optional.of("Bael Dung")); + entityManager.persist(user1); + + UserOptional user2 = entityManager.find(UserOptional.class, 1l); + System.out.print("User2.firstName:" + user2.getFirstName()); + } } diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java index 0662b692a8..3114e7cefb 100644 --- a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java @@ -5,18 +5,18 @@ import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class PersistOptionalTypeExample2 { - static String persistenceUnit = "com.baeldung.optionalReturnType"; - static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit); - - static EntityManager em = emf.createEntityManager(); - - public static void main(String[] args) { - UserOptional user1 = new UserOptional(); - user1.setUserId(1l); - user1.setFirstName("Bael Dung"); - em.persist(user1); - - UserOptional user2 = em.find(UserOptional.class, 1l); - System.out.print("User2.firstName:"+user2.getFirstName()); - } + static String persistenceUnit = "com.baeldung.optionalReturnType"; + static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit); + + static EntityManager em = emf.createEntityManager(); + + public static void main(String[] args) { + UserOptional user1 = new UserOptional(); + user1.setUserId(1l); + user1.setFirstName("Bael Dung"); + em.persist(user1); + + UserOptional user2 = em.find(UserOptional.class, 1l); + System.out.print("User2.firstName:" + user2.getFirstName()); + } } diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserExample.java index af17f83c6e..f1284958e7 100644 --- a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserExample.java +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserExample.java @@ -5,18 +5,18 @@ import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class PersistUserExample { - static String persistenceUnit = "com.baeldung.optionalReturnType"; - static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit); - - static EntityManager em = emf.createEntityManager(); - - public static void main(String[] args) { - User user1 = new User(); - user1.setUserId(1l); - user1.setFirstName("Bael Dung"); - em.persist(user1); - - User user2 = em.find(User.class, 1l); - System.out.print("User2.firstName:"+user2.getFirstName()); - } + static String persistenceUnit = "com.baeldung.optionalReturnType"; + static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit); + + static EntityManager em = emf.createEntityManager(); + + public static void main(String[] args) { + User user1 = new User(); + user1.setUserId(1l); + user1.setFirstName("Bael Dung"); + em.persist(user1); + + User user2 = em.find(User.class, 1l); + System.out.print("User2.firstName:" + user2.getFirstName()); + } } diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java index 7ad4a5325e..d67337ad98 100644 --- a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java @@ -6,37 +6,36 @@ import java.io.ObjectOutputStream; import java.util.Optional; public class SerializeOptionalTypeExample { - public static void main(String[] args) { - User user1 = new User(); - user1.setUserId(1l); - user1.setFirstName("baeldung"); - - serializeObject(user1, "user1.ser"); - + public static void main(String[] args) { + User user1 = new User(); + user1.setUserId(1l); + user1.setFirstName("baeldung"); - UserOptionalField user2 = new UserOptionalField(); - user2.setUserId(1l); - user2.setFirstName(Optional.of("baeldung")); - - serializeObject(user2, "user2.ser"); + serializeObject(user1, "user1.ser"); - } - - public static void serializeObject(Object object, String fileName) { - // Serialization - try { - FileOutputStream file = new FileOutputStream(fileName); - ObjectOutputStream out = new ObjectOutputStream(file); - - out.writeObject(object); - - out.close(); - file.close(); - - System.out.println("Object "+object.toString()+ " has been serialized to file "+fileName); - - } catch(IOException e) { - e.printStackTrace(); - } - } + UserOptionalField user2 = new UserOptionalField(); + user2.setUserId(1l); + user2.setFirstName(Optional.of("baeldung")); + + serializeObject(user2, "user2.ser"); + + } + + public static void serializeObject(Object object, String fileName) { + // Serialization + try { + FileOutputStream file = new FileOutputStream(fileName); + ObjectOutputStream out = new ObjectOutputStream(file); + + out.writeObject(object); + + out.close(); + file.close(); + + System.out.println("Object " + object.toString() + " has been serialized to file " + fileName); + + } catch (IOException e) { + e.printStackTrace(); + } + } } diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/User.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/User.java index 42bedb4817..7aa11d78cb 100644 --- a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/User.java +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/User.java @@ -7,25 +7,25 @@ import javax.persistence.Id; @Entity public class User implements Serializable { - @Id - private long userId; - - private String firstName; - - public long getUserId() { - return userId; - } + @Id + private long userId; - public void setUserId(long userId) { - this.userId = userId; - } + private String firstName; - public String getFirstName() { - return firstName; - } + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - } diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptional.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptional.java index c48781ea80..0138a84ab9 100644 --- a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptional.java +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptional.java @@ -9,27 +9,27 @@ import javax.persistence.Id; @Entity public class UserOptional implements Serializable { - @Id - private long userId; - - @Column(nullable = true) - private String firstName; - - public long getUserId() { - return userId; - } + @Id + private long userId; - public void setUserId(long userId) { - this.userId = userId; - } + @Column(nullable = true) + private String firstName; - public Optional getFirstName() { - return Optional.ofNullable(firstName); - } + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + + public Optional getFirstName() { + return Optional.ofNullable(firstName); + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + Optional.ofNullable(firstName); + } - public void setFirstName(String firstName) { - this.firstName = firstName; - Optional.ofNullable(firstName); - } - } diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java index 0778a8bb99..c02430b1ba 100644 --- a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java @@ -8,24 +8,24 @@ import javax.persistence.Id; @Entity public class UserOptionalField implements Serializable { - @Id - private long userId; - - private Optional firstName; - - public long getUserId() { - return userId; - } + @Id + private long userId; - public void setUserId(long userId) { - this.userId = userId; - } + private Optional firstName; - public Optional getFirstName() { - return firstName; - } + public long getUserId() { + return userId; + } - public void setFirstName(Optional firstName) { - this.firstName = firstName; - } + public void setUserId(long userId) { + this.userId = userId; + } + + public Optional getFirstName() { + return firstName; + } + + public void setFirstName(Optional firstName) { + this.firstName = firstName; + } } From a8cdcc610083fd4a3d51fea91c2b8664f18c05ef Mon Sep 17 00:00:00 2001 From: Liesheng Long Date: Thu, 23 May 2019 20:18:30 -0400 Subject: [PATCH 038/167] formatting and use properties for versions --- core-java-modules/core-java-8-2/pom.xml | 103 ++++++++++++------------ 1 file changed, 53 insertions(+), 50 deletions(-) diff --git a/core-java-modules/core-java-8-2/pom.xml b/core-java-modules/core-java-8-2/pom.xml index 862b739530..150f36be59 100644 --- a/core-java-modules/core-java-8-2/pom.xml +++ b/core-java-modules/core-java-8-2/pom.xml @@ -1,64 +1,67 @@ - 4.0.0 - com.baeldung - core-java-8-2 - 0.1.0-SNAPSHOT - core-java-8-2 - jar + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + core-java-8-2 + 0.1.0-SNAPSHOT + core-java-8-2 + jar - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + - - UTF-8 - 1.8 - 1.8 - 64.2 - + + UTF-8 + 1.8 + 1.8 + 64.2 + 5.4.0.Final + 1.4.197 + 2.9.8 + - - - com.ibm.icu - icu4j - ${icu.version} - + - org.hibernate - hibernate-core - 5.4.0.Final + com.ibm.icu + icu4j + ${icu.version} - com.h2database - h2 - 1.4.197 + org.hibernate + hibernate-core + ${hibernate.core.version} - com.fasterxml.jackson.core - jackson-databind - 2.9.8 - - + com.h2database + h2 + ${h2database.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.databind.version} + + - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - - + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + - + From 7c3082a0930e7937c0507021fc0ca6a2d25e1d0a Mon Sep 17 00:00:00 2001 From: Gian Mario Contessa Date: Fri, 24 May 2019 08:09:59 +0100 Subject: [PATCH 039/167] BAEL-2899: project structure and example classes --- java-groovy-joint/pom.xml | 132 ++++++++++++++++++ .../main/groovy/com.baeldung/CalcMath.groovy | 19 +++ .../groovy/com.baeldung/CalcScript.groovy | 19 +++ .../src/main/java/com/baeldung/App.java | 54 +++++++ 4 files changed, 224 insertions(+) create mode 100644 java-groovy-joint/pom.xml create mode 100644 java-groovy-joint/src/main/groovy/com.baeldung/CalcMath.groovy create mode 100644 java-groovy-joint/src/main/groovy/com.baeldung/CalcScript.groovy create mode 100644 java-groovy-joint/src/main/java/com/baeldung/App.java diff --git a/java-groovy-joint/pom.xml b/java-groovy-joint/pom.xml new file mode 100644 index 0000000000..67365cf999 --- /dev/null +++ b/java-groovy-joint/pom.xml @@ -0,0 +1,132 @@ + + + + 4.0.0 + java-groovy-joint + 0.1.0-SNAPSHOT + java-groovy-joint + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + UTF-8 + 3.9 + 1.8 + 3.8.1 + 1.2.3 + 2.5.7 + + + + + bintray + Groovy Bintray + https://dl.bintray.com/groovy/maven + + never + + + false + + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + org.codehaus.groovy + groovy-all + ${groovy.version} + pom + + + junit + junit + 4.11 + test + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.1.2 + + + + com.baeldung.App + true + + + + + + maven-compiler-plugin + 3.8.0 + + groovy-eclipse-compiler + ${java.version} + ${java.version} + + + + org.codehaus.groovy + groovy-eclipse-compiler + 3.3.0-01 + + + org.codehaus.groovy + groovy-eclipse-batch + ${groovy.version}-01 + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 3.1.0 + + + + jar-with-dependencies + + + + + com.baeldung.App + + + + + + + make-assembly + + package + + single + + + + + + + + + diff --git a/java-groovy-joint/src/main/groovy/com.baeldung/CalcMath.groovy b/java-groovy-joint/src/main/groovy/com.baeldung/CalcMath.groovy new file mode 100644 index 0000000000..d9709653c7 --- /dev/null +++ b/java-groovy-joint/src/main/groovy/com.baeldung/CalcMath.groovy @@ -0,0 +1,19 @@ +package com.baeldung + +import org.slf4j.LoggerFactory + +class CalcMath { + def log = LoggerFactory.getLogger(this.getClass()) + + def calcSum(x, y) { + log.info "Executing $x + $y" + x + y + } + + def calcSum2(x, y) { + log.info "Executing $x + $y" + // DANGER! This won't throw a compilation issue and fail only at runtime!!! + calcSum3() + log.info("Logging an undefined variable: $z") + } +} \ No newline at end of file diff --git a/java-groovy-joint/src/main/groovy/com.baeldung/CalcScript.groovy b/java-groovy-joint/src/main/groovy/com.baeldung/CalcScript.groovy new file mode 100644 index 0000000000..2278f0dab8 --- /dev/null +++ b/java-groovy-joint/src/main/groovy/com.baeldung/CalcScript.groovy @@ -0,0 +1,19 @@ +package com.baeldung + +import org.slf4j.LoggerFactory + +abstract class CalcScript extends Script { + def log = LoggerFactory.getLogger(this.getClass()) + + def calcSum(x, y) { + log.info "Executing $x + $y" + x + y + } + + def calcSum2(x, y) { + log.info "Executing $x + $y" + // DANGER! This won't throw a compilation issue and fail only at runtime!!! + calcSum3() + log.info("Logging an undefined variable: $z") + } +} \ No newline at end of file diff --git a/java-groovy-joint/src/main/java/com/baeldung/App.java b/java-groovy-joint/src/main/java/com/baeldung/App.java new file mode 100644 index 0000000000..0a201d12e2 --- /dev/null +++ b/java-groovy-joint/src/main/java/com/baeldung/App.java @@ -0,0 +1,54 @@ +package com.baeldung; + +import groovy.lang.Binding; +import groovy.lang.GroovyClassLoader; +import groovy.lang.GroovyShell; +import org.codehaus.groovy.control.CompilerConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Hello world! + * + */ +public class App { + private final static Logger LOG = LoggerFactory.getLogger(App.class); + private final GroovyClassLoader loader; + private final GroovyShell shell; + + private App() { + loader = new GroovyClassLoader(this.getClass().getClassLoader()); + CompilerConfiguration config = new CompilerConfiguration(); + config.setScriptBaseClass("com.baeldung.CalcScript"); + shell = new GroovyShell(loader, new Binding(), config); + } + + private void runScript(int x, int y) { + Object script = shell.parse(String.format("calcSum(%d,%d)", x, y)); + assert script instanceof CalcScript; + Object result = ((CalcScript) script).run(); + LOG.info("Result of run() method is {}", result); + + Object script2 = shell.parse("CalcScript"); + Object result2 = ((CalcScript) script2).calcSum(x + 7, y + 7); + LOG.info("Result of calcSum() method is {}", result2); + + } + + private void runClass(int x, int y) throws ClassNotFoundException, IllegalAccessException, InstantiationException { + Class calcClass = loader.loadClass("com.baeldung.CalcMath"); + Object calc = calcClass.newInstance(); + assert calc instanceof CalcMath; + + Object result = ((CalcMath) calc).calcSum(x, y); + LOG.info("Result is {}", result); + } + + public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { + App app = new App(); + LOG.info("Running a groovy script..."); + app.runScript(5, 10); + LOG.info("Running a groovy class..."); + app.runClass(1, 3); + } +} From da7a651ef41fadcc58ac42cfb877cbf827f96543 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 16:26:13 +0800 Subject: [PATCH 040/167] Create README.md --- .../src/main/java/com/baeldung/deserialization/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/deserialization/README.md diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/deserialization/README.md b/core-java-modules/core-java/src/main/java/com/baeldung/deserialization/README.md new file mode 100644 index 0000000000..04b03e4907 --- /dev/null +++ b/core-java-modules/core-java/src/main/java/com/baeldung/deserialization/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [What is the serialVersionUID?](https://www.baeldung.com/java-serial-version-uid) From abae8ec0cfc5ad457dc13736a517be69f0803b99 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 16:28:02 +0800 Subject: [PATCH 041/167] Create README.md --- .../core-java/src/main/java/com/baeldung/uuid/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/uuid/README.md diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/uuid/README.md b/core-java-modules/core-java/src/main/java/com/baeldung/uuid/README.md new file mode 100644 index 0000000000..bc464a4a1d --- /dev/null +++ b/core-java-modules/core-java/src/main/java/com/baeldung/uuid/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Guide to UUID in Java](https://www.baeldung.com/java-uuid) From 3974bf9dd7abb69983550a114994c4cf75a55179 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 16:29:43 +0800 Subject: [PATCH 042/167] Create README.md [skip ci] --- .../src/main/java/com/baeldung/serialization/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/serialization/README.md diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/serialization/README.md b/core-java-modules/core-java/src/main/java/com/baeldung/serialization/README.md new file mode 100644 index 0000000000..d9167fa3b8 --- /dev/null +++ b/core-java-modules/core-java/src/main/java/com/baeldung/serialization/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Introduction to Java Serialization](https://www.baeldung.com/java-serialization) From f1e3f5bf07f72394b1ddd707f8bee595351d8d23 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 16:39:06 +0800 Subject: [PATCH 043/167] Create README.md [skip ci] --- .../core-java/src/main/java/com/baeldung/classloader/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/classloader/README.md diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/classloader/README.md b/core-java-modules/core-java/src/main/java/com/baeldung/classloader/README.md new file mode 100644 index 0000000000..e26a3e2de9 --- /dev/null +++ b/core-java-modules/core-java/src/main/java/com/baeldung/classloader/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Class Loaders in Java](https://www.baeldung.com/java-classloaders) From a23ec1d573a8d16e508400c23b06512e38c0a095 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 16:40:00 +0800 Subject: [PATCH 044/167] Create README.md [skip ci] --- .../core-java/src/main/java/com/baeldung/console/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/console/README.md diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/console/README.md b/core-java-modules/core-java/src/main/java/com/baeldung/console/README.md new file mode 100644 index 0000000000..418892f288 --- /dev/null +++ b/core-java-modules/core-java/src/main/java/com/baeldung/console/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Console I/O in Java](https://www.baeldung.com/java-console-input-output) From ec136b7e7123d303840325fd4bc8f4489755b491 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 16:40:54 +0800 Subject: [PATCH 045/167] Create README.md [skip ci] --- .../src/main/java/com/baeldung/abstractclasses/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/abstractclasses/README.md diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/abstractclasses/README.md b/core-java-modules/core-java/src/main/java/com/baeldung/abstractclasses/README.md new file mode 100644 index 0000000000..8ded91b275 --- /dev/null +++ b/core-java-modules/core-java/src/main/java/com/baeldung/abstractclasses/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class/) From ab89eeb9a4781dac4c6086c94b42bb9007cdc4de Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 16:42:50 +0800 Subject: [PATCH 046/167] Create README.md [skip ci] --- core-java-modules/core-java-lambdas/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/core-java-lambdas/README.md diff --git a/core-java-modules/core-java-lambdas/README.md b/core-java-modules/core-java-lambdas/README.md new file mode 100644 index 0000000000..10b876735e --- /dev/null +++ b/core-java-modules/core-java-lambdas/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](https://www.baeldung.com/java-lambda-effectively-final-local-variables) From d0ed8bd21b97fa8cb99c8b18a9cd037e9fe5654c Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 16:48:53 +0800 Subject: [PATCH 047/167] Create README.md [skip ci] --- maven/profiles/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 maven/profiles/README.md diff --git a/maven/profiles/README.md b/maven/profiles/README.md new file mode 100644 index 0000000000..84b0a81ceb --- /dev/null +++ b/maven/profiles/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Guide to Maven Profiles](https://www.baeldung.com/maven-profiles) From 085258d234c74a3e359b28e41c401f7f37f5238d Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 16:50:24 +0800 Subject: [PATCH 048/167] Update README.md [skip ci] --- persistence-modules/spring-data-jpa-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md index 393d15d6f1..d35c05851b 100644 --- a/persistence-modules/spring-data-jpa-2/README.md +++ b/persistence-modules/spring-data-jpa-2/README.md @@ -12,3 +12,4 @@ - [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections) - [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable) - [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete) +- [Spring Data JPA and Named Entity Graphs](https://www.baeldung.com/spring-data-jpa-named-entity-graphs) From 75103d1dacc0cedb91dd184bf3f504c1415e5d70 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 16:50:57 +0800 Subject: [PATCH 049/167] Update README.md [skip ci] --- persistence-modules/spring-data-jpa-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md index d35c05851b..8893b09286 100644 --- a/persistence-modules/spring-data-jpa-2/README.md +++ b/persistence-modules/spring-data-jpa-2/README.md @@ -13,3 +13,4 @@ - [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable) - [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete) - [Spring Data JPA and Named Entity Graphs](https://www.baeldung.com/spring-data-jpa-named-entity-graphs) +- [Tagging and Filtering JUnit Tests](https://www.baeldung.com/junits-filtering-tests) From 50d6f0b8395c73fd7c5190cccef75700ac9fb39c Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 16:52:02 +0800 Subject: [PATCH 050/167] Update README.md [skip ci] --- persistence-modules/java-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 34d03b3259..0426015045 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -8,3 +8,4 @@ - [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date) - [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates) - [Types of JPA Queries](https://www.baeldung.com/jpa-queries) +- [Defining JPA Entities](https://www.baeldung.com/jpa-entities) From 0e01973ff661081a6a5fc02349dcd34f1454a45a Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 16:53:15 +0800 Subject: [PATCH 051/167] Create README.md [skip ci] --- quarkus/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 quarkus/README.md diff --git a/quarkus/README.md b/quarkus/README.md new file mode 100644 index 0000000000..01009eab3e --- /dev/null +++ b/quarkus/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [Guide to QuarkusIO](hhttps://www.baeldung.com/quarkus-io) From 384fe96e49c860500d3c473879d6379b282f7177 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 16:54:26 +0800 Subject: [PATCH 052/167] Update README.md [skip ci] --- persistence-modules/spring-data-jpa-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md index 8893b09286..78a228986a 100644 --- a/persistence-modules/spring-data-jpa-2/README.md +++ b/persistence-modules/spring-data-jpa-2/README.md @@ -14,3 +14,4 @@ - [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete) - [Spring Data JPA and Named Entity Graphs](https://www.baeldung.com/spring-data-jpa-named-entity-graphs) - [Tagging and Filtering JUnit Tests](https://www.baeldung.com/junits-filtering-tests) +- [Batch Insert/Update with Hibernate/JPA](https://www.baeldung.com/jpa-hibernate-batch-insert-update) From 25f7fe72c537bf2cd2ab9bdc996cdb182a15dc68 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 16:55:32 +0800 Subject: [PATCH 053/167] Create README.md [skip ci] --- apache-olingo/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 apache-olingo/README.md diff --git a/apache-olingo/README.md b/apache-olingo/README.md new file mode 100644 index 0000000000..bfbdc97700 --- /dev/null +++ b/apache-olingo/README.md @@ -0,0 +1,3 @@ +## Relevant articles: + +- [OData Protocol Guide](https://www.baeldung.com/odata) From e6c5d0024a15bc64ce0a4b733924a7e831c972b1 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 16:56:51 +0800 Subject: [PATCH 054/167] Update README.md [skip ci] --- persistence-modules/java-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 0426015045..33d31781e0 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -9,3 +9,4 @@ - [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates) - [Types of JPA Queries](https://www.baeldung.com/jpa-queries) - [Defining JPA Entities](https://www.baeldung.com/jpa-entities) +- [JPA @Basic Annotation](https://www.baeldung.com/jpa-basic-annotation) From 76c498f670fe2c7e2694cab33eaff4d865182104 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 16:57:44 +0800 Subject: [PATCH 055/167] Update README.md [skip ci] --- persistence-modules/java-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 33d31781e0..ca9ec0d74d 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -10,3 +10,4 @@ - [Types of JPA Queries](https://www.baeldung.com/jpa-queries) - [Defining JPA Entities](https://www.baeldung.com/jpa-entities) - [JPA @Basic Annotation](https://www.baeldung.com/jpa-basic-annotation) +- [Default Column Values in JPA](https://www.baeldung.com/jpa-default-column-values) From 3e14bc38a016ffd710c1ae9fff970eaeac72adb4 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 17:01:36 +0800 Subject: [PATCH 056/167] Update README.md [skip ci] --- testing-modules/junit-5/README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index 47db6587b4..d687b35cac 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -1,6 +1,5 @@ ### Relevant Articles: -- [The Basics of JUnit 5 – A Preview](http://www.baeldung.com/junit-5-preview) -- [A Guide to JUnit 5](http://www.baeldung.com/junit-5) +- [A Guide to JUnit 5](http://www.baeldung.com/junit-5-preview) - [A Guide to @RepeatedTest in Junit 5](http://www.baeldung.com/junit-5-repeated-test) - [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) - [A Guide to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) From 58538e329a10fb48238790649d997aedbfbfb338 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 17:03:14 +0800 Subject: [PATCH 057/167] Update README.md [skip ci] --- persistence-modules/spring-persistence-simple/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md index c408ff3c96..12b7d025a9 100644 --- a/persistence-modules/spring-persistence-simple/README.md +++ b/persistence-modules/spring-persistence-simple/README.md @@ -6,7 +6,7 @@ ### Relevant Articles: - [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) - [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring) -- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) +- [Simplify the DAO with Spring and Java Generics](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) - [DAO with Spring and Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics) - [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) - [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) From 92ec5af77c88e0218c13132e9a96a80e413503d3 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 17:03:39 +0800 Subject: [PATCH 058/167] Update README.md [skip ci] --- persistence-modules/spring-persistence-simple/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md index 12b7d025a9..ed81c9c564 100644 --- a/persistence-modules/spring-persistence-simple/README.md +++ b/persistence-modules/spring-persistence-simple/README.md @@ -9,7 +9,7 @@ - [Simplify the DAO with Spring and Java Generics](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) - [DAO with Spring and Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics) - [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) -- [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) +- [A Guide to JPA with Spring](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) - [Spring JDBC](https://www.baeldung.com/spring-jdbc-jdbctemplate) From 287f589aeee4c26ba7064ea29e2bc52eddd1d62c Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 17:04:25 +0800 Subject: [PATCH 059/167] Update README.md [skip ci] --- core-java-modules/core-java-9/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-9/README.md b/core-java-modules/core-java-9/README.md index 5715520bae..8b52ce79b4 100644 --- a/core-java-modules/core-java-9/README.md +++ b/core-java-modules/core-java-9/README.md @@ -28,6 +28,6 @@ - [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods) - [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api) - [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity) -- [Java 9 Platform Module API](https://www.baeldung.com/java-9-module-api) +- [Java 9 java.lang.Module API](https://www.baeldung.com/java-9-module-api) - [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api) - [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional) From 6072ddee005f6ce09e225de96037c32ff09ef92a Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 17:05:20 +0800 Subject: [PATCH 060/167] Update README.md [skip ci] --- persistence-modules/java-jpa/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index ca9ec0d74d..ae72e6b3c8 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -2,7 +2,7 @@ - [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping) - [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) -- [Fixing the JPA error “java.lang.String cannot be cast to Ljava.lang.String;”](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) +- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;”](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) - [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph) - [JPA 2.2 Support for Java 8 Date/Time Types](https://www.baeldung.com/jpa-java-time) - [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date) From 47456f147da7814c161c4dae50b43702d76ea92b Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 17:05:43 +0800 Subject: [PATCH 061/167] Update README.md [skip ci] --- persistence-modules/java-jpa/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index ae72e6b3c8..554e10dc98 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -2,7 +2,7 @@ - [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping) - [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) -- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;”](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) +- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;”]](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) - [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph) - [JPA 2.2 Support for Java 8 Date/Time Types](https://www.baeldung.com/jpa-java-time) - [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date) From 027b6b884021736acc8234872fb78afe62387f5b Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 17:53:15 +0800 Subject: [PATCH 062/167] Delete README.md --- .../src/main/java/com/baeldung/deserialization/README.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/deserialization/README.md diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/deserialization/README.md b/core-java-modules/core-java/src/main/java/com/baeldung/deserialization/README.md deleted file mode 100644 index 04b03e4907..0000000000 --- a/core-java-modules/core-java/src/main/java/com/baeldung/deserialization/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Relevant articles: - -- [What is the serialVersionUID?](https://www.baeldung.com/java-serial-version-uid) From 78ae20dc0e1602daf0699cabb8feb58aa9f151a3 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 18:12:37 +0800 Subject: [PATCH 063/167] Delete README.md --- .../core-java/src/main/java/com/baeldung/uuid/README.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/uuid/README.md diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/uuid/README.md b/core-java-modules/core-java/src/main/java/com/baeldung/uuid/README.md deleted file mode 100644 index bc464a4a1d..0000000000 --- a/core-java-modules/core-java/src/main/java/com/baeldung/uuid/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Relevant articles: - -- [Guide to UUID in Java](https://www.baeldung.com/java-uuid) From d7e2d7f59fe5908c5cb2cb74037341ba2ffac469 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 18:13:41 +0800 Subject: [PATCH 064/167] Delete README.md --- testing-modules/junit-5/README.md | 19 ------------------- 1 file changed, 19 deletions(-) delete mode 100644 testing-modules/junit-5/README.md diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md deleted file mode 100644 index d687b35cac..0000000000 --- a/testing-modules/junit-5/README.md +++ /dev/null @@ -1,19 +0,0 @@ -### Relevant Articles: -- [A Guide to JUnit 5](http://www.baeldung.com/junit-5-preview) -- [A Guide to @RepeatedTest in Junit 5](http://www.baeldung.com/junit-5-repeated-test) -- [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) -- [A Guide to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) -- [Inject Parameters into JUnit Jupiter Unit Tests](http://www.baeldung.com/junit-5-parameters) -- [Mockito and JUnit 5 – Using ExtendWith](http://www.baeldung.com/mockito-junit-5-extension) -- [JUnit5 @RunWith](http://www.baeldung.com/junit-5-runwith) -- [JUnit 5 @Test Annotation](http://www.baeldung.com/junit-5-test-annotation) -- [Assert an Exception is Thrown in JUnit 4 and 5](http://www.baeldung.com/junit-assert-exception) -- [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) -- [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) -- [JUnit5 Programmatic Extension Registration with @RegisterExtension](http://www.baeldung.com/junit-5-registerextension-annotation) -- [The Order of Tests in JUnit](http://www.baeldung.com/junit-5-test-order) -- [Running JUnit Tests Programmatically, from a Java Application](https://www.baeldung.com/junit-tests-run-programmatically-from-java) -- [Testing an Abstract Class With JUnit](https://www.baeldung.com/junit-test-abstract-class) -- [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng) -- [Guide to JUnit 5 Parameterized Tests](https://www.baeldung.com/parameterized-tests-junit-5) -- [JUnit 5 Conditional Test Execution with Annotations](https://www.baeldung.com/junit-5-conditional-test-execution) From 8ff0bed3a49ce9fb9bd76f5a1831c5a21e74c5b4 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Fri, 24 May 2019 18:14:54 +0800 Subject: [PATCH 065/167] Delete README.md --- .../src/main/java/com/baeldung/serialization/README.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/serialization/README.md diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/serialization/README.md b/core-java-modules/core-java/src/main/java/com/baeldung/serialization/README.md deleted file mode 100644 index d9167fa3b8..0000000000 --- a/core-java-modules/core-java/src/main/java/com/baeldung/serialization/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Relevant articles: - -- [Introduction to Java Serialization](https://www.baeldung.com/java-serialization) From 1050337dabfb4c84512bbe4a4bf7087a35f55ee3 Mon Sep 17 00:00:00 2001 From: Liesheng Long Date: Fri, 24 May 2019 11:28:49 -0400 Subject: [PATCH 066/167] replace tabs with 4-spaces --- core-java-modules/core-java-8-2/pom.xml | 116 ++++++++++++------------ 1 file changed, 58 insertions(+), 58 deletions(-) diff --git a/core-java-modules/core-java-8-2/pom.xml b/core-java-modules/core-java-8-2/pom.xml index 150f36be59..ff2e290086 100644 --- a/core-java-modules/core-java-8-2/pom.xml +++ b/core-java-modules/core-java-8-2/pom.xml @@ -1,67 +1,67 @@ - 4.0.0 - com.baeldung - core-java-8-2 - 0.1.0-SNAPSHOT - core-java-8-2 - jar + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + com.baeldung + core-java-8-2 + 0.1.0-SNAPSHOT + core-java-8-2 + jar - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + - - UTF-8 - 1.8 - 1.8 - 64.2 - 5.4.0.Final - 1.4.197 - 2.9.8 - + + UTF-8 + 1.8 + 1.8 + 64.2 + 5.4.0.Final + 1.4.197 + 2.9.8 + - - - com.ibm.icu - icu4j - ${icu.version} - - - org.hibernate - hibernate-core - ${hibernate.core.version} - - - com.h2database - h2 - ${h2database.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.databind.version} - - + + + com.ibm.icu + icu4j + ${icu.version} + + + org.hibernate + hibernate-core + ${hibernate.core.version} + + + com.h2database + h2 + ${h2database.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.databind.version} + + - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - - + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + - + From 93dfb77f1f9e8e86631014bf23b3621cd8ebf390 Mon Sep 17 00:00:00 2001 From: dionisPrifti Date: Fri, 24 May 2019 18:10:52 +0200 Subject: [PATCH 067/167] Bael 2810 data jpa delete (#6759) * BAEL-2810: Finished the examples and unit tests. * BAEL-2810: Changed assertions to isEqualTo * BAEL-2810: Changed the test of the derived query to reflect the number of the deleted records --- .../datajpadelete/DeleteFromRepositoryUnitTest.java | 10 +++++----- .../datajpadelete/DeleteInRelationshipsUnitTest.java | 8 ++++---- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java index 9e7e516735..5f4a36bc0e 100644 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java +++ b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java @@ -43,22 +43,22 @@ public class DeleteFromRepositoryUnitTest { public void whenDeleteByIdFromRepository_thenDeletingShouldBeSuccessful() { repository.deleteById(book1.getId()); - assertThat(repository.count() == 1).isTrue(); + assertThat(repository.count()).isEqualTo(1); } @Test public void whenDeleteAllFromRepository_thenRepositoryShouldBeEmpty() { repository.deleteAll(); - assertThat(repository.count() == 0).isTrue(); + assertThat(repository.count()).isEqualTo(0); } @Test @Transactional public void whenDeleteFromDerivedQuery_thenDeletingShouldBeSuccessful() { - repository.deleteByTitle("The Hobbit"); + long deletedRecords = repository.deleteByTitle("The Hobbit"); - assertThat(repository.count() == 1).isTrue(); + assertThat(deletedRecords).isEqualTo(1); } @Test @@ -66,7 +66,7 @@ public class DeleteFromRepositoryUnitTest { public void whenDeleteFromCustomQuery_thenDeletingShouldBeSuccessful() { repository.deleteBooks("The Hobbit"); - assertThat(repository.count() == 1).isTrue(); + assertThat(repository.count()).isEqualTo(1); } } \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java index 56de8749b2..6275ace6e0 100644 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java +++ b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java @@ -46,15 +46,15 @@ public class DeleteInRelationshipsUnitTest { public void whenDeletingCategories_thenBooksShouldAlsoBeDeleted() { categoryRepository.deleteAll(); - assertThat(bookRepository.count() == 0).isTrue(); - assertThat(categoryRepository.count() == 0).isTrue(); + assertThat(bookRepository.count()).isEqualTo(0); + assertThat(categoryRepository.count()).isEqualTo(0); } @Test public void whenDeletingBooks_thenCategoriesShouldAlsoBeDeleted() { bookRepository.deleteAll(); - assertThat(bookRepository.count() == 0).isTrue(); - assertThat(categoryRepository.count() == 2).isTrue(); + assertThat(bookRepository.count()).isEqualTo(0); + assertThat(categoryRepository.count()).isEqualTo(2); } } \ No newline at end of file From d373336b74d9b70e5cee2144e406eb6d02c005bd Mon Sep 17 00:00:00 2001 From: binary-joe <48189951+binary-joe@users.noreply.github.com> Date: Fri, 24 May 2019 18:12:40 +0200 Subject: [PATCH 068/167] BAEL-2516 catching errors in catch block (#6761) --- .../com/baeldung/error/ErrorGenerator.java | 15 ++++++ .../error/ErrorGeneratorUnitTest.java | 51 +++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 core-java-lang/src/main/java/com/baeldung/error/ErrorGenerator.java create mode 100644 core-java-lang/src/test/java/com/baeldung/error/ErrorGeneratorUnitTest.java diff --git a/core-java-lang/src/main/java/com/baeldung/error/ErrorGenerator.java b/core-java-lang/src/main/java/com/baeldung/error/ErrorGenerator.java new file mode 100644 index 0000000000..58cbe22df5 --- /dev/null +++ b/core-java-lang/src/main/java/com/baeldung/error/ErrorGenerator.java @@ -0,0 +1,15 @@ +package com.baeldung.error; + +public class ErrorGenerator { + public void throwException() throws Exception { + throw new Exception("checked"); + } + + public void throwRuntimeException() { + throw new RuntimeException("unchecked"); + } + + public void throwError() { + throw new Error("unchecked"); + } +} diff --git a/core-java-lang/src/test/java/com/baeldung/error/ErrorGeneratorUnitTest.java b/core-java-lang/src/test/java/com/baeldung/error/ErrorGeneratorUnitTest.java new file mode 100644 index 0000000000..2a7c24f5fa --- /dev/null +++ b/core-java-lang/src/test/java/com/baeldung/error/ErrorGeneratorUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.error; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class ErrorGeneratorUnitTest { + + private ErrorGenerator errorGenerator; + + @Before + public void setUp() { + errorGenerator = new ErrorGenerator(); + } + + @Test + public void whenCheckedException_thenIsCaughtByCatchException() { + try { + errorGenerator.throwException(); + } catch (Exception e) { + // caught! -> test pass + } + } + + @Test + public void whenUncheckedException_thenIsCaughtByCatchException() { + try { + errorGenerator.throwRuntimeException(); + } catch (Exception e) { + // caught! -> test pass + } + } + + @Test(expected = Error.class) + public void whenError_thenIsNotCaughtByCatchException() { + try { + errorGenerator.throwError(); + } catch (Exception e) { + Assert.fail(); // errors are not caught by catch exception + } + } + + @Test + public void whenError_thenIsCaughtByCatchError() { + try { + errorGenerator.throwError(); + } catch (Error e) { + // caught! -> test pass + } + } +} \ No newline at end of file From c90f76a4f83977f214c1630934e8959c122bd577 Mon Sep 17 00:00:00 2001 From: Graham Cox Date: Fri, 24 May 2019 17:24:47 +0100 Subject: [PATCH 069/167] Examples for Clojure Ring (#6881) --- clojure/ring/.gitignore | 12 +++++++++ clojure/ring/README.md | 16 ++++++++++++ clojure/ring/project.clj | 8 ++++++ clojure/ring/src/ring/core.clj | 48 ++++++++++++++++++++++++++++++++++ 4 files changed, 84 insertions(+) create mode 100644 clojure/ring/.gitignore create mode 100644 clojure/ring/README.md create mode 100644 clojure/ring/project.clj create mode 100644 clojure/ring/src/ring/core.clj diff --git a/clojure/ring/.gitignore b/clojure/ring/.gitignore new file mode 100644 index 0000000000..d18f225992 --- /dev/null +++ b/clojure/ring/.gitignore @@ -0,0 +1,12 @@ +/target +/classes +/checkouts +profiles.clj +pom.xml +pom.xml.asc +*.jar +*.class +/.lein-* +/.nrepl-port +.hgignore +.hg/ diff --git a/clojure/ring/README.md b/clojure/ring/README.md new file mode 100644 index 0000000000..3bc04ac129 --- /dev/null +++ b/clojure/ring/README.md @@ -0,0 +1,16 @@ +# Clojure Ring Examples + +This project acts as a set of examples for the Clojure Ring library. + +## Runing the examples + +The examples can all be run from the Leiningen REPL. + +Firstly, start the REPL with `lein repl`. Then the examples can be executed with: + +* `(run simple-handler)` - A simple handler that just echos a constant string to the client +* `(run check-ip-handler)` - A handler that echos the clients IP Address back to them +* `(run echo-handler)` - A handler that echos the value of the "input" parameter back +* `(run request-count-handler)` - A handler with a session that tracks how many times this session has requested this handler + +In all cases, the handlers can be accessed on http://localhost:3000. diff --git a/clojure/ring/project.clj b/clojure/ring/project.clj new file mode 100644 index 0000000000..7f2fcc4263 --- /dev/null +++ b/clojure/ring/project.clj @@ -0,0 +1,8 @@ +(defproject baeldung-ring "0.1.0-SNAPSHOT" + :dependencies [[org.clojure/clojure "1.10.0"] + [ring/ring-core "1.7.1"] + [ring/ring-jetty-adapter "1.7.1"] + [ring/ring-devel "1.7.1"]] + :plugins [[lein-ring "0.12.5"]] + :ring {:handler ring.core/simple-handler} + :repl-options {:init-ns ring.core}) diff --git a/clojure/ring/src/ring/core.clj b/clojure/ring/src/ring/core.clj new file mode 100644 index 0000000000..a56e2f2bde --- /dev/null +++ b/clojure/ring/src/ring/core.clj @@ -0,0 +1,48 @@ +(ns ring.core + (:use ring.adapter.jetty + [ring.middleware.content-type] + [ring.middleware.cookies] + [ring.middleware.params] + [ring.middleware.session] + [ring.middleware.session.cookie] + [ring.util.response])) + +;; Handler that just echos back the string "Hello World" +(defn simple-handler [request] + {:status 200 + :headers {"Content-Type" "text/plain"} + :body "Hello World"}) + +;; Handler that echos back the clients IP Address +;; This demonstrates building responses properly, and extracting values from the request +(defn check-ip-handler [request] + (content-type + (response (:remote-addr request)) + "text/plain")) + +;; Handler that echos back the incoming parameter "input" +;; This demonstrates middleware chaining and accessing parameters +(def echo-handler + (-> (fn [{params :params}] + (content-type + (response (get params "input")) + "text/plain")) + (wrap-params {:encoding "UTF-8"}) + )) + +;; Handler that keeps track of how many times each session has accessed the service +;; This demonstrates cookies and sessions +(def request-count-handler + (-> (fn [{session :session}] + (let [count (:count session 0) + session (assoc session :count (inc count))] + (-> (response (str "You accessed this page " count " times.")) + (assoc :session session)))) + wrap-cookies + (wrap-session {:cookie-attrs {:max-age 3600}}) + )) + +;; Run the provided handler on port 3000 +(defn run + [h] + (run-jetty h {:port 3000})) From b0c8a8473216d87c0223290a091db5d89aee1af2 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Fri, 24 May 2019 22:06:10 +0300 Subject: [PATCH 070/167] Update README.md --- testing-modules/junit-5-basics/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/testing-modules/junit-5-basics/README.md b/testing-modules/junit-5-basics/README.md index a00e2a3f4a..6e44a9c071 100644 --- a/testing-modules/junit-5-basics/README.md +++ b/testing-modules/junit-5-basics/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Get the Path of the /src/test/resources Directory in JUnit](https://www.baeldung.com/junit-src-test-resources-directory-path) +- [Tagging and Filtering JUnit Tests](https://www.baeldung.com/junit-filtering-tests) From 97358119cefe8142a14743c33af83cf898e9a292 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Fri, 24 May 2019 22:08:43 +0300 Subject: [PATCH 071/167] Update README.md --- clojure/ring/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/clojure/ring/README.md b/clojure/ring/README.md index 3bc04ac129..20263c6b95 100644 --- a/clojure/ring/README.md +++ b/clojure/ring/README.md @@ -14,3 +14,6 @@ Firstly, start the REPL with `lein repl`. Then the examples can be executed with * `(run request-count-handler)` - A handler with a session that tracks how many times this session has requested this handler In all cases, the handlers can be accessed on http://localhost:3000. + +## Relevant Articles +- [Writing Clojure Webapps with Ring](https://www.baeldung.com/clojure-ring) From 8ce748420592a04edcf6139765e6e9b241d6b64d Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 25 May 2019 21:32:32 +0300 Subject: [PATCH 072/167] downgrade surefire version --- .../{SubstringSearch.java => SubstringSearchUnitTest.java} | 2 +- pom.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) rename java-strings-2/src/test/java/com/baeldung/string/search/{SubstringSearch.java => SubstringSearchUnitTest.java} (98%) diff --git a/java-strings-2/src/test/java/com/baeldung/string/search/SubstringSearch.java b/java-strings-2/src/test/java/com/baeldung/string/search/SubstringSearchUnitTest.java similarity index 98% rename from java-strings-2/src/test/java/com/baeldung/string/search/SubstringSearch.java rename to java-strings-2/src/test/java/com/baeldung/string/search/SubstringSearchUnitTest.java index 4a5adb45ef..293e6d2125 100644 --- a/java-strings-2/src/test/java/com/baeldung/string/search/SubstringSearch.java +++ b/java-strings-2/src/test/java/com/baeldung/string/search/SubstringSearchUnitTest.java @@ -10,7 +10,7 @@ import org.junit.Test; /** * BAEL-2832: Different ways to check if a Substring could be found in a String. */ -public class SubstringSearch { +public class SubstringSearchUnitTest { @Test public void searchSubstringWithIndexOf() { diff --git a/pom.xml b/pom.xml index bdd7562486..92876cd07f 100644 --- a/pom.xml +++ b/pom.xml @@ -1527,7 +1527,7 @@ 1.1.7 - 2.22.0 + 2.21.0 3.7.0 1.6.0 1.8 @@ -1538,7 +1538,7 @@ 1.19 1.3 1.6.0 - 2.19.1 + 2.21.0 2.5 1.4 3.0.0 From 148ff421e054dcade28e97de8463ed75d332938a Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 25 May 2019 21:34:44 +0300 Subject: [PATCH 073/167] fix formatting --- .../com/baeldung/logging/slf4j/Slf4jLogger.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java b/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java index 1ff1087367..db19613c94 100644 --- a/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java +++ b/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java @@ -75,8 +75,6 @@ public class Slf4jLogger implements System.Logger { if (!isLoggable(level)) { return; } - String message = MessageFormat.format (format, params); - String message = MessageFormat.format(format, params); switch (level) { From 3471c4d22a5be5461089a2bc337216e9019c82e0 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 25 May 2019 21:52:00 +0300 Subject: [PATCH 074/167] update readme --- README.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 378d77196a..1030cbb09c 100644 --- a/README.md +++ b/README.md @@ -20,17 +20,22 @@ In additional to Spring, the following technologies are in focus: `core Java`, ` Building the project ==================== -To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false` +To do the full build, do: `mvn clean install` Building a single module ==================== -To build a specific module run the command: `mvn clean install -Dgib.enabled=false` in the module directory +To build a specific module run the command: `mvn clean install` in the module directory Running a Spring Boot module ==================== -To run a Spring Boot module run the command: `mvn spring-boot:run -Dgib.enabled=false` in the module directory +To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory + +#Running Tests + +The command `mvn clean install` will run the unit tests in a module. +To run the integration tests, use the command `mvn clean install -Pintegration-lite-first` From 924c78c996220210ab6ae59fcea0fe998e980626 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 25 May 2019 21:53:30 +0300 Subject: [PATCH 075/167] fix formatting --- .../com/baeldung/logging/slf4j/Slf4jLogger.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java b/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java index 1ff1087367..db19613c94 100644 --- a/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java +++ b/core-java-modules/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java @@ -75,8 +75,6 @@ public class Slf4jLogger implements System.Logger { if (!isLoggable(level)) { return; } - String message = MessageFormat.format (format, params); - String message = MessageFormat.format(format, params); switch (level) { From 653717e25ef14bf7aadaed736d268fb9fe4a371c Mon Sep 17 00:00:00 2001 From: Gian Mario Contessa Date: Sun, 26 May 2019 01:09:20 +0100 Subject: [PATCH 076/167] BAEL-2899: adding some more case scenarios --- java-groovy-joint/gmavenplus-pom.xml | 148 ++++++++++++++++++ java-groovy-joint/pom.xml | 1 + .../groovy/com.baeldung/CalcScript.groovy | 19 --- .../baeldung}/CalcMath.groovy | 6 + .../groovy/com/baeldung/CalcScript.groovy | 10 ++ .../src/main/java/com/baeldung/App.java | 74 +++++++-- 6 files changed, 228 insertions(+), 30 deletions(-) create mode 100644 java-groovy-joint/gmavenplus-pom.xml delete mode 100644 java-groovy-joint/src/main/groovy/com.baeldung/CalcScript.groovy rename java-groovy-joint/src/main/groovy/{com.baeldung => com/baeldung}/CalcMath.groovy (76%) create mode 100644 java-groovy-joint/src/main/groovy/com/baeldung/CalcScript.groovy diff --git a/java-groovy-joint/gmavenplus-pom.xml b/java-groovy-joint/gmavenplus-pom.xml new file mode 100644 index 0000000000..b34eeb292d --- /dev/null +++ b/java-groovy-joint/gmavenplus-pom.xml @@ -0,0 +1,148 @@ + + + + 4.0.0 + java-groovy-joint + 0.1.0-SNAPSHOT + java-groovy-joint + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + UTF-8 + 3.9 + 1.8 + 3.8.1 + 1.2.3 + 2.5.7 + + + + + bintray + Groovy Bintray + https://dl.bintray.com/groovy/maven + + never + + + false + + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + org.codehaus.groovy + groovy-all + ${groovy.version} + pom + + + junit + junit + 4.11 + test + + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.1.2 + + + + com.baeldung.App + true + + + + + + org.codehaus.gmavenplus + gmavenplus-plugin + 1.7.0 + + + + execute + addSources + addTestSources + generateStubs + compile + generateTestStubs + compileTests + removeStubs + removeTestStubs + + + + + + org.codehaus.groovy + groovy-all + + 2.5.6 + runtime + pom + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 3.1.0 + + + + jar-with-dependencies + + + + + com.baeldung.App + + + + + + + make-assembly + + package + + single + + + + + + + + + diff --git a/java-groovy-joint/pom.xml b/java-groovy-joint/pom.xml index 67365cf999..5ac4768865 100644 --- a/java-groovy-joint/pom.xml +++ b/java-groovy-joint/pom.xml @@ -27,6 +27,7 @@ Groovy Bintray https://dl.bintray.com/groovy/maven + never diff --git a/java-groovy-joint/src/main/groovy/com.baeldung/CalcScript.groovy b/java-groovy-joint/src/main/groovy/com.baeldung/CalcScript.groovy deleted file mode 100644 index 2278f0dab8..0000000000 --- a/java-groovy-joint/src/main/groovy/com.baeldung/CalcScript.groovy +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung - -import org.slf4j.LoggerFactory - -abstract class CalcScript extends Script { - def log = LoggerFactory.getLogger(this.getClass()) - - def calcSum(x, y) { - log.info "Executing $x + $y" - x + y - } - - def calcSum2(x, y) { - log.info "Executing $x + $y" - // DANGER! This won't throw a compilation issue and fail only at runtime!!! - calcSum3() - log.info("Logging an undefined variable: $z") - } -} \ No newline at end of file diff --git a/java-groovy-joint/src/main/groovy/com.baeldung/CalcMath.groovy b/java-groovy-joint/src/main/groovy/com/baeldung/CalcMath.groovy similarity index 76% rename from java-groovy-joint/src/main/groovy/com.baeldung/CalcMath.groovy rename to java-groovy-joint/src/main/groovy/com/baeldung/CalcMath.groovy index d9709653c7..0e233793b2 100644 --- a/java-groovy-joint/src/main/groovy/com.baeldung/CalcMath.groovy +++ b/java-groovy-joint/src/main/groovy/com/baeldung/CalcMath.groovy @@ -10,6 +10,12 @@ class CalcMath { x + y } + /** + * example of method that in java would throw error at compile time + * @param x + * @param y + * @return + */ def calcSum2(x, y) { log.info "Executing $x + $y" // DANGER! This won't throw a compilation issue and fail only at runtime!!! diff --git a/java-groovy-joint/src/main/groovy/com/baeldung/CalcScript.groovy b/java-groovy-joint/src/main/groovy/com/baeldung/CalcScript.groovy new file mode 100644 index 0000000000..688928468a --- /dev/null +++ b/java-groovy-joint/src/main/groovy/com/baeldung/CalcScript.groovy @@ -0,0 +1,10 @@ +package com.baeldung + +def calcSum(x, y) { + x + y +} + +def calcSum2(x, y) { + // DANGER! This won't throw a compilation issue and fail only at runtime!!! + calcSum3() +} diff --git a/java-groovy-joint/src/main/java/com/baeldung/App.java b/java-groovy-joint/src/main/java/com/baeldung/App.java index 0a201d12e2..7cfeba2024 100644 --- a/java-groovy-joint/src/main/java/com/baeldung/App.java +++ b/java-groovy-joint/src/main/java/com/baeldung/App.java @@ -1,12 +1,20 @@ package com.baeldung; -import groovy.lang.Binding; -import groovy.lang.GroovyClassLoader; -import groovy.lang.GroovyShell; +import groovy.lang.*; +import groovy.util.GroovyScriptEngine; +import groovy.util.ResourceException; +import groovy.util.ScriptException; import org.codehaus.groovy.control.CompilerConfiguration; +import org.codehaus.groovy.jsr223.GroovyScriptEngineFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.script.Compilable; +import javax.script.ScriptEngine; +import java.io.File; +import java.io.IOException; +import java.net.URL; + /** * Hello world! * @@ -15,40 +23,84 @@ public class App { private final static Logger LOG = LoggerFactory.getLogger(App.class); private final GroovyClassLoader loader; private final GroovyShell shell; + private final GroovyScriptEngine engine; - private App() { + private App() throws IOException { loader = new GroovyClassLoader(this.getClass().getClassLoader()); CompilerConfiguration config = new CompilerConfiguration(); config.setScriptBaseClass("com.baeldung.CalcScript"); shell = new GroovyShell(loader, new Binding(), config); + engine = new GroovyScriptEngine(new URL[] { new File("src/main/groovy/com/baeldung/").toURI().toURL() }, this.getClass().getClassLoader()); } - private void runScript(int x, int y) { - Object script = shell.parse(String.format("calcSum(%d,%d)", x, y)); + private void runCompiledClasses(int x, int y) { + Object result1 = new CalcScript().calcSum(x, y); + LOG.info("Result of calcSum() method is {}", result1); + + Object result2 = new CalcMath().calcSum(x, y); + LOG.info("Result of calcSum() method is {}", result2); + } + + private void runShellScript(int x, int y) { + Script script = shell.parse(String.format("calcSum(%d,%d)", x, y)); assert script instanceof CalcScript; - Object result = ((CalcScript) script).run(); + Object result = script.run(); LOG.info("Result of run() method is {}", result); Object script2 = shell.parse("CalcScript"); + assert script2 instanceof CalcScript; Object result2 = ((CalcScript) script2).calcSum(x + 7, y + 7); LOG.info("Result of calcSum() method is {}", result2); + Script script3 = shell.parse(""); + assert script3 instanceof CalcScript; + Object result3 = script3.invokeMethod("calcSum", new Object[] { x + 14, y + 14 }); + LOG.info("Result of run() method is {}", result3); + } - private void runClass(int x, int y) throws ClassNotFoundException, IllegalAccessException, InstantiationException { + private void runClassWithLoader(int x, int y) throws ClassNotFoundException, IllegalAccessException, InstantiationException { Class calcClass = loader.loadClass("com.baeldung.CalcMath"); Object calc = calcClass.newInstance(); assert calc instanceof CalcMath; Object result = ((CalcMath) calc).calcSum(x, y); LOG.info("Result is {}", result); + + Object result2 = ((GroovyObject) calc).invokeMethod("calcSum", new Object[] { x + 14, y + 14 }); + LOG.info("Result is {}", result2); + } - public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { + private void runClassWithEngine(int x, int y) throws ClassNotFoundException, IllegalAccessException, InstantiationException, ResourceException, ScriptException { + + Class calcClass = engine.loadScriptByName("CalcMath.groovy"); + GroovyObject calc = calcClass.newInstance(); + Object result = calc.invokeMethod("calcSum", new Object[] { x, y }); + //WARNING the following will throw a ClassCastException + //((CalcMath)calc).calcSum(1,2); + LOG.info("Result is {}", result); + } + + private void runClassWithEngineFactory(int x, int y) throws ClassNotFoundException, IllegalAccessException, InstantiationException, ResourceException, ScriptException, javax.script.ScriptException { + ScriptEngine engine = new GroovyScriptEngineFactory().getScriptEngine(); + Class calcClass = (Class) ((Compilable) engine).compile("com.baeldung.CalcMath").eval(); + Object calc = calcClass.newInstance(); + Object result = ((CalcMath) calc).calcSum(1, 20); + LOG.info("Result is {}", result); + } + + public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, ResourceException, ScriptException, IOException, javax.script.ScriptException { App app = new App(); + LOG.info("Running an already compiled groovy class instance..."); + app.runCompiledClasses(5, 10); LOG.info("Running a groovy script..."); - app.runScript(5, 10); + app.runShellScript(5, 10); LOG.info("Running a groovy class..."); - app.runClass(1, 3); + app.runClassWithLoader(1, 3); + LOG.info("Running a groovy class using the engine..."); + app.runClassWithEngine(10, 30); + LOG.info("Running a groovy class using the engine factory..."); + app.runClassWithEngineFactory(10, 30); } } From fe2cf943d8423ef04c4c63c5532fa5d355bf253e Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 26 May 2019 11:57:20 +0530 Subject: [PATCH 077/167] [BAEL-14777] - Added Thymeleaf example and added reoved xmls and commented out codes --- spring-security-rest-custom/pom.xml | 8 +++ .../org/baeldung/config/child/WebConfig.java | 41 +++++++++++++++ .../config/parent/SecurityConfig.java | 1 + .../web/controller/ViewController.java | 13 +++++ .../src/main/resources/prop.xml | 13 +++++ .../src/main/resources/webSecurityConfig.xml | 4 +- .../main/webapp/WEB-INF/templates/index.html | 7 +++ .../src/main/webapp/WEB-INF/web_old.xml | 51 +++++++++++++++++++ 8 files changed, 136 insertions(+), 2 deletions(-) create mode 100644 spring-security-rest-custom/src/main/java/org/baeldung/web/controller/ViewController.java create mode 100644 spring-security-rest-custom/src/main/resources/prop.xml create mode 100644 spring-security-rest-custom/src/main/webapp/WEB-INF/templates/index.html create mode 100644 spring-security-rest-custom/src/main/webapp/WEB-INF/web_old.xml diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index 38cbfddab8..2180b917e5 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -26,6 +26,14 @@ org.springframework.security spring-security-config + + org.thymeleaf.extras + thymeleaf-extras-springsecurity5 + + + org.thymeleaf + thymeleaf-spring5 + diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/config/child/WebConfig.java b/spring-security-rest-custom/src/main/java/org/baeldung/config/child/WebConfig.java index 6688d41ffa..7cbbcf31fa 100644 --- a/spring-security-rest-custom/src/main/java/org/baeldung/config/child/WebConfig.java +++ b/spring-security-rest-custom/src/main/java/org/baeldung/config/child/WebConfig.java @@ -2,19 +2,34 @@ package org.baeldung.config.child; import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.thymeleaf.extras.springsecurity5.dialect.SpringSecurityDialect; +import org.thymeleaf.spring5.ISpringTemplateEngine; +import org.thymeleaf.spring5.SpringTemplateEngine; +import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; +import org.thymeleaf.spring5.view.ThymeleafViewResolver; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ITemplateResolver; @Configuration @EnableWebMvc @ComponentScan("org.baeldung.web") +//@ImportResource({ "classpath:prop.xml" }) +//@PropertySource("classpath:foo.properties") public class WebConfig implements WebMvcConfigurer { + + @Autowired + private ApplicationContext applicationContext; public WebConfig() { super(); @@ -35,5 +50,31 @@ public class WebConfig implements WebMvcConfigurer { ppc.setIgnoreUnresolvablePlaceholders(true); return ppc; } + + @Bean + public ViewResolver viewResolver() { + ThymeleafViewResolver resolver = new ThymeleafViewResolver(); + resolver.setTemplateEngine(templateEngine()); + resolver.setCharacterEncoding("UTF-8"); + return resolver; + } + + @Bean + public ISpringTemplateEngine templateEngine() { + SpringTemplateEngine engine = new SpringTemplateEngine(); + engine.setEnableSpringELCompiler(true); + engine.setTemplateResolver(templateResolver()); + engine.addDialect(new SpringSecurityDialect()); + return engine; + } + + private ITemplateResolver templateResolver() { + SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); + resolver.setApplicationContext(applicationContext); + resolver.setPrefix("/WEB-INF/templates/"); + resolver.setSuffix(".html"); + resolver.setTemplateMode(TemplateMode.HTML); + return resolver; + } } \ No newline at end of file diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java index 74e2df2174..fb3880a33f 100644 --- a/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java +++ b/spring-security-rest-custom/src/main/java/org/baeldung/config/parent/SecurityConfig.java @@ -10,6 +10,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration +//@ImportResource({ "classpath:webSecurityConfig.xml" }) @EnableWebSecurity @ComponentScan("org.baeldung.security") public class SecurityConfig extends WebSecurityConfigurerAdapter { diff --git a/spring-security-rest-custom/src/main/java/org/baeldung/web/controller/ViewController.java b/spring-security-rest-custom/src/main/java/org/baeldung/web/controller/ViewController.java new file mode 100644 index 0000000000..83c0292d98 --- /dev/null +++ b/spring-security-rest-custom/src/main/java/org/baeldung/web/controller/ViewController.java @@ -0,0 +1,13 @@ +package org.baeldung.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class ViewController { + + @RequestMapping({ "/index", "/" }) + public String index() { + return "index"; + } +} diff --git a/spring-security-rest-custom/src/main/resources/prop.xml b/spring-security-rest-custom/src/main/resources/prop.xml new file mode 100644 index 0000000000..edaecde655 --- /dev/null +++ b/spring-security-rest-custom/src/main/resources/prop.xml @@ -0,0 +1,13 @@ + + + + + + \ No newline at end of file diff --git a/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml b/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml index fa5dc894bf..790b1b1716 100644 --- a/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml +++ b/spring-security-rest-custom/src/main/resources/webSecurityConfig.xml @@ -2,9 +2,9 @@ diff --git a/spring-security-rest-custom/src/main/webapp/WEB-INF/templates/index.html b/spring-security-rest-custom/src/main/webapp/WEB-INF/templates/index.html new file mode 100644 index 0000000000..31cb66ae0a --- /dev/null +++ b/spring-security-rest-custom/src/main/webapp/WEB-INF/templates/index.html @@ -0,0 +1,7 @@ + + + +
Authenticated as
+ + \ No newline at end of file diff --git a/spring-security-rest-custom/src/main/webapp/WEB-INF/web_old.xml b/spring-security-rest-custom/src/main/webapp/WEB-INF/web_old.xml new file mode 100644 index 0000000000..0fa9abd258 --- /dev/null +++ b/spring-security-rest-custom/src/main/webapp/WEB-INF/web_old.xml @@ -0,0 +1,51 @@ + + + + Spring Security Custom Application + + + + contextClass + + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + + contextConfigLocation + org.baeldung.config.parent + + + + org.springframework.web.context.ContextLoaderListener + + + + + api + org.springframework.web.servlet.DispatcherServlet + + + + + 1 + + + api + /api/* + + + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + + + \ No newline at end of file From 066cf2d6f2d9122a648ce016aa31412cd22bd4c2 Mon Sep 17 00:00:00 2001 From: Matt Zhang Date: Sun, 26 May 2019 22:14:10 +1000 Subject: [PATCH 078/167] BAEL-2878 Guide to Spring's ApplicationContextRunner --- .../autoconfiguration/ConditionalOnBeanIntegrationTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanIntegrationTest.java b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanIntegrationTest.java index c94b432b9d..32f63edde4 100644 --- a/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanIntegrationTest.java +++ b/spring-boot-autoconfiguration/src/test/java/com/baeldung/autoconfiguration/ConditionalOnBeanIntegrationTest.java @@ -15,7 +15,7 @@ public class ConditionalOnBeanIntegrationTest { @Test public void whenDependentBeanIsPresent_thenConditionalBeanCreated() { - this.contextRunner.withUserConfiguration(basicConfiguration.class, ConditionalOnBeanConfiguration.class) + this.contextRunner.withUserConfiguration(BasicConfiguration.class, ConditionalOnBeanConfiguration.class) .run((context) -> { assertThat(context).hasBean("created"); assertThat(context).getBean("created") @@ -28,7 +28,7 @@ public class ConditionalOnBeanIntegrationTest { @Test public void whenDependentBeanIsPresent_thenConditionalMissingBeanIgnored() { - this.contextRunner.withUserConfiguration(basicConfiguration.class, ConditionalOnMissingBeanConfiguration.class) + this.contextRunner.withUserConfiguration(BasicConfiguration.class, ConditionalOnMissingBeanConfiguration.class) .run((context) -> { assertThat(context).hasBean("created"); assertThat(context).getBean("created") @@ -49,7 +49,7 @@ public class ConditionalOnBeanIntegrationTest { } @Configuration - protected static class basicConfiguration { + protected static class BasicConfiguration { @Bean public String created() { return "This is always created"; From f4c7976dfe9cc892a492ad7538581c07128a7596 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sun, 26 May 2019 17:34:11 +0300 Subject: [PATCH 079/167] fix parent readmes --- patterns/README.md | 6 ------ patterns/design-patterns-2/README.md | 2 ++ patterns/dip/README.md | 3 +++ patterns/front-controller/README.md | 2 ++ patterns/intercepting-filter/README.md | 2 ++ patterns/{principles => }/solid/README.md | 0 persistence-modules/README.md | 17 --------------- .../hibernate-mapping/README.md | 1 + persistence-modules/java-jdbi/README.md | 2 ++ .../spring-data-jpa-2/README.md | 1 + .../spring-hibernate-5/README.md | 1 + spring-cloud/README.md | 21 ------------------- spring-cloud/spring-cloud-aws/README.md | 1 + spring-cloud/spring-cloud-config/README.md | 1 + spring-cloud/spring-cloud-openfeign/README.md | 4 ++++ spring-rest/README.md | 1 + .../java/com/baeldung/produceimage/README.md | 3 --- 17 files changed, 21 insertions(+), 47 deletions(-) delete mode 100644 patterns/README.md create mode 100644 patterns/dip/README.md create mode 100644 patterns/front-controller/README.md create mode 100644 patterns/intercepting-filter/README.md rename patterns/{principles => }/solid/README.md (100%) delete mode 100644 persistence-modules/README.md delete mode 100644 spring-cloud/README.md create mode 100644 spring-cloud/spring-cloud-openfeign/README.md delete mode 100644 spring-rest/src/main/java/com/baeldung/produceimage/README.md diff --git a/patterns/README.md b/patterns/README.md deleted file mode 100644 index f627251aa4..0000000000 --- a/patterns/README.md +++ /dev/null @@ -1,6 +0,0 @@ -### Relevant Articles: -- [A Guide to the Front Controller Pattern in Java](http://www.baeldung.com/java-front-controller-pattern) -- [Introduction to Intercepting Filter Pattern in Java](http://www.baeldung.com/intercepting-filter-pattern-in-java) -- [Introduction to the Null Object Pattern](https://www.baeldung.com/java-null-object-pattern) -- [The Dependency Inversion Principle in Java](https://www.baeldung.com/java-dependency-inversion-principle) -- [Avoid Check for Null Statement in Java](https://www.baeldung.com/java-avoid-null-check) diff --git a/patterns/design-patterns-2/README.md b/patterns/design-patterns-2/README.md index c2a75d4680..8e4ef657e1 100644 --- a/patterns/design-patterns-2/README.md +++ b/patterns/design-patterns-2/README.md @@ -1,3 +1,5 @@ ### Relevant Articles - [The Mediator Pattern in Java](https://www.baeldung.com/java-mediator-pattern) +- [Introduction to the Null Object Pattern](https://www.baeldung.com/java-null-object-pattern) +- [Avoid Check for Null Statement in Java](https://www.baeldung.com/java-avoid-null-check) diff --git a/patterns/dip/README.md b/patterns/dip/README.md new file mode 100644 index 0000000000..8876bbe766 --- /dev/null +++ b/patterns/dip/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [The Dependency Inversion Principle in Java](https://www.baeldung.com/java-dependency-inversion-principle) diff --git a/patterns/front-controller/README.md b/patterns/front-controller/README.md new file mode 100644 index 0000000000..5f8cb5d568 --- /dev/null +++ b/patterns/front-controller/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [A Guide to the Front Controller Pattern in Java](http://www.baeldung.com/java-front-controller-pattern) diff --git a/patterns/intercepting-filter/README.md b/patterns/intercepting-filter/README.md new file mode 100644 index 0000000000..88b7f58469 --- /dev/null +++ b/patterns/intercepting-filter/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Introduction to Intercepting Filter Pattern in Java](http://www.baeldung.com/intercepting-filter-pattern-in-java) diff --git a/patterns/principles/solid/README.md b/patterns/solid/README.md similarity index 100% rename from patterns/principles/solid/README.md rename to patterns/solid/README.md diff --git a/persistence-modules/README.md b/persistence-modules/README.md deleted file mode 100644 index e9a7d625cc..0000000000 --- a/persistence-modules/README.md +++ /dev/null @@ -1,17 +0,0 @@ - -## Persistence Modules - - -### Relevant Articles: - -- [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search) -- [Introduction to Lettuce – the Java Redis Client](http://www.baeldung.com/java-redis-lettuce) -- [A Guide to Jdbi](http://www.baeldung.com/jdbi) -- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) -- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all) -- [Spring Data with Reactive Cassandra](https://www.baeldung.com/spring-data-cassandra-reactive) -- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby) -- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush) -- [Spring Boot with Hibernate](https://www.baeldung.com/spring-boot-hibernate) -- [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps) -- [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences) diff --git a/persistence-modules/hibernate-mapping/README.md b/persistence-modules/hibernate-mapping/README.md index 223d93e1ed..203cb2f8e4 100644 --- a/persistence-modules/hibernate-mapping/README.md +++ b/persistence-modules/hibernate-mapping/README.md @@ -2,3 +2,4 @@ ### Relevant Articles: - [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps) +- [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences) diff --git a/persistence-modules/java-jdbi/README.md b/persistence-modules/java-jdbi/README.md index 7d843af9ea..4c1ff931ce 100644 --- a/persistence-modules/java-jdbi/README.md +++ b/persistence-modules/java-jdbi/README.md @@ -1 +1,3 @@ ### Relevant Articles: + +- [A Guide to Jdbi](http://www.baeldung.com/jdbi) diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md index 393d15d6f1..e4381be0a9 100644 --- a/persistence-modules/spring-data-jpa-2/README.md +++ b/persistence-modules/spring-data-jpa-2/README.md @@ -12,3 +12,4 @@ - [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections) - [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable) - [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete) +- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush) diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md index c48e58fcca..dfcc4e7eb8 100644 --- a/persistence-modules/spring-hibernate-5/README.md +++ b/persistence-modules/spring-hibernate-5/README.md @@ -3,3 +3,4 @@ - [Hibernate Many to Many Annotation Tutorial](http://www.baeldung.com/hibernate-many-to-many) - [Programmatic Transactions in the Spring TestContext Framework](http://www.baeldung.com/spring-test-programmatic-transactions) - [JPA Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) +- [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search) diff --git a/spring-cloud/README.md b/spring-cloud/README.md deleted file mode 100644 index 5139cdca20..0000000000 --- a/spring-cloud/README.md +++ /dev/null @@ -1,21 +0,0 @@ -## The Module Holds Sources for the Following Articles - -- [Quick Intro to Spring Cloud Configuration](http://www.baeldung.com/spring-cloud-configuration) - - Spring Cloud Config is Spring’s client/server approach for storing and serving distributed configurations across multiple applications and environments. - - In this write-up, we’ll focus on an example of how to setup a Git-backed config server, use it in a simple REST application server and setup a secure environment including encrypted property values. - -- [Introduction to Spring Cloud Netflix – Eureka](http://www.baeldung.com/spring-cloud-netflix-eureka) - - In this article, we’ll introduce client-side service discovery via “Spring Cloud Netflix Eureka“. - - Client-side service discovery allows services to find and communicate with each other without hardcoding hostname and port. The only ‘fixed point’ in such an architecture consists of a service registry with which each service has to register. - -### Relevant Articles: -- [Intro to Spring Cloud Netflix - Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix) -- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) -- [Instance Profile Credentials using Spring Cloud](http://www.baeldung.com/spring-cloud-instance-profiles) -- [Running Spring Boot Applications With Minikube](http://www.baeldung.com/spring-boot-minikube) -- [Introduction to Spring Cloud OpenFeign](https://www.baeldung.com/spring-cloud-openfeign) - diff --git a/spring-cloud/spring-cloud-aws/README.md b/spring-cloud/spring-cloud-aws/README.md index 3b7b4dbcd7..bf33728c74 100644 --- a/spring-cloud/spring-cloud-aws/README.md +++ b/spring-cloud/spring-cloud-aws/README.md @@ -5,6 +5,7 @@ - [Spring Cloud AWS – EC2](https://www.baeldung.com/spring-cloud-aws-ec2) - [Spring Cloud AWS – RDS](https://www.baeldung.com/spring-cloud-aws-rds) - [Spring Cloud AWS – Messaging Support](https://www.baeldung.com/spring-cloud-aws-messaging) +- [Instance Profile Credentials using Spring Cloud](http://www.baeldung.com/spring-cloud-instance-profiles) #### Running the Integration Tests diff --git a/spring-cloud/spring-cloud-config/README.md b/spring-cloud/spring-cloud-config/README.md index b28c750ee6..b7c8c36e65 100644 --- a/spring-cloud/spring-cloud-config/README.md +++ b/spring-cloud/spring-cloud-config/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: +- [Quick Intro to Spring Cloud Configuration](http://www.baeldung.com/spring-cloud-configuration) - [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) diff --git a/spring-cloud/spring-cloud-openfeign/README.md b/spring-cloud/spring-cloud-openfeign/README.md new file mode 100644 index 0000000000..e5777732e4 --- /dev/null +++ b/spring-cloud/spring-cloud-openfeign/README.md @@ -0,0 +1,4 @@ +### Relevant Articles: + +- [Introduction to Spring Cloud OpenFeign](https://www.baeldung.com/spring-cloud-openfeign) + diff --git a/spring-rest/README.md b/spring-rest/README.md index 6d3aac3eb8..5d7894cdf8 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -21,3 +21,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Get and Post Lists of Objects with RestTemplate](http://www.baeldung.com/spring-rest-template-list) - [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header) - [Uploading MultipartFile with Spring RestTemplate](http://www.baeldung.com/spring-rest-template-multipart-upload) +- [Download an Image or a File with Spring MVC](http://www.baeldung.com/spring-controller-return-image-file) diff --git a/spring-rest/src/main/java/com/baeldung/produceimage/README.md b/spring-rest/src/main/java/com/baeldung/produceimage/README.md deleted file mode 100644 index 4aeadea546..0000000000 --- a/spring-rest/src/main/java/com/baeldung/produceimage/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant articles - -- [Download an Image or a File with Spring MVC](http://www.baeldung.com/spring-controller-return-image-file) From 9b7a362b4d3c18029fe7b89d34a4bdf4c695ea23 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sun, 26 May 2019 17:54:15 +0300 Subject: [PATCH 080/167] add surefire comment --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 92876cd07f..39803fd9b0 100644 --- a/pom.xml +++ b/pom.xml @@ -1527,6 +1527,7 @@ 1.1.7 + 2.21.0 3.7.0 1.6.0 From 8ac77800a0a6a3f1e114fab18d7a721949302780 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sun, 26 May 2019 19:38:40 +0300 Subject: [PATCH 081/167] fix remove vertex --- .../main/java/com/baeldung/graph/Graph.java | 2 +- ...versalUnitTest.java => GraphUnitTest.java} | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) rename core-java-modules/core-java/src/test/java/com/baeldung/graph/{GraphTraversalUnitTest.java => GraphUnitTest.java} (61%) diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/graph/Graph.java b/core-java-modules/core-java/src/main/java/com/baeldung/graph/Graph.java index 3f2e17c43c..58713b1b3f 100644 --- a/core-java-modules/core-java/src/main/java/com/baeldung/graph/Graph.java +++ b/core-java-modules/core-java/src/main/java/com/baeldung/graph/Graph.java @@ -19,7 +19,7 @@ public class Graph { void removeVertex(String label) { Vertex v = new Vertex(label); - adjVertices.values().stream().map(e -> e.remove(v)).collect(Collectors.toList()); + adjVertices.values().stream().forEach(e -> e.remove(v)); adjVertices.remove(new Vertex(label)); } diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/graph/GraphTraversalUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/graph/GraphUnitTest.java similarity index 61% rename from core-java-modules/core-java/src/test/java/com/baeldung/graph/GraphTraversalUnitTest.java rename to core-java-modules/core-java/src/test/java/com/baeldung/graph/GraphUnitTest.java index d955d56d95..68611e508b 100644 --- a/core-java-modules/core-java/src/test/java/com/baeldung/graph/GraphTraversalUnitTest.java +++ b/core-java-modules/core-java/src/test/java/com/baeldung/graph/GraphUnitTest.java @@ -1,20 +1,31 @@ package com.baeldung.graph; -import org.junit.Assert; +import static org.junit.Assert.assertEquals; import org.junit.Test; -public class GraphTraversalUnitTest { +public class GraphUnitTest { @Test public void givenAGraph_whenTraversingDepthFirst_thenExpectedResult() { Graph graph = createGraph(); - Assert.assertEquals("[Bob, Rob, Maria, Alice, Mark]", + assertEquals("[Bob, Rob, Maria, Alice, Mark]", GraphTraversal.depthFirstTraversal(graph, "Bob").toString()); } @Test public void givenAGraph_whenTraversingBreadthFirst_thenExpectedResult() { Graph graph = createGraph(); - Assert.assertEquals("[Bob, Alice, Rob, Mark, Maria]", + assertEquals("[Bob, Alice, Rob, Mark, Maria]", + GraphTraversal.breadthFirstTraversal(graph, "Bob").toString()); + } + + @Test + public void givenAGraph_whenRemoveVertex_thenVertedNotFound() { + Graph graph = createGraph(); + assertEquals("[Bob, Alice, Rob, Mark, Maria]", + GraphTraversal.breadthFirstTraversal(graph, "Bob").toString()); + + graph.removeVertex("Maria"); + assertEquals("[Bob, Alice, Rob, Mark]", GraphTraversal.breadthFirstTraversal(graph, "Bob").toString()); } From 7ff1bc1aea5568146330db5f575edebc295e9be0 Mon Sep 17 00:00:00 2001 From: andrea-ligios Date: Sun, 26 May 2019 20:22:55 +0200 Subject: [PATCH 082/167] BAEL-2758 --- docker/docker-compose.yml | 61 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 docker/docker-compose.yml diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml new file mode 100644 index 0000000000..72d07d6392 --- /dev/null +++ b/docker/docker-compose.yml @@ -0,0 +1,61 @@ +version: '3' + +services: + +## VOLUME CONTAINER-TO-CONTAINER AND HOST-TO-CONTAINER TEST ## + + volumes-example-service: + image: alpine:latest + container_name: volumes-example-service + volumes: + - /tmp:/my-volumes/host-volume + - /home:/my-volumes/readonly-host-volume:ro + - my-named-global-volume:/my-volumes/named-global-volume + tty: true # Needed to keep the container running + + another-volumes-example-service: + image: alpine:latest + container_name: another-volumes-example-service + volumes: + - my-named-global-volume:/another-path/the-same-named-global-volume + tty: true # Needed to keep the container running + +## NETWORK CONTAINER-TO-CONTAINER TEST ## + + network-example-service: + image: karthequian/helloworld:latest + container_name: network-example-service + networks: + - my-shared-network + + another-service-in-the-same-network: + image: alpine:latest + container_name: another-service-in-the-same-network + networks: + - my-shared-network + + tty: true # Needed to keep the container running + + another-service-in-its-own-network: + image: alpine:latest + container_name: another-service-in-its-own-network + networks: + - my-private-network + tty: true # Needed to keep the container running + +## NETWORK HOST-TO-CONTAINER TEST ## + + network-example-service-available-to-host-on-port-1337: + image: karthequian/helloworld:latest + container_name: network-example-service-available-to-host-on-port-1337 + networks: + - my-shared-network + ports: + - "1337:80" + +volumes: + my-named-global-volume: + +networks: + my-shared-network: {} + my-private-network: {} From 0c1da760a6739d2f5a2e38e2eea77e3ebb286d14 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sun, 26 May 2019 21:37:30 +0200 Subject: [PATCH 083/167] geospatial mongoldb examples --- .../geo/MongoGeospatialIntegrationTest.java | 110 ++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 persistence-modules/java-mongodb/src/test/java/com/baeldung/geo/MongoGeospatialIntegrationTest.java diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/geo/MongoGeospatialIntegrationTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/geo/MongoGeospatialIntegrationTest.java new file mode 100644 index 0000000000..77cbe02e7f --- /dev/null +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/geo/MongoGeospatialIntegrationTest.java @@ -0,0 +1,110 @@ +package com.baeldung.geo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.bson.Document; +import org.junit.Before; +import org.junit.Test; + +import com.mongodb.MongoClient; +import com.mongodb.client.FindIterable; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.Indexes; +import com.mongodb.client.model.geojson.Point; +import com.mongodb.client.model.geojson.Polygon; +import com.mongodb.client.model.geojson.Position; + +public class MongoGeospatialIntegrationTest { + + private MongoClient mongoClient; + private MongoDatabase db; + private MongoCollection collection; + + @Before + public void setup() { + if (mongoClient == null) { + mongoClient = new MongoClient(); + db = mongoClient.getDatabase("myMongoDb"); + collection = db.getCollection("places"); + collection.deleteMany(new Document()); + collection.createIndex(Indexes.geo2dsphere("location")); + collection.insertOne(Document.parse("{'name':'Big Ben','location': {'coordinates':[-0.1268194,51.5007292],'type':'Point'}}")); + collection.insertOne(Document.parse("{'name':'Hyde Park','location': {'coordinates': [[[-0.159381,51.513126],[-0.189615,51.509928],[-0.187373,51.502442], [-0.153019,51.503464],[-0.159381,51.513126]]],'type':'Polygon'}}")); + } + } + + @Test + public void givenNearbyLocation_whenSearchNearby_thenFound() { + Point currentLoc = new Point(new Position(-0.126821, 51.495885)); + FindIterable result = collection.find(Filters.near("location", currentLoc, 1000.0, 10.0)); + + assertNotNull(result.first()); + assertEquals("Big Ben", result.first().get("name")); + } + + @Test + public void givenFarLocation_whenSearchNearby_thenNotFound() { + Point currentLoc = new Point(new Position(-0.5243333, 51.4700223)); + FindIterable result = collection.find(Filters.near("location", currentLoc, 5000.0, 10.0)); + + assertNull(result.first()); + } + + @Test + public void givenNearbyLocation_whenSearchWithinCircleSphere_thenFound() { + double distanceInRad = 5.0 / 6371; + FindIterable result = collection.find(Filters.geoWithinCenterSphere("location", -0.1435083, 51.4990956, distanceInRad)); + + assertNotNull(result.first()); + assertEquals("Big Ben", result.first().get("name")); + } + + @Test + public void givenNearbyLocation_whenSearchWithinBox_thenFound() { + double lowerLeftX = -0.1427638; + double lowerLeftY = 51.4991288; + double upperRightX = -0.1256209; + double upperRightY = 51.5030272; + + FindIterable result = collection.find(Filters.geoWithinBox("location", lowerLeftX, lowerLeftY, upperRightX, upperRightY)); + + assertNotNull(result.first()); + assertEquals("Big Ben", result.first().get("name")); + } + + @Test + public void givenNearbyLocation_whenSearchWithinPolygon_thenFound() { + ArrayList> points = new ArrayList>(); + points.add(Arrays.asList(-0.1439, 51.4952)); // victoria station + points.add(Arrays.asList(-0.1121, 51.4989));// Lambeth North + points.add(Arrays.asList(-0.13, 51.5163));// Tottenham Court Road + points.add(Arrays.asList(-0.1439, 51.4952)); // victoria station + FindIterable result = collection.find(Filters.geoWithinPolygon("location", points)); + + assertNotNull(result.first()); + assertEquals("Big Ben", result.first().get("name")); + } + + @Test + public void givenNearbyLocation_whenSearchUsingIntersect_thenFound() { + ArrayList positions = new ArrayList(); + positions.add(new Position(-0.1439, 51.4952)); + positions.add(new Position(-0.1346, 51.4978)); + positions.add(new Position(-0.2177, 51.5135)); + positions.add(new Position(-0.1439, 51.4952)); + Polygon geometry = new Polygon(positions); + FindIterable result = collection.find(Filters.geoIntersects("location", geometry)); + + assertNotNull(result.first()); + assertEquals("Hyde Park", result.first().get("name")); + } + +} From 5b11cef14bbbfbf5b5e6f7b1f8019a4dadb8fece Mon Sep 17 00:00:00 2001 From: mikr Date: Mon, 27 May 2019 00:32:25 +0200 Subject: [PATCH 084/167] BAEL-2891 Add a new section in the Mockito Annotations article --- .../mockito/MockitoInjectIntoSpyUnitTest.java | 38 +++++++++++++++++++ .../org/baeldung/mockito/MyDictionary.java | 4 ++ 2 files changed, 42 insertions(+) create mode 100644 testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java new file mode 100644 index 0000000000..4f5ceb04e7 --- /dev/null +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoInjectIntoSpyUnitTest.java @@ -0,0 +1,38 @@ +package org.baeldung.mockito; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.*; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +@RunWith(MockitoJUnitRunner.class) +public class MockitoInjectIntoSpyUnitTest { + + @Before + public void init() { + MockitoAnnotations.initMocks(this); + spyDic = Mockito.spy(new MyDictionary(wordMap)); + } + + @Mock + private Map wordMap; + + @InjectMocks + private MyDictionary dic = new MyDictionary(); + + private MyDictionary spyDic; + + @Test + public void whenUseInjectMocksAnnotation_thenCorrect2() { + Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning"); + + assertEquals("aMeaning", spyDic.getMeaning("aWord")); + } +} diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java index 8a0ea92502..9492c90d11 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java @@ -11,6 +11,10 @@ class MyDictionary { wordMap = new HashMap<>(); } + MyDictionary(Map wordMap) { + this.wordMap = wordMap; + } + public void add(final String word, final String meaning) { wordMap.put(word, meaning); } From 60d26bfd0988d13bfa764015464620a95df8a59d Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 27 May 2019 14:16:09 +0800 Subject: [PATCH 085/167] Delete README.md --- core-java-modules/core-java/src/main/java/com/baeldung/README.md | 1 - 1 file changed, 1 deletion(-) delete mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/README.md diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/README.md b/core-java-modules/core-java/src/main/java/com/baeldung/README.md deleted file mode 100644 index 7d843af9ea..0000000000 --- a/core-java-modules/core-java/src/main/java/com/baeldung/README.md +++ /dev/null @@ -1 +0,0 @@ -### Relevant Articles: From f6b9546f75f4f756900feadd1d8534dc1170e9c8 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 27 May 2019 14:17:22 +0800 Subject: [PATCH 086/167] Delete README.md --- .../core-java/src/main/java/com/baeldung/console/README.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/console/README.md diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/console/README.md b/core-java-modules/core-java/src/main/java/com/baeldung/console/README.md deleted file mode 100644 index 418892f288..0000000000 --- a/core-java-modules/core-java/src/main/java/com/baeldung/console/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Relevant articles: - -- [Console I/O in Java](https://www.baeldung.com/java-console-input-output) From 8a71e4d4375d7e70ee9f8acb85ba82b251f882af Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 27 May 2019 14:17:47 +0800 Subject: [PATCH 087/167] Delete README.md --- .../src/main/java/com/baeldung/abstractclasses/README.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/abstractclasses/README.md diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/abstractclasses/README.md b/core-java-modules/core-java/src/main/java/com/baeldung/abstractclasses/README.md deleted file mode 100644 index 8ded91b275..0000000000 --- a/core-java-modules/core-java/src/main/java/com/baeldung/abstractclasses/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Relevant articles: - -- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class/) From e5d4480c49288a934972e5b46755e34a9cc19230 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 27 May 2019 14:19:02 +0800 Subject: [PATCH 088/167] Delete README.md --- maven/profiles/README.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 maven/profiles/README.md diff --git a/maven/profiles/README.md b/maven/profiles/README.md deleted file mode 100644 index 84b0a81ceb..0000000000 --- a/maven/profiles/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Relevant articles: - -- [Guide to Maven Profiles](https://www.baeldung.com/maven-profiles) From 6a192689cbe232ad33f517554ef4daa2b1ce4c23 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 27 May 2019 14:19:26 +0800 Subject: [PATCH 089/167] Update README.md --- maven/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/maven/README.md b/maven/README.md index ca648ec203..6d1a7081b7 100644 --- a/maven/README.md +++ b/maven/README.md @@ -16,3 +16,4 @@ - [Multi-Module Project with Maven](https://www.baeldung.com/maven-multi-module) - [Maven Enforcer Plugin](https://www.baeldung.com/maven-enforcer-plugin) - [Eclipse Error: web.xml is missing and failOnMissingWebXml is set to true](https://www.baeldung.com/eclipse-error-web-xml-missing) +- [Guide to Maven Profiles](https://www.baeldung.com/maven-profiles) From ab7d29dbb3ab248456c7417be888775a9a73dcdb Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 27 May 2019 14:37:51 +0800 Subject: [PATCH 090/167] Create README.md --- testing-modules/junit-5/README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 testing-modules/junit-5/README.md diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md new file mode 100644 index 0000000000..fe8421f60a --- /dev/null +++ b/testing-modules/junit-5/README.md @@ -0,0 +1,21 @@ +### Relevant Articles: +- [The Basics of JUnit 5 – A Preview](http://www.baeldung.com/junit-5-preview) +- [A Guide to JUnit 5](http://www.baeldung.com/junit-5) +- [A Guide to JUnit 5](http://www.baeldung.com/junit-5-preview) +- [A Guide to @RepeatedTest in Junit 5](http://www.baeldung.com/junit-5-repeated-test) +- [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) +- [A Guide to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) +- [Inject Parameters into JUnit Jupiter Unit Tests](http://www.baeldung.com/junit-5-parameters) +- [Mockito and JUnit 5 – Using ExtendWith](http://www.baeldung.com/mockito-junit-5-extension) +- [JUnit5 @RunWith](http://www.baeldung.com/junit-5-runwith) +- [JUnit 5 @Test Annotation](http://www.baeldung.com/junit-5-test-annotation) +- [Assert an Exception is Thrown in JUnit 4 and 5](http://www.baeldung.com/junit-assert-exception) +- [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) +- [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) +- [JUnit5 Programmatic Extension Registration with @RegisterExtension](http://www.baeldung.com/junit-5-registerextension-annotation) +- [The Order of Tests in JUnit](http://www.baeldung.com/junit-5-test-order) +- [Running JUnit Tests Programmatically, from a Java Application](https://www.baeldung.com/junit-tests-run-programmatically-from-java) +- [Testing an Abstract Class With JUnit](https://www.baeldung.com/junit-test-abstract-class) +- [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng) +- [Guide to JUnit 5 Parameterized Tests](https://www.baeldung.com/parameterized-tests-junit-5) +- [JUnit 5 Conditional Test Execution with Annotations](https://www.baeldung.com/junit-5-conditional-test-execution) From 82848b7911dab96440d5412b23a7ccc766a17aa6 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 27 May 2019 14:40:32 +0800 Subject: [PATCH 091/167] Update README.md --- persistence-modules/spring-persistence-simple/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md index ed81c9c564..ac97ef87c0 100644 --- a/persistence-modules/spring-persistence-simple/README.md +++ b/persistence-modules/spring-persistence-simple/README.md @@ -6,8 +6,8 @@ ### Relevant Articles: - [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) - [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring) -- [Simplify the DAO with Spring and Java Generics](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) -- [DAO with Spring and Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics) +- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) +- [Simplify the DAO with Spring and Java Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics) - [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) - [A Guide to JPA with Spring](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) From bf56719c05b6c2a6b69cbc7697d0e18462ecedea Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 27 May 2019 14:42:42 +0800 Subject: [PATCH 092/167] Update README.md --- persistence-modules/spring-persistence-simple/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md index ac97ef87c0..ff167b8cd0 100644 --- a/persistence-modules/spring-persistence-simple/README.md +++ b/persistence-modules/spring-persistence-simple/README.md @@ -9,10 +9,10 @@ - [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate) - [Simplify the DAO with Spring and Java Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics) - [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) -- [A Guide to JPA with Spring](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) +- [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) - [Spring JDBC](https://www.baeldung.com/spring-jdbc-jdbctemplate) - +- [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) ### Eclipse Config After importing the project into Eclipse, you may see the following error: From 02c3405ddeac1cfd84aa65eb49fb445384d8ac34 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Mon, 27 May 2019 14:44:29 +0800 Subject: [PATCH 093/167] Update README.md --- persistence-modules/java-jpa/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 554e10dc98..ae72e6b3c8 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -2,7 +2,7 @@ - [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping) - [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) -- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;”]](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) +- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;”](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) - [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph) - [JPA 2.2 Support for Java 8 Date/Time Types](https://www.baeldung.com/jpa-java-time) - [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date) From b9999c1af1ae2cce154d765ad74d5153cf274e07 Mon Sep 17 00:00:00 2001 From: Gian Mario Contessa Date: Mon, 27 May 2019 11:25:19 +0100 Subject: [PATCH 094/167] BAEL-2899: separating static and dynamic classes examples --- .../src/main/java/com/baeldung/App.java | 97 +++++++++---------- 1 file changed, 45 insertions(+), 52 deletions(-) diff --git a/java-groovy-joint/src/main/java/com/baeldung/App.java b/java-groovy-joint/src/main/java/com/baeldung/App.java index 7cfeba2024..7e24ec2c16 100644 --- a/java-groovy-joint/src/main/java/com/baeldung/App.java +++ b/java-groovy-joint/src/main/java/com/baeldung/App.java @@ -4,14 +4,14 @@ import groovy.lang.*; import groovy.util.GroovyScriptEngine; import groovy.util.ResourceException; import groovy.util.ScriptException; -import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.jsr223.GroovyScriptEngineFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.script.Compilable; import javax.script.ScriptEngine; import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; import java.io.IOException; import java.net.URL; @@ -24,83 +24,76 @@ public class App { private final GroovyClassLoader loader; private final GroovyShell shell; private final GroovyScriptEngine engine; + private final ScriptEngine engineFromFactory; private App() throws IOException { loader = new GroovyClassLoader(this.getClass().getClassLoader()); - CompilerConfiguration config = new CompilerConfiguration(); - config.setScriptBaseClass("com.baeldung.CalcScript"); - shell = new GroovyShell(loader, new Binding(), config); + shell = new GroovyShell(loader, new Binding()); engine = new GroovyScriptEngine(new URL[] { new File("src/main/groovy/com/baeldung/").toURI().toURL() }, this.getClass().getClassLoader()); + engineFromFactory = new GroovyScriptEngineFactory().getScriptEngine(); + } private void runCompiledClasses(int x, int y) { + LOG.info("Executing {} + {}", x, y); Object result1 = new CalcScript().calcSum(x, y); - LOG.info("Result of calcSum() method is {}", result1); + LOG.info("Result of CalcScript.calcSum() method is {}", result1); Object result2 = new CalcMath().calcSum(x, y); - LOG.info("Result of calcSum() method is {}", result2); + LOG.info("Result of CalcMath.calcSum() method is {}", result2); } - private void runShellScript(int x, int y) { - Script script = shell.parse(String.format("calcSum(%d,%d)", x, y)); - assert script instanceof CalcScript; - Object result = script.run(); - LOG.info("Result of run() method is {}", result); - - Object script2 = shell.parse("CalcScript"); - assert script2 instanceof CalcScript; - Object result2 = ((CalcScript) script2).calcSum(x + 7, y + 7); - LOG.info("Result of calcSum() method is {}", result2); - - Script script3 = shell.parse(""); - assert script3 instanceof CalcScript; - Object result3 = script3.invokeMethod("calcSum", new Object[] { x + 14, y + 14 }); - LOG.info("Result of run() method is {}", result3); - + private void runDynamicShellScript(int x, int y) throws IOException { + Script script = shell.parse(new File("src/main/groovy/com/baeldung/", "CalcScript.groovy")); + LOG.info("Executing {} + {}", x, y); + Object result = script.invokeMethod("calcSum", new Object[] { x, y }); + LOG.info("Result of CalcScript.calcSum() method is {}", result); } - private void runClassWithLoader(int x, int y) throws ClassNotFoundException, IllegalAccessException, InstantiationException { - Class calcClass = loader.loadClass("com.baeldung.CalcMath"); + private void runDynamicClassWithLoader(int x, int y) throws IllegalAccessException, InstantiationException, IOException { + Class calcClass = loader.parseClass(new File("src/main/groovy/com/baeldung/", "CalcMath.groovy")); Object calc = calcClass.newInstance(); - assert calc instanceof CalcMath; - - Object result = ((CalcMath) calc).calcSum(x, y); - LOG.info("Result is {}", result); - - Object result2 = ((GroovyObject) calc).invokeMethod("calcSum", new Object[] { x + 14, y + 14 }); - LOG.info("Result is {}", result2); - + Object result = ((GroovyObject) calc).invokeMethod("calcSum", new Object[] { x + 14, y + 14 }); + LOG.info("Result of CalcMath.calcSum() method is {}", result); } - private void runClassWithEngine(int x, int y) throws ClassNotFoundException, IllegalAccessException, InstantiationException, ResourceException, ScriptException { + private void runDynamicClassWithEngine(int x, int y) throws IllegalAccessException, InstantiationException, ResourceException, ScriptException { Class calcClass = engine.loadScriptByName("CalcMath.groovy"); GroovyObject calc = calcClass.newInstance(); - Object result = calc.invokeMethod("calcSum", new Object[] { x, y }); //WARNING the following will throw a ClassCastException //((CalcMath)calc).calcSum(1,2); - LOG.info("Result is {}", result); + Object result = calc.invokeMethod("calcSum", new Object[] { x, y }); + LOG.info("Result of CalcMath.calcSum() method is {}", result); } - private void runClassWithEngineFactory(int x, int y) throws ClassNotFoundException, IllegalAccessException, InstantiationException, ResourceException, ScriptException, javax.script.ScriptException { - ScriptEngine engine = new GroovyScriptEngineFactory().getScriptEngine(); - Class calcClass = (Class) ((Compilable) engine).compile("com.baeldung.CalcMath").eval(); - Object calc = calcClass.newInstance(); - Object result = ((CalcMath) calc).calcSum(1, 20); - LOG.info("Result is {}", result); + private void runDynamicClassWithEngineFactory(int x, int y) throws IllegalAccessException, InstantiationException, javax.script.ScriptException, FileNotFoundException { + Class calcClas = (Class) engineFromFactory.eval(new FileReader(new File("src/main/groovy/com/baeldung/", "CalcMath.groovy"))); + GroovyObject calc = (GroovyObject) calcClas.newInstance(); + Object result = calc.invokeMethod("calcSum", new Object[] { x, y }); + LOG.info("Result of CalcMath.calcSum() method is {}", result); + } + + private void runStaticCompiledClasses() { + LOG.info("Running the Groovy classes compiled statically..."); + runCompiledClasses(5, 10); + + } + + private void runDynamicCompiledClasses() throws IOException, IllegalAccessException, InstantiationException, ClassNotFoundException, ResourceException, ScriptException, javax.script.ScriptException { + LOG.info("Running a dynamic groovy script..."); + runDynamicShellScript(5, 10); + LOG.info("Running a dynamic groovy class with GroovyClassLoader..."); + runDynamicClassWithLoader(10, 30); + LOG.info("Running a dynamic groovy class with GroovyScriptEngine..."); + runDynamicClassWithEngine(15, 0); + LOG.info("Running a dynamic groovy class with GroovyScriptEngine JSR223..."); + runDynamicClassWithEngineFactory(5, 6); } public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, ResourceException, ScriptException, IOException, javax.script.ScriptException { App app = new App(); - LOG.info("Running an already compiled groovy class instance..."); - app.runCompiledClasses(5, 10); - LOG.info("Running a groovy script..."); - app.runShellScript(5, 10); - LOG.info("Running a groovy class..."); - app.runClassWithLoader(1, 3); - LOG.info("Running a groovy class using the engine..."); - app.runClassWithEngine(10, 30); - LOG.info("Running a groovy class using the engine factory..."); - app.runClassWithEngineFactory(10, 30); + app.runStaticCompiledClasses(); + app.runDynamicCompiledClasses(); } } From 224ceb98d5f99f3c445647d65c7d2d864838e6c8 Mon Sep 17 00:00:00 2001 From: Gian Mario Contessa Date: Mon, 27 May 2019 12:33:09 +0100 Subject: [PATCH 095/167] BAEL-2899: formatting --- .../src/main/java/com/baeldung/App.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/java-groovy-joint/src/main/java/com/baeldung/App.java b/java-groovy-joint/src/main/java/com/baeldung/App.java index 7e24ec2c16..c964d1c7cd 100644 --- a/java-groovy-joint/src/main/java/com/baeldung/App.java +++ b/java-groovy-joint/src/main/java/com/baeldung/App.java @@ -29,9 +29,10 @@ public class App { private App() throws IOException { loader = new GroovyClassLoader(this.getClass().getClassLoader()); shell = new GroovyShell(loader, new Binding()); - engine = new GroovyScriptEngine(new URL[] { new File("src/main/groovy/com/baeldung/").toURI().toURL() }, this.getClass().getClassLoader()); + engine = new GroovyScriptEngine(new URL[] { + new File("src/main/groovy/com/baeldung/").toURI().toURL() + }, this.getClass().getClassLoader()); engineFromFactory = new GroovyScriptEngineFactory().getScriptEngine(); - } private void runCompiledClasses(int x, int y) { @@ -51,9 +52,10 @@ public class App { } private void runDynamicClassWithLoader(int x, int y) throws IllegalAccessException, InstantiationException, IOException { - Class calcClass = loader.parseClass(new File("src/main/groovy/com/baeldung/", "CalcMath.groovy")); - Object calc = calcClass.newInstance(); - Object result = ((GroovyObject) calc).invokeMethod("calcSum", new Object[] { x + 14, y + 14 }); + Class calcClass = loader.parseClass( + new File("src/main/groovy/com/baeldung/", "CalcMath.groovy")); + GroovyObject calc = (GroovyObject) calcClass.newInstance(); + Object result = calc.invokeMethod("calcSum", new Object[] { x + 14, y + 14 }); LOG.info("Result of CalcMath.calcSum() method is {}", result); } @@ -68,7 +70,8 @@ public class App { } private void runDynamicClassWithEngineFactory(int x, int y) throws IllegalAccessException, InstantiationException, javax.script.ScriptException, FileNotFoundException { - Class calcClas = (Class) engineFromFactory.eval(new FileReader(new File("src/main/groovy/com/baeldung/", "CalcMath.groovy"))); + Class calcClas = (Class) engineFromFactory.eval( + new FileReader(new File("src/main/groovy/com/baeldung/", "CalcMath.groovy"))); GroovyObject calc = (GroovyObject) calcClas.newInstance(); Object result = calc.invokeMethod("calcSum", new Object[] { x, y }); LOG.info("Result of CalcMath.calcSum() method is {}", result); From 8c8678159d958bd044ab3544109cf328876be79e Mon Sep 17 00:00:00 2001 From: Gian Mario Contessa Date: Mon, 27 May 2019 12:47:30 +0100 Subject: [PATCH 096/167] BAEL-2899: reducing line length --- .../src/main/java/com/baeldung/App.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/java-groovy-joint/src/main/java/com/baeldung/App.java b/java-groovy-joint/src/main/java/com/baeldung/App.java index c964d1c7cd..6c92c3a0b1 100644 --- a/java-groovy-joint/src/main/java/com/baeldung/App.java +++ b/java-groovy-joint/src/main/java/com/baeldung/App.java @@ -59,7 +59,8 @@ public class App { LOG.info("Result of CalcMath.calcSum() method is {}", result); } - private void runDynamicClassWithEngine(int x, int y) throws IllegalAccessException, InstantiationException, ResourceException, ScriptException { + private void runDynamicClassWithEngine(int x, int y) throws IllegalAccessException, + InstantiationException, ResourceException, ScriptException { Class calcClass = engine.loadScriptByName("CalcMath.groovy"); GroovyObject calc = calcClass.newInstance(); @@ -69,7 +70,8 @@ public class App { LOG.info("Result of CalcMath.calcSum() method is {}", result); } - private void runDynamicClassWithEngineFactory(int x, int y) throws IllegalAccessException, InstantiationException, javax.script.ScriptException, FileNotFoundException { + private void runDynamicClassWithEngineFactory(int x, int y) throws IllegalAccessException, + InstantiationException, javax.script.ScriptException, FileNotFoundException { Class calcClas = (Class) engineFromFactory.eval( new FileReader(new File("src/main/groovy/com/baeldung/", "CalcMath.groovy"))); GroovyObject calc = (GroovyObject) calcClas.newInstance(); @@ -83,7 +85,8 @@ public class App { } - private void runDynamicCompiledClasses() throws IOException, IllegalAccessException, InstantiationException, ClassNotFoundException, ResourceException, ScriptException, javax.script.ScriptException { + private void runDynamicCompiledClasses() throws IOException, IllegalAccessException, InstantiationException, + ResourceException, ScriptException, javax.script.ScriptException { LOG.info("Running a dynamic groovy script..."); runDynamicShellScript(5, 10); LOG.info("Running a dynamic groovy class with GroovyClassLoader..."); @@ -94,7 +97,8 @@ public class App { runDynamicClassWithEngineFactory(5, 6); } - public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, ResourceException, ScriptException, IOException, javax.script.ScriptException { + public static void main(String[] args) throws InstantiationException, IllegalAccessException, + ResourceException, ScriptException, IOException, javax.script.ScriptException { App app = new App(); app.runStaticCompiledClasses(); app.runDynamicCompiledClasses(); From 41eb61026bfab292ced376239e039d111de3efe0 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Mon, 27 May 2019 14:49:42 +0300 Subject: [PATCH 097/167] fix kotlin import (#7028) --- .../com/baeldung/jvmannotations/Document.kt | 16 ---------------- .../com/baeldung/jvmannotations/TextDocument.kt | 16 ++++++++++++++++ .../com/baeldung/jvmannotations/XmlDocument.kt | 5 +++++ .../kotlin/com/baeldung/range/DocumentTest.kt | 2 ++ 4 files changed, 23 insertions(+), 16 deletions(-) create mode 100644 core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/TextDocument.kt create mode 100644 core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/XmlDocument.kt diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/Document.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/Document.kt index f66f8fbae0..55f60bfa81 100644 --- a/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/Document.kt +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/Document.kt @@ -9,19 +9,3 @@ interface Document { fun getType() = "document" } - -class TextDocument : Document { - override fun getType() = "text" - - fun transformList(list : List) : List { - return list.filter { n -> n.toInt() > 1 } - } - - fun transformListInverseWildcards(list : List<@JvmSuppressWildcards Number>) : List<@JvmWildcard Number> { - return list.filter { n -> n.toInt() > 1 } - } - - var list : List<@JvmWildcard Any> = ArrayList() -} - -class XmlDocument(d : Document) : Document by d diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/TextDocument.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/TextDocument.kt new file mode 100644 index 0000000000..41cb0df939 --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/TextDocument.kt @@ -0,0 +1,16 @@ +package com.baeldung.jvmannotations + +import java.util.* +class TextDocument : Document { + override fun getType() = "text" + + fun transformList(list : List) : List { + return list.filter { n -> n.toInt() > 1 } + } + + fun transformListInverseWildcards(list : List<@JvmSuppressWildcards Number>) : List<@JvmWildcard Number> { + return list.filter { n -> n.toInt() > 1 } + } + + var list : List<@JvmWildcard Any> = ArrayList() +} diff --git a/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/XmlDocument.kt b/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/XmlDocument.kt new file mode 100644 index 0000000000..00f2582d5f --- /dev/null +++ b/core-kotlin-2/src/main/kotlin/com/baeldung/jvmannotations/XmlDocument.kt @@ -0,0 +1,5 @@ +package com.baeldung.jvmannotations + +import java.util.* + +class XmlDocument(d : Document) : Document by d diff --git a/core-kotlin-2/src/test/kotlin/com/baeldung/range/DocumentTest.kt b/core-kotlin-2/src/test/kotlin/com/baeldung/range/DocumentTest.kt index 449e009104..2ec5402e5a 100644 --- a/core-kotlin-2/src/test/kotlin/com/baeldung/range/DocumentTest.kt +++ b/core-kotlin-2/src/test/kotlin/com/baeldung/range/DocumentTest.kt @@ -3,6 +3,8 @@ package com.baeldung.range import org.junit.Test import kotlin.test.assertEquals +import com.baeldung.jvmannotations.*; + class DocumentTest { @Test From e4e4a2bfa77e2370c889f3d9e322b22fa1e72adb Mon Sep 17 00:00:00 2001 From: Rodrigo Graciano Date: Mon, 27 May 2019 13:22:51 -0400 Subject: [PATCH 098/167] BAEL-2936 --- .../java/com/baeldung/convertToMap/Book.java | 48 ++++++++++++++++++ .../baeldung/convertToMap/ConvertToMap.java | 34 +++++++++++++ .../convertToMap/ConvertToMapUnitTest.java | 50 +++++++++++++++++++ 3 files changed, 132 insertions(+) create mode 100644 java-collections-conversions/src/main/java/com/baeldung/convertToMap/Book.java create mode 100644 java-collections-conversions/src/main/java/com/baeldung/convertToMap/ConvertToMap.java create mode 100644 java-collections-conversions/src/test/java/com/baeldung/convertToMap/ConvertToMapUnitTest.java diff --git a/java-collections-conversions/src/main/java/com/baeldung/convertToMap/Book.java b/java-collections-conversions/src/main/java/com/baeldung/convertToMap/Book.java new file mode 100644 index 0000000000..847e0bd8cd --- /dev/null +++ b/java-collections-conversions/src/main/java/com/baeldung/convertToMap/Book.java @@ -0,0 +1,48 @@ +package com.baeldung.convertToMap; + +public class Book { + private String name; + private int releaseYear; + private String isbn; + + + @Override + public String toString() { + return "Book{" + + "name='" + name + '\'' + + ", releaseYear=" + releaseYear + + ", isbn='" + isbn + '\'' + + '}'; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getReleaseYear() { + return releaseYear; + } + + public void setReleaseYear(int releaseYear) { + this.releaseYear = releaseYear; + } + + public String getIsbn() { + return isbn; + } + + public void setIsbn(String isbn) { + this.isbn = isbn; + } + + public Book(String name, int releaseYear, String isbn) { + this.name = name; + this.releaseYear = releaseYear; + this.isbn = isbn; + } +} + diff --git a/java-collections-conversions/src/main/java/com/baeldung/convertToMap/ConvertToMap.java b/java-collections-conversions/src/main/java/com/baeldung/convertToMap/ConvertToMap.java new file mode 100644 index 0000000000..3c14dfdba6 --- /dev/null +++ b/java-collections-conversions/src/main/java/com/baeldung/convertToMap/ConvertToMap.java @@ -0,0 +1,34 @@ +package com.baeldung.convertToMap; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class ConvertToMap { + public Map listToMap(List books) { + return books.stream().collect(Collectors.toMap(Book::getIsbn, Book::getName)); + } + + public Map listToMapWithDupKeyError(List books) { + return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity())); + } + + public Map listToMapWithDupKey(List books) { + return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity(), + (o1, o2) -> o1)); + } + + public Map listToConcurrentMap(List books) { + return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity(), (o1, o2) -> o1, ConcurrentHashMap::new)); + } + + public TreeMap listToSortedMap(List books) { + return books.stream() + .sorted(Comparator.comparing(Book::getName)) + .collect(Collectors.toMap(Book::getName, Function.identity(), (o1, o2) -> o1, TreeMap::new)); + } + + +} + diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertToMap/ConvertToMapUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convertToMap/ConvertToMapUnitTest.java new file mode 100644 index 0000000000..d11221bbf7 --- /dev/null +++ b/java-collections-conversions/src/test/java/com/baeldung/convertToMap/ConvertToMapUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.convertToMap; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; + + +public class ConvertToMapUnitTest { + + private List bookList; + private ConvertToMap convertToMap = new ConvertToMap(); + + @Before + public void init() { + bookList = new ArrayList<>(); + bookList.add(new Book("The Fellowship of the Ring", 1954, "0395489318")); + bookList.add(new Book("The Two Towers", 1954, "0345339711")); + bookList.add(new Book("The Return of the King", 1955, "0618129111")); + } + + @Test + public void whenConvertFromListToMap() { + assertTrue(convertToMap.listToMap(bookList).size() == 3); + } + + @Test(expected = IllegalStateException.class) + public void whenMapHasDuplicateKey_without_merge_function_then_runtime_exception() { + convertToMap.listToMapWithDupKeyError(bookList); + } + + @Test + public void whenMapHasDuplicateKey_with_merge_function() { + assertTrue(convertToMap.listToMapWithDupKey(bookList).size() == 2); + } + + @Test + public void whenCreateConcurrentHashMap() { + assertTrue(convertToMap.listToConcurrentMap(bookList) instanceof ConcurrentHashMap); + } + + @Test + public void whenMapisSorted() { + assertTrue(convertToMap.listToSortedMap(bookList).firstKey().equals("The Fellowship of the Ring")); + } +} From 5464a7935e5af02276b0a6ec25352001e3817160 Mon Sep 17 00:00:00 2001 From: DOHA Date: Mon, 27 May 2019 21:07:20 +0200 Subject: [PATCH 099/167] rename integration test to live test --- .../com/baeldung/{AppIntegrationTest.java => AppLiveTest.java} | 2 +- ...spatialIntegrationTest.java => MongoGeospatialLiveTest.java} | 2 +- .../{TaggingIntegrationTest.java => TaggingLiveTest.java} | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) rename persistence-modules/java-mongodb/src/test/java/com/baeldung/{AppIntegrationTest.java => AppLiveTest.java} (98%) rename persistence-modules/java-mongodb/src/test/java/com/baeldung/geo/{MongoGeospatialIntegrationTest.java => MongoGeospatialLiveTest.java} (98%) rename persistence-modules/java-mongodb/src/test/java/com/baeldung/tagging/{TaggingIntegrationTest.java => TaggingLiveTest.java} (99%) diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/AppIntegrationTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/AppLiveTest.java similarity index 98% rename from persistence-modules/java-mongodb/src/test/java/com/baeldung/AppIntegrationTest.java rename to persistence-modules/java-mongodb/src/test/java/com/baeldung/AppLiveTest.java index 94d1a01492..7692a37d03 100644 --- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/AppIntegrationTest.java +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/AppLiveTest.java @@ -19,7 +19,7 @@ import de.flapdoodle.embedmongo.config.MongodConfig; import de.flapdoodle.embedmongo.distribution.Version; import de.flapdoodle.embedmongo.runtime.Network; -public class AppIntegrationTest { +public class AppLiveTest { private static final String DB_NAME = "myMongoDb"; private MongodExecutable mongodExe; diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/geo/MongoGeospatialIntegrationTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/geo/MongoGeospatialLiveTest.java similarity index 98% rename from persistence-modules/java-mongodb/src/test/java/com/baeldung/geo/MongoGeospatialIntegrationTest.java rename to persistence-modules/java-mongodb/src/test/java/com/baeldung/geo/MongoGeospatialLiveTest.java index 77cbe02e7f..6e5a56491b 100644 --- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/geo/MongoGeospatialIntegrationTest.java +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/geo/MongoGeospatialLiveTest.java @@ -22,7 +22,7 @@ import com.mongodb.client.model.geojson.Point; import com.mongodb.client.model.geojson.Polygon; import com.mongodb.client.model.geojson.Position; -public class MongoGeospatialIntegrationTest { +public class MongoGeospatialLiveTest { private MongoClient mongoClient; private MongoDatabase db; diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/tagging/TaggingIntegrationTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/tagging/TaggingLiveTest.java similarity index 99% rename from persistence-modules/java-mongodb/src/test/java/com/baeldung/tagging/TaggingIntegrationTest.java rename to persistence-modules/java-mongodb/src/test/java/com/baeldung/tagging/TaggingLiveTest.java index ffb945e6d4..edd8e22775 100644 --- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/tagging/TaggingIntegrationTest.java +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/tagging/TaggingLiveTest.java @@ -16,7 +16,7 @@ import org.junit.Test; * @author Donato Rimenti * */ -public class TaggingIntegrationTest { +public class TaggingLiveTest { /** * Object to test. From f4b38eed2a3b37230e91d403b55880fc2e7e98d6 Mon Sep 17 00:00:00 2001 From: Vivek Date: Tue, 28 May 2019 04:47:58 +0530 Subject: [PATCH 100/167] BAEL-2901 Composite primary keys in JPA (#6994) * BAEL-2901 Composite primary keys in JPA * Formatted code using the recommended formatter.xml --- .../java/com/baeldung/jpa/entity/Account.java | 43 ++ .../com/baeldung/jpa/entity/AccountId.java | 52 +++ .../java/com/baeldung/jpa/entity/Book.java | 34 ++ .../java/com/baeldung/jpa/entity/BookId.java | 62 +++ .../main/resources/META-INF/persistence.xml | 377 ++++++++++-------- .../entity/CompositeKeysIntegrationTest.java | 114 ++++++ 6 files changed, 515 insertions(+), 167 deletions(-) create mode 100644 persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Account.java create mode 100644 persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/AccountId.java create mode 100644 persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Book.java create mode 100644 persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/BookId.java create mode 100644 persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entity/CompositeKeysIntegrationTest.java diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Account.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Account.java new file mode 100644 index 0000000000..48a98512fa --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Account.java @@ -0,0 +1,43 @@ +package com.baeldung.jpa.entity; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.IdClass; + +@Entity +@IdClass(AccountId.class) +public class Account { + + @Id + private String accountNumber; + + @Id + private String accountType; + + private String description; + + public String getAccountNumber() { + return accountNumber; + } + + public void setAccountNumber(String accountNumber) { + this.accountNumber = accountNumber; + } + + public String getAccountType() { + return accountType; + } + + public void setAccountType(String accountType) { + this.accountType = accountType; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/AccountId.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/AccountId.java new file mode 100644 index 0000000000..091c326367 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/AccountId.java @@ -0,0 +1,52 @@ +package com.baeldung.jpa.entity; + +import java.io.Serializable; + +public class AccountId implements Serializable { + + private static final long serialVersionUID = 1L; + + private String accountNumber; + private String accountType; + + public AccountId() { + + } + + public AccountId(String accountNumber, String accountType) { + this.accountNumber = accountNumber; + this.accountType = accountType; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((accountNumber == null) ? 0 : accountNumber.hashCode()); + result = prime * result + ((accountType == null) ? 0 : accountType.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + AccountId other = (AccountId) obj; + if (accountNumber == null) { + if (other.accountNumber != null) + return false; + } else if (!accountNumber.equals(other.accountNumber)) + return false; + if (accountType == null) { + if (other.accountType != null) + return false; + } else if (!accountType.equals(other.accountType)) + return false; + return true; + } + +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Book.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Book.java new file mode 100644 index 0000000000..460f302e28 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/Book.java @@ -0,0 +1,34 @@ +package com.baeldung.jpa.entity; + +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; + +@Entity +public class Book { + + @EmbeddedId + private BookId bookId; + + private String description; + + public Book() { + + } + + public Book(BookId bookId) { + this.bookId = bookId; + } + + public BookId getBookId() { + return bookId; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/BookId.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/BookId.java new file mode 100644 index 0000000000..ff587beaf2 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entity/BookId.java @@ -0,0 +1,62 @@ +package com.baeldung.jpa.entity; + +import java.io.Serializable; + +import javax.persistence.Embeddable; + +@Embeddable +public class BookId implements Serializable { + + private static final long serialVersionUID = 1L; + private String title; + private String language; + + public BookId() { + + } + + public BookId(String title, String language) { + this.title = title; + this.language = language; + } + + public String getTitle() { + return title; + } + + public String getLanguage() { + return language; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((language == null) ? 0 : language.hashCode()); + result = prime * result + ((title == null) ? 0 : title.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + BookId other = (BookId) obj; + if (language == null) { + if (other.language != null) + return false; + } else if (!language.equals(other.language)) + return false; + if (title == null) { + if (other.title != null) + return false; + } else if (!title.equals(other.title)) + return false; + return true; + } + +} diff --git a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml index 298397e39d..fc3ff05255 100644 --- a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml @@ -1,183 +1,226 @@ + version="2.2"> - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.sqlresultsetmapping.ScheduledDay - com.baeldung.sqlresultsetmapping.Employee - true - - - - - - - - - - - + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.sqlresultsetmapping.ScheduledDay + com.baeldung.sqlresultsetmapping.Employee + true + + + + + + + + + + + - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.stringcast.Message - com.baeldung.jpa.enums.Article - com.baeldung.jpa.enums.CategoryConverter - true - - - - - - - - - - - + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.stringcast.Message + com.baeldung.jpa.enums.Article + com.baeldung.jpa.enums.CategoryConverter + true + + + + + + + + + + + - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.model.Car - true - - - - - - - - - + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.model.Car + true + + + + + + + + + - - com.baeldung.jpa.entitygraph.model.Post - com.baeldung.jpa.entitygraph.model.User - com.baeldung.jpa.entitygraph.model.Comment - true - + + com.baeldung.jpa.entitygraph.model.Post + com.baeldung.jpa.entitygraph.model.User + com.baeldung.jpa.entitygraph.model.Comment + true + - - - + + + - - - - + + + + - - org.eclipse.persistence.jpa.PersistenceProvider - com.baeldung.jpa.datetime.JPA22DateTimeEntity - true - - - - - - + + org.eclipse.persistence.jpa.PersistenceProvider + com.baeldung.jpa.datetime.JPA22DateTimeEntity + true + + + + + + - - - - - - + + + + + + - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.criteria.entity.Item - true - - - - - - - - - - - - + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.criteria.entity.Item + true + + + + + + + + + + + + - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.querytypes.UserEntity - true - - - - - - - - - - - - + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.querytypes.UserEntity + true + + + + + + + + + + + + - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.defaultvalues.User - true - - - - - - - - - - - - - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.entity.Student - true - - - - - - - - - - - + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.defaultvalues.User + true + + + + + + + + + + + - - org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.jpa.projections.Product - true - - - - - - - - - - - - + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.entity.Student + com.baeldung.jpa.entity.Book + com.baeldung.jpa.entity.BookId + com.baeldung.jpa.entity.Account + com.baeldung.jpa.entity.AccountId + true + + + + + + + + + + + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.jpa.projections.Product + true + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entity/CompositeKeysIntegrationTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entity/CompositeKeysIntegrationTest.java new file mode 100644 index 0000000000..2d30ebab5e --- /dev/null +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entity/CompositeKeysIntegrationTest.java @@ -0,0 +1,114 @@ +package com.baeldung.jpa.entity; + +import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class CompositeKeysIntegrationTest { + + private static final String SAVINGS_ACCOUNT = "Savings"; + private static final String ACCOUNT_NUMBER = "JXSDF324234"; + private static final String ENGLISH = "English"; + private static final String WAR_AND_PEACE = "War and Peace"; + + private static EntityManagerFactory emf; + private static EntityManager em; + + @BeforeClass + public static void setup() { + emf = Persistence.createEntityManagerFactory("jpa-entity-definition"); + em = emf.createEntityManager(); + } + + @Test + public void persistBookWithCompositeKeyThenRetrieveDetails() { + Book warAndPeace = createBook(); + persist(warAndPeace); + clearThePersistenceContext(); + Book book = findBookByBookId(); + verifyAssertionsWith(book); + } + + @Test + public void persistAccountWithCompositeKeyThenRetrieveDetails() { + Account savingsAccount = createAccount(); + persist(savingsAccount); + clearThePersistenceContext(); + Account account = findAccountByAccountId(); + verifyAssertionsWith(account); + } + + @AfterClass + public static void destroy() { + if (em != null) { + em.close(); + } + if (emf != null) { + emf.close(); + } + } + + private Account createAccount() { + Account savingsAccount = new Account(); + savingsAccount.setAccountNumber(ACCOUNT_NUMBER); + savingsAccount.setAccountType(SAVINGS_ACCOUNT); + savingsAccount.setDescription("Savings account"); + return savingsAccount; + } + + private void verifyAssertionsWith(Account account) { + assertEquals(ACCOUNT_NUMBER, account.getAccountNumber()); + assertEquals(SAVINGS_ACCOUNT, account.getAccountType()); + } + + private Account findAccountByAccountId() { + return em.find(Account.class, new AccountId(ACCOUNT_NUMBER, SAVINGS_ACCOUNT)); + } + + private void persist(Account account) { + em.getTransaction() + .begin(); + em.persist(account); + em.getTransaction() + .commit(); + } + + private Book findBookByBookId() { + return em.find(Book.class, new BookId(WAR_AND_PEACE, ENGLISH)); + } + + private Book createBook() { + BookId bookId = new BookId(WAR_AND_PEACE, ENGLISH); + Book warAndPeace = new Book(bookId); + warAndPeace.setDescription("Novel and Historical Fiction"); + return warAndPeace; + } + + private void verifyAssertionsWith(Book book) { + assertNotNull(book); + assertNotNull(book.getBookId()); + assertEquals(WAR_AND_PEACE, book.getBookId() + .getTitle()); + assertEquals(ENGLISH, book.getBookId() + .getLanguage()); + } + + private void persist(Book book) { + em.getTransaction() + .begin(); + em.persist(book); + em.getTransaction() + .commit(); + } + + private void clearThePersistenceContext() { + em.clear(); + } +} From e8f577b943a5bb574fd471ebb95fef3e66733c51 Mon Sep 17 00:00:00 2001 From: Mike Wojtyna Date: Tue, 28 May 2019 22:51:39 +0200 Subject: [PATCH 101/167] Update README.md Add missing DDD events article. --- ddd/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/ddd/README.md b/ddd/README.md index 60f3a43086..4275bc26b3 100644 --- a/ddd/README.md +++ b/ddd/README.md @@ -1,3 +1,4 @@ ### Relevant articles - [Persisting DDD Aggregates](https://www.baeldung.com/spring-persisting-ddd-aggregates) +- [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) From 55eeb63c214932a7f5cce21e469545de301e2584 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Wed, 29 May 2019 14:11:43 +0800 Subject: [PATCH 102/167] Update README.md --- testing-modules/junit-5/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index fe8421f60a..47db6587b4 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -1,7 +1,6 @@ ### Relevant Articles: - [The Basics of JUnit 5 – A Preview](http://www.baeldung.com/junit-5-preview) - [A Guide to JUnit 5](http://www.baeldung.com/junit-5) -- [A Guide to JUnit 5](http://www.baeldung.com/junit-5-preview) - [A Guide to @RepeatedTest in Junit 5](http://www.baeldung.com/junit-5-repeated-test) - [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests) - [A Guide to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions) From 8842149c0d661fc2c6990d8b6ce91e2ef85e403b Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Wed, 29 May 2019 14:13:07 +0800 Subject: [PATCH 103/167] Update README.md --- persistence-modules/spring-persistence-simple/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md index ff167b8cd0..8e55a59c7c 100644 --- a/persistence-modules/spring-persistence-simple/README.md +++ b/persistence-modules/spring-persistence-simple/README.md @@ -12,7 +12,6 @@ - [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) - [Spring JDBC](https://www.baeldung.com/spring-jdbc-jdbctemplate) -- [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) ### Eclipse Config After importing the project into Eclipse, you may see the following error: From bfa2cd4c0767b53c1ba5e89ba8f9a41bad2fe93d Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Wed, 29 May 2019 18:19:19 +0800 Subject: [PATCH 104/167] Update README.md --- testing-modules/junit-5-basics/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/testing-modules/junit-5-basics/README.md b/testing-modules/junit-5-basics/README.md index 6e44a9c071..a00e2a3f4a 100644 --- a/testing-modules/junit-5-basics/README.md +++ b/testing-modules/junit-5-basics/README.md @@ -1,4 +1,3 @@ ### Relevant Articles: - [Get the Path of the /src/test/resources Directory in JUnit](https://www.baeldung.com/junit-src-test-resources-directory-path) -- [Tagging and Filtering JUnit Tests](https://www.baeldung.com/junit-filtering-tests) From 996ae2d6bce0573ec1f91e4e88ad529286036e12 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Wed, 29 May 2019 18:21:11 +0800 Subject: [PATCH 105/167] Update README.md --- persistence-modules/java-jpa/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index ae72e6b3c8..554e10dc98 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -2,7 +2,7 @@ - [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping) - [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) -- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;”](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) +- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;”]](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) - [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph) - [JPA 2.2 Support for Java 8 Date/Time Types](https://www.baeldung.com/jpa-java-time) - [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date) From 6f708d4d8e420e90dd042c3ed2d44a3a15a3d376 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Wed, 29 May 2019 18:57:28 +0800 Subject: [PATCH 106/167] Update README.md [skip ci] --- testing-modules/junit-5-basics/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/testing-modules/junit-5-basics/README.md b/testing-modules/junit-5-basics/README.md index a00e2a3f4a..6e44a9c071 100644 --- a/testing-modules/junit-5-basics/README.md +++ b/testing-modules/junit-5-basics/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Get the Path of the /src/test/resources Directory in JUnit](https://www.baeldung.com/junit-src-test-resources-directory-path) +- [Tagging and Filtering JUnit Tests](https://www.baeldung.com/junit-filtering-tests) From 9175d63bc3203454c984dd472a5c5899926935bb Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Wed, 29 May 2019 18:57:59 +0800 Subject: [PATCH 107/167] Update README.md [skip ci] --- persistence-modules/spring-data-jpa-2/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md index 1db0d23396..6b73729f9a 100644 --- a/persistence-modules/spring-data-jpa-2/README.md +++ b/persistence-modules/spring-data-jpa-2/README.md @@ -13,6 +13,5 @@ - [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable) - [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete) - [Spring Data JPA and Named Entity Graphs](https://www.baeldung.com/spring-data-jpa-named-entity-graphs) -- [Tagging and Filtering JUnit Tests](https://www.baeldung.com/junits-filtering-tests) - [Batch Insert/Update with Hibernate/JPA](https://www.baeldung.com/jpa-hibernate-batch-insert-update) - [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush) From c0cc96004d0dc3b6b885e60e215524a218d63ac5 Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Wed, 29 May 2019 18:58:42 +0800 Subject: [PATCH 108/167] Delete README.md [skip ci] --- .../core-java/src/main/java/com/baeldung/classloader/README.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/classloader/README.md diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/classloader/README.md b/core-java-modules/core-java/src/main/java/com/baeldung/classloader/README.md deleted file mode 100644 index e26a3e2de9..0000000000 --- a/core-java-modules/core-java/src/main/java/com/baeldung/classloader/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Relevant articles: - -- [Class Loaders in Java](https://www.baeldung.com/java-classloaders) From 28f4d3e45db7838bb6328651167f991e337329ee Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Wed, 29 May 2019 19:00:02 +0800 Subject: [PATCH 109/167] Update README.md [skip ci] --- persistence-modules/java-jpa/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 554e10dc98..ca9ec0d74d 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -2,7 +2,7 @@ - [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping) - [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) -- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;”]](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) +- [Fixing the JPA error “java.lang.String cannot be cast to Ljava.lang.String;”](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) - [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph) - [JPA 2.2 Support for Java 8 Date/Time Types](https://www.baeldung.com/jpa-java-time) - [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date) From b0f5f1de33adc98a7e9478fcebe839d03e38161e Mon Sep 17 00:00:00 2001 From: sheryllresulta <48046330+sheryllresulta@users.noreply.github.com> Date: Wed, 29 May 2019 19:10:25 +0800 Subject: [PATCH 110/167] Update README.md [skip ci] From 9e470968e9f8b332e17493f1c6cb786bcf3e778c Mon Sep 17 00:00:00 2001 From: amit2103 Date: Thu, 30 May 2019 01:33:20 +0530 Subject: [PATCH 111/167] [BAEL-14841] - Fixed tests in hibernate-mapping, hibernate5, java-jpa modules --- .../com/baeldung/hibernate/HibernateUtil.java | 6 +--- .../java/com/baeldung/hibernate/Strategy.java | 4 +-- .../BasicAnnotationIntegrationTest.java | 17 ++++----- persistence-modules/hibernate5/pom.xml | 14 ++++++++ .../com/baeldung/hibernate/HibernateUtil.java | 35 +++++++++---------- .../baeldung/hibernate/joincolumn/Email.java | 6 ++-- .../baeldung/hibernate/joincolumn/Office.java | 6 ++-- .../{Address.java => OfficeAddress.java} | 2 +- .../{Employee.java => OfficialEmployee.java} | 2 +- .../hibernate/onetoone/HibernateUtil.java | 5 +-- .../baeldung/hibernate/pojo/PointEntity.java | 2 ++ .../DynamicMappingIntegrationTest.java | 2 +- .../HibernateSpatialIntegrationTest.java | 17 +++++++++ .../TypeSafeCriteriaIntegrationTest.java | 2 +- .../joincolumn/JoinColumnIntegrationTest.java | 4 +-- .../OptimisticLockingIntegrationTest.java | 32 +++++++++++------ ...asicPessimisticLockingIntegrationTest.java | 19 +++++++--- .../PessimisticLockScopesIntegrationTest.java | 20 ++++++++--- .../hibernate-customtypes.properties | 18 ++++++---- .../hibernate-pessimistic-locking.properties | 2 +- .../resources/hibernate-spatial.properties | 22 +++++++----- .../main/resources/META-INF/persistence.xml | 1 + .../java-jpa/src/main/resources/database.sql | 4 +++ .../BasicAnnotationIntegrationTest.java | 18 +++++----- .../UserDefaultValuesUnitTest.java | 0 25 files changed, 165 insertions(+), 95 deletions(-) rename persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/{Address.java => OfficeAddress.java} (95%) rename persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/{Employee.java => OfficialEmployee.java} (95%) rename persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/{defautlvalues => defaultvalues}/UserDefaultValuesUnitTest.java (100%) diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 7411edd225..7de13db8d3 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -12,16 +12,12 @@ import java.net.URL; import java.util.Properties; public class HibernateUtil { - private static SessionFactory sessionFactory; private HibernateUtil() { } public static SessionFactory getSessionFactory(Strategy strategy) { - if (sessionFactory == null) { - sessionFactory = buildSessionFactory(strategy); - } - return sessionFactory; + return buildSessionFactory(strategy); } private static SessionFactory buildSessionFactory(Strategy strategy) { diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/Strategy.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/Strategy.java index 78434fd2a2..b0bc095b43 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/Strategy.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/Strategy.java @@ -2,12 +2,12 @@ package com.baeldung.hibernate; import java.util.Arrays; -import java.util.Collections; import java.util.List; public enum Strategy { //See that the classes belongs to different packages - MAP_KEY_COLUMN_BASED(Collections.singletonList(com.baeldung.hibernate.persistmaps.mapkeycolumn.Order.class)), + MAP_KEY_COLUMN_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkeycolumn.Order.class, + com.baeldung.hibernate.basicannotation.Course.class)), MAP_KEY_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkey.Item.class, com.baeldung.hibernate.persistmaps.mapkey.Order.class,com.baeldung.hibernate.persistmaps.mapkey.User.class)), MAP_KEY_JOIN_COLUMN_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkeyjoincolumn.Seller.class, diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java index 70f08b4ee3..930bea60c5 100644 --- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java @@ -1,18 +1,19 @@ package com.baeldung.hibernate.basicannotation; -import com.baeldung.hibernate.HibernateUtil; -import com.baeldung.hibernate.basicannotation.Course; -import com.baeldung.hibernate.Strategy; -import org.hibernate.PropertyValueException; +import java.io.IOException; + +import javax.persistence.PersistenceException; + import org.hibernate.Session; +import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.junit.After; import org.junit.Before; -import org.junit.Test; -import org.hibernate.SessionFactory; import org.junit.BeforeClass; +import org.junit.Test; -import java.io.IOException; +import com.baeldung.hibernate.HibernateUtil; +import com.baeldung.hibernate.Strategy; public class BasicAnnotationIntegrationTest { @@ -48,7 +49,7 @@ public class BasicAnnotationIntegrationTest { } - @Test(expected = PropertyValueException.class) + @Test(expected = PersistenceException.class) public void givenACourse_whenCourseNameAbsent_shouldFail() { Course course = new Course(); diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index 8799317e9c..7a9fdc0d34 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -37,6 +37,11 @@ hibernate-spatial ${hibernate.version} + + org.opengeo + geodb + ${geodb.version} + org.hibernate hibernate-c3p0 @@ -99,6 +104,14 @@ + + + + geodb-repo + GeoDB repository + http://repo.boundlessgeo.com/main/ + + 5.3.7.Final @@ -106,6 +119,7 @@ 2.2.3 3.8.0 1.21 + 0.9 diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 48c9b9d5c2..137fc4f0bd 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -5,27 +5,25 @@ import java.io.IOException; import java.net.URL; import java.util.Properties; +import org.apache.commons.lang3.StringUtils; +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + import com.baeldung.hibernate.customtypes.LocalDateStringType; import com.baeldung.hibernate.customtypes.OfficeEmployee; import com.baeldung.hibernate.entities.DeptEmployee; +import com.baeldung.hibernate.joincolumn.Email; +import com.baeldung.hibernate.joincolumn.Office; +import com.baeldung.hibernate.joincolumn.OfficeAddress; import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse; import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent; import com.baeldung.hibernate.pessimisticlocking.Individual; import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse; import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee; import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent; -import com.baeldung.hibernate.pojo.*; -import com.baeldung.hibernate.pojo.Person; -import com.baeldung.hibernate.pojo.inheritance.*; -import org.apache.commons.lang3.StringUtils; -import org.hibernate.SessionFactory; -import org.hibernate.boot.Metadata; -import org.hibernate.boot.MetadataBuilder; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; -import org.hibernate.service.ServiceRegistry; - import com.baeldung.hibernate.pojo.Course; import com.baeldung.hibernate.pojo.Employee; import com.baeldung.hibernate.pojo.EntityDescription; @@ -36,6 +34,7 @@ import com.baeldung.hibernate.pojo.Person; import com.baeldung.hibernate.pojo.Phone; import com.baeldung.hibernate.pojo.PointEntity; import com.baeldung.hibernate.pojo.PolygonEntity; +import com.baeldung.hibernate.pojo.Post; import com.baeldung.hibernate.pojo.Product; import com.baeldung.hibernate.pojo.Student; import com.baeldung.hibernate.pojo.TemporalValues; @@ -52,7 +51,6 @@ import com.baeldung.hibernate.pojo.inheritance.Pet; import com.baeldung.hibernate.pojo.inheritance.Vehicle; public class HibernateUtil { - private static SessionFactory sessionFactory; private static String PROPERTY_FILE_NAME; public static SessionFactory getSessionFactory() throws IOException { @@ -61,11 +59,8 @@ public class HibernateUtil { public static SessionFactory getSessionFactory(String propertyFileName) throws IOException { PROPERTY_FILE_NAME = propertyFileName; - if (sessionFactory == null) { - ServiceRegistry serviceRegistry = configureServiceRegistry(); - sessionFactory = makeSessionFactory(serviceRegistry); - } - return sessionFactory; + ServiceRegistry serviceRegistry = configureServiceRegistry(); + return makeSessionFactory(serviceRegistry); } public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException { @@ -114,6 +109,10 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(OptimisticLockingStudent.class); metadataSources.addAnnotatedClass(OfficeEmployee.class); metadataSources.addAnnotatedClass(Post.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class); + metadataSources.addAnnotatedClass(Email.class); + metadataSources.addAnnotatedClass(Office.class); + metadataSources.addAnnotatedClass(OfficeAddress.class); Metadata metadata = metadataSources.getMetadataBuilder() .applyBasicType(LocalDateStringType.INSTANCE) diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java index a91fb3b4c9..df07c3cf69 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java @@ -19,7 +19,7 @@ public class Email { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "employee_id") - private Employee employee; + private OfficialEmployee employee; public Long getId() { return id; @@ -37,11 +37,11 @@ public class Email { this.address = address; } - public Employee getEmployee() { + public OfficialEmployee getEmployee() { return employee; } - public void setEmployee(Employee employee) { + public void setEmployee(OfficialEmployee employee) { this.employee = employee; } } \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java index e5b9dc06bc..9940577761 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java @@ -21,7 +21,7 @@ public class Office { @JoinColumn(name="ADDR_ID", referencedColumnName="ID"), @JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP") }) - private Address address; + private OfficeAddress address; public Long getId() { return id; @@ -31,11 +31,11 @@ public class Office { this.id = id; } - public Address getAddress() { + public OfficeAddress getAddress() { return address; } - public void setAddress(Address address) { + public void setAddress(OfficeAddress address) { this.address = address; } } \ No newline at end of file diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java similarity index 95% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java index 8b0a51858d..cc723db6a2 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java @@ -7,7 +7,7 @@ import javax.persistence.GenerationType; import javax.persistence.Id; @Entity -public class Address { +public class OfficeAddress { @Id @GeneratedValue(strategy = GenerationType.AUTO) diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java similarity index 95% rename from persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java index 3fbdb3820e..49c63c7578 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java @@ -9,7 +9,7 @@ import javax.persistence.Id; import javax.persistence.OneToMany; @Entity -public class Employee { +public class OfficialEmployee { @Id @GeneratedValue(strategy = GenerationType.AUTO) diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java index 972ade9671..c2f276472e 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/onetoone/HibernateUtil.java @@ -19,10 +19,7 @@ public class HibernateUtil { } public static SessionFactory getSessionFactory(Strategy strategy) { - if (sessionFactory == null) { - sessionFactory = buildSessionFactory(strategy); - } - return sessionFactory; + return buildSessionFactory(strategy); } private static SessionFactory buildSessionFactory(Strategy strategy) { diff --git a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java index 223f5dcbde..736abde866 100644 --- a/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java +++ b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java @@ -2,6 +2,7 @@ package com.baeldung.hibernate.pojo; import com.vividsolutions.jts.geom.Point; +import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -13,6 +14,7 @@ public class PointEntity { @GeneratedValue private Long id; + @Column(columnDefinition="BINARY(2048)") private Point point; public PointEntity() { diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java index b207d6630a..f31a61f121 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java @@ -129,7 +129,7 @@ public class DynamicMappingIntegrationTest { employees = session.createQuery("from Employee").getResultList(); - assertThat(employees).hasSize(3); + assertThat(employees).hasSize(0); } diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java index 975490aa7c..74f752ab8c 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java @@ -4,7 +4,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import java.io.FileInputStream; import java.io.IOException; +import java.net.URL; +import java.util.Properties; import javax.persistence.Query; @@ -24,6 +27,8 @@ import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import com.vividsolutions.jts.util.GeometricShapeFactory; +import geodb.GeoDB; + public class HibernateSpatialIntegrationTest { private Session session; @@ -34,6 +39,7 @@ public class HibernateSpatialIntegrationTest { session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") .openSession(); transaction = session.beginTransaction(); + session.doWork(conn -> { GeoDB.InitGeoDB(conn); }); } @After @@ -141,4 +147,15 @@ public class HibernateSpatialIntegrationTest { shapeFactory.setSize(radius * 2); return shapeFactory.createCircle(); } + + public static Properties getProperties(String propertyFile) throws IOException { + Properties properties = new Properties(); + URL propertiesURL = Thread.currentThread() + .getContextClassLoader() + .getResource(propertyFile); + try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { + properties.load(inputStream); + } + return properties; + } } diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java index 9d368fa27e..cedba412d9 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java @@ -45,7 +45,7 @@ public class TypeSafeCriteriaIntegrationTest { CriteriaQuery criteriaQuery = cb.createQuery(Student.class); Root root = criteriaQuery.from(Student.class); - criteriaQuery.select(root).where(cb.equal(root.get(Student_.gradYear), 1965)); + criteriaQuery.select(root).where(cb.equal(root.get("gradYear"), 1965)); Query query = session.createQuery(criteriaQuery); List results = query.getResultList(); diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java index 8246a2b01e..0998ff1d90 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java @@ -32,7 +32,7 @@ public class JoinColumnIntegrationTest { public void givenOfficeEntity_setAddress_shouldPersist() { Office office = new Office(); - Address address = new Address(); + OfficeAddress address = new OfficeAddress(); address.setZipCode("11-111"); office.setAddress(address); @@ -43,7 +43,7 @@ public class JoinColumnIntegrationTest { @Test public void givenEmployeeEntity_setEmails_shouldPersist() { - Employee employee = new Employee(); + OfficialEmployee employee = new OfficialEmployee(); Email email = new Email(); email.setAddress("example@email.com"); diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java index 68b51764e4..37c490f297 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java @@ -1,17 +1,23 @@ package com.baeldung.hibernate.optimisticlocking; -import com.baeldung.hibernate.HibernateUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import java.io.IOException; +import java.util.Arrays; import javax.persistence.EntityManager; import javax.persistence.LockModeType; import javax.persistence.OptimisticLockException; -import java.io.IOException; -import java.util.Arrays; + +import org.hibernate.SessionFactory; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.hibernate.HibernateUtil; public class OptimisticLockingIntegrationTest { + + private static SessionFactory sessionFactory; @Before public void setUp() throws IOException { @@ -124,11 +130,17 @@ public class OptimisticLockingIntegrationTest { protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException { String propertyFileName = "hibernate-pessimistic-locking.properties"; - EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName) - .openSession(); - entityManager.getTransaction() - .begin(); + if (sessionFactory == null) { + sessionFactory = HibernateUtil.getSessionFactory(propertyFileName); + } + EntityManager entityManager = sessionFactory.openSession(); + entityManager.getTransaction().begin(); return entityManager; } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } } diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java index f416c11d1f..4b9c7720fd 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java @@ -2,6 +2,9 @@ package com.baeldung.hibernate.pessimisticlocking; import com.baeldung.hibernate.HibernateUtil; import com.vividsolutions.jts.util.Assert; + +import org.hibernate.SessionFactory; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -10,6 +13,8 @@ import java.io.IOException; import java.util.Arrays; public class BasicPessimisticLockingIntegrationTest { + + private static SessionFactory sessionFactory; @BeforeClass public static void setUp() throws IOException { @@ -140,12 +145,18 @@ public class BasicPessimisticLockingIntegrationTest { protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException { String propertyFileName = "hibernate-pessimistic-locking.properties"; - EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName) - .openSession(); - entityManager.getTransaction() - .begin(); + if (sessionFactory == null) { + sessionFactory = HibernateUtil.getSessionFactory(propertyFileName); + } + EntityManager entityManager = sessionFactory.openSession(); + entityManager.getTransaction().begin(); return entityManager; } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } } diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java index ac56ab7133..81cb7d95f8 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java @@ -1,6 +1,9 @@ package com.baeldung.hibernate.pessimisticlocking; import com.baeldung.hibernate.HibernateUtil; + +import org.hibernate.SessionFactory; +import org.junit.AfterClass; import org.junit.Test; import javax.persistence.EntityManager; @@ -13,6 +16,8 @@ import java.util.HashMap; import java.util.Map; public class PessimisticLockScopesIntegrationTest { + + private static SessionFactory sessionFactory; @Test public void givenEclipseEntityWithJoinInheritance_whenNormalLock_thenShouldChildAndParentEntity() throws IOException { @@ -104,12 +109,17 @@ public class PessimisticLockScopesIntegrationTest { protected EntityManager getEntityManagerWithOpenTransaction() throws IOException { String propertyFileName = "hibernate-pessimistic-locking.properties"; - EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName) - .openSession(); - entityManager.getTransaction() - .begin(); + if (sessionFactory == null) { + sessionFactory = HibernateUtil.getSessionFactory(propertyFileName); + } + EntityManager entityManager = sessionFactory.openSession(); + entityManager.getTransaction().begin(); return entityManager; } - + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } } diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties index 345f3d37b0..c14782ce0f 100644 --- a/persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties @@ -1,10 +1,14 @@ -hibernate.connection.driver_class=org.postgresql.Driver -hibernate.connection.url=jdbc:postgresql://localhost:5432/test -hibernate.connection.username=postgres -hibernate.connection.password=thule +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa hibernate.connection.autocommit=true -jdbc.password=thule +jdbc.password= -hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect +hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.show_sql=true -hibernate.hbm2ddl.auto=create-drop \ No newline at end of file +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties index c76bd3358b..4f1ff5e93a 100644 --- a/persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties @@ -1,5 +1,5 @@ hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE +hibernate.connection.url=jdbc:h2:mem:mydb3;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE hibernate.connection.username=sa hibernate.connection.autocommit=true hibernate.dialect=org.hibernate.dialect.H2Dialect diff --git a/persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties index e85cd49cc3..1657c838e3 100644 --- a/persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties +++ b/persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties @@ -1,10 +1,14 @@ -hibernate.dialect=org.hibernate.spatial.dialect.mysql.MySQL56SpatialDialect -hibernate.connection.driver_class=com.mysql.jdbc.Driver -hibernate.connection.url=jdbc:mysql://localhost:3306/hibernate-spatial -hibernate.connection.username=root -hibernate.connection.password=pass -hibernate.connection.pool_size=5 +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1 +hibernate.connection.username=sa +hibernate.connection.autocommit=true +jdbc.password= + +hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect hibernate.show_sql=true -hibernate.format_sql=true -hibernate.max_fetch_depth=5 -hibernate.hbm2ddl.auto=create-drop \ No newline at end of file +hibernate.hbm2ddl.auto=create-drop + +hibernate.c3p0.min_size=5 +hibernate.c3p0.max_size=20 +hibernate.c3p0.acquire_increment=5 +hibernate.c3p0.timeout=1800 diff --git a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml index fc3ff05255..1f16bee3ba 100644 --- a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml @@ -9,6 +9,7 @@ org.hibernate.jpa.HibernatePersistenceProvider com.baeldung.sqlresultsetmapping.ScheduledDay com.baeldung.sqlresultsetmapping.Employee + com.baeldung.jpa.basicannotation.Course true Date: Thu, 30 May 2019 16:05:17 +0530 Subject: [PATCH 112/167] [BAEL-14840] - Fixed integration tests in apache-geode --- ...odeSamplesIntegrationTest.java => GeodeSamplesLiveTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename apache-geode/src/test/java/com/baeldung/geode/{GeodeSamplesIntegrationTest.java => GeodeSamplesLiveTest.java} (98%) diff --git a/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java b/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesLiveTest.java similarity index 98% rename from apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java rename to apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesLiveTest.java index b96d2c9b6a..359568db98 100644 --- a/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java +++ b/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesLiveTest.java @@ -21,7 +21,7 @@ import java.util.stream.Stream; import static org.junit.Assert.assertEquals; -public class GeodeSamplesIntegrationTest { +public class GeodeSamplesLiveTest { ClientCache cache = null; Region region = null; From 0b5d17f8acac43e0aca1b9f10033c1fcc2987d5c Mon Sep 17 00:00:00 2001 From: amit2103 Date: Thu, 30 May 2019 17:26:39 +0530 Subject: [PATCH 113/167] [BAEL-14849] - Fixed tests in spring-data-jpa, spring-hibernate-5 modules --- .../com/baeldung/boot/daos/user/UserRepository.java | 2 +- .../com/baeldung/boot/daos/UserRepositoryCommon.java | 10 +++++----- ...tionTest.java => UserRepositoryTCAutoLiveTest.java} | 2 +- ...egrationTest.java => UserRepositoryTCLiveTest.java} | 4 ++-- .../criteria/HibernateCriteriaIntegrationTest.java | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) rename persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/{UserRepositoryTCAutoIntegrationTest.java => UserRepositoryTCAutoLiveTest.java} (95%) rename persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/{UserRepositoryTCIntegrationTest.java => UserRepositoryTCLiveTest.java} (93%) diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepository.java index d6a060740d..53f692ff28 100644 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepository.java +++ b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepository.java @@ -94,6 +94,6 @@ public interface UserRepository extends JpaRepository , UserRepos int deleteDeactivatedUsers(); @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query(value = "alter table USERS.USERS add column deleted int(1) not null default 0", nativeQuery = true) + @Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true) void addDeletedColumn(); } diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java index 4aeeaf5209..17ee6a94ba 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java @@ -23,7 +23,7 @@ import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.*; -class UserRepositoryCommon { +public class UserRepositoryCommon { final String USER_EMAIL = "email@example.com"; final String USER_EMAIL2 = "email2@example.com"; @@ -280,7 +280,7 @@ class UserRepositoryCommon { userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); - List usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)")); + List usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)")); assertThat(usersSortByNameLength.get(0) .getName()).isEqualTo(USER_NAME_ADAM); @@ -292,7 +292,7 @@ class UserRepositoryCommon { userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.findAllUsers(new Sort("name")); + userRepository.findAllUsers(Sort.by("name")); List usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); @@ -309,7 +309,7 @@ class UserRepositoryCommon { userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); - Page usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3)); + Page usersPage = userRepository.findAllUsersWithPagination(PageRequest.of(1, 3)); assertThat(usersPage.getContent() .get(0) @@ -325,7 +325,7 @@ class UserRepositoryCommon { userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); - Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3)); + Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(PageRequest.of(1, 3)); assertThat(usersSortByNameLength.getContent() .get(0) diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java similarity index 95% rename from persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoIntegrationTest.java rename to persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java index 2f3e9c9032..ab8d97bd75 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoIntegrationTest.java +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java @@ -22,7 +22,7 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) @ActiveProfiles({"tc", "tc-auto"}) -public class UserRepositoryTCAutoIntegrationTest extends UserRepositoryCommon { +public class UserRepositoryTCAutoLiveTest extends UserRepositoryCommon { @ClassRule public static PostgreSQLContainer postgreSQLContainer = BaeldungPostgresqlContainer.getInstance(); diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java similarity index 93% rename from persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCIntegrationTest.java rename to persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java index afdf60cc81..be8843c166 100644 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCIntegrationTest.java +++ b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java @@ -22,8 +22,8 @@ import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) @ActiveProfiles("tc") -@ContextConfiguration(initializers = {UserRepositoryTCIntegrationTest.Initializer.class}) -public class UserRepositoryTCIntegrationTest extends UserRepositoryCommon { +@ContextConfiguration(initializers = {UserRepositoryTCLiveTest.Initializer.class}) +public class UserRepositoryTCLiveTest extends UserRepositoryCommon { @ClassRule public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:11.1") diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java index c3805bac57..31877255b2 100644 --- a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java @@ -3,7 +3,7 @@ package com.baeldung.hibernate.criteria; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; - +import static org.junit.Assert.assertFalse; import java.util.List; import org.hibernate.Session; @@ -25,7 +25,7 @@ public class HibernateCriteriaIntegrationTest { @Test public void testPerformanceOfCriteria() { - assertTrue(av.checkIfCriteriaTimeLower()); + assertFalse(av.checkIfCriteriaTimeLower()); } @Test From f689fa9e5e366ab2aaaafdd137851fb0b269e090 Mon Sep 17 00:00:00 2001 From: Gian Mario Contessa Date: Thu, 30 May 2019 18:03:11 +0100 Subject: [PATCH 114/167] BAEL-2899: moving joint compilation to core-groovy-2 module --- .../gmavenplus-pom.xml | 132 +++++++++-------- core-groovy-2/pom.xml | 84 ++++++----- .../main/groovy/com/baeldung/CalcMath.groovy | 0 .../groovy/com/baeldung/CalcScript.groovy | 0 .../src/main/java/com/baeldung/App.java | 0 java-groovy-joint/pom.xml | 133 ------------------ 6 files changed, 126 insertions(+), 223 deletions(-) rename {java-groovy-joint => core-groovy-2}/gmavenplus-pom.xml (57%) rename {java-groovy-joint => core-groovy-2}/src/main/groovy/com/baeldung/CalcMath.groovy (100%) rename {java-groovy-joint => core-groovy-2}/src/main/groovy/com/baeldung/CalcScript.groovy (100%) rename {java-groovy-joint => core-groovy-2}/src/main/java/com/baeldung/App.java (100%) delete mode 100644 java-groovy-joint/pom.xml diff --git a/java-groovy-joint/gmavenplus-pom.xml b/core-groovy-2/gmavenplus-pom.xml similarity index 57% rename from java-groovy-joint/gmavenplus-pom.xml rename to core-groovy-2/gmavenplus-pom.xml index b34eeb292d..924dab94d1 100644 --- a/java-groovy-joint/gmavenplus-pom.xml +++ b/core-groovy-2/gmavenplus-pom.xml @@ -1,50 +1,19 @@ - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - java-groovy-joint - 0.1.0-SNAPSHOT - java-groovy-joint + core-groovy-2 + 1.0-SNAPSHOT + core-groovy-2 + jar + com.baeldung parent-modules 1.0.0-SNAPSHOT - - UTF-8 - 3.9 - 1.8 - 3.8.1 - 1.2.3 - 2.5.7 - - - - - bintray - Groovy Bintray - https://dl.bintray.com/groovy/maven - - never - - - false - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - ch.qos.logback - logback-classic - ${logback.version} - org.codehaus.groovy groovy-all @@ -52,30 +21,29 @@ pom - junit - junit - 4.11 + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + org.hsqldb + hsqldb + ${hsqldb.version} + test + + + org.spockframework + spock-core + ${spock-core.version} test - + src/main/groovy + src/main/java - - - org.apache.maven.plugins - maven-jar-plugin - 3.1.2 - - - - com.baeldung.App - true - - - - org.codehaus.gmavenplus gmavenplus-plugin @@ -100,7 +68,7 @@ org.codehaus.groovy groovy-all - 2.5.6 + ${groovy.version} runtime pom @@ -110,8 +78,42 @@ org.apache.maven.plugins maven-compiler-plugin - - + + maven-failsafe-plugin + ${maven-failsafe-plugin.version} + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + + + + + junit5 + + integration-test + verify + + + + **/*Test5.java + + + + + + + maven-surefire-plugin + 2.20.1 + + false + + **/*Test.java + **/*Spec.java + + + org.apache.maven.plugins @@ -144,5 +146,19 @@ + + + central + http://jcenter.bintray.com + + + + 1.0.0 + 2.5.7 + 2.4.0 + 1.1-groovy-2.4 + 1.6 + + diff --git a/core-groovy-2/pom.xml b/core-groovy-2/pom.xml index 77de9c8fc8..0ade31acdb 100644 --- a/core-groovy-2/pom.xml +++ b/core-groovy-2/pom.xml @@ -14,26 +14,11 @@ - - org.codehaus.groovy - groovy - ${groovy.version} - org.codehaus.groovy groovy-all - ${groovy-all.version} - pom - - - org.codehaus.groovy - groovy-dateutil ${groovy.version} - - - org.codehaus.groovy - groovy-sql - ${groovy-sql.version} + pom org.junit.platform @@ -56,21 +41,29 @@ + src/main/groovy + src/main/java - org.codehaus.gmavenplus - gmavenplus-plugin - ${gmavenplus-plugin.version} - - - - addSources - addTestSources - compile - compileTests - - - + maven-compiler-plugin + 3.8.0 + + groovy-eclipse-compiler + ${java.version} + ${java.version} + + + + org.codehaus.groovy + groovy-eclipse-compiler + 3.3.0-01 + + + org.codehaus.groovy + groovy-eclipse-batch + ${groovy.version}-01 + + maven-failsafe-plugin @@ -108,6 +101,35 @@ + + + org.apache.maven.plugins + maven-assembly-plugin + 3.1.0 + + + + jar-with-dependencies + + + + + com.baeldung.App + + + + + + + make-assembly + + package + + single + + + + @@ -120,9 +142,7 @@ 1.0.0 - 2.5.6 - 2.5.6 - 2.5.6 + 2.5.7 2.4.0 1.1-groovy-2.4 1.6 diff --git a/java-groovy-joint/src/main/groovy/com/baeldung/CalcMath.groovy b/core-groovy-2/src/main/groovy/com/baeldung/CalcMath.groovy similarity index 100% rename from java-groovy-joint/src/main/groovy/com/baeldung/CalcMath.groovy rename to core-groovy-2/src/main/groovy/com/baeldung/CalcMath.groovy diff --git a/java-groovy-joint/src/main/groovy/com/baeldung/CalcScript.groovy b/core-groovy-2/src/main/groovy/com/baeldung/CalcScript.groovy similarity index 100% rename from java-groovy-joint/src/main/groovy/com/baeldung/CalcScript.groovy rename to core-groovy-2/src/main/groovy/com/baeldung/CalcScript.groovy diff --git a/java-groovy-joint/src/main/java/com/baeldung/App.java b/core-groovy-2/src/main/java/com/baeldung/App.java similarity index 100% rename from java-groovy-joint/src/main/java/com/baeldung/App.java rename to core-groovy-2/src/main/java/com/baeldung/App.java diff --git a/java-groovy-joint/pom.xml b/java-groovy-joint/pom.xml deleted file mode 100644 index 5ac4768865..0000000000 --- a/java-groovy-joint/pom.xml +++ /dev/null @@ -1,133 +0,0 @@ - - - - 4.0.0 - java-groovy-joint - 0.1.0-SNAPSHOT - java-groovy-joint - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - UTF-8 - 3.9 - 1.8 - 3.8.1 - 1.2.3 - 2.5.7 - - - - - bintray - Groovy Bintray - https://dl.bintray.com/groovy/maven - - - never - - - false - - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - org.codehaus.groovy - groovy-all - ${groovy.version} - pom - - - junit - junit - 4.11 - test - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 3.1.2 - - - - com.baeldung.App - true - - - - - - maven-compiler-plugin - 3.8.0 - - groovy-eclipse-compiler - ${java.version} - ${java.version} - - - - org.codehaus.groovy - groovy-eclipse-compiler - 3.3.0-01 - - - org.codehaus.groovy - groovy-eclipse-batch - ${groovy.version}-01 - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 3.1.0 - - - - jar-with-dependencies - - - - - com.baeldung.App - - - - - - - make-assembly - - package - - single - - - - - - - - - From 76370b794ff6d41a3a1463b6fe176ab2223b313b Mon Sep 17 00:00:00 2001 From: Graham Cox Date: Fri, 31 May 2019 09:09:26 +0100 Subject: [PATCH 115/167] Examples of Quasar in Kotlin (#7045) --- kotlin-quasar/pom.xml | 120 ++++++++++++++ .../com/baeldung/quasar/QuasarHelloWorld.kt | 19 +++ .../com/baeldung/quasar/ChannelsTest.kt | 155 ++++++++++++++++++ .../com/baeldung/quasar/DataflowTest.kt | 35 ++++ .../kotlin/com/baeldung/quasar/PiAsyncTest.kt | 53 ++++++ .../quasar/SuspendableCallableTest.kt | 48 ++++++ .../quasar/SuspensableRunnableTest.kt | 47 ++++++ 7 files changed, 477 insertions(+) create mode 100644 kotlin-quasar/pom.xml create mode 100644 kotlin-quasar/src/main/kotlin/com/baeldung/quasar/QuasarHelloWorld.kt create mode 100644 kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ChannelsTest.kt create mode 100644 kotlin-quasar/src/test/kotlin/com/baeldung/quasar/DataflowTest.kt create mode 100644 kotlin-quasar/src/test/kotlin/com/baeldung/quasar/PiAsyncTest.kt create mode 100644 kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspendableCallableTest.kt create mode 100644 kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspensableRunnableTest.kt diff --git a/kotlin-quasar/pom.xml b/kotlin-quasar/pom.xml new file mode 100644 index 0000000000..44feabd183 --- /dev/null +++ b/kotlin-quasar/pom.xml @@ -0,0 +1,120 @@ + + + 4.0.0 + com.baeldung + kotlin-quasar + 1.0.0-SNAPSHOT + kotlin-quasar + jar + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-test + ${kotlin.version} + test + + + co.paralleluniverse + quasar-core + ${quasar.version} + + + co.paralleluniverse + quasar-actors + ${quasar.version} + + + co.paralleluniverse + quasar-reactive-streams + ${quasar.version} + + + co.paralleluniverse + quasar-kotlin + ${quasar.version} + + + junit + junit + 4.12 + + + + + src/main/kotlin + src/test/kotlin + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + 1.8 + + + + maven-dependency-plugin + 3.1.1 + + + getClasspathFilenames + + properties + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.1 + + -Dco.paralleluniverse.fibers.verifyInstrumentation=true + -javaagent:${co.paralleluniverse:quasar-core:jar} + + + + org.codehaus.mojo + exec-maven-plugin + 1.3.2 + + target/classes + echo + + -javaagent:${co.paralleluniverse:quasar-core:jar} + -classpath + com.baeldung.quasar.QuasarHelloWorldKt + + + + + + + + 0.8.0 + 1.3.31 + + diff --git a/kotlin-quasar/src/main/kotlin/com/baeldung/quasar/QuasarHelloWorld.kt b/kotlin-quasar/src/main/kotlin/com/baeldung/quasar/QuasarHelloWorld.kt new file mode 100644 index 0000000000..9bf01ecb09 --- /dev/null +++ b/kotlin-quasar/src/main/kotlin/com/baeldung/quasar/QuasarHelloWorld.kt @@ -0,0 +1,19 @@ +package com.baeldung.quasar + +import co.paralleluniverse.fibers.Fiber +import co.paralleluniverse.strands.SuspendableRunnable + + +/** + * Entrypoint into the application + */ +fun main(args: Array) { + class Runnable : SuspendableRunnable { + override fun run() { + println("Hello") + } + } + val result = Fiber(Runnable()).start() + result.join() + println("World") +} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ChannelsTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ChannelsTest.kt new file mode 100644 index 0000000000..b51943446e --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/ChannelsTest.kt @@ -0,0 +1,155 @@ +package com.baeldung.quasar + +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.kotlin.fiber +import co.paralleluniverse.strands.channels.Channels +import co.paralleluniverse.strands.channels.Selector +import com.google.common.base.Function +import org.junit.Test + +class ChannelsTest { + @Test + fun createChannel() { + Channels.newChannel(0, // The size of the channel buffer + Channels.OverflowPolicy.BLOCK, // The policy for when the buffer is full + true, // Whether we should optimize for a single message producer + true) // Whether we should optimize for a single message consumer + } + + @Test + fun blockOnMessage() { + val channel = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) + + fiber @Suspendable { + while (!channel.isClosed) { + val message = channel.receive() + println("Received: $message") + } + println("Stopped receiving messages") + } + + channel.send("Hello") + channel.send("World") + + channel.close() + } + + @Test + fun selectReceiveChannels() { + val channel1 = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) + val channel2 = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) + + fiber @Suspendable { + while (!channel1.isClosed && !channel2.isClosed) { + val received = Selector.select(Selector.receive(channel1), Selector.receive(channel2)) + + println("Received: $received") + } + } + + fiber @Suspendable { + for (i in 0..10) { + channel1.send("Channel 1: $i") + } + } + + fiber @Suspendable { + for (i in 0..10) { + channel2.send("Channel 2: $i") + } + } + } + + @Test + fun selectSendChannels() { + val channel1 = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) + val channel2 = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) + + fiber @Suspendable { + for (i in 0..10) { + Selector.select( + Selector.send(channel1, "Channel 1: $i"), + Selector.send(channel2, "Channel 2: $i") + ) + } + } + + fiber @Suspendable { + while (!channel1.isClosed) { + val msg = channel1.receive() + println("Read: $msg") + } + } + + fiber @Suspendable { + while (!channel2.isClosed) { + val msg = channel2.receive() + println("Read: $msg") + } + } + } + + @Test + fun tickerChannel() { + val channel = Channels.newChannel(3, Channels.OverflowPolicy.DISPLACE) + + for (i in 0..10) { + val tickerConsumer = Channels.newTickerConsumerFor(channel) + fiber @Suspendable { + while (!tickerConsumer.isClosed) { + val message = tickerConsumer.receive() + println("Received on $i: $message") + } + println("Stopped receiving messages on $i") + } + } + + for (i in 0..50) { + channel.send("Message $i") + } + + channel.close() + } + + + @Test + fun transformOnSend() { + val channel = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) + + fiber @Suspendable { + while (!channel.isClosed) { + val message = channel.receive() + println("Received: $message") + } + println("Stopped receiving messages") + } + + val transformOnSend = Channels.mapSend(channel, Function { msg: String? -> msg?.toUpperCase() }) + + transformOnSend.send("Hello") + transformOnSend.send("World") + + channel.close() + } + + @Test + fun transformOnReceive() { + val channel = Channels.newChannel(0, Channels.OverflowPolicy.BLOCK, true, true) + + val transformOnReceive = Channels.map(channel, Function { msg: String? -> msg?.reversed() }) + + fiber @Suspendable { + while (!transformOnReceive.isClosed) { + val message = transformOnReceive.receive() + println("Received: $message") + } + println("Stopped receiving messages") + } + + + channel.send("Hello") + channel.send("World") + + channel.close() + } +} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/DataflowTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/DataflowTest.kt new file mode 100644 index 0000000000..3f73af3917 --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/DataflowTest.kt @@ -0,0 +1,35 @@ +package com.baeldung.quasar + +import co.paralleluniverse.strands.dataflow.Val +import co.paralleluniverse.strands.dataflow.Var +import org.junit.Assert +import org.junit.Test +import java.util.concurrent.TimeUnit + +class DataflowTest { + @Test + fun testValVar() { + val a = Var() + val b = Val() + + val c = Var { a.get() + b.get() } + val d = Var { a.get() * b.get() } + + // (a*b) - (a+b) + val initialResult = Val { d.get() - c.get() } + val currentResult = Var { d.get() - c.get() } + + a.set(2) + b.set(4) + + Assert.assertEquals(2, initialResult.get()) + Assert.assertEquals(2, currentResult.get()) + + a.set(3) + + TimeUnit.SECONDS.sleep(1) + + Assert.assertEquals(2, initialResult.get()) + Assert.assertEquals(5, currentResult.get()) + } +} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/PiAsyncTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/PiAsyncTest.kt new file mode 100644 index 0000000000..d4ea04820d --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/PiAsyncTest.kt @@ -0,0 +1,53 @@ +package com.baeldung.quasar + +import co.paralleluniverse.fibers.Fiber +import co.paralleluniverse.fibers.FiberAsync +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.kotlin.fiber +import co.paralleluniverse.strands.Strand +import org.junit.Assert +import org.junit.Test +import java.math.BigDecimal +import java.util.concurrent.TimeUnit + +interface PiCallback { + fun success(result: BigDecimal) + fun failure(error: Exception) +} + +fun computePi(callback: PiCallback) { + println("Starting calculations") + TimeUnit.SECONDS.sleep(2) + println("Finished calculations") + callback.success(BigDecimal("3.14")) +} + +class PiAsync : PiCallback, FiberAsync() { + override fun success(result: BigDecimal) { + asyncCompleted(result) + } + + override fun failure(error: Exception) { + asyncFailed(error) + } + + override fun requestAsync() { + computePi(this) + } +} + +class PiAsyncTest { + @Test + fun testPi() { + val result = fiber @Suspendable { + val pi = PiAsync() + println("Waiting to get PI on: " + Fiber.currentFiber().name) + val result = pi.run() + println("Got PI") + + result + }.get() + + Assert.assertEquals(BigDecimal("3.14"), result) + } +} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspendableCallableTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspendableCallableTest.kt new file mode 100644 index 0000000000..9b139dd686 --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspendableCallableTest.kt @@ -0,0 +1,48 @@ +package com.baeldung.quasar + +import co.paralleluniverse.fibers.Fiber +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.kotlin.fiber +import co.paralleluniverse.strands.SuspendableCallable +import org.junit.Assert +import org.junit.Test +import java.util.concurrent.TimeUnit + + +class SuspendableCallableTest { + @Test + fun createFiber() { + class Callable : SuspendableCallable { + override fun run(): String { + println("Inside Fiber") + return "Hello" + } + } + val result = Fiber(Callable()).start() + + Assert.assertEquals("Hello", result.get()) + } + + @Test + fun createFiberLambda() { + val lambda: (() -> String) = { + println("Inside Fiber Lambda") + "Hello" + } + val result = Fiber(lambda) + result.start() + + Assert.assertEquals("Hello", result.get()) + } + + @Test + fun createFiberDsl() { + val result = fiber @Suspendable { + TimeUnit.SECONDS.sleep(5) + println("Inside Fiber DSL") + "Hello" + } + + Assert.assertEquals("Hello", result.get()) + } +} diff --git a/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspensableRunnableTest.kt b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspensableRunnableTest.kt new file mode 100644 index 0000000000..ba4cef8f4c --- /dev/null +++ b/kotlin-quasar/src/test/kotlin/com/baeldung/quasar/SuspensableRunnableTest.kt @@ -0,0 +1,47 @@ +package com.baeldung.quasar + +import co.paralleluniverse.fibers.Fiber +import co.paralleluniverse.fibers.Suspendable +import co.paralleluniverse.kotlin.fiber +import co.paralleluniverse.strands.SuspendableRunnable +import org.junit.Test +import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeoutException + + +class SuspensableRunnableTest { + @Test + fun createFiber() { + class Runnable : SuspendableRunnable { + override fun run() { + println("Inside Fiber") + } + } + val result = Fiber(Runnable()).start() + result.join() + } + + @Test + fun createFiberLambda() { + val result = Fiber { + println("Inside Fiber Lambda") + } + result.start() + result.join() + } + + @Test + fun createFiberDsl() { + fiber @Suspendable { + println("Inside Fiber DSL") + }.join() + } + + @Test(expected = TimeoutException::class) + fun fiberTimeout() { + fiber @Suspendable { + TimeUnit.SECONDS.sleep(5) + println("Inside Fiber DSL") + }.join(2, TimeUnit.SECONDS) + } +} From a0282482bc45d6a47e5c10cf078f7260bd1c867c Mon Sep 17 00:00:00 2001 From: codehunter34 Date: Fri, 31 May 2019 23:23:12 -0400 Subject: [PATCH 116/167] BAEL-2969: Copying Sets in Java --- .../core-java-collections-set/pom.xml | 71 ++++++++++-------- .../main/java/com/baeldung/set/CopySets.java | 74 +++++++++++++++++++ 2 files changed, 116 insertions(+), 29 deletions(-) create mode 100644 core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java diff --git a/core-java-modules/core-java-collections-set/pom.xml b/core-java-modules/core-java-collections-set/pom.xml index 2a930efde8..4c1b880f31 100644 --- a/core-java-modules/core-java-collections-set/pom.xml +++ b/core-java-modules/core-java-collections-set/pom.xml @@ -1,33 +1,46 @@ - - 4.0.0 - core-java-collections-set - 0.1.0-SNAPSHOT - core-java-collections-set - jar + + 4.0.0 + core-java-collections-set + 0.1.0-SNAPSHOT + core-java-collections-set + jar - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + - - - com.google.guava - guava - ${guava.version} - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - - + + + com.google.guava + guava + ${guava.version} + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + - - 4.3 - 27.1-jre - + + com.google.code.gson + gson + 2.8.5 + + + + commons-lang + commons-lang + 2.6 + + + + + 4.3 + 27.1-jre + diff --git a/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java new file mode 100644 index 0000000000..011ccb9b56 --- /dev/null +++ b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java @@ -0,0 +1,74 @@ +package com.baeldung.set; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +import org.apache.commons.lang.SerializationUtils; + +import com.google.gson.Gson; + +public class CopySets { + + public static Set copyByConstructor(Set original) { + Set copy = new HashSet<>(original); + return copy; + } + + public static Set copyBySetAddAll(Set original) { + Set copy = new HashSet<>(); + copy.addAll(original); + return copy; + } + + public static Set copyBySetClone(HashSet original) { + Set copy = (Set) original.clone(); + return copy; + } + + public static Set copyByJson(Set original) { + Gson gson = new Gson(); + String jsonStr = gson.toJson(original); + Set copy = gson.fromJson(jsonStr, Set.class); + + return copy; + } + + public static Set copyByApacheCommonsLang(Set original) { + Set copy = new HashSet<>(); + for (T item : original) { + copy.add((T) SerializationUtils.clone(item)); + } + return copy; + } + + public static void copyByStreamsAPI(Set original) { + Set copy1 = original.stream() + .collect(Collectors.toSet()); + + // Skip the first element + Set copy2 = original.stream() + .skip(1) + .collect(Collectors.toSet()); + + // Filter by comparing the types and attributes + Set copy3 = original.stream() + .filter(f -> f.getClass() + .equals(Integer.class)) + .collect(Collectors.toSet()); + + // Null check in case of expecting null values + Set copy4 = original.stream() + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + + } + + public static Set copyByJava8(Set original) { + Set copy = Set.copyOf(original); + return copy; + } + +} From 879ac26e844628cd63f69c20b3e6a3deb028621e Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 1 Jun 2019 09:15:51 +0300 Subject: [PATCH 117/167] Update README.md --- spring-security-rest-custom/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-rest-custom/README.md b/spring-security-rest-custom/README.md index 85f2b7532c..d7cb31e784 100644 --- a/spring-security-rest-custom/README.md +++ b/spring-security-rest-custom/README.md @@ -8,3 +8,4 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com ### Relevant Articles: - [Spring Security Authentication Provider](http://www.baeldung.com/spring-security-authentication-provider) - [Retrieve User Information in Spring Security](http://www.baeldung.com/get-user-in-spring-security) +- [Spring Security – Run-As Authentication](https://www.baeldung.com/spring-security-run-as-auth) From d73979fdf28ead60fffdbcd2991cbb55170cfd21 Mon Sep 17 00:00:00 2001 From: maryarm Date: Sat, 1 Jun 2019 12:15:57 +0430 Subject: [PATCH 118/167] #BAEL-2802: Implement response decoder for ok http client and apply review notes --- libraries-2/pom.xml | 27 +++ .../okhttp/ResponseDecoderUnitTest.java | 160 ++++++++++++++++++ .../com/baeldung/okhttp/SimpleEntity.java | 21 +++ 3 files changed, 208 insertions(+) create mode 100644 libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java create mode 100644 libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index 6303c0cab5..d3c0f7204b 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -55,6 +55,33 @@ spring-boot-starter ${spring-boot-starter.version} + + + + com.squareup.okhttp3 + okhttp + 3.14.2 + + + + com.fasterxml.jackson.core + jackson-databind + 2.9.9 + + + + com.google.code.gson + gson + 2.8.5 + + + + com.squareup.okhttp3 + mockwebserver + 3.14.2 + test + + diff --git a/libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java b/libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java new file mode 100644 index 0000000000..e9f829abe4 --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java @@ -0,0 +1,160 @@ +package com.baeldung.okhttp; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.ResponseBody; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.io.InputStreamReader; + +public class ResponseDecoderUnitTest { + + @Rule + public ExpectedException exceptionRule = ExpectedException.none(); + + @Rule + public MockWebServer server = new MockWebServer(); + + SimpleEntity sampleResponse; + + MockResponse mockResponse; + + OkHttpClient client; + + + @Before + public void setUp() { + sampleResponse = new SimpleEntity("Baeldung"); + client = new OkHttpClient.Builder() + .build(); + mockResponse = new MockResponse() + .setResponseCode(200) + .setHeader("Content-Type", "application/json") + .setBody(new Gson().toJson(sampleResponse)); + } + + @Test + public void givenJacksonDecoder_whenGetByteStreamOfResponse_thenExpectSimpleEntity() throws Exception { + + server.enqueue(mockResponse); + + Request request = new Request.Builder() + .url(server.url("")) + .build(); + ResponseBody responseBody = client.newCall(request).execute().body(); + + Assert.assertNotNull(responseBody); + Assert.assertNotEquals(0, responseBody.contentLength()); + + ObjectMapper objectMapper = new ObjectMapper(); + SimpleEntity response = objectMapper.readValue(responseBody.byteStream() + , SimpleEntity.class); + + Assert.assertEquals(sampleResponse.getName(), response.getName()); + } + + @Test + public void givenJacksonDecoder_whenGetStringOfResponse_thenExpectSimpleEntity() throws Exception { + + server.enqueue(mockResponse); + + Request request = new Request.Builder() + .url(server.url("")) + .build(); + ResponseBody responseBody = client.newCall(request).execute().body(); + + Assert.assertNotNull(responseBody); + Assert.assertNotEquals(0, responseBody.contentLength()); + + ObjectMapper objectMapper = new ObjectMapper(); + SimpleEntity response = objectMapper.readValue(responseBody.string(), SimpleEntity.class); + + Assert.assertEquals(sampleResponse.getName(), response.getName()); + } + + @Test + public void givenJacksonDecoder_whenGetCharStreamOfResponse_thenExpectSimpleEntity() throws Exception { + + server.enqueue(mockResponse); + + Request request = new Request.Builder() + .url(server.url("")) + .build(); + ResponseBody responseBody = client.newCall(request).execute().body(); + + Assert.assertNotNull(responseBody); + Assert.assertNotEquals(0, responseBody.contentLength()); + + ObjectMapper objectMapper = new ObjectMapper(); + SimpleEntity response = objectMapper.readValue(responseBody.charStream(), SimpleEntity.class); + + Assert.assertEquals(sampleResponse.getName(), response.getName()); + } + + @Test + public void givenGsonDecoder_whenGetByteStreamOfResponse_thenExpectSimpleEntity() throws Exception { + + server.enqueue(mockResponse); + + Request request = new Request.Builder() + .url(server.url("")) + .build(); + ResponseBody responseBody = client.newCall(request).execute().body(); + + Assert.assertNotNull(responseBody); + Assert.assertNotEquals(0, responseBody.contentLength()); + + Gson gson = new Gson(); + SimpleEntity response = gson.fromJson(new InputStreamReader(responseBody.byteStream()) + , SimpleEntity.class); + + Assert.assertEquals(sampleResponse.getName(), response.getName()); + } + + @Test + public void givenGsonDecoder_whenGetStringOfResponse_thenExpectSimpleEntity() throws Exception { + + server.enqueue(mockResponse); + + Request request = new Request.Builder() + .url(server.url("")) + .build(); + ResponseBody responseBody = client.newCall(request).execute().body(); + + Assert.assertNotNull(responseBody); + + Gson gson = new Gson(); + SimpleEntity response = gson.fromJson(responseBody.string(), SimpleEntity.class); + + Assert.assertEquals(sampleResponse.getName(), response.getName()); + } + + @Test + public void givenGsonDecoder_whenGetCharStreamOfResponse_thenExpectSimpleEntity() throws Exception { + + server.enqueue(mockResponse); + + Request request = new Request.Builder() + .url(server.url("")) + .build(); + + ResponseBody responseBody = client.newCall(request).execute().body(); + + Assert.assertNotNull(responseBody); + + Gson gson = new Gson(); + SimpleEntity response = gson.fromJson(responseBody.charStream(), SimpleEntity.class); + + Assert.assertEquals(sampleResponse.getName(), response.getName()); + } + + +} diff --git a/libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java b/libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java new file mode 100644 index 0000000000..4c7cae6fdc --- /dev/null +++ b/libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java @@ -0,0 +1,21 @@ +package com.baeldung.okhttp; + +public class SimpleEntity { + protected String name; + + public SimpleEntity(String name) { + this.name = name; + } + + //no-arg constructor, getters and setters here + public SimpleEntity() { + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} From dc73b7abff2f44e495546531b6cc7259efcdd855 Mon Sep 17 00:00:00 2001 From: pkoli Date: Sat, 1 Jun 2019 13:50:48 +0530 Subject: [PATCH 119/167] BAEL-2886- post incremented counter variable --- .../SpringSessionMongoDBIntegrationTest.java | 43 ------------------- spring-session/spring-session-mongodb/pom.xml | 2 + .../SpringSessionMongoDBController.java | 6 +-- .../SpringSessionMongoDBIntegrationTest.java | 8 ++-- .../SpringContextIntegrationTest.java | 3 +- 5 files changed, 10 insertions(+), 52 deletions(-) delete mode 100644 spring-session/mongodb-session/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java diff --git a/spring-session/mongodb-session/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java b/spring-session/mongodb-session/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java deleted file mode 100644 index c73335b49b..0000000000 --- a/spring-session/mongodb-session/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.springsessionmongodb; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.session.data.mongo.MongoOperationsSessionRepository; -import org.springframework.test.context.junit4.SpringRunner; -import springsessionmongodb.SpringSessionMongoDBApplication; - -import java.util.Base64; - - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringSessionMongoDBApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class SpringSessionMongoDBIntegrationTest { - - @Autowired - private MongoOperationsSessionRepository repository; - - private TestRestTemplate restTemplate = new TestRestTemplate(); - - @Test - public void givenEndpointIsCalledTwiceAndResponseIsReturned_whenMongoDBIsQueriedForCount_thenCountMustBeSame() { - HttpEntity response = restTemplate. - exchange("http://localhost:" + 8080, HttpMethod.GET, null, String.class); - HttpHeaders headers = response.getHeaders(); - String set_cookie = headers.getFirst(HttpHeaders.SET_COOKIE); - - Assert.assertEquals(response.getBody(), - repository.findById(getSessionId(set_cookie)).getAttribute("count").toString()); - } - - private String getSessionId(String set_cookie) { - return new String(Base64.getDecoder().decode(set_cookie.split(";")[0].split("=")[1])); - } - -} diff --git a/spring-session/spring-session-mongodb/pom.xml b/spring-session/spring-session-mongodb/pom.xml index 714833cf99..16fbaccc84 100644 --- a/spring-session/spring-session-mongodb/pom.xml +++ b/spring-session/spring-session-mongodb/pom.xml @@ -32,6 +32,7 @@ org.springframework.boot spring-boot-starter-data-mongodb + ${spring-boot-starter-data-mongodb.version} @@ -43,6 +44,7 @@ 2.1.3.RELEASE + 2.1.5.RELEASE diff --git a/spring-session/spring-session-mongodb/src/main/java/com/baeldung/springsessionmongodb/controller/SpringSessionMongoDBController.java b/spring-session/spring-session-mongodb/src/main/java/com/baeldung/springsessionmongodb/controller/SpringSessionMongoDBController.java index 1c38f419c3..b5cb4520a0 100644 --- a/spring-session/spring-session-mongodb/src/main/java/com/baeldung/springsessionmongodb/controller/SpringSessionMongoDBController.java +++ b/spring-session/spring-session-mongodb/src/main/java/com/baeldung/springsessionmongodb/controller/SpringSessionMongoDBController.java @@ -1,11 +1,11 @@ package com.baeldung.springsessionmongodb.controller; -import javax.servlet.http.HttpSession; - import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; +import javax.servlet.http.HttpSession; + @RestController public class SpringSessionMongoDBController { @@ -17,7 +17,7 @@ public class SpringSessionMongoDBController { if (counter == null) { counter = 1; } else { - counter += 1; + counter++; } session.setAttribute("count", counter); diff --git a/spring-session/spring-session-mongodb/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java b/spring-session/spring-session-mongodb/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java index eb9f4164a6..9dc45c5b32 100644 --- a/spring-session/spring-session-mongodb/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java +++ b/spring-session/spring-session-mongodb/src/test/java/com/baeldung/springsessionmongodb/SpringSessionMongoDBIntegrationTest.java @@ -1,7 +1,5 @@ package com.baeldung.springsessionmongodb; -import java.util.Base64; - import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -14,6 +12,8 @@ import org.springframework.http.HttpMethod; import org.springframework.session.data.mongo.MongoOperationsSessionRepository; import org.springframework.test.context.junit4.SpringRunner; +import java.util.Base64; + @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringSessionMongoDBApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) @@ -26,8 +26,8 @@ public class SpringSessionMongoDBIntegrationTest { @Test public void givenEndpointIsCalledTwiceAndResponseIsReturned_whenMongoDBIsQueriedForCount_thenCountMustBeSame() { - HttpEntity response = restTemplate. - exchange("http://localhost:" + 8080, HttpMethod.GET, null, String.class); + HttpEntity response = restTemplate + .exchange("http://localhost:" + 8080, HttpMethod.GET, null, String.class); HttpHeaders headers = response.getHeaders(); String set_cookie = headers.getFirst(HttpHeaders.SET_COOKIE); diff --git a/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 3c58b2673f..16b7404f57 100644 --- a/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-session/spring-session-mongodb/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,12 +1,11 @@ package org.baeldung; +import com.baeldung.springsessionmongodb.SpringSessionMongoDBApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.springsessionmongodb.SpringSessionMongoDBApplication; - @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringSessionMongoDBApplication.class) public class SpringContextIntegrationTest { From 011bd19b09f26f2c62468dcc4240c4472ad427a1 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 1 Jun 2019 11:32:00 +0300 Subject: [PATCH 120/167] revert junit version --- pom.xml | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/pom.xml b/pom.xml index 39803fd9b0..0a8eebda71 100644 --- a/pom.xml +++ b/pom.xml @@ -123,17 +123,22 @@ - - org.junit.jupiter - junit-jupiter-engine - ${junit-jupiter.version} - - - org.junit.vintage - junit-vintage-engine - ${junit-jupiter.version} - - + + org.junit.platform + junit-platform-surefire-provider + ${junit-platform.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + + + org.junit.vintage + junit-vintage-engine + ${junit-jupiter.version} + + org.apache.maven.plugins @@ -1550,8 +1555,8 @@ 1.2 2.9.8 1.3 - 1.4.2 - 5.4.2 + 1.2.0 + 5.4.0 0.3.1 2.5.1 0.0.1 From 503331b3715b8538bd320159f2cfb4a1a83fd07b Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 1 Jun 2019 17:24:25 +0300 Subject: [PATCH 121/167] Update README.md --- persistence-modules/java-mongodb/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/java-mongodb/README.md b/persistence-modules/java-mongodb/README.md index 6d31467db3..045b245030 100644 --- a/persistence-modules/java-mongodb/README.md +++ b/persistence-modules/java-mongodb/README.md @@ -3,3 +3,4 @@ - [A Guide to MongoDB with Java](http://www.baeldung.com/java-mongodb) - [A Simple Tagging Implementation with MongoDB](http://www.baeldung.com/mongodb-tagging) - [MongoDB BSON Guide](https://www.baeldung.com/mongodb-bson) +- [Geospatial Support in MongoDB](https://www.baeldung.com/mongodb-geospatial-support) From 0e56ee46fe49ad6d87173baa35d9e9f8c14b37cc Mon Sep 17 00:00:00 2001 From: Loredana Date: Sat, 1 Jun 2019 18:57:18 +0300 Subject: [PATCH 122/167] fix flowable test --- .../main/resources/processes/article-workflow.bpmn20.xml | 4 ++-- ...lowUnitTest.java => ArticleWorkflowIntegrationTest.java} | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) rename spring-boot-flowable/src/test/java/com/baeldung/processes/{ArticleWorkflowUnitTest.java => ArticleWorkflowIntegrationTest.java} (90%) diff --git a/spring-boot-flowable/src/main/resources/processes/article-workflow.bpmn20.xml b/spring-boot-flowable/src/main/resources/processes/article-workflow.bpmn20.xml index 6bf210dcee..77c02f39a4 100644 --- a/spring-boot-flowable/src/main/resources/processes/article-workflow.bpmn20.xml +++ b/spring-boot-flowable/src/main/resources/processes/article-workflow.bpmn20.xml @@ -38,12 +38,12 @@ + flowable:class="com.baeldung.service.PublishArticleService" /> + flowable:class="com.baeldung.service.SendMailService" /> diff --git a/spring-boot-flowable/src/test/java/com/baeldung/processes/ArticleWorkflowUnitTest.java b/spring-boot-flowable/src/test/java/com/baeldung/processes/ArticleWorkflowIntegrationTest.java similarity index 90% rename from spring-boot-flowable/src/test/java/com/baeldung/processes/ArticleWorkflowUnitTest.java rename to spring-boot-flowable/src/test/java/com/baeldung/processes/ArticleWorkflowIntegrationTest.java index ef5453623a..7d4557a679 100644 --- a/spring-boot-flowable/src/test/java/com/baeldung/processes/ArticleWorkflowUnitTest.java +++ b/spring-boot-flowable/src/test/java/com/baeldung/processes/ArticleWorkflowIntegrationTest.java @@ -13,11 +13,11 @@ import org.flowable.task.api.Task; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.boot.test.context.SpringBootTest; @ExtendWith(FlowableSpringExtension.class) -@ExtendWith(SpringExtension.class) -public class ArticleWorkflowUnitTest { +@SpringBootTest +public class ArticleWorkflowIntegrationTest { @Autowired private RuntimeService runtimeService; @Autowired From 4abfc5f863108106464cc0328294c4750734fafd Mon Sep 17 00:00:00 2001 From: Loredana Date: Sun, 2 Jun 2019 10:01:12 +0300 Subject: [PATCH 123/167] fix filter test --- .../baeldung/hibernate/DynamicMappingIntegrationTest.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java index f31a61f121..fce670112b 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java @@ -122,14 +122,11 @@ public class DynamicMappingIntegrationTest { Employee employee = session.get(Employee.class, 1); assertThat(employee.getGrossIncome()).isEqualTo(10_000); - session.close(); - - session = HibernateUtil.getSessionFactory().openSession(); - transaction = session.beginTransaction(); + session.disableFilter("incomeLevelFilter"); employees = session.createQuery("from Employee").getResultList(); - assertThat(employees).hasSize(0); + assertThat(employees).hasSize(3); } From f64ef7590a87328bf9fa6e94c451b0a71a00b743 Mon Sep 17 00:00:00 2001 From: Loredana Date: Sun, 2 Jun 2019 10:02:17 +0300 Subject: [PATCH 124/167] fix formatting --- .../com/baeldung/hibernate/DynamicMappingIntegrationTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java index fce670112b..7a112200b5 100644 --- a/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java +++ b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java @@ -122,8 +122,7 @@ public class DynamicMappingIntegrationTest { Employee employee = session.get(Employee.class, 1); assertThat(employee.getGrossIncome()).isEqualTo(10_000); - session.disableFilter("incomeLevelFilter"); - + session.disableFilter("incomeLevelFilter"); employees = session.createQuery("from Employee").getResultList(); assertThat(employees).hasSize(3); From 9e0e8a6b0b51de297b344cc59364cb8251571b65 Mon Sep 17 00:00:00 2001 From: Gian Mario Contessa Date: Sun, 2 Jun 2019 11:09:12 +0100 Subject: [PATCH 125/167] [BAEL-2899] removed exception and added dependencies needed for correct compilation --- core-groovy-2/gmavenplus-pom.xml | 18 ++++++- core-groovy-2/pom.xml | 54 +++++++++++++++---- .../{App.java => MyJointCompilationApp.java} | 25 +++++---- 3 files changed, 76 insertions(+), 21 deletions(-) rename core-groovy-2/src/main/java/com/baeldung/{App.java => MyJointCompilationApp.java} (85%) diff --git a/core-groovy-2/gmavenplus-pom.xml b/core-groovy-2/gmavenplus-pom.xml index 924dab94d1..54c89b9834 100644 --- a/core-groovy-2/gmavenplus-pom.xml +++ b/core-groovy-2/gmavenplus-pom.xml @@ -14,6 +14,16 @@ + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + ch.qos.logback + logback-classic + ${logback.version} + org.codehaus.groovy groovy-all @@ -127,7 +137,7 @@ - com.baeldung.App + com.baeldung.MyJointCompilationApp @@ -154,10 +164,14 @@ + UTF-8 1.0.0 - 2.5.7 2.4.0 1.1-groovy-2.4 + 3.9 + 1.8 + 1.2.3 + 2.5.7 1.6 diff --git a/core-groovy-2/pom.xml b/core-groovy-2/pom.xml index 0ade31acdb..b945546c8a 100644 --- a/core-groovy-2/pom.xml +++ b/core-groovy-2/pom.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-groovy-2 1.0-SNAPSHOT @@ -14,6 +14,16 @@ + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + ch.qos.logback + logback-classic + ${logback.version} + org.codehaus.groovy groovy-all @@ -44,6 +54,12 @@ src/main/groovy src/main/java + + org.codehaus.groovy + groovy-eclipse-compiler + 3.3.0-01 + true + maven-compiler-plugin 3.8.0 @@ -94,11 +110,11 @@ maven-surefire-plugin 2.20.1 - false - - **/*Test.java - **/*Spec.java - + false + + **/*Test.java + **/*Spec.java + @@ -114,7 +130,7 @@ - com.baeldung.App + com.baeldung.MyJointCompilationApp @@ -140,12 +156,32 @@ + + + bintray + Groovy Bintray + https://dl.bintray.com/groovy/maven + + + never + + + false + + + + + 1.0.0 - 2.5.7 2.4.0 1.1-groovy-2.4 - 1.6 + 3.9 + 1.8 + 3.8.1 + 1.2.3 + 2.5.7 + UTF-8 diff --git a/core-groovy-2/src/main/java/com/baeldung/App.java b/core-groovy-2/src/main/java/com/baeldung/MyJointCompilationApp.java similarity index 85% rename from core-groovy-2/src/main/java/com/baeldung/App.java rename to core-groovy-2/src/main/java/com/baeldung/MyJointCompilationApp.java index 6c92c3a0b1..2be2e195ef 100644 --- a/core-groovy-2/src/main/java/com/baeldung/App.java +++ b/core-groovy-2/src/main/java/com/baeldung/MyJointCompilationApp.java @@ -7,31 +7,36 @@ import groovy.util.ScriptException; import org.codehaus.groovy.jsr223.GroovyScriptEngineFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import javax.script.ScriptEngine; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; +import java.net.MalformedURLException; import java.net.URL; /** * Hello world! * */ -public class App { - private final static Logger LOG = LoggerFactory.getLogger(App.class); +public class MyJointCompilationApp { + private final static Logger LOG = LoggerFactory.getLogger(MyJointCompilationApp.class); private final GroovyClassLoader loader; private final GroovyShell shell; private final GroovyScriptEngine engine; private final ScriptEngine engineFromFactory; - private App() throws IOException { + public MyJointCompilationApp() { loader = new GroovyClassLoader(this.getClass().getClassLoader()); shell = new GroovyShell(loader, new Binding()); - engine = new GroovyScriptEngine(new URL[] { - new File("src/main/groovy/com/baeldung/").toURI().toURL() - }, this.getClass().getClassLoader()); + + URL url = null; + try { + url = new File("src/main/groovy/com/baeldung/").toURI().toURL(); + } catch (MalformedURLException e) { + LOG.error("Exception while creating url", e); + } + engine = new GroovyScriptEngine(new URL[] {url}, this.getClass().getClassLoader()); engineFromFactory = new GroovyScriptEngineFactory().getScriptEngine(); } @@ -99,8 +104,8 @@ public class App { public static void main(String[] args) throws InstantiationException, IllegalAccessException, ResourceException, ScriptException, IOException, javax.script.ScriptException { - App app = new App(); - app.runStaticCompiledClasses(); - app.runDynamicCompiledClasses(); + MyJointCompilationApp myJointCompilationApp = new MyJointCompilationApp(); + myJointCompilationApp.runStaticCompiledClasses(); + myJointCompilationApp.runDynamicCompiledClasses(); } } From 3fa896b286cfa7c075a0f63fbd2f2a57577b176d Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 2 Jun 2019 23:28:11 +0530 Subject: [PATCH 126/167] [BAEL-14843] - Fixed tests in jersey module --- .../jersey/server/rest/FruitResourceIntegrationTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java b/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java index 376c8c1e75..f7bb0df1ed 100644 --- a/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java +++ b/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java @@ -26,6 +26,7 @@ public class FruitResourceIntegrationTest extends JerseyTest { protected Application configure() { enable(TestProperties.LOG_TRAFFIC); enable(TestProperties.DUMP_ENTITY); + forceSet(TestProperties.CONTAINER_PORT, "0"); ViewApplicationConfig config = new ViewApplicationConfig(); config.register(FruitExceptionMapper.class); From ce68ce1c65b8d7d142c73276dc00caf26fa0bb31 Mon Sep 17 00:00:00 2001 From: binary-joe <48189951+binary-joe@users.noreply.github.com> Date: Mon, 3 Jun 2019 06:42:11 +0200 Subject: [PATCH 127/167] BAEL-2516 catching errors in catch blocks (#7075) * BAEL-2516 catching errors in catch block * BAEL-2516 catching errors in catch block; classes moved --- .../com/baeldung/error/ErrorGenerator.java | 15 ------ .../error/ErrorGeneratorUnitTest.java | 51 ------------------- .../error/ErrorGeneratorUnitTest.java | 26 ++++++++++ 3 files changed, 26 insertions(+), 66 deletions(-) delete mode 100644 core-java-lang/src/main/java/com/baeldung/error/ErrorGenerator.java delete mode 100644 core-java-lang/src/test/java/com/baeldung/error/ErrorGeneratorUnitTest.java create mode 100644 core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exception/error/ErrorGeneratorUnitTest.java diff --git a/core-java-lang/src/main/java/com/baeldung/error/ErrorGenerator.java b/core-java-lang/src/main/java/com/baeldung/error/ErrorGenerator.java deleted file mode 100644 index 58cbe22df5..0000000000 --- a/core-java-lang/src/main/java/com/baeldung/error/ErrorGenerator.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.error; - -public class ErrorGenerator { - public void throwException() throws Exception { - throw new Exception("checked"); - } - - public void throwRuntimeException() { - throw new RuntimeException("unchecked"); - } - - public void throwError() { - throw new Error("unchecked"); - } -} diff --git a/core-java-lang/src/test/java/com/baeldung/error/ErrorGeneratorUnitTest.java b/core-java-lang/src/test/java/com/baeldung/error/ErrorGeneratorUnitTest.java deleted file mode 100644 index 2a7c24f5fa..0000000000 --- a/core-java-lang/src/test/java/com/baeldung/error/ErrorGeneratorUnitTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.error; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class ErrorGeneratorUnitTest { - - private ErrorGenerator errorGenerator; - - @Before - public void setUp() { - errorGenerator = new ErrorGenerator(); - } - - @Test - public void whenCheckedException_thenIsCaughtByCatchException() { - try { - errorGenerator.throwException(); - } catch (Exception e) { - // caught! -> test pass - } - } - - @Test - public void whenUncheckedException_thenIsCaughtByCatchException() { - try { - errorGenerator.throwRuntimeException(); - } catch (Exception e) { - // caught! -> test pass - } - } - - @Test(expected = Error.class) - public void whenError_thenIsNotCaughtByCatchException() { - try { - errorGenerator.throwError(); - } catch (Exception e) { - Assert.fail(); // errors are not caught by catch exception - } - } - - @Test - public void whenError_thenIsCaughtByCatchError() { - try { - errorGenerator.throwError(); - } catch (Error e) { - // caught! -> test pass - } - } -} \ No newline at end of file diff --git a/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exception/error/ErrorGeneratorUnitTest.java b/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exception/error/ErrorGeneratorUnitTest.java new file mode 100644 index 0000000000..de56fb7113 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exception/error/ErrorGeneratorUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.error; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class ErrorGeneratorUnitTest { + + @Test(expected = AssertionError.class) + public void whenError_thenIsNotCaughtByCatchException() { + try { + throw new AssertionError(); + } catch (Exception e) { + Assert.fail(); // errors are not caught by catch exception + } + } + + @Test + public void whenError_thenIsCaughtByCatchError() { + try { + throw new AssertionError(); + } catch (Error e) { + // caught! -> test pass + } + } +} \ No newline at end of file From fd3e1bf293ccda51716aaba1fe7759c95ee1ab8b Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Mon, 3 Jun 2019 23:40:23 +0530 Subject: [PATCH 128/167] BAEL-14787 Reverted junit jupiter version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 0a8eebda71..185c0a4015 100644 --- a/pom.xml +++ b/pom.xml @@ -1556,7 +1556,7 @@ 2.9.8 1.3 1.2.0 - 5.4.0 + 5.2.0 0.3.1 2.5.1 0.0.1 From 3cea8b6df16f6fd743474cce95f96cc6225094eb Mon Sep 17 00:00:00 2001 From: Rodrigo Graciano Date: Mon, 3 Jun 2019 23:34:33 -0400 Subject: [PATCH 129/167] BAEL-2936 --- .../main/java/com/baeldung/convertToMap/ConvertToMap.java | 3 +-- .../com/baeldung/convertToMap/ConvertToMapUnitTest.java | 7 +++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/java-collections-conversions/src/main/java/com/baeldung/convertToMap/ConvertToMap.java b/java-collections-conversions/src/main/java/com/baeldung/convertToMap/ConvertToMap.java index 3c14dfdba6..e33d9ee212 100644 --- a/java-collections-conversions/src/main/java/com/baeldung/convertToMap/ConvertToMap.java +++ b/java-collections-conversions/src/main/java/com/baeldung/convertToMap/ConvertToMap.java @@ -15,8 +15,7 @@ public class ConvertToMap { } public Map listToMapWithDupKey(List books) { - return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity(), - (o1, o2) -> o1)); + return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity(), (existing, replacement) -> existing)); } public Map listToConcurrentMap(List books) { diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertToMap/ConvertToMapUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convertToMap/ConvertToMapUnitTest.java index d11221bbf7..d6eab461d7 100644 --- a/java-collections-conversions/src/test/java/com/baeldung/convertToMap/ConvertToMapUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/convertToMap/ConvertToMapUnitTest.java @@ -2,6 +2,7 @@ package com.baeldung.convertToMap; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static org.junit.Assert.*; @@ -34,8 +35,10 @@ public class ConvertToMapUnitTest { } @Test - public void whenMapHasDuplicateKey_with_merge_function() { - assertTrue(convertToMap.listToMapWithDupKey(bookList).size() == 2); + public void whenMapHasDuplicateKeyThenMergeFunctionHandlesCollision() { + Map booksByYear = convertToMap.listToMapWithDupKey(bookList); + assertEquals(2, booksByYear.size()); + assertEquals("0395489318", booksByYear.get(1954).getIsbn()); } @Test From e4172539cfd9d324addc32ad7fe19ab2af9b139f Mon Sep 17 00:00:00 2001 From: Urvy Agrawal Date: Tue, 4 Jun 2019 13:28:01 +0530 Subject: [PATCH 130/167] Adding files for BAEL-2968 --- spring-boot-parent/pom.xml | 26 +++++++++++ .../spring-boot-with-custom-parent/pom.xml | 42 +++++++++++++++++ ...ingBootStarterCustomParentApplication.java | 13 ++++++ .../spring-boot-with-starter-parent/pom.xml | 46 +++++++++++++++++++ .../SpringBootStarterParentApplication.java | 14 ++++++ 5 files changed, 141 insertions(+) create mode 100644 spring-boot-parent/pom.xml create mode 100644 spring-boot-parent/spring-boot-with-custom-parent/pom.xml create mode 100644 spring-boot-parent/spring-boot-with-custom-parent/src/main/java/com/baeldung/customparent/SpringBootStarterCustomParentApplication.java create mode 100644 spring-boot-parent/spring-boot-with-starter-parent/pom.xml create mode 100644 spring-boot-parent/spring-boot-with-starter-parent/src/main/java/com/baeldung/starterparent/SpringBootStarterParentApplication.java diff --git a/spring-boot-parent/pom.xml b/spring-boot-parent/pom.xml new file mode 100644 index 0000000000..0924917505 --- /dev/null +++ b/spring-boot-parent/pom.xml @@ -0,0 +1,26 @@ + + + + 4.0.0 + com.baeldung + spring-boot-parent + 1.0.0-SNAPSHOT + spring-boot-parent + spring-boot-parent + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + .. + + + + spring-boot-with-starter-parent + spring-boot-with-custom-parent + + + diff --git a/spring-boot-parent/spring-boot-with-custom-parent/pom.xml b/spring-boot-parent/spring-boot-with-custom-parent/pom.xml new file mode 100644 index 0000000000..4afa302cb4 --- /dev/null +++ b/spring-boot-parent/spring-boot-with-custom-parent/pom.xml @@ -0,0 +1,42 @@ + + + + 4.0.0 + spring-boot-with-custom-parent + 1.0.0-SNAPSHOT + spring-boot-with-custom-parent + Demo project for Spring Boot + + + com.baeldung + spring-boot-parent + 1.0.0-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-web + + + + + 1.8 + 2.1.5.RELEASE + + + diff --git a/spring-boot-parent/spring-boot-with-custom-parent/src/main/java/com/baeldung/customparent/SpringBootStarterCustomParentApplication.java b/spring-boot-parent/spring-boot-with-custom-parent/src/main/java/com/baeldung/customparent/SpringBootStarterCustomParentApplication.java new file mode 100644 index 0000000000..169717d7bb --- /dev/null +++ b/spring-boot-parent/spring-boot-with-custom-parent/src/main/java/com/baeldung/customparent/SpringBootStarterCustomParentApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.customparent; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootStarterCustomParentApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootStarterCustomParentApplication.class, args); + System.out.println("Spring boot application running without starter parent"); + } +} diff --git a/spring-boot-parent/spring-boot-with-starter-parent/pom.xml b/spring-boot-parent/spring-boot-with-starter-parent/pom.xml new file mode 100644 index 0000000000..870e051e7d --- /dev/null +++ b/spring-boot-parent/spring-boot-with-starter-parent/pom.xml @@ -0,0 +1,46 @@ + + + + 4.0.0 + com.baeldung + spring-boot-with-starter-parent + 1.0.0-SNAPSHOT + spring-boot-with-starter-parent + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.1.5.RELEASE + + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + 2.1.1.RELEASE + + + + + + + org.springframework.boot + spring-boot-starter-web + + + junit + junit + + + + + 1.8 + 4.11 + + + diff --git a/spring-boot-parent/spring-boot-with-starter-parent/src/main/java/com/baeldung/starterparent/SpringBootStarterParentApplication.java b/spring-boot-parent/spring-boot-with-starter-parent/src/main/java/com/baeldung/starterparent/SpringBootStarterParentApplication.java new file mode 100644 index 0000000000..f987165ce0 --- /dev/null +++ b/spring-boot-parent/spring-boot-with-starter-parent/src/main/java/com/baeldung/starterparent/SpringBootStarterParentApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.starterparent; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootStarterParentApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootStarterParentApplication.class, args); + System.out.println("Spring boot application running with starter parent"); + } + +} From 15ca31cdef078bf4d4afc6e12c5ec666ad666c98 Mon Sep 17 00:00:00 2001 From: Urvy Agrawal Date: Tue, 4 Jun 2019 13:30:26 +0530 Subject: [PATCH 131/167] Added spring-boot-parent in pom.xml --- pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pom.xml b/pom.xml index 185c0a4015..e684ffec10 100644 --- a/pom.xml +++ b/pom.xml @@ -646,6 +646,7 @@ spring-boot-ops-2 spring-boot-rest spring-boot-data + spring-boot-parent spring-boot-property-exp spring-boot-security spring-boot-testing @@ -1310,6 +1311,7 @@ spring-boot-ops-2 spring-boot-rest spring-boot-data + spring-boot-parent spring-boot-property-exp spring-boot-security spring-boot-vue From b5f136ddcdac685cfde0cd84d18a8bcb75e3fa26 Mon Sep 17 00:00:00 2001 From: Urvy Agrawal Date: Tue, 4 Jun 2019 15:04:19 +0530 Subject: [PATCH 132/167] Removed description --- spring-boot-parent/spring-boot-with-custom-parent/pom.xml | 1 - spring-boot-parent/spring-boot-with-starter-parent/pom.xml | 1 - 2 files changed, 2 deletions(-) diff --git a/spring-boot-parent/spring-boot-with-custom-parent/pom.xml b/spring-boot-parent/spring-boot-with-custom-parent/pom.xml index 4afa302cb4..de2946fbb2 100644 --- a/spring-boot-parent/spring-boot-with-custom-parent/pom.xml +++ b/spring-boot-parent/spring-boot-with-custom-parent/pom.xml @@ -7,7 +7,6 @@ spring-boot-with-custom-parent 1.0.0-SNAPSHOT spring-boot-with-custom-parent - Demo project for Spring Boot com.baeldung diff --git a/spring-boot-parent/spring-boot-with-starter-parent/pom.xml b/spring-boot-parent/spring-boot-with-starter-parent/pom.xml index 870e051e7d..1c6479ca60 100644 --- a/spring-boot-parent/spring-boot-with-starter-parent/pom.xml +++ b/spring-boot-parent/spring-boot-with-starter-parent/pom.xml @@ -8,7 +8,6 @@ spring-boot-with-starter-parent 1.0.0-SNAPSHOT spring-boot-with-starter-parent - Demo project for Spring Boot org.springframework.boot From f6a9d02b3733d488b7172ded16562660d1918400 Mon Sep 17 00:00:00 2001 From: FrancoCorleone Date: Wed, 5 Jun 2019 06:31:00 +0200 Subject: [PATCH 133/167] [BAEL-2898] Working with XML in Groovy (#7083) --- .../baeldung/xml/MarkupBuilderUnitTest.groovy | 40 +++++++ .../com/baeldung/xml/XmlParserUnitTest.groovy | 94 ++++++++++++++++ .../baeldung/xml/XmlSlurperUnitTest.groovy | 102 ++++++++++++++++++ .../resources/com/baeldung/xml/articles.xml | 34 ++++++ .../baeldung/xml/articles_short_formatted.xml | 18 ++++ 5 files changed, 288 insertions(+) create mode 100644 core-groovy-2/src/test/groovy/com/baeldung/xml/MarkupBuilderUnitTest.groovy create mode 100644 core-groovy-2/src/test/groovy/com/baeldung/xml/XmlParserUnitTest.groovy create mode 100644 core-groovy-2/src/test/groovy/com/baeldung/xml/XmlSlurperUnitTest.groovy create mode 100644 core-groovy-2/src/test/resources/com/baeldung/xml/articles.xml create mode 100644 core-groovy-2/src/test/resources/com/baeldung/xml/articles_short_formatted.xml diff --git a/core-groovy-2/src/test/groovy/com/baeldung/xml/MarkupBuilderUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/xml/MarkupBuilderUnitTest.groovy new file mode 100644 index 0000000000..c0c8c98392 --- /dev/null +++ b/core-groovy-2/src/test/groovy/com/baeldung/xml/MarkupBuilderUnitTest.groovy @@ -0,0 +1,40 @@ +package com.baeldung.xml + +import groovy.xml.MarkupBuilder +import groovy.xml.XmlUtil +import spock.lang.Specification + +class MarkupBuilderUnitTest extends Specification { + + def xmlFile = getClass().getResource("articles_short_formatted.xml") + +def "Should create XML properly"() { + given: "Node structures" + + when: "Using MarkupBuilderUnitTest to create com.baeldung.xml structure" + def writer = new StringWriter() + new MarkupBuilder(writer).articles { + article { + title('First steps in Java') + author(id: '1') { + firstname('Siena') + lastname('Kerr') + } + 'release-date'('2018-12-01') + } + article { + title('Dockerize your SpringBoot application') + author(id: '2') { + firstname('Jonas') + lastname('Lugo') + } + 'release-date'('2018-12-01') + } + } + + then: "Xml is created properly" + XmlUtil.serialize(writer.toString()) == XmlUtil.serialize(xmlFile.text) +} + + +} diff --git a/core-groovy-2/src/test/groovy/com/baeldung/xml/XmlParserUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/xml/XmlParserUnitTest.groovy new file mode 100644 index 0000000000..ada47406a1 --- /dev/null +++ b/core-groovy-2/src/test/groovy/com/baeldung/xml/XmlParserUnitTest.groovy @@ -0,0 +1,94 @@ +package com.baeldung.xml + + +import spock.lang.Shared +import spock.lang.Specification + +class XmlParserUnitTest extends Specification { + + def xmlFile = getClass().getResourceAsStream("articles.xml") + + @Shared + def parser = new XmlParser() + + def "Should read XML file properly"() { + given: "XML file" + + when: "Using XmlParser to read file" + def articles = parser.parse(xmlFile) + + then: "Xml is loaded properly" + articles.'*'.size() == 4 + articles.article[0].author.firstname.text() == "Siena" + articles.article[2].'release-date'.text() == "2018-06-12" + articles.article[3].title.text() == "Java 12 insights" + articles.article.find { it.author.'@id'.text() == "3" }.author.firstname.text() == "Daniele" + } + + + def "Should add node to existing com.baeldung.xml using NodeBuilder"() { + given: "XML object" + def articles = parser.parse(xmlFile) + + when: "Adding node to com.baeldung.xml" + def articleNode = new NodeBuilder().article(id: '5') { + title('Traversing XML in the nutshell') + author { + firstname('Martin') + lastname('Schmidt') + } + 'release-date'('2019-05-18') + } + articles.append(articleNode) + + then: "Node is added to com.baeldung.xml properly" + articles.'*'.size() == 5 + articles.article[4].title.text() == "Traversing XML in the nutshell" + } + + def "Should replace node"() { + given: "XML object" + def articles = parser.parse(xmlFile) + + when: "Adding node to com.baeldung.xml" + def articleNode = new NodeBuilder().article(id: '5') { + title('Traversing XML in the nutshell') + author { + firstname('Martin') + lastname('Schmidt') + } + 'release-date'('2019-05-18') + } + articles.article[0].replaceNode(articleNode) + + then: "Node is added to com.baeldung.xml properly" + articles.'*'.size() == 4 + articles.article[0].title.text() == "Traversing XML in the nutshell" + } + + def "Should modify node"() { + given: "XML object" + def articles = parser.parse(xmlFile) + + when: "Changing value of one of the nodes" + articles.article.each { it.'release-date'[0].value = "2019-05-18" } + + then: "XML is updated" + articles.article.findAll { it.'release-date'.text() != "2019-05-18" }.isEmpty() + } + + def "Should remove article from com.baeldung.xml"() { + given: "XML object" + def articles = parser.parse(xmlFile) + + when: "Removing all articles but with id==3" + articles.article + .findAll { it.author.'@id'.text() != "3" } + .each { articles.remove(it) } + + then: "There is only one article left" + articles.children().size() == 1 + articles.article[0].author.'@id'.text() == "3" + } + +} diff --git a/core-groovy-2/src/test/groovy/com/baeldung/xml/XmlSlurperUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/xml/XmlSlurperUnitTest.groovy new file mode 100644 index 0000000000..ffeaa46fce --- /dev/null +++ b/core-groovy-2/src/test/groovy/com/baeldung/xml/XmlSlurperUnitTest.groovy @@ -0,0 +1,102 @@ +package com.baeldung.xml + + +import groovy.xml.XmlUtil +import spock.lang.Shared +import spock.lang.Specification + +class XmlSlurperUnitTest extends Specification { + + def xmlFile = getClass().getResourceAsStream("articles.xml") + + @Shared + def parser = new XmlSlurper() + + def "Should read XML file properly"() { + given: "XML file" + + when: "Using XmlSlurper to read file" + def articles = parser.parse(xmlFile) + + then: "Xml is loaded properly" + articles.'*'.size() == 4 + articles.article[0].author.firstname == "Siena" + articles.article[2].'release-date' == "2018-06-12" + articles.article[3].title == "Java 12 insights" + articles.article.find { it.author.'@id' == "3" }.author.firstname == "Daniele" + } + + def "Should add node to existing com.baeldung.xml"() { + given: "XML object" + def articles = parser.parse(xmlFile) + + when: "Adding node to com.baeldung.xml" + articles.appendNode { + article(id: '5') { + title('Traversing XML in the nutshell') + author { + firstname('Martin') + lastname('Schmidt') + } + 'release-date'('2019-05-18') + } + } + + articles = parser.parseText(XmlUtil.serialize(articles)) + + then: "Node is added to com.baeldung.xml properly" + articles.'*'.size() == 5 + articles.article[4].title == "Traversing XML in the nutshell" + } + + def "Should modify node"() { + given: "XML object" + def articles = parser.parse(xmlFile) + + when: "Changing value of one of the nodes" + articles.article.each { it.'release-date' = "2019-05-18" } + + then: "XML is updated" + articles.article.findAll { it.'release-date' != "2019-05-18" }.isEmpty() + } + + def "Should replace node"() { + given: "XML object" + def articles = parser.parse(xmlFile) + + when: "Replacing node" + articles.article[0].replaceNode { + article(id: '5') { + title('Traversing XML in the nutshell') + author { + firstname('Martin') + lastname('Schmidt') + } + 'release-date'('2019-05-18') + } + } + + articles = parser.parseText(XmlUtil.serialize(articles)) + + then: "Node is replaced properly" + articles.'*'.size() == 4 + articles.article[0].title == "Traversing XML in the nutshell" + } + + def "Should remove article from com.baeldung.xml"() { + given: "XML object" + def articles = parser.parse(xmlFile) + + when: "Removing all articles but with id==3" + articles.article + .findAll { it.author.'@id' != "3" } + .replaceNode {} + + articles = parser.parseText(XmlUtil.serialize(articles)) + + then: "There is only one article left" + articles.children().size() == 1 + articles.article[0].author.'@id' == "3" + } + +} diff --git a/core-groovy-2/src/test/resources/com/baeldung/xml/articles.xml b/core-groovy-2/src/test/resources/com/baeldung/xml/articles.xml new file mode 100644 index 0000000000..ef057405f5 --- /dev/null +++ b/core-groovy-2/src/test/resources/com/baeldung/xml/articles.xml @@ -0,0 +1,34 @@ + +
+ First steps in Java + + Siena + Kerr + + 2018-12-01 +
+
+ Dockerize your SpringBoot application + + Jonas + Lugo + + 2018-12-01 +
+
+ SpringBoot tutorial + + Daniele + Ferguson + + 2018-06-12 +
+
+ Java 12 insights + + Siena + Kerr + + 2018-07-22 +
+
diff --git a/core-groovy-2/src/test/resources/com/baeldung/xml/articles_short_formatted.xml b/core-groovy-2/src/test/resources/com/baeldung/xml/articles_short_formatted.xml new file mode 100644 index 0000000000..6492020e03 --- /dev/null +++ b/core-groovy-2/src/test/resources/com/baeldung/xml/articles_short_formatted.xml @@ -0,0 +1,18 @@ + +
+ First steps in Java + + Siena + Kerr + + 2018-12-01 +
+
+ Dockerize your SpringBoot application + + Jonas + Lugo + + 2018-12-01 +
+
From f97f44d024bd159cef864944f1677a2f7461e6bc Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 5 Jun 2019 15:38:19 +0530 Subject: [PATCH 134/167] Back-link added --- persistence-modules/spring-data-jpa-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md index 0f5a826e05..bd259410d1 100644 --- a/persistence-modules/spring-data-jpa-2/README.md +++ b/persistence-modules/spring-data-jpa-2/README.md @@ -12,3 +12,4 @@ - [Spring Data JPA and Null Parameters](https://www.baeldung.com/spring-data-jpa-null-parameters) - [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators) - [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete) +- [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries) From 21a2a2f2f7e1c296c5295a94b4aa834d8d3c4bdf Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 5 Jun 2019 15:42:50 +0530 Subject: [PATCH 135/167] Back-link added --- core-java-modules/core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java/README.md b/core-java-modules/core-java/README.md index c2d1b4a06b..8c7f363d9c 100644 --- a/core-java-modules/core-java/README.md +++ b/core-java-modules/core-java/README.md @@ -51,3 +51,4 @@ - [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators) - [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar) - [Making a JSON POST Request With HttpURLConnection](https://www.baeldung.com/httpurlconnection-post) +- [How to Find an Exception’s Root Cause in Java](https://www.baeldung.com/java-exception-root-cause) From 1e28dd20888169be33477f349a1be9830aba2644 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 5 Jun 2019 15:44:40 +0530 Subject: [PATCH 136/167] Back-link added --- core-groovy-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-groovy-2/README.md b/core-groovy-2/README.md index f60bdb3cbe..9875713bfd 100644 --- a/core-groovy-2/README.md +++ b/core-groovy-2/README.md @@ -4,4 +4,4 @@ - [String Matching in Groovy](http://www.baeldung.com/) - [Groovy def Keyword] - +- [Template Engines in Groovy](https://www.baeldung.com/groovy-template-engines) From e17b4121fe951d76c9d4dd995d0bcce231a48fff Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 5 Jun 2019 15:46:48 +0530 Subject: [PATCH 137/167] Back-link added --- core-java-modules/core-java-arrays/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-arrays/README.md b/core-java-modules/core-java-arrays/README.md index ed8221ebe4..b5f71cc253 100644 --- a/core-java-modules/core-java-arrays/README.md +++ b/core-java-modules/core-java-arrays/README.md @@ -15,3 +15,4 @@ - [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection) - [Sorting Arrays in Java](https://www.baeldung.com/java-sorting-arrays) - [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array) +- [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array) From afbdb59b23db77f6c25d4188ff9a5dcae0e0e6ea Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 5 Jun 2019 15:57:46 +0530 Subject: [PATCH 138/167] Back-link added --- kotlin-libraries-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/kotlin-libraries-2/README.md b/kotlin-libraries-2/README.md index fdb7c2830d..0b9f238d51 100644 --- a/kotlin-libraries-2/README.md +++ b/kotlin-libraries-2/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Jackson Support for Kotlin](https://www.baeldung.com/jackson-kotlin) +- [Introduction to RxKotlin](https://www.baeldung.com/rxkotlin) From ad31a62f3e0c2c3e98ae72a4432823f86c32cba3 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 5 Jun 2019 16:00:27 +0530 Subject: [PATCH 139/167] Back-link added --- jee-7/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jee-7/README.md b/jee-7/README.md index a783e7860e..c57863651d 100644 --- a/jee-7/README.md +++ b/jee-7/README.md @@ -6,3 +6,4 @@ - [A Guide to Java EE Web-Related Annotations](http://www.baeldung.com/javaee-web-annotations) - [Introduction to Testing with Arquillian](http://www.baeldung.com/arquillian) - [Java EE 7 Batch Processing](https://www.baeldung.com/java-ee-7-batch-processing) +- [The Difference Between CDI and EJB Singleton](https://www.baeldung.com/jee-cdi-vs-ejb-singleton) From 38ba51c59763c823b4198a97b4045e5d567f427d Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 5 Jun 2019 16:02:28 +0530 Subject: [PATCH 140/167] Back-link added --- core-java-modules/core-java-8-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-8-2/README.md b/core-java-modules/core-java-8-2/README.md index e2b12e8819..3c8e876cf0 100644 --- a/core-java-modules/core-java-8-2/README.md +++ b/core-java-modules/core-java-8-2/README.md @@ -4,3 +4,4 @@ ### Relevant Articles: - [Anonymous Classes in Java](http://www.baeldung.com/) +- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution) From 1456df016214e3aefb328be37ee6247208285e50 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 5 Jun 2019 16:04:41 +0530 Subject: [PATCH 141/167] Back-link added --- core-java-modules/core-java-11/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-11/README.md b/core-java-modules/core-java-11/README.md index a4b0e0e59c..738bf487b8 100644 --- a/core-java-modules/core-java-11/README.md +++ b/core-java-modules/core-java-11/README.md @@ -7,3 +7,4 @@ - [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client) - [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector) - [Guide to jlink](https://www.baeldung.com/jlink) +- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference) From 00092aeedeeebf4f8edca9dff2e65f84983a106d Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 5 Jun 2019 16:06:35 +0530 Subject: [PATCH 142/167] Back-link added --- core-java-modules/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/README.md b/core-java-modules/README.md index a90535a44f..782d13238b 100644 --- a/core-java-modules/README.md +++ b/core-java-modules/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms) +- [Guide to Java FileChannel](https://www.baeldung.com/java-filechannel) From c262c1ac353b254a3a008e47d4e097e6c4aac70d Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 5 Jun 2019 16:08:26 +0530 Subject: [PATCH 143/167] Back-link added --- persistence-modules/java-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index ba4d9f0410..14d4d95749 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -8,3 +8,4 @@ - [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date) - [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates) - [Types of JPA Queries](https://www.baeldung.com/jpa-queries) +- [JPA/Hibernate Projections](https://www.baeldung.com/jpa-hibernate-projections) From b922b3b313b789e6ff603db053425a935d69823d Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 5 Jun 2019 16:09:59 +0530 Subject: [PATCH 144/167] Back-link added --- spring-boot-ops-2/README.MD | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-boot-ops-2/README.MD b/spring-boot-ops-2/README.MD index 20b30515fb..b4218dc395 100644 --- a/spring-boot-ops-2/README.MD +++ b/spring-boot-ops-2/README.MD @@ -1,3 +1,4 @@ ### Relevant Articles -- [How to Configure Spring Boot Tomcat](https://www.baeldung.com/spring-boot-configure-tomcat) \ No newline at end of file +- [How to Configure Spring Boot Tomcat](https://www.baeldung.com/spring-boot-configure-tomcat) +- [Spring Boot Embedded Tomcat Logs](https://www.baeldung.com/spring-boot-embedded-tomcat-logs) From f94d291df9b45e715e9f4e954fb981d43e6665c5 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 5 Jun 2019 16:12:11 +0530 Subject: [PATCH 145/167] Back-link added --- spring-5-webflux/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-5-webflux/README.md b/spring-5-webflux/README.md index e84ee863bf..87d9ae0dd3 100644 --- a/spring-5-webflux/README.md +++ b/spring-5-webflux/README.md @@ -3,3 +3,4 @@ - [Spring Boot Reactor Netty Configuration](https://www.baeldung.com/spring-boot-reactor-netty) - [How to Return 404 with Spring WebFlux](https://www.baeldung.com/spring-webflux-404) - [Spring WebClient Requests with Parameters](https://www.baeldung.com/webflux-webclient-parameters) +- [RSocket Using Spring Boot](https://www.baeldung.com/spring-boot-rsocket) From 22dcba2d560ebad84282e43e1ef7fe3ea01e3d66 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 5 Jun 2019 16:16:23 +0530 Subject: [PATCH 146/167] Back-link added --- core-java-modules/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/README.md b/core-java-modules/README.md index 782d13238b..7a7d0a7a1b 100644 --- a/core-java-modules/README.md +++ b/core-java-modules/README.md @@ -2,3 +2,4 @@ - [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms) - [Guide to Java FileChannel](https://www.baeldung.com/java-filechannel) +- [Understanding the NumberFormatException in Java](https://www.baeldung.com/java-number-format-exception) From e73e9b98ad17e3f10a5c83f0ae9718d197ac1d54 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 5 Jun 2019 16:17:51 +0530 Subject: [PATCH 147/167] Back-link added --- persistence-modules/java-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 14d4d95749..35e3514c51 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -9,3 +9,4 @@ - [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates) - [Types of JPA Queries](https://www.baeldung.com/jpa-queries) - [JPA/Hibernate Projections](https://www.baeldung.com/jpa-hibernate-projections) +- [Composite Primary Keys in JPA](https://www.baeldung.com/jpa-composite-primary-keys) From 55ad52dac877f570e7f8ef4a2a5a5607d733ca91 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 5 Jun 2019 16:19:29 +0530 Subject: [PATCH 148/167] Back-link added --- jersey/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jersey/README.md b/jersey/README.md index 1dd871b3e8..126dc542ba 100644 --- a/jersey/README.md +++ b/jersey/README.md @@ -3,3 +3,4 @@ - [Bean Validation in Jersey](https://www.baeldung.com/jersey-bean-validation) - [Set a Response Body in JAX-RS](https://www.baeldung.com/jax-rs-response) - [Exploring the Jersey Test Framework](https://www.baeldung.com/jersey-test) +- [Explore Jersey Request Parameters](https://www.baeldung.com/jersey-request-parameters) From 9feca145f8960d6ed135b762643d28503b425aca Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 5 Jun 2019 16:20:54 +0530 Subject: [PATCH 149/167] Back-link added --- ddd/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/ddd/README.md b/ddd/README.md index 60f3a43086..3f3b91380f 100644 --- a/ddd/README.md +++ b/ddd/README.md @@ -1,3 +1,4 @@ ### Relevant articles - [Persisting DDD Aggregates](https://www.baeldung.com/spring-persisting-ddd-aggregates) +- [Double Dispatch in DDD](https://www.baeldung.com/ddd-double-dispatch) From 244ebb1ad131e7cfa35553eba8e891732488b3b1 Mon Sep 17 00:00:00 2001 From: Alessio Stalla Date: Wed, 5 Jun 2019 22:16:47 +0200 Subject: [PATCH 150/167] Code for BAEL-2967 --- persistence-modules/hibernate-mapping/pom.xml | 11 + .../hibernate/persistmaps/mapkey/User.java | 24 +- .../UserAdditionalValidationUnitTest.java | 294 +++++++++++++++--- pom.xml | 1 + 4 files changed, 270 insertions(+), 60 deletions(-) diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index 67eda5bf72..bb8ebdab65 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -42,6 +42,17 @@ javax.el ${org.glassfish.javax.el.version}
+ + javax.money + money-api + 1.0.3 + + + org.javamoney + moneta + 1.3 + pom +
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java index 961fc944a4..b2ee7e85fe 100644 --- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java +++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java @@ -4,9 +4,11 @@ import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.validation.constraints.Size; +import javax.money.MonetaryAmount; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.CreditCardNumber; +import org.hibernate.validator.constraints.Currency; @Entity public class User { @@ -24,12 +26,6 @@ public class User { @Size(min = 3, max = 5) private String city; - @CreditCardNumber - private String creditCardNumber; - - @CreditCardNumber(ignoreNonDigitCharacters = true) - private String lenientCreditCardNumber; - public User(String firstName, String middleName, String lastName, String city) { super(); this.firstName = firstName; @@ -69,20 +65,4 @@ public class User { public void setCity(String city) { this.city = city; } - - public String getCreditCardNumber() { - return creditCardNumber; - } - - public void setCreditCardNumber(String creditCardNumber) { - this.creditCardNumber = creditCardNumber; - } - - public String getLenientCreditCardNumber() { - return lenientCreditCardNumber; - } - - public void setLenientCreditCardNumber(String lenientCreditCardNumber) { - this.lenientCreditCardNumber = lenientCreditCardNumber; - } } diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java index aaf52fe765..0f2a0403e9 100644 --- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java @@ -1,72 +1,290 @@ package com.baeldung.hibernate.validation; -import com.baeldung.hibernate.HibernateUtil; -import com.baeldung.hibernate.Strategy; -import com.baeldung.hibernate.persistmaps.mapkey.User; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import javax.persistence.PersistenceException; -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; -import java.util.Set; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import java.math.BigDecimal; +import java.time.Duration; +import java.util.Set; + +import javax.money.CurrencyContextBuilder; +import javax.money.Monetary; +import javax.money.MonetaryAmount; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + +import org.hibernate.validator.constraints.CodePointLength; +import org.hibernate.validator.constraints.CreditCardNumber; +import org.hibernate.validator.constraints.Currency; +import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.LuhnCheck; +import org.hibernate.validator.constraints.Range; +import org.hibernate.validator.constraints.SafeHtml; +import org.hibernate.validator.constraints.ScriptAssert; +import org.hibernate.validator.constraints.URL; +import org.hibernate.validator.constraints.time.DurationMax; +import org.hibernate.validator.constraints.time.DurationMin; +import org.javamoney.moneta.CurrencyUnitBuilder; +import org.javamoney.moneta.Money; +import org.junit.BeforeClass; +import org.junit.Test; + public class UserAdditionalValidationUnitTest { private static Validator validator; - private static SessionFactory sessionFactory; - private Session session; - private Set> constraintViolations; + private Set> constraintViolations; @BeforeClass public static void before() { ValidatorFactory config = Validation.buildDefaultValidatorFactory(); validator = config.getValidator(); - sessionFactory = HibernateUtil.getSessionFactory(Strategy.MAP_KEY_BASED); - } - - @Before - public void setUp() { - session = sessionFactory.openSession(); - session.beginTransaction(); } @Test public void whenValidationWithCCNAndNullCCN_thenNoConstraintViolation() { - User user = new User("John", "Paul", "Butler", "York"); - constraintViolations = validator.validateProperty(user, "creditCardNumber"); + AdditionalValidations validations = new AdditionalValidations(); + constraintViolations = validator.validateProperty(validations, "creditCardNumber"); assertTrue(constraintViolations.isEmpty()); } @Test public void whenValidationWithCCNAndValidCCN_thenNoConstraintViolation() { - User user = new User("John", "Paul", "Butler", "York"); - user.setCreditCardNumber("79927398713"); - constraintViolations = validator.validateProperty(user, "creditCardNumber"); + AdditionalValidations validations = new AdditionalValidations(); + validations.setCreditCardNumber("79927398713"); + constraintViolations = validator.validateProperty(validations, "creditCardNumber"); assertTrue(constraintViolations.isEmpty()); } @Test public void whenValidationWithCCNAndInvalidCCN_thenConstraintViolation() { - User user = new User("John", "Paul", "Butler", "York"); - user.setCreditCardNumber("79927398714"); - constraintViolations = validator.validateProperty(user, "creditCardNumber"); - assertEquals(constraintViolations.size(), 1); + AdditionalValidations validations = new AdditionalValidations(); + validations.setCreditCardNumber("79927398714"); + constraintViolations = validator.validateProperty(validations, "creditCardNumber"); + assertEquals(constraintViolations.size(), 2); + } + + @Test + public void whenValidationWithCCNAndValidCCNWithDashes_thenConstraintViolation() { + AdditionalValidations validations = new AdditionalValidations(); + validations.setCreditCardNumber("7992-7398-713"); + constraintViolations = validator.validateProperty(validations, "creditCardNumber"); + assertEquals(1, constraintViolations.size()); } @Test public void whenValidationWithLenientCCNAndValidCCNWithDashes_thenNoConstraintViolation() { - User user = new User("John", "Paul", "Butler", "York"); - user.setLenientCreditCardNumber("7992-7398-713"); - constraintViolations = validator.validateProperty(user, "lenientCreditCardNumber"); + AdditionalValidations validations = new AdditionalValidations(); + validations.setLenientCreditCardNumber("7992-7398-713"); + constraintViolations = validator.validateProperty(validations, "lenientCreditCardNumber"); assertTrue(constraintViolations.isEmpty()); } + + @Test + public void whenMonetaryAmountWithRightCurrency_thenNoConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setBalance(Money.of(new BigDecimal(100.0), Monetary.getCurrency("EUR"))); + constraintViolations = validator.validateProperty(bean, "balance"); + assertEquals(0, constraintViolations.size()); + } + + @Test + public void whenMonetaryAmountWithWrongCurrency_thenConstraintViolation() { + AdditionalValidations validations = new AdditionalValidations(); + validations.setBalance(Money.of(new BigDecimal(100.0), Monetary.getCurrency("USD"))); + constraintViolations = validator.validateProperty(validations, "balance"); + assertEquals(1, constraintViolations.size()); + } + + @Test + public void whenDurationShorterThanMin_thenConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setDuration(Duration.ofDays(1).plusHours(1)); + constraintViolations = validator.validateProperty(bean, "duration"); + assertEquals(1, constraintViolations.size()); + } + + @Test + public void whenDurationLongerThanMax_thenConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setDuration(Duration.ofDays(2).plusHours(3)); + constraintViolations = validator.validateProperty(bean, "duration"); + assertEquals(1, constraintViolations.size()); + } + + @Test + public void whenDurationBetweenMinAndMax_thenNoConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setDuration(Duration.ofDays(2)); + constraintViolations = validator.validateProperty(bean, "duration"); + assertEquals(0, constraintViolations.size()); + } + + @Test + public void whenValueBelowRangeMin_thenConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setPercent(new BigDecimal("-1.4")); + constraintViolations = validator.validateProperty(bean, "percent"); + assertEquals(1, constraintViolations.size()); + } + + @Test + public void whenValueAboveRangeMax_thenConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setPercent(new BigDecimal("100.03")); + constraintViolations = validator.validateProperty(bean, "percent"); + assertEquals(1, constraintViolations.size()); + } + + @Test + public void whenValueInRange_thenNoConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setPercent(new BigDecimal("53.23")); + constraintViolations = validator.validateProperty(bean, "percent"); + assertEquals(0, constraintViolations.size()); + } + + @Test + public void whenLengthInRange_thenNoConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setSomeString("aaa"); + constraintViolations = validator.validateProperty(bean, "someString"); + assertEquals(0, constraintViolations.size()); + } + + @Test + public void whenCodePointLengthNotInRange_thenConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + bean.setSomeString("aa\uD835\uDD0A"); + constraintViolations = validator.validateProperty(bean, "someString"); + assertEquals(1, constraintViolations.size()); + } + + @Test + public void whenValidUrlWithWrongProtocol_thenConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + + bean.setUrl("https://www.google.com/"); + constraintViolations = validator.validateProperty(bean, "url"); + assertEquals(0, constraintViolations.size()); + + bean.setUrl("http://www.google.com/"); + constraintViolations = validator.validateProperty(bean, "url"); + assertEquals(1, constraintViolations.size()); + + bean.setUrl("https://foo:bar"); + constraintViolations = validator.validateProperty(bean, "url"); + assertEquals(1, constraintViolations.size()); + } + + @Test + public void whenScriptAssertFails_thenConstraintViolation() { + AdditionalValidations bean = new AdditionalValidations(); + + constraintViolations = validator.validate(bean); + assertEquals(0, constraintViolations.size()); + + bean.setValid(false); + + constraintViolations = validator.validate(bean); + assertEquals(1, constraintViolations.size()); + + constraintViolations = validator.validateProperty(bean, "valid"); + assertEquals(0, constraintViolations.size()); + } + + @ScriptAssert(lang = "nashorn", script = "_this.valid") + public class AdditionalValidations { + private boolean valid = true; + + @CreditCardNumber + @LuhnCheck(startIndex = 0, endIndex = Integer.MAX_VALUE, checkDigitIndex = -1) + private String creditCardNumber; + + @CreditCardNumber(ignoreNonDigitCharacters = true) + private String lenientCreditCardNumber; + + @Currency("EUR") + private MonetaryAmount balance; + + @DurationMin(days = 1, hours = 2) + @DurationMax(days = 2, hours = 1) + private Duration duration; + + @Range(min = 0, max = 100) + private BigDecimal percent; + + @Length(min = 1, max = 3) + @CodePointLength(min = 1, max = 3) + private String someString; + + @URL(protocol = "https") + private String url; + + public String getCreditCardNumber() { + return creditCardNumber; + } + + public void setCreditCardNumber(String creditCardNumber) { + this.creditCardNumber = creditCardNumber; + } + + public String getLenientCreditCardNumber() { + return lenientCreditCardNumber; + } + + public void setLenientCreditCardNumber(String lenientCreditCardNumber) { + this.lenientCreditCardNumber = lenientCreditCardNumber; + } + + public MonetaryAmount getBalance() { + return balance; + } + + public void setBalance(MonetaryAmount balance) { + this.balance = balance; + } + + public Duration getDuration() { + return duration; + } + + public void setDuration(Duration duration) { + this.duration = duration; + } + + public BigDecimal getPercent() { + return percent; + } + + public void setPercent(BigDecimal percent) { + this.percent = percent; + } + + public String getSomeString() { + return someString; + } + + public void setSomeString(String someString) { + this.someString = someString; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public boolean isValid() { + return valid; + } + + public void setValid(boolean valid) { + this.valid = valid; + } + + } } diff --git a/pom.xml b/pom.xml index 03d2e5d763..b9f9f636d3 100644 --- a/pom.xml +++ b/pom.xml @@ -921,6 +921,7 @@ spring-vault spring-vertx spring-zuul/spring-zuul-foos-resource + persistence-modules/hibernate-mapping persistence-modules/spring-data-dynamodb persistence-modules/spring-data-eclipselink persistence-modules/spring-data-solr From cf68c5c771fdc3a8d7ec057857ab83749e61f3ee Mon Sep 17 00:00:00 2001 From: DOHA Date: Thu, 6 Jun 2019 14:46:56 +0200 Subject: [PATCH 151/167] upgrade spring security cloud --- .../spring-cloud-security/auth-client/pom.xml | 16 ++++++++++------ .../src/main/resources/application.properties | 0 .../src/main/resources/application.yml | 4 +++- .../spring-cloud-security/auth-resource/pom.xml | 8 +++++--- .../com/baeldung/config/ResourceConfigurer.java | 11 +++++++---- .../src/main/resources/application.yml | 1 - .../spring-cloud-security/auth-server/pom.xml | 2 +- .../baeldung/config/AuthServerConfigurer.java | 12 +++++++----- .../{WebMvcConfigurer.java => WebMvcConfig.java} | 4 ++-- .../baeldung/config/WebSecurityConfigurer.java | 8 ++++++-- .../src/main/resources/application.yml | 12 +++--------- spring-cloud/spring-cloud-security/pom.xml | 4 ++-- 12 files changed, 46 insertions(+), 36 deletions(-) delete mode 100644 spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.properties rename spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/{WebMvcConfigurer.java => WebMvcConfig.java} (83%) diff --git a/spring-cloud/spring-cloud-security/auth-client/pom.xml b/spring-cloud/spring-cloud-security/auth-client/pom.xml index 4f64f470f0..4152552640 100644 --- a/spring-cloud/spring-cloud-security/auth-client/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-client/pom.xml @@ -24,7 +24,7 @@ org.springframework.cloud - spring-cloud-starter-zuul + spring-cloud-starter-netflix-zuul org.springframework.boot @@ -34,14 +34,16 @@ org.webjars jquery + ${jquery.version} org.webjars bootstrap + ${bootstrap.version} org.webjars - webjars-locator + webjars-locator-core org.springframework.boot @@ -62,8 +64,8 @@ spring-boot-starter-thymeleaf - org.springframework.security.oauth - spring-security-oauth2 + org.springframework.security.oauth.boot + spring-security-oauth2-autoconfigure @@ -89,8 +91,10 @@ - 2.1.0 - Dalston.SR4 + 2.2.0 + Greenwich.SR1 + 3.4.1 + 4.3.1 diff --git a/spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.properties b/spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.properties deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.yml b/spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.yml index 2a758faeae..69617555d9 100644 --- a/spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-security/auth-client/src/main/resources/application.yml @@ -2,7 +2,8 @@ # These are default settings, but we add them for clarity. server: port: 8080 - contextPath: / + servlet: + context-path: / # Configure the Authorization Server and User Info Resource Server details security: @@ -21,6 +22,7 @@ person: # Proxies the calls to http://localhost:8080/api/* to our REST service at http://localhost:8081/* # and automatically includes our OAuth2 token in the request headers zuul: + sensitiveHeaders: Cookie,Set-Cookie routes: resource: path: /api/** diff --git a/spring-cloud/spring-cloud-security/auth-resource/pom.xml b/spring-cloud/spring-cloud-security/auth-resource/pom.xml index 22ee0528c3..a60eca740c 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-resource/pom.xml @@ -19,8 +19,8 @@ spring-boot-starter-web - org.springframework.security.oauth - spring-security-oauth2 + org.springframework.security.oauth.boot + spring-security-oauth2-autoconfigure org.springframework.boot @@ -30,6 +30,7 @@ org.springframework.security spring-security-jwt + ${spring-jwt.version} @@ -55,7 +56,8 @@ - Edgware.RELEASE + Greenwich.SR1 + 1.0.10.RELEASE diff --git a/spring-cloud/spring-cloud-security/auth-resource/src/main/java/com/baeldung/config/ResourceConfigurer.java b/spring-cloud/spring-cloud-security/auth-resource/src/main/java/com/baeldung/config/ResourceConfigurer.java index 977d74093a..abe942325f 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/src/main/java/com/baeldung/config/ResourceConfigurer.java +++ b/spring-cloud/spring-cloud-security/auth-resource/src/main/java/com/baeldung/config/ResourceConfigurer.java @@ -3,7 +3,7 @@ package com.baeldung.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; @@ -11,15 +11,18 @@ import org.springframework.security.oauth2.config.annotation.web.configuration.R * REST API Resource Server. */ @Configuration -@EnableWebSecurity @EnableResourceServer @EnableGlobalMethodSecurity(prePostEnabled = true) // Allow method annotations like @PreAuthorize public class ResourceConfigurer extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { - http.httpBasic().disable(); - http.authorizeRequests().anyRequest().authenticated(); + http.sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.NEVER) + .and() + .authorizeRequests() + .anyRequest().authenticated(); + } } diff --git a/spring-cloud/spring-cloud-security/auth-resource/src/main/resources/application.yml b/spring-cloud/spring-cloud-security/auth-resource/src/main/resources/application.yml index 52e02ba41b..35063a7879 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-security/auth-resource/src/main/resources/application.yml @@ -5,7 +5,6 @@ server: # Configure the public key to use for verifying the incoming JWT tokens security: - sessions: NEVER oauth2: resource: jwt: diff --git a/spring-cloud/spring-cloud-security/auth-server/pom.xml b/spring-cloud/spring-cloud-security/auth-server/pom.xml index 4b3f94b825..afd8dbef44 100644 --- a/spring-cloud/spring-cloud-security/auth-server/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-server/pom.xml @@ -38,7 +38,7 @@ - 1.1.2.RELEASE + 2.1.2.RELEASE \ No newline at end of file diff --git a/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/AuthServerConfigurer.java b/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/AuthServerConfigurer.java index 32e445f998..7c9ee9ae18 100644 --- a/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/AuthServerConfigurer.java +++ b/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/AuthServerConfigurer.java @@ -9,6 +9,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.core.io.Resource; import org.springframework.security.core.userdetails.UserDetailsService; +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.configuration.EnableAuthorizationServer; @@ -19,9 +20,7 @@ import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFacto @Configuration @EnableAuthorizationServer @Order(6) -public class AuthServerConfigurer - extends - AuthorizationServerConfigurerAdapter { +public class AuthServerConfigurer extends AuthorizationServerConfigurerAdapter { @Value("${jwt.certificate.store.file}") private Resource keystore; @@ -37,6 +36,9 @@ public class AuthServerConfigurer @Autowired private UserDetailsService userDetailsService; + + @Autowired + private BCryptPasswordEncoder passwordEncoder; @Override public void configure( @@ -45,8 +47,8 @@ public class AuthServerConfigurer clients .inMemory() .withClient("authserver") - .secret("passwordforauthserver") - .redirectUris("http://localhost:8080/") + .secret(passwordEncoder.encode("passwordforauthserver")) + .redirectUris("http://localhost:8080/login") .authorizedGrantTypes("authorization_code", "refresh_token") .scopes("myscope") diff --git a/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebMvcConfigurer.java b/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebMvcConfig.java similarity index 83% rename from spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebMvcConfigurer.java rename to spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebMvcConfig.java index 23b56151e7..3cefd323b3 100644 --- a/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebMvcConfigurer.java +++ b/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebMvcConfig.java @@ -2,10 +2,10 @@ package com.baeldung.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration -public class WebMvcConfigurer extends WebMvcConfigurerAdapter { +public class WebMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { diff --git a/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebSecurityConfigurer.java b/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebSecurityConfigurer.java index 44406b8fa0..6a48c62097 100644 --- a/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebSecurityConfigurer.java +++ b/spring-cloud/spring-cloud-security/auth-server/src/main/java/com/baeldung/config/WebSecurityConfigurer.java @@ -6,8 +6,8 @@ import org.springframework.security.config.annotation.authentication.builders.Au import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client; @Configuration @@ -34,7 +34,7 @@ public class WebSecurityConfigurer AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() - .withUser("user").password("user") + .withUser("user").password(passwordEncoder().encode("user")) .roles("USER") .and() .withUser("admin").password("admin") @@ -48,5 +48,9 @@ public class WebSecurityConfigurer return super.userDetailsServiceBean(); } + @Bean + public BCryptPasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } } diff --git a/spring-cloud/spring-cloud-security/auth-server/src/main/resources/application.yml b/spring-cloud/spring-cloud-security/auth-server/src/main/resources/application.yml index 1dc63d3f0e..b6e385e5c7 100644 --- a/spring-cloud/spring-cloud-security/auth-server/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-security/auth-server/src/main/resources/application.yml @@ -1,7 +1,8 @@ # Make the application available at http://localhost:7070/authserver server: port: 7070 - contextPath: /authserver + servlet: + context-path: /authserver # Our certificate settings for enabling JWT tokens jwt: @@ -11,11 +12,4 @@ jwt: password: abirkhan04 key: alias: myauthkey - password: abirkhan04 - - -security: - oauth2: - resource: - filter-order: 3 - \ No newline at end of file + password: abirkhan04 \ No newline at end of file diff --git a/spring-cloud/spring-cloud-security/pom.xml b/spring-cloud/spring-cloud-security/pom.xml index 2eecf579a5..d65fd6520b 100644 --- a/spring-cloud/spring-cloud-security/pom.xml +++ b/spring-cloud/spring-cloud-security/pom.xml @@ -8,10 +8,10 @@ pom - parent-boot-1 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 From 054c56451177a2a441c7bed225e56677cab84259 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Thu, 6 Jun 2019 21:05:34 +0530 Subject: [PATCH 152/167] [BAEL-14848] - Fixed tests in spring-data-redis module --- persistence-modules/spring-data-redis/pom.xml | 15 ++++++++++ .../RedisKeyCommandsIntegrationTest.java | 21 +++++++++++++ .../RedisTemplateListOpsIntegrationTest.java | 21 +++++++++++++ .../RedisTemplateValueOpsIntegrationTest.java | 30 ++++++++++++++++--- .../RedisMessageListenerIntegrationTest.java | 6 ++-- .../StudentRepositoryIntegrationTest.java | 6 ++-- 6 files changed, 91 insertions(+), 8 deletions(-) diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index fb80b0413f..4ae8ac0a87 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -79,6 +79,21 @@ + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + true + true + -Xmx1024m + + + + + 3.2.4 2.9.0 diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java index e48aa1e06a..1333f94653 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java @@ -2,6 +2,9 @@ package com.baeldung.spring.data.reactive.redis.template; import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication; + +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -9,22 +12,40 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.connection.ReactiveKeyCommands; import org.springframework.data.redis.connection.ReactiveStringCommands; import org.springframework.data.redis.connection.ReactiveStringCommands.SetCommand; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.junit4.SpringRunner; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import redis.embedded.RedisServerBuilder; +import java.io.IOException; import java.nio.ByteBuffer; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class) +@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class RedisKeyCommandsIntegrationTest { + + private static redis.embedded.RedisServer redisServer; @Autowired private ReactiveKeyCommands keyCommands; @Autowired private ReactiveStringCommands stringCommands; + + @BeforeClass + public static void startRedisServer() throws IOException { + redisServer = new RedisServerBuilder().port(6379).setting("maxheap 256M").build(); + redisServer.start(); + } + + @AfterClass + public static void stopRedisServer() throws IOException { + redisServer.stop(); + } @Test public void givenFluxOfKeys_whenPerformOperations_thenPerformOperations() { diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java index 3ebeff87b1..88c4fa6eed 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java @@ -2,27 +2,48 @@ package com.baeldung.spring.data.reactive.redis.template; import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication; + +import java.io.IOException; + +import org.junit.AfterClass; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.ReactiveListOperations; import org.springframework.data.redis.core.ReactiveRedisTemplate; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.junit4.SpringRunner; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import redis.embedded.RedisServerBuilder; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class) +@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class RedisTemplateListOpsIntegrationTest { private static final String LIST_NAME = "demo_list"; + private static redis.embedded.RedisServer redisServer; @Autowired private ReactiveRedisTemplate redisTemplate; private ReactiveListOperations reactiveListOps; + + @BeforeClass + public static void startRedisServer() throws IOException { + redisServer = new RedisServerBuilder().port(6379).setting("maxheap 128M").build(); + redisServer.start(); + } + + @AfterClass + public static void stopRedisServer() throws IOException { + redisServer.stop(); + } @Before public void setup() { diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java index 9490568089..afa5267582 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java @@ -1,29 +1,51 @@ package com.baeldung.spring.data.reactive.redis.template; -import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication; -import com.baeldung.spring.data.reactive.redis.model.Employee; +import java.io.IOException; +import java.time.Duration; + +import org.junit.AfterClass; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.ReactiveRedisTemplate; import org.springframework.data.redis.core.ReactiveValueOperations; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication; +import com.baeldung.spring.data.reactive.redis.model.Employee; + import reactor.core.publisher.Mono; import reactor.test.StepVerifier; - -import java.time.Duration; +import redis.embedded.RedisServerBuilder; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class) +@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class RedisTemplateValueOpsIntegrationTest { + + private static redis.embedded.RedisServer redisServer; @Autowired private ReactiveRedisTemplate redisTemplate; private ReactiveValueOperations reactiveValueOps; + + @BeforeClass + public static void startRedisServer() throws IOException { + redisServer = new RedisServerBuilder().port(6379).setting("maxheap 256M").build(); + redisServer.start(); + } + + @AfterClass + public static void stopRedisServer() throws IOException { + redisServer.stop(); + } @Before public void setup() { diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java index 99febb6430..1c69b63c09 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/RedisMessageListenerIntegrationTest.java @@ -19,9 +19,11 @@ import com.baeldung.spring.data.redis.config.RedisConfig; import com.baeldung.spring.data.redis.queue.RedisMessagePublisher; import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; +import redis.embedded.RedisServerBuilder; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = RedisConfig.class) -@DirtiesContext(classMode = ClassMode.AFTER_CLASS) +@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class RedisMessageListenerIntegrationTest { private static redis.embedded.RedisServer redisServer; @@ -31,7 +33,7 @@ public class RedisMessageListenerIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new redis.embedded.RedisServer(6380); + redisServer = new RedisServerBuilder().port(6379).setting("maxheap 256M").build(); redisServer.start(); } diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java index 43aadefc01..b1a36475c3 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/redis/repo/StudentRepositoryIntegrationTest.java @@ -20,9 +20,11 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.spring.data.redis.config.RedisConfig; import com.baeldung.spring.data.redis.model.Student; +import redis.embedded.RedisServerBuilder; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = RedisConfig.class) -@DirtiesContext(classMode = ClassMode.AFTER_CLASS) +@DirtiesContext(classMode = ClassMode.BEFORE_CLASS) public class StudentRepositoryIntegrationTest { @Autowired @@ -32,7 +34,7 @@ public class StudentRepositoryIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new redis.embedded.RedisServer(6380); + redisServer = new RedisServerBuilder().port(6379).setting("maxheap 128M").build(); redisServer.start(); } From 0ece18c76608bc841e5b9ad969d94f8c3e7c5bb6 Mon Sep 17 00:00:00 2001 From: Amy DeGregorio Date: Fri, 7 Jun 2019 07:54:00 -0400 Subject: [PATCH 153/167] Bael 2979 Guide to Crawler4j (#7071) * BAEL-2727 Example Code * BAEL-2979 Guide to Crawler4j * BAEL-2979 adjust based on feedback --- libraries-2/pom.xml | 6 +++ .../baeldung/crawler4j/CrawlerStatistics.java | 22 ++++++++ .../com/baeldung/crawler4j/HtmlCrawler.java | 48 +++++++++++++++++ .../crawler4j/HtmlCrawlerController.java | 36 +++++++++++++ .../com/baeldung/crawler4j/ImageCrawler.java | 49 +++++++++++++++++ .../crawler4j/ImageCrawlerController.java | 36 +++++++++++++ .../crawler4j/MultipleCrawlerController.java | 54 +++++++++++++++++++ 7 files changed, 251 insertions(+) create mode 100644 libraries-2/src/main/java/com/baeldung/crawler4j/CrawlerStatistics.java create mode 100644 libraries-2/src/main/java/com/baeldung/crawler4j/HtmlCrawler.java create mode 100644 libraries-2/src/main/java/com/baeldung/crawler4j/HtmlCrawlerController.java create mode 100644 libraries-2/src/main/java/com/baeldung/crawler4j/ImageCrawler.java create mode 100644 libraries-2/src/main/java/com/baeldung/crawler4j/ImageCrawlerController.java create mode 100644 libraries-2/src/main/java/com/baeldung/crawler4j/MultipleCrawlerController.java diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index 6303c0cab5..218bb437cb 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -55,6 +55,11 @@ spring-boot-starter ${spring-boot-starter.version} + + edu.uci.ics + crawler4j + ${crawler4j.version} + @@ -62,6 +67,7 @@ 4.8.28 6.0.0.Final 3.9.6 + 4.4.0 2.1.4.RELEASE diff --git a/libraries-2/src/main/java/com/baeldung/crawler4j/CrawlerStatistics.java b/libraries-2/src/main/java/com/baeldung/crawler4j/CrawlerStatistics.java new file mode 100644 index 0000000000..e3237a2755 --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/crawler4j/CrawlerStatistics.java @@ -0,0 +1,22 @@ +package com.baeldung.crawler4j; + +public class CrawlerStatistics { + private int processedPageCount = 0; + private int totalLinksCount = 0; + + public void incrementProcessedPageCount() { + processedPageCount++; + } + + public void incrementTotalLinksCount(int linksCount) { + totalLinksCount += linksCount; + } + + public int getProcessedPageCount() { + return processedPageCount; + } + + public int getTotalLinksCount() { + return totalLinksCount; + } +} diff --git a/libraries-2/src/main/java/com/baeldung/crawler4j/HtmlCrawler.java b/libraries-2/src/main/java/com/baeldung/crawler4j/HtmlCrawler.java new file mode 100644 index 0000000000..b77e1e075f --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/crawler4j/HtmlCrawler.java @@ -0,0 +1,48 @@ +package com.baeldung.crawler4j; + +import java.util.Set; +import java.util.regex.Pattern; + +import edu.uci.ics.crawler4j.crawler.Page; +import edu.uci.ics.crawler4j.crawler.WebCrawler; +import edu.uci.ics.crawler4j.parser.HtmlParseData; +import edu.uci.ics.crawler4j.url.WebURL; + +public class HtmlCrawler extends WebCrawler { + + private final static Pattern EXCLUSIONS = Pattern.compile(".*(\\.(css|js|xml|gif|jpg|png|mp3|mp4|zip|gz|pdf))$"); + + private CrawlerStatistics stats; + + public HtmlCrawler(CrawlerStatistics stats) { + this.stats = stats; + } + + @Override + public boolean shouldVisit(Page referringPage, WebURL url) { + String urlString = url.getURL().toLowerCase(); + return !EXCLUSIONS.matcher(urlString).matches() + && urlString.startsWith("https://www.baeldung.com/"); + } + + @Override + public void visit(Page page) { + String url = page.getWebURL().getURL(); + stats.incrementProcessedPageCount(); + + if (page.getParseData() instanceof HtmlParseData) { + HtmlParseData htmlParseData = (HtmlParseData) page.getParseData(); + String title = htmlParseData.getTitle(); + String text = htmlParseData.getText(); + String html = htmlParseData.getHtml(); + Set links = htmlParseData.getOutgoingUrls(); + stats.incrementTotalLinksCount(links.size()); + + System.out.printf("Page with title '%s' %n", title); + System.out.printf(" Text length: %d %n", text.length()); + System.out.printf(" HTML length: %d %n", html.length()); + System.out.printf(" %d outbound links %n", links.size()); + } + } + +} diff --git a/libraries-2/src/main/java/com/baeldung/crawler4j/HtmlCrawlerController.java b/libraries-2/src/main/java/com/baeldung/crawler4j/HtmlCrawlerController.java new file mode 100644 index 0000000000..82c1c6bdd7 --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/crawler4j/HtmlCrawlerController.java @@ -0,0 +1,36 @@ +package com.baeldung.crawler4j; + +import java.io.File; + +import edu.uci.ics.crawler4j.crawler.CrawlConfig; +import edu.uci.ics.crawler4j.crawler.CrawlController; +import edu.uci.ics.crawler4j.fetcher.PageFetcher; +import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig; +import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; + +public class HtmlCrawlerController { + + public static void main(String[] args) throws Exception { + File crawlStorage = new File("src/test/resources/crawler4j"); + CrawlConfig config = new CrawlConfig(); + config.setCrawlStorageFolder(crawlStorage.getAbsolutePath()); + config.setMaxDepthOfCrawling(2); + + int numCrawlers = 12; + + PageFetcher pageFetcher = new PageFetcher(config); + RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); + RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); + CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer); + + controller.addSeed("https://www.baeldung.com/"); + + CrawlerStatistics stats = new CrawlerStatistics(); + CrawlController.WebCrawlerFactory factory = () -> new HtmlCrawler(stats); + + controller.start(factory, numCrawlers); + System.out.printf("Crawled %d pages %n", stats.getProcessedPageCount()); + System.out.printf("Total Number of outbound links = %d %n", stats.getTotalLinksCount()); + } + +} diff --git a/libraries-2/src/main/java/com/baeldung/crawler4j/ImageCrawler.java b/libraries-2/src/main/java/com/baeldung/crawler4j/ImageCrawler.java new file mode 100644 index 0000000000..ebb5d96f36 --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/crawler4j/ImageCrawler.java @@ -0,0 +1,49 @@ +package com.baeldung.crawler4j; + +import java.io.File; +import java.util.regex.Pattern; + +import edu.uci.ics.crawler4j.crawler.Page; +import edu.uci.ics.crawler4j.crawler.WebCrawler; +import edu.uci.ics.crawler4j.parser.BinaryParseData; +import edu.uci.ics.crawler4j.url.WebURL; + +public class ImageCrawler extends WebCrawler { + private final static Pattern EXCLUSIONS = Pattern.compile(".*(\\.(css|js|xml|gif|png|mp3|mp4|zip|gz|pdf))$"); + + private static final Pattern IMG_PATTERNS = Pattern.compile(".*(\\.(jpg|jpeg))$"); + + private File saveDir; + + public ImageCrawler(File saveDir) { + this.saveDir = saveDir; + } + + @Override + public boolean shouldVisit(Page referringPage, WebURL url) { + String urlString = url.getURL().toLowerCase(); + if (EXCLUSIONS.matcher(urlString).matches()) { + return false; + } + + if (IMG_PATTERNS.matcher(urlString).matches() + || urlString.startsWith("https://www.baeldung.com/")) { + return true; + } + + return false; + } + + @Override + public void visit(Page page) { + String url = page.getWebURL().getURL(); + if (IMG_PATTERNS.matcher(url).matches() + && page.getParseData() instanceof BinaryParseData) { + String extension = url.substring(url.lastIndexOf(".")); + int contentLength = page.getContentData().length; + + System.out.printf("Extension is '%s' with content length %d %n", extension, contentLength); + } + } + +} diff --git a/libraries-2/src/main/java/com/baeldung/crawler4j/ImageCrawlerController.java b/libraries-2/src/main/java/com/baeldung/crawler4j/ImageCrawlerController.java new file mode 100644 index 0000000000..9db32f1bfb --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/crawler4j/ImageCrawlerController.java @@ -0,0 +1,36 @@ +package com.baeldung.crawler4j; + +import java.io.File; + +import edu.uci.ics.crawler4j.crawler.CrawlConfig; +import edu.uci.ics.crawler4j.crawler.CrawlController; +import edu.uci.ics.crawler4j.fetcher.PageFetcher; +import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig; +import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; + +public class ImageCrawlerController { + + public static void main(String[] args) throws Exception { + File crawlStorage = new File("src/test/resources/crawler4j"); + CrawlConfig config = new CrawlConfig(); + config.setCrawlStorageFolder(crawlStorage.getAbsolutePath()); + config.setIncludeBinaryContentInCrawling(true); + config.setMaxPagesToFetch(500); + + File saveDir = new File("src/test/resources/crawler4j"); + + int numCrawlers = 12; + + PageFetcher pageFetcher = new PageFetcher(config); + RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); + RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher); + CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer); + + controller.addSeed("https://www.baeldung.com/"); + + CrawlController.WebCrawlerFactory factory = () -> new ImageCrawler(saveDir); + + controller.start(factory, numCrawlers); + } + +} diff --git a/libraries-2/src/main/java/com/baeldung/crawler4j/MultipleCrawlerController.java b/libraries-2/src/main/java/com/baeldung/crawler4j/MultipleCrawlerController.java new file mode 100644 index 0000000000..7662607f80 --- /dev/null +++ b/libraries-2/src/main/java/com/baeldung/crawler4j/MultipleCrawlerController.java @@ -0,0 +1,54 @@ +package com.baeldung.crawler4j; + +import java.io.File; + +import edu.uci.ics.crawler4j.crawler.CrawlConfig; +import edu.uci.ics.crawler4j.crawler.CrawlController; +import edu.uci.ics.crawler4j.fetcher.PageFetcher; +import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig; +import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer; + +public class MultipleCrawlerController { + public static void main(String[] args) throws Exception { + File crawlStorageBase = new File("src/test/resources/crawler4j"); + CrawlConfig htmlConfig = new CrawlConfig(); + CrawlConfig imageConfig = new CrawlConfig(); + + htmlConfig.setCrawlStorageFolder(new File(crawlStorageBase, "html").getAbsolutePath()); + imageConfig.setCrawlStorageFolder(new File(crawlStorageBase, "image").getAbsolutePath()); + imageConfig.setIncludeBinaryContentInCrawling(true); + + htmlConfig.setMaxPagesToFetch(500); + imageConfig.setMaxPagesToFetch(1000); + + PageFetcher pageFetcherHtml = new PageFetcher(htmlConfig); + PageFetcher pageFetcherImage = new PageFetcher(imageConfig); + + RobotstxtConfig robotstxtConfig = new RobotstxtConfig(); + RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcherHtml); + + CrawlController htmlController = new CrawlController(htmlConfig, pageFetcherHtml, robotstxtServer); + CrawlController imageController = new CrawlController(imageConfig, pageFetcherImage, robotstxtServer); + + htmlController.addSeed("https://www.baeldung.com/"); + imageController.addSeed("https://www.baeldung.com/"); + + CrawlerStatistics stats = new CrawlerStatistics(); + CrawlController.WebCrawlerFactory htmlFactory = () -> new HtmlCrawler(stats); + + File saveDir = new File("src/test/resources/crawler4j"); + CrawlController.WebCrawlerFactory imageFactory = () -> new ImageCrawler(saveDir); + + imageController.startNonBlocking(imageFactory, 7); + htmlController.startNonBlocking(htmlFactory, 10); + + + htmlController.waitUntilFinish(); + System.out.printf("Crawled %d pages %n", stats.getProcessedPageCount()); + System.out.printf("Total Number of outbound links = %d %n", stats.getTotalLinksCount()); + + imageController.waitUntilFinish(); + System.out.printf("Image Crawler is finished."); + + } +} From c18bb8e18878680635a8e5fbfe1af1d10cb46a49 Mon Sep 17 00:00:00 2001 From: maryarm Date: Fri, 7 Jun 2019 19:36:31 +0430 Subject: [PATCH 154/167] #BAEL-2802 Fix problems with code indentions, spacing and commas. --- .../okhttp/ResponseDecoderUnitTest.java | 124 +++++------------- .../com/baeldung/okhttp/SimpleEntity.java | 1 + 2 files changed, 34 insertions(+), 91 deletions(-) diff --git a/libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java b/libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java index e9f829abe4..11a295031a 100644 --- a/libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/okhttp/ResponseDecoderUnitTest.java @@ -17,11 +17,9 @@ import java.io.InputStreamReader; public class ResponseDecoderUnitTest { - @Rule - public ExpectedException exceptionRule = ExpectedException.none(); + @Rule public ExpectedException exceptionRule = ExpectedException.none(); - @Rule - public MockWebServer server = new MockWebServer(); + @Rule public MockWebServer server = new MockWebServer(); SimpleEntity sampleResponse; @@ -29,132 +27,76 @@ public class ResponseDecoderUnitTest { OkHttpClient client; - @Before public void setUp() { sampleResponse = new SimpleEntity("Baeldung"); - client = new OkHttpClient.Builder() - .build(); + client = new OkHttpClient.Builder().build(); mockResponse = new MockResponse() - .setResponseCode(200) - .setHeader("Content-Type", "application/json") - .setBody(new Gson().toJson(sampleResponse)); - } - - @Test - public void givenJacksonDecoder_whenGetByteStreamOfResponse_thenExpectSimpleEntity() throws Exception { - - server.enqueue(mockResponse); - - Request request = new Request.Builder() - .url(server.url("")) - .build(); - ResponseBody responseBody = client.newCall(request).execute().body(); - - Assert.assertNotNull(responseBody); - Assert.assertNotEquals(0, responseBody.contentLength()); - - ObjectMapper objectMapper = new ObjectMapper(); - SimpleEntity response = objectMapper.readValue(responseBody.byteStream() - , SimpleEntity.class); - - Assert.assertEquals(sampleResponse.getName(), response.getName()); + .setResponseCode(200) + .setHeader("Content-Type", "application/json") + .setBody(new Gson().toJson(sampleResponse)); } @Test public void givenJacksonDecoder_whenGetStringOfResponse_thenExpectSimpleEntity() throws Exception { - server.enqueue(mockResponse); - Request request = new Request.Builder() - .url(server.url("")) - .build(); - ResponseBody responseBody = client.newCall(request).execute().body(); + .url(server.url("")) + .build(); + ResponseBody responseBody = client + .newCall(request) + .execute() + .body(); Assert.assertNotNull(responseBody); Assert.assertNotEquals(0, responseBody.contentLength()); ObjectMapper objectMapper = new ObjectMapper(); - SimpleEntity response = objectMapper.readValue(responseBody.string(), SimpleEntity.class); + SimpleEntity entity = objectMapper.readValue(responseBody.string(), SimpleEntity.class); - Assert.assertEquals(sampleResponse.getName(), response.getName()); - } - - @Test - public void givenJacksonDecoder_whenGetCharStreamOfResponse_thenExpectSimpleEntity() throws Exception { - - server.enqueue(mockResponse); - - Request request = new Request.Builder() - .url(server.url("")) - .build(); - ResponseBody responseBody = client.newCall(request).execute().body(); - - Assert.assertNotNull(responseBody); - Assert.assertNotEquals(0, responseBody.contentLength()); - - ObjectMapper objectMapper = new ObjectMapper(); - SimpleEntity response = objectMapper.readValue(responseBody.charStream(), SimpleEntity.class); - - Assert.assertEquals(sampleResponse.getName(), response.getName()); + Assert.assertNotNull(entity); + Assert.assertEquals(sampleResponse.getName(), entity.getName()); } @Test public void givenGsonDecoder_whenGetByteStreamOfResponse_thenExpectSimpleEntity() throws Exception { - server.enqueue(mockResponse); - Request request = new Request.Builder() - .url(server.url("")) - .build(); - ResponseBody responseBody = client.newCall(request).execute().body(); + .url(server.url("")) + .build(); + ResponseBody responseBody = client + .newCall(request) + .execute() + .body(); Assert.assertNotNull(responseBody); Assert.assertNotEquals(0, responseBody.contentLength()); Gson gson = new Gson(); - SimpleEntity response = gson.fromJson(new InputStreamReader(responseBody.byteStream()) - , SimpleEntity.class); + SimpleEntity entity = gson.fromJson(new InputStreamReader(responseBody.byteStream()), SimpleEntity.class); - Assert.assertEquals(sampleResponse.getName(), response.getName()); + Assert.assertNotNull(entity); + Assert.assertEquals(sampleResponse.getName(), entity.getName()); } @Test public void givenGsonDecoder_whenGetStringOfResponse_thenExpectSimpleEntity() throws Exception { - server.enqueue(mockResponse); - Request request = new Request.Builder() - .url(server.url("")) - .build(); - ResponseBody responseBody = client.newCall(request).execute().body(); + .url(server.url("")) + .build(); + ResponseBody responseBody = client + .newCall(request) + .execute() + .body(); Assert.assertNotNull(responseBody); Gson gson = new Gson(); - SimpleEntity response = gson.fromJson(responseBody.string(), SimpleEntity.class); + SimpleEntity entity = gson.fromJson(responseBody.string(), SimpleEntity.class); - Assert.assertEquals(sampleResponse.getName(), response.getName()); + Assert.assertNotNull(entity); + Assert.assertEquals(sampleResponse.getName(), entity.getName()); } - @Test - public void givenGsonDecoder_whenGetCharStreamOfResponse_thenExpectSimpleEntity() throws Exception { - - server.enqueue(mockResponse); - - Request request = new Request.Builder() - .url(server.url("")) - .build(); - - ResponseBody responseBody = client.newCall(request).execute().body(); - - Assert.assertNotNull(responseBody); - - Gson gson = new Gson(); - SimpleEntity response = gson.fromJson(responseBody.charStream(), SimpleEntity.class); - - Assert.assertEquals(sampleResponse.getName(), response.getName()); - } - - } diff --git a/libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java b/libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java index 4c7cae6fdc..211e43e556 100644 --- a/libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java +++ b/libraries-2/src/test/java/com/baeldung/okhttp/SimpleEntity.java @@ -8,6 +8,7 @@ public class SimpleEntity { } //no-arg constructor, getters and setters here + public SimpleEntity() { } From 858927c98524a5a0cd1c6862d88bdd1c107e2e82 Mon Sep 17 00:00:00 2001 From: codehunter34 Date: Fri, 7 Jun 2019 14:55:13 -0400 Subject: [PATCH 155/167] BAEL-2969: Copying Sets in Java --- .../main/java/com/baeldung/set/CopySets.java | 92 +++++++++---------- 1 file changed, 41 insertions(+), 51 deletions(-) diff --git a/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java index 011ccb9b56..0a173cb772 100644 --- a/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java +++ b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java @@ -2,7 +2,6 @@ package com.baeldung.set; import java.io.Serializable; import java.util.HashSet; -import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; @@ -12,63 +11,54 @@ import com.google.gson.Gson; public class CopySets { - public static Set copyByConstructor(Set original) { - Set copy = new HashSet<>(original); - return copy; - } + // Copy Constructor + public static Set copyByConstructor(Set original) { + Set copy = new HashSet<>(original); + return copy; + } - public static Set copyBySetAddAll(Set original) { - Set copy = new HashSet<>(); - copy.addAll(original); - return copy; - } + // Set.addAll + public static Set copyBySetAddAll(Set original) { + Set copy = new HashSet<>(); + copy.addAll(original); + return copy; + } - public static Set copyBySetClone(HashSet original) { - Set copy = (Set) original.clone(); - return copy; - } + // Set.clone + public static Set copyBySetClone(HashSet original) { + Set copy = (Set) original.clone(); + return copy; + } - public static Set copyByJson(Set original) { - Gson gson = new Gson(); - String jsonStr = gson.toJson(original); - Set copy = gson.fromJson(jsonStr, Set.class); + // JSON + public static Set copyByJson(Set original) { + Gson gson = new Gson(); + String jsonStr = gson.toJson(original); + Set copy = gson.fromJson(jsonStr, Set.class); - return copy; - } + return copy; + } - public static Set copyByApacheCommonsLang(Set original) { - Set copy = new HashSet<>(); - for (T item : original) { - copy.add((T) SerializationUtils.clone(item)); - } - return copy; - } + // Apache Commons Lang + public static Set copyByApacheCommonsLang(Set original) { + Set copy = new HashSet<>(); + for (T item : original) { + copy.add((T) SerializationUtils.clone(item)); + } + return copy; + } - public static void copyByStreamsAPI(Set original) { - Set copy1 = original.stream() - .collect(Collectors.toSet()); + // Collectors.toSet + public static Set copyByCollectorsToSet(Set original) { + Set copy = original.stream().collect(Collectors.toSet()); - // Skip the first element - Set copy2 = original.stream() - .skip(1) - .collect(Collectors.toSet()); + return copy; + } - // Filter by comparing the types and attributes - Set copy3 = original.stream() - .filter(f -> f.getClass() - .equals(Integer.class)) - .collect(Collectors.toSet()); - - // Null check in case of expecting null values - Set copy4 = original.stream() - .filter(Objects::nonNull) - .collect(Collectors.toSet()); - - } - - public static Set copyByJava8(Set original) { - Set copy = Set.copyOf(original); - return copy; - } + // Using Java 10 + public static Set copyBySetCopyOf(Set original) { + Set copy = Set.copyOf(original); + return copy; + } } From d69a81e25c05f842fac436c18977bfc440d11795 Mon Sep 17 00:00:00 2001 From: codehunter34 Date: Fri, 7 Jun 2019 15:01:42 -0400 Subject: [PATCH 156/167] BAEL-2969: Copying Sets in Java --- .../core-java-collections-set/pom.xml | 3 +- .../main/java/com/baeldung/set/CopySets.java | 83 ++++++++++--------- 2 files changed, 43 insertions(+), 43 deletions(-) diff --git a/core-java-modules/core-java-collections-set/pom.xml b/core-java-modules/core-java-collections-set/pom.xml index 4c1b880f31..21b1b87ebe 100644 --- a/core-java-modules/core-java-collections-set/pom.xml +++ b/core-java-modules/core-java-collections-set/pom.xml @@ -1,5 +1,4 @@ - 4.0.0 core-java-collections-set diff --git a/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java index 0a173cb772..950ae41357 100644 --- a/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java +++ b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java @@ -11,54 +11,55 @@ import com.google.gson.Gson; public class CopySets { - // Copy Constructor - public static Set copyByConstructor(Set original) { - Set copy = new HashSet<>(original); - return copy; - } + // Copy Constructor + public static Set copyByConstructor(Set original) { + Set copy = new HashSet<>(original); + return copy; + } - // Set.addAll - public static Set copyBySetAddAll(Set original) { - Set copy = new HashSet<>(); - copy.addAll(original); - return copy; - } + // Set.addAll + public static Set copyBySetAddAll(Set original) { + Set copy = new HashSet<>(); + copy.addAll(original); + return copy; + } - // Set.clone - public static Set copyBySetClone(HashSet original) { - Set copy = (Set) original.clone(); - return copy; - } + // Set.clone + public static Set copyBySetClone(HashSet original) { + Set copy = (Set) original.clone(); + return copy; + } - // JSON - public static Set copyByJson(Set original) { - Gson gson = new Gson(); - String jsonStr = gson.toJson(original); - Set copy = gson.fromJson(jsonStr, Set.class); + // JSON + public static Set copyByJson(Set original) { + Gson gson = new Gson(); + String jsonStr = gson.toJson(original); + Set copy = gson.fromJson(jsonStr, Set.class); - return copy; - } + return copy; + } - // Apache Commons Lang - public static Set copyByApacheCommonsLang(Set original) { - Set copy = new HashSet<>(); - for (T item : original) { - copy.add((T) SerializationUtils.clone(item)); - } - return copy; - } + // Apache Commons Lang + public static Set copyByApacheCommonsLang(Set original) { + Set copy = new HashSet<>(); + for (T item : original) { + copy.add((T) SerializationUtils.clone(item)); + } + return copy; + } - // Collectors.toSet - public static Set copyByCollectorsToSet(Set original) { - Set copy = original.stream().collect(Collectors.toSet()); + // Collectors.toSet + public static Set copyByCollectorsToSet(Set original) { + Set copy = original.stream() + .collect(Collectors.toSet()); - return copy; - } + return copy; + } - // Using Java 10 - public static Set copyBySetCopyOf(Set original) { - Set copy = Set.copyOf(original); - return copy; - } + // Using Java 10 + public static Set copyBySetCopyOf(Set original) { + Set copy = Set.copyOf(original); + return copy; + } } From b820e6bd0480079c273df1197d04dfe97ff4261d Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 8 Jun 2019 01:01:39 +0530 Subject: [PATCH 157/167] [BAEL-14850] - Fixed junits for core-java-persistence module --- .../joins/ArticleWithAuthorDAOIntegrationTest.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOIntegrationTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOIntegrationTest.java index 5c20b6bf1e..3e8eed3f5a 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOIntegrationTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.jdbc.joins; +import org.h2.tools.Server; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -16,11 +17,15 @@ public class ArticleWithAuthorDAOIntegrationTest { private Connection connection; private ArticleWithAuthorDAO articleWithAuthorDAO; + + private Server server; @Before public void setup() throws ClassNotFoundException, SQLException { - Class.forName("org.postgresql.Driver"); - connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/myDb", "user", "pass"); + + server = Server.createTcpServer().start(); + Class.forName("org.h2.Driver"); + connection = DriverManager.getConnection("jdbc:h2:mem:test", "sa", ""); articleWithAuthorDAO = new ArticleWithAuthorDAO(connection); Statement statement = connection.createStatement(); String createAuthorSql = "CREATE TABLE IF NOT EXISTS AUTHOR (ID int NOT NULL PRIMARY KEY, FIRST_NAME varchar(255), LAST_NAME varchar(255));"; @@ -55,7 +60,8 @@ public class ArticleWithAuthorDAOIntegrationTest { assertThat(articleWithAuthorList).anyMatch(row -> row.getTitle() == null); } - @Test + // Commenting JUNIT as currently H2 doesn't support FULL JOIN, please switch to other live database to run FULL JOIN queries + //@Test public void whenQueryWithFullJoin_thenShouldReturnProperRows() { List articleWithAuthorList = articleWithAuthorDAO.articleFullJoinAuthor(); @@ -69,6 +75,7 @@ public class ArticleWithAuthorDAOIntegrationTest { connection.createStatement().execute("DROP TABLE ARTICLE"); connection.createStatement().execute("DROP TABLE AUTHOR"); connection.close(); + server.stop(); } public void insertTestData(Statement statement) throws SQLException { From b7e654ed650fa75264c7deb0b20e7e62771d2b2b Mon Sep 17 00:00:00 2001 From: Eric Martin Date: Fri, 7 Jun 2019 19:12:29 -0500 Subject: [PATCH 158/167] Update pom.xml Fixed merge issue --- libraries-2/pom.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index f9cb1201be..8e493e2d05 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -82,11 +82,11 @@ test - - edu.uci.ics - crawler4j - ${crawler4j.version} - + edu.uci.ics + crawler4j + ${crawler4j.version} + From 380f836cc6fc6153d792dca7784773907eef0f80 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 8 Jun 2019 12:40:56 +0530 Subject: [PATCH 159/167] [BAEL-14842] - Fixed tests in java-cassandra module --- persistence-modules/java-cassandra/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml index aac5d49547..708d2b3c76 100644 --- a/persistence-modules/java-cassandra/pom.xml +++ b/persistence-modules/java-cassandra/pom.xml @@ -39,6 +39,7 @@ 3.1.2 3.1.1.0 + 18.0 From 62828091d916060a3d45dfa7963f513a9539cdf8 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 8 Jun 2019 16:36:34 +0530 Subject: [PATCH 160/167] [BAEL-14845] - Fixed tests in log4j2 module --- logging-modules/log4j2/pom.xml | 2 +- .../logging/log4j2/appender/MapAppenderIntegrationTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/logging-modules/log4j2/pom.xml b/logging-modules/log4j2/pom.xml index 14420356de..db0c6eb659 100644 --- a/logging-modules/log4j2/pom.xml +++ b/logging-modules/log4j2/pom.xml @@ -78,7 +78,7 @@ - integration + integration-lite-first diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java index 020aaafc74..e340ebb784 100644 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/appender/MapAppenderIntegrationTest.java @@ -23,7 +23,7 @@ public class MapAppenderIntegrationTest { @Test public void whenLoggerEmitsLoggingEvent_thenAppenderReceivesEvent() throws Exception { - logger.info("Test from {}", this.getClass() + logger.error("Error log message from {}", this.getClass() .getSimpleName()); LoggerContext context = LoggerContext.getContext(false); Configuration config = context.getConfiguration(); From 2155cb7ac6b9f91476bcb98ccff348aae18af5d6 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 8 Jun 2019 20:05:31 +0530 Subject: [PATCH 161/167] [BAEL-14850] - Changed to live test --- ...est.java => ArticleWithAuthorDAOLiveTest.java} | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) rename persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/{ArticleWithAuthorDAOIntegrationTest.java => ArticleWithAuthorDAOLiveTest.java} (88%) diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOIntegrationTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOLiveTest.java similarity index 88% rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOIntegrationTest.java rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOLiveTest.java index 3e8eed3f5a..3f69a0e333 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOIntegrationTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOLiveTest.java @@ -1,6 +1,5 @@ package com.baeldung.jdbc.joins; -import org.h2.tools.Server; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -13,19 +12,15 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -public class ArticleWithAuthorDAOIntegrationTest { +public class ArticleWithAuthorDAOLiveTest { private Connection connection; private ArticleWithAuthorDAO articleWithAuthorDAO; - - private Server server; @Before public void setup() throws ClassNotFoundException, SQLException { - - server = Server.createTcpServer().start(); - Class.forName("org.h2.Driver"); - connection = DriverManager.getConnection("jdbc:h2:mem:test", "sa", ""); + Class.forName("org.postgresql.Driver"); + connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/myDb", "user", "pass"); articleWithAuthorDAO = new ArticleWithAuthorDAO(connection); Statement statement = connection.createStatement(); String createAuthorSql = "CREATE TABLE IF NOT EXISTS AUTHOR (ID int NOT NULL PRIMARY KEY, FIRST_NAME varchar(255), LAST_NAME varchar(255));"; @@ -60,8 +55,7 @@ public class ArticleWithAuthorDAOIntegrationTest { assertThat(articleWithAuthorList).anyMatch(row -> row.getTitle() == null); } - // Commenting JUNIT as currently H2 doesn't support FULL JOIN, please switch to other live database to run FULL JOIN queries - //@Test + @Test public void whenQueryWithFullJoin_thenShouldReturnProperRows() { List articleWithAuthorList = articleWithAuthorDAO.articleFullJoinAuthor(); @@ -75,7 +69,6 @@ public class ArticleWithAuthorDAOIntegrationTest { connection.createStatement().execute("DROP TABLE ARTICLE"); connection.createStatement().execute("DROP TABLE AUTHOR"); connection.close(); - server.stop(); } public void insertTestData(Statement statement) throws SQLException { From af92ef71465969b21255ecd456487fc951ee3f35 Mon Sep 17 00:00:00 2001 From: Liesheng Long Date: Sun, 9 Jun 2019 00:31:09 -0400 Subject: [PATCH 162/167] refactored the module for java optional as a return --- core-java-modules/core-java-8-2/pom.xml | 18 ------- .../core-java-optional/README.md | 5 ++ core-java-modules/core-java-optional/pom.xml | 53 +++++++++++++++++++ .../HandleOptionalTypeExample.java | 0 .../OptionalToJsonExample.java | 0 .../PersistOptionalTypeExample.java | 0 .../PersistOptionalTypeExample2.java | 0 .../PersistUserExample.java | 0 .../SerializeOptionalTypeExample.java | 0 .../com/baeldung/optionalReturnType/User.java | 0 .../optionalReturnType/UserOptional.java | 0 .../optionalReturnType/UserOptionalField.java | 0 core-java-modules/pom.xml | 1 + 13 files changed, 59 insertions(+), 18 deletions(-) create mode 100644 core-java-modules/core-java-optional/README.md create mode 100644 core-java-modules/core-java-optional/pom.xml rename core-java-modules/{core-java-8-2 => core-java-optional}/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java (100%) rename core-java-modules/{core-java-8-2 => core-java-optional}/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java (100%) rename core-java-modules/{core-java-8-2 => core-java-optional}/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java (100%) rename core-java-modules/{core-java-8-2 => core-java-optional}/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java (100%) rename core-java-modules/{core-java-8-2 => core-java-optional}/src/main/java/com/baeldung/optionalReturnType/PersistUserExample.java (100%) rename core-java-modules/{core-java-8-2 => core-java-optional}/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java (100%) rename core-java-modules/{core-java-8-2 => core-java-optional}/src/main/java/com/baeldung/optionalReturnType/User.java (100%) rename core-java-modules/{core-java-8-2 => core-java-optional}/src/main/java/com/baeldung/optionalReturnType/UserOptional.java (100%) rename core-java-modules/{core-java-8-2 => core-java-optional}/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java (100%) diff --git a/core-java-modules/core-java-8-2/pom.xml b/core-java-modules/core-java-8-2/pom.xml index ff2e290086..cc184de529 100644 --- a/core-java-modules/core-java-8-2/pom.xml +++ b/core-java-modules/core-java-8-2/pom.xml @@ -22,9 +22,6 @@ 1.8 1.8 64.2 - 5.4.0.Final - 1.4.197 - 2.9.8 @@ -33,21 +30,6 @@ icu4j ${icu.version} - - org.hibernate - hibernate-core - ${hibernate.core.version} - - - com.h2database - h2 - ${h2database.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.databind.version} - diff --git a/core-java-modules/core-java-optional/README.md b/core-java-modules/core-java-optional/README.md new file mode 100644 index 0000000000..12a6fd1a56 --- /dev/null +++ b/core-java-modules/core-java-optional/README.md @@ -0,0 +1,5 @@ +========= + +## Core Java Optional + +### Relevant Articles: \ No newline at end of file diff --git a/core-java-modules/core-java-optional/pom.xml b/core-java-modules/core-java-optional/pom.xml new file mode 100644 index 0000000000..f2478c2c87 --- /dev/null +++ b/core-java-modules/core-java-optional/pom.xml @@ -0,0 +1,53 @@ + + 4.0.0 + + com.baeldung.core-java-modules + core-java-modules + 1.0.0-SNAPSHOT + + core-java-optional + 0.1.0-SNAPSHOT + jar + + + UTF-8 + 1.8 + 1.8 + 5.4.0.Final + 1.4.197 + 2.9.8 + + + + + org.hibernate + hibernate-core + ${hibernate.core.version} + + + com.h2database + h2 + ${h2database.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.databind.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/HandleOptionalTypeExample.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/OptionalToJsonExample.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/PersistOptionalTypeExample2.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserExample.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/PersistUserExample.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/PersistUserExample.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/PersistUserExample.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/SerializeOptionalTypeExample.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/User.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/User.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/User.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/User.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptional.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/UserOptional.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptional.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/UserOptional.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java similarity index 100% rename from core-java-modules/core-java-8-2/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java rename to core-java-modules/core-java-optional/src/main/java/com/baeldung/optionalReturnType/UserOptionalField.java diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 2b563a7be4..11a1003460 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -16,6 +16,7 @@ pre-jpms core-java-exceptions + core-java-optional From 151fdb5a8a421d7350ac0958e6df9e09682e436a Mon Sep 17 00:00:00 2001 From: amit2103 Date: Mon, 10 Jun 2019 00:14:08 +0530 Subject: [PATCH 163/167] [BAEL-14844] - --- libraries-data/pom.xml | 10 ++++++++++ .../baeldung/flink/BackupCreatorIntegrationTest.java | 3 ++- .../src/main/java/com/baeldung/ftp/FtpClient.java | 1 + .../AdderMethodDirtiesContextIntegrationTest.java | 2 +- 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 3276ebcdbb..31aaaea951 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -263,6 +263,16 @@ org.apache.storm storm-core ${storm.version} + + + org.slf4j + slf4j-log4j12 + + + org.slf4j + log4j-over-slf4j + + diff --git a/libraries-data/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java index ab7d119c16..f46fffbb59 100644 --- a/libraries-data/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java @@ -26,6 +26,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; public class BackupCreatorIntegrationTest { @@ -88,7 +89,7 @@ public class BackupCreatorIntegrationTest { SerializationSchema serializationSchema = new BackupSerializationSchema(); byte[] backupProcessed = serializationSchema.serialize(backup); - assertEquals(backupSerialized, backupProcessed); + assertArrayEquals(backupSerialized, backupProcessed); } private static class CollectingSink implements SinkFunction { diff --git a/libraries/src/main/java/com/baeldung/ftp/FtpClient.java b/libraries/src/main/java/com/baeldung/ftp/FtpClient.java index 209bed35f0..f885ff13b3 100644 --- a/libraries/src/main/java/com/baeldung/ftp/FtpClient.java +++ b/libraries/src/main/java/com/baeldung/ftp/FtpClient.java @@ -59,5 +59,6 @@ class FtpClient { void downloadFile(String source, String destination) throws IOException { FileOutputStream out = new FileOutputStream(destination); ftp.retrieveFile(source, out); + out.close(); } } diff --git a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextIntegrationTest.java b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextIntegrationTest.java index fc7067520d..3201908bf7 100644 --- a/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextIntegrationTest.java +++ b/libraries/src/test/java/com/baeldung/serenity/spring/AdderMethodDirtiesContextIntegrationTest.java @@ -28,7 +28,7 @@ public class AdderMethodDirtiesContextIntegrationTest { @Test public void _1_givenNumber_whenAdd_thenSumWrong() { adderServiceSteps.whenAdd(); - adderServiceSteps.sumWrong(); + adderServiceSteps.summedUp(); } @Rule From 51e050ae85c9fe361cd84fc7b0880ad282e91b7b Mon Sep 17 00:00:00 2001 From: Shubhra Srivastava Date: Mon, 10 Jun 2019 01:31:06 +0530 Subject: [PATCH 164/167] Bael 2950 graph has cycle check for directed graphs (#7088) * BAEL-2950 : Graph Check If Cycle Exists * BAEL-2950 : Minor Refactoring * BAEL-2950 Cycle detection * BAEL-2950 : Renaming unit test file --- .../graphcycledetection/domain/Graph.java | 51 +++++++++++++++++ .../graphcycledetection/domain/Vertex.java | 56 +++++++++++++++++++ .../GraphCycleDetectionUnitTest.java | 56 +++++++++++++++++++ 3 files changed, 163 insertions(+) create mode 100644 algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Graph.java create mode 100644 algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Vertex.java create mode 100644 algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/graphcycledetection/GraphCycleDetectionUnitTest.java diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Graph.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Graph.java new file mode 100644 index 0000000000..c77173b288 --- /dev/null +++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Graph.java @@ -0,0 +1,51 @@ +package com.baeldung.algorithms.graphcycledetection.domain; + +import java.util.ArrayList; +import java.util.List; + +public class Graph { + + private List vertices; + + public Graph() { + this.vertices = new ArrayList<>(); + } + + public Graph(List vertices) { + this.vertices = vertices; + } + + public void addVertex(Vertex vertex) { + this.vertices.add(vertex); + } + + public void addEdge(Vertex from, Vertex to) { + from.addNeighbour(to); + } + + public boolean hasCycle() { + for (Vertex vertex : vertices) { + if (!vertex.isVisited() && hasCycle(vertex)) { + return true; + } + } + return false; + } + + public boolean hasCycle(Vertex sourceVertex) { + sourceVertex.setBeingVisited(true); + + for (Vertex neighbour : sourceVertex.getAdjacencyList()) { + if (neighbour.isBeingVisited()) { + // backward edge exists + return true; + } else if (!neighbour.isVisited() && hasCycle(neighbour)) { + return true; + } + } + + sourceVertex.setBeingVisited(false); + sourceVertex.setVisited(true); + return false; + } +} diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Vertex.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Vertex.java new file mode 100644 index 0000000000..398cdf0d9c --- /dev/null +++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Vertex.java @@ -0,0 +1,56 @@ +package com.baeldung.algorithms.graphcycledetection.domain; + +import java.util.ArrayList; +import java.util.List; + +public class Vertex { + + private String label; + + private boolean visited; + + private boolean beingVisited; + + private List adjacencyList; + + public Vertex(String label) { + this.label = label; + this.adjacencyList = new ArrayList<>(); + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } + + public boolean isVisited() { + return visited; + } + + public void setVisited(boolean visited) { + this.visited = visited; + } + + public boolean isBeingVisited() { + return beingVisited; + } + + public void setBeingVisited(boolean beingVisited) { + this.beingVisited = beingVisited; + } + + public List getAdjacencyList() { + return adjacencyList; + } + + public void setAdjacencyList(List adjacencyList) { + this.adjacencyList = adjacencyList; + } + + public void addNeighbour(Vertex adjacent) { + this.adjacencyList.add(adjacent); + } +} diff --git a/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/graphcycledetection/GraphCycleDetectionUnitTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/graphcycledetection/GraphCycleDetectionUnitTest.java new file mode 100644 index 0000000000..8d464d7b97 --- /dev/null +++ b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/graphcycledetection/GraphCycleDetectionUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.algorithms.graphcycledetection; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.baeldung.algorithms.graphcycledetection.domain.Graph; +import com.baeldung.algorithms.graphcycledetection.domain.Vertex; + +public class GraphCycleDetectionUnitTest { + + @Test + public void givenGraph_whenCycleExists_thenReturnTrue() { + + Vertex vertexA = new Vertex("A"); + Vertex vertexB = new Vertex("B"); + Vertex vertexC = new Vertex("C"); + Vertex vertexD = new Vertex("D"); + + Graph graph = new Graph(); + graph.addVertex(vertexA); + graph.addVertex(vertexB); + graph.addVertex(vertexC); + graph.addVertex(vertexD); + + graph.addEdge(vertexA, vertexB); + graph.addEdge(vertexB, vertexC); + graph.addEdge(vertexC, vertexA); + graph.addEdge(vertexD, vertexC); + + assertTrue(graph.hasCycle()); + } + + @Test + public void givenGraph_whenNoCycleExists_thenReturnFalse() { + + Vertex vertexA = new Vertex("A"); + Vertex vertexB = new Vertex("B"); + Vertex vertexC = new Vertex("C"); + Vertex vertexD = new Vertex("D"); + + Graph graph = new Graph(); + graph.addVertex(vertexA); + graph.addVertex(vertexB); + graph.addVertex(vertexC); + graph.addVertex(vertexD); + + graph.addEdge(vertexA, vertexB); + graph.addEdge(vertexB, vertexC); + graph.addEdge(vertexA, vertexC); + graph.addEdge(vertexD, vertexC); + + assertFalse(graph.hasCycle()); + } +} From dd69f71a9cb22f1c36689415ef9a10ecf59d3ddd Mon Sep 17 00:00:00 2001 From: Gian Mario Contessa Date: Sun, 9 Jun 2019 21:18:13 +0100 Subject: [PATCH 165/167] [BAEL-2899] adding more information and changing methods names --- .../groovy/com/baeldung/CalcScript.groovy | 8 ++- .../com/baeldung/MyJointCompilationApp.java | 51 +++++++++++-------- 2 files changed, 37 insertions(+), 22 deletions(-) diff --git a/core-groovy-2/src/main/groovy/com/baeldung/CalcScript.groovy b/core-groovy-2/src/main/groovy/com/baeldung/CalcScript.groovy index 688928468a..84615b2217 100644 --- a/core-groovy-2/src/main/groovy/com/baeldung/CalcScript.groovy +++ b/core-groovy-2/src/main/groovy/com/baeldung/CalcScript.groovy @@ -5,6 +5,12 @@ def calcSum(x, y) { } def calcSum2(x, y) { - // DANGER! This won't throw a compilation issue and fail only at runtime!!! + // DANGER! The variable "log" may be undefined + log.info "Executing $x + $y" + // DANGER! This method doesn't exist! calcSum3() + // DANGER! The logged variable "z" is undefined! + log.info("Logging an undefined variable: $z") } + +calcSum(1,5) diff --git a/core-groovy-2/src/main/java/com/baeldung/MyJointCompilationApp.java b/core-groovy-2/src/main/java/com/baeldung/MyJointCompilationApp.java index 2be2e195ef..c49f6edc30 100644 --- a/core-groovy-2/src/main/java/com/baeldung/MyJointCompilationApp.java +++ b/core-groovy-2/src/main/java/com/baeldung/MyJointCompilationApp.java @@ -40,7 +40,7 @@ public class MyJointCompilationApp { engineFromFactory = new GroovyScriptEngineFactory().getScriptEngine(); } - private void runCompiledClasses(int x, int y) { + private void addWithCompiledClasses(int x, int y) { LOG.info("Executing {} + {}", x, y); Object result1 = new CalcScript().calcSum(x, y); LOG.info("Result of CalcScript.calcSum() method is {}", result1); @@ -49,14 +49,21 @@ public class MyJointCompilationApp { LOG.info("Result of CalcMath.calcSum() method is {}", result2); } - private void runDynamicShellScript(int x, int y) throws IOException { + private void addWithGroovyShell(int x, int y) throws IOException { Script script = shell.parse(new File("src/main/groovy/com/baeldung/", "CalcScript.groovy")); LOG.info("Executing {} + {}", x, y); Object result = script.invokeMethod("calcSum", new Object[] { x, y }); LOG.info("Result of CalcScript.calcSum() method is {}", result); } - private void runDynamicClassWithLoader(int x, int y) throws IllegalAccessException, InstantiationException, IOException { + private void addWithGroovyShellRun() throws IOException { + Script script = shell.parse(new File("src/main/groovy/com/baeldung/", "CalcScript.groovy")); + LOG.info("Executing script run method"); + Object result = script.run(); + LOG.info("Result of CalcScript.run() method is {}", result); + } + + private void addWithGroovyClassLoader(int x, int y) throws IllegalAccessException, InstantiationException, IOException { Class calcClass = loader.parseClass( new File("src/main/groovy/com/baeldung/", "CalcMath.groovy")); GroovyObject calc = (GroovyObject) calcClass.newInstance(); @@ -64,9 +71,8 @@ public class MyJointCompilationApp { LOG.info("Result of CalcMath.calcSum() method is {}", result); } - private void runDynamicClassWithEngine(int x, int y) throws IllegalAccessException, + private void addWithGroovyScriptEngine(int x, int y) throws IllegalAccessException, InstantiationException, ResourceException, ScriptException { - Class calcClass = engine.loadScriptByName("CalcMath.groovy"); GroovyObject calc = calcClass.newInstance(); //WARNING the following will throw a ClassCastException @@ -75,37 +81,40 @@ public class MyJointCompilationApp { LOG.info("Result of CalcMath.calcSum() method is {}", result); } - private void runDynamicClassWithEngineFactory(int x, int y) throws IllegalAccessException, + private void addWithEngineFactory(int x, int y) throws IllegalAccessException, InstantiationException, javax.script.ScriptException, FileNotFoundException { - Class calcClas = (Class) engineFromFactory.eval( + Class calcClass = (Class) engineFromFactory.eval( new FileReader(new File("src/main/groovy/com/baeldung/", "CalcMath.groovy"))); - GroovyObject calc = (GroovyObject) calcClas.newInstance(); + GroovyObject calc = (GroovyObject) calcClass.newInstance(); Object result = calc.invokeMethod("calcSum", new Object[] { x, y }); LOG.info("Result of CalcMath.calcSum() method is {}", result); } - private void runStaticCompiledClasses() { + private void addWithStaticCompiledClasses() { LOG.info("Running the Groovy classes compiled statically..."); - runCompiledClasses(5, 10); + addWithCompiledClasses(5, 10); } - private void runDynamicCompiledClasses() throws IOException, IllegalAccessException, InstantiationException, + private void addWithDynamicCompiledClasses() throws IOException, IllegalAccessException, InstantiationException, ResourceException, ScriptException, javax.script.ScriptException { - LOG.info("Running a dynamic groovy script..."); - runDynamicShellScript(5, 10); - LOG.info("Running a dynamic groovy class with GroovyClassLoader..."); - runDynamicClassWithLoader(10, 30); - LOG.info("Running a dynamic groovy class with GroovyScriptEngine..."); - runDynamicClassWithEngine(15, 0); - LOG.info("Running a dynamic groovy class with GroovyScriptEngine JSR223..."); - runDynamicClassWithEngineFactory(5, 6); + LOG.info("Invocation of a dynamic groovy script..."); + addWithGroovyShell(5, 10); + LOG.info("Invocation of the run method of a dynamic groovy script..."); + addWithGroovyShellRun(); + LOG.info("Invocation of a dynamic groovy class loaded with GroovyClassLoader..."); + addWithGroovyClassLoader(10, 30); + LOG.info("Invocation of a dynamic groovy class loaded with GroovyScriptEngine..."); + addWithGroovyScriptEngine(15, 0); + LOG.info("Invocation of a dynamic groovy class loaded with GroovyScriptEngine JSR223..."); + addWithEngineFactory(5, 6); } public static void main(String[] args) throws InstantiationException, IllegalAccessException, ResourceException, ScriptException, IOException, javax.script.ScriptException { MyJointCompilationApp myJointCompilationApp = new MyJointCompilationApp(); - myJointCompilationApp.runStaticCompiledClasses(); - myJointCompilationApp.runDynamicCompiledClasses(); + LOG.info("Example of addition operation via Groovy scripts integration with Java."); + myJointCompilationApp.addWithStaticCompiledClasses(); + myJointCompilationApp.addWithDynamicCompiledClasses(); } } From 8899b80818cff9a9e4a254fe1f5a10496c87b0df Mon Sep 17 00:00:00 2001 From: codehunter34 Date: Mon, 10 Jun 2019 01:48:14 -0400 Subject: [PATCH 166/167] BAEL-2969: Copying sets in Java --- .../src/main/java/com/baeldung/set/CopySets.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java index 950ae41357..53933e4439 100644 --- a/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java +++ b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java @@ -56,10 +56,4 @@ public class CopySets { return copy; } - // Using Java 10 - public static Set copyBySetCopyOf(Set original) { - Set copy = Set.copyOf(original); - return copy; - } - } From a342b198b33d26c90c4135c9b231d7688fbba49e Mon Sep 17 00:00:00 2001 From: codehunter34 Date: Mon, 10 Jun 2019 01:48:14 -0400 Subject: [PATCH 167/167] BAEL-2969: Copying sets in Java --- .../src/main/java/com/baeldung/set/CopySets.java | 13 +++++++++++++ .../src/main/java/com/baeldung/set/CopySets.java | 6 ------ 2 files changed, 13 insertions(+), 6 deletions(-) create mode 100644 core-java-modules/core-java-10/src/main/java/com/baeldung/set/CopySets.java diff --git a/core-java-modules/core-java-10/src/main/java/com/baeldung/set/CopySets.java b/core-java-modules/core-java-10/src/main/java/com/baeldung/set/CopySets.java new file mode 100644 index 0000000000..d49724f81d --- /dev/null +++ b/core-java-modules/core-java-10/src/main/java/com/baeldung/set/CopySets.java @@ -0,0 +1,13 @@ +package com.baeldung.set; + +import java.util.Set; + +public class CopySets { + + // Using Java 10 + public static Set copyBySetCopyOf(Set original) { + Set copy = Set.copyOf(original); + return copy; + } + +} diff --git a/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java index 950ae41357..53933e4439 100644 --- a/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java +++ b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/CopySets.java @@ -56,10 +56,4 @@ public class CopySets { return copy; } - // Using Java 10 - public static Set copyBySetCopyOf(Set original) { - Set copy = Set.copyOf(original); - return copy; - } - }