From e3a84dae5b623ed2245d35ccaf5073e5582113fa Mon Sep 17 00:00:00 2001 From: Dmytro Korniienko Date: Sun, 9 Sep 2018 13:13:17 +0300 Subject: [PATCH 01/75] BAEL-2070 Qualifier used instead of Primary to distinguish between different repository beans --- .../baeldung/dependency/exception/app/PurchaseDeptService.java | 3 ++- .../dependency/exception/repository/DressRepository.java | 3 ++- .../dependency/exception/repository/ShoeRepository.java | 2 ++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java b/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java index 1e6fad63aa..e0fe01acdd 100644 --- a/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/app/PurchaseDeptService.java @@ -1,13 +1,14 @@ package com.baeldung.dependency.exception.app; import com.baeldung.dependency.exception.repository.InventoryRepository; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @Service public class PurchaseDeptService { private InventoryRepository repository; - public PurchaseDeptService(InventoryRepository repository) { + public PurchaseDeptService(@Qualifier("dresses") InventoryRepository repository) { this.repository = repository; } } \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java index 4a6c836143..5a1371ce04 100644 --- a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/DressRepository.java @@ -1,9 +1,10 @@ package com.baeldung.dependency.exception.repository; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Repository; -@Primary +@Qualifier("dresses") @Repository public class DressRepository implements InventoryRepository { } diff --git a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java index 60495914cd..227d8934b6 100644 --- a/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java +++ b/spring-core/src/main/java/com/baeldung/dependency/exception/repository/ShoeRepository.java @@ -1,7 +1,9 @@ package com.baeldung.dependency.exception.repository; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; +@Qualifier("shoes") @Repository public class ShoeRepository implements InventoryRepository { } From 9664247f4f426bea83b625a510b76ffe9068e08c Mon Sep 17 00:00:00 2001 From: Dmytro Korniienko Date: Mon, 10 Sep 2018 21:29:38 +0300 Subject: [PATCH 02/75] BAEL-2095 CrudRepository save() method --- .../baeldung/config/CustomConfiguration.java | 29 ++++++++++++++++ .../dao/repositories/InventoryRepository.java | 7 ++++ .../baeldung/domain/MerchandiseEntity.java | 34 +++++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 spring-data-jpa/src/main/java/com/baeldung/config/CustomConfiguration.java create mode 100644 spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InventoryRepository.java create mode 100644 spring-data-jpa/src/main/java/com/baeldung/domain/MerchandiseEntity.java diff --git a/spring-data-jpa/src/main/java/com/baeldung/config/CustomConfiguration.java b/spring-data-jpa/src/main/java/com/baeldung/config/CustomConfiguration.java new file mode 100644 index 0000000000..5af5351d76 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/config/CustomConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.config; + +import com.baeldung.dao.repositories.InventoryRepository; +import com.baeldung.domain.MerchandiseEntity; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@SpringBootApplication +@EnableJpaRepositories(basePackageClasses = InventoryRepository.class) +@EntityScan(basePackageClasses = MerchandiseEntity.class) +public class CustomConfiguration { + public static void main(String[] args) { + ConfigurableApplicationContext context = SpringApplication.run(CustomConfiguration.class, args); + + InventoryRepository repo = context.getBean(InventoryRepository.class); + + MerchandiseEntity pants = new MerchandiseEntity("Pair of Pants"); + repo.save(pants); + + MerchandiseEntity shorts = new MerchandiseEntity("Pair of Shorts"); + repo.save(shorts); + + pants.setTitle("Branded Luxury Pants"); + repo.save(pants); + } +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InventoryRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InventoryRepository.java new file mode 100644 index 0000000000..a575f0b915 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InventoryRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.dao.repositories; + +import com.baeldung.domain.MerchandiseEntity; +import org.springframework.data.repository.CrudRepository; + +public interface InventoryRepository extends CrudRepository { +} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/MerchandiseEntity.java b/spring-data-jpa/src/main/java/com/baeldung/domain/MerchandiseEntity.java new file mode 100644 index 0000000000..921edf1b85 --- /dev/null +++ b/spring-data-jpa/src/main/java/com/baeldung/domain/MerchandiseEntity.java @@ -0,0 +1,34 @@ +package com.baeldung.domain; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class MerchandiseEntity { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String title; + + public MerchandiseEntity() { + } + + public MerchandiseEntity(String title) { + this.title = title; + } + + public Long getId() { + return id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} From 2e60aa32a251a43e3153c5aeb9609bde16995e60 Mon Sep 17 00:00:00 2001 From: Dmytro Korniienko Date: Tue, 11 Sep 2018 00:13:41 +0300 Subject: [PATCH 03/75] (REVERT) BAEL-2095 CrudRepository save() method --- .../baeldung/config/CustomConfiguration.java | 29 ---------------- .../dao/repositories/InventoryRepository.java | 7 ---- .../baeldung/domain/MerchandiseEntity.java | 34 ------------------- 3 files changed, 70 deletions(-) delete mode 100644 spring-data-jpa/src/main/java/com/baeldung/config/CustomConfiguration.java delete mode 100644 spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InventoryRepository.java delete mode 100644 spring-data-jpa/src/main/java/com/baeldung/domain/MerchandiseEntity.java diff --git a/spring-data-jpa/src/main/java/com/baeldung/config/CustomConfiguration.java b/spring-data-jpa/src/main/java/com/baeldung/config/CustomConfiguration.java deleted file mode 100644 index 5af5351d76..0000000000 --- a/spring-data-jpa/src/main/java/com/baeldung/config/CustomConfiguration.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.config; - -import com.baeldung.dao.repositories.InventoryRepository; -import com.baeldung.domain.MerchandiseEntity; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -@SpringBootApplication -@EnableJpaRepositories(basePackageClasses = InventoryRepository.class) -@EntityScan(basePackageClasses = MerchandiseEntity.class) -public class CustomConfiguration { - public static void main(String[] args) { - ConfigurableApplicationContext context = SpringApplication.run(CustomConfiguration.class, args); - - InventoryRepository repo = context.getBean(InventoryRepository.class); - - MerchandiseEntity pants = new MerchandiseEntity("Pair of Pants"); - repo.save(pants); - - MerchandiseEntity shorts = new MerchandiseEntity("Pair of Shorts"); - repo.save(shorts); - - pants.setTitle("Branded Luxury Pants"); - repo.save(pants); - } -} diff --git a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InventoryRepository.java b/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InventoryRepository.java deleted file mode 100644 index a575f0b915..0000000000 --- a/spring-data-jpa/src/main/java/com/baeldung/dao/repositories/InventoryRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.dao.repositories; - -import com.baeldung.domain.MerchandiseEntity; -import org.springframework.data.repository.CrudRepository; - -public interface InventoryRepository extends CrudRepository { -} diff --git a/spring-data-jpa/src/main/java/com/baeldung/domain/MerchandiseEntity.java b/spring-data-jpa/src/main/java/com/baeldung/domain/MerchandiseEntity.java deleted file mode 100644 index 921edf1b85..0000000000 --- a/spring-data-jpa/src/main/java/com/baeldung/domain/MerchandiseEntity.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.domain; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class MerchandiseEntity { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - private String title; - - public MerchandiseEntity() { - } - - public MerchandiseEntity(String title) { - this.title = title; - } - - public Long getId() { - return id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } -} From 2a7a33f71748db1ac7161de1f1bc650ca8fe9440 Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Fri, 28 Sep 2018 06:15:03 +0530 Subject: [PATCH 04/75] BAEL-2169 --- libraries-data/ebean/pom.xml | 59 ++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 libraries-data/ebean/pom.xml diff --git a/libraries-data/ebean/pom.xml b/libraries-data/ebean/pom.xml new file mode 100644 index 0000000000..2e319e1523 --- /dev/null +++ b/libraries-data/ebean/pom.xml @@ -0,0 +1,59 @@ + + 4.0.0 + + com.baeldung + ebean + 0.0.1-SNAPSHOT + jar + + ebean + http://maven.apache.org + + + UTF-8 + + + + + io.ebean + ebean + 11.22.4 + + + com.h2database + h2 + 1.4.196 + + + ch.qos.logback + logback-classic + 1.2.3 + + + + + + + + io.ebean + ebean-maven-plugin + 11.11.2 + + + + main + process-classes + + debug=1 + + + enhance + + + + + + + + From 18f4728a9f4cc73a5f615ea2ec12c3229add6da3 Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Fri, 28 Sep 2018 06:17:40 +0530 Subject: [PATCH 05/75] Create Address.java --- .../com/baeldung/ebean/model/Address.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 libraries-data/ebean/src/main/java/com/baeldung/ebean/model/Address.java diff --git a/libraries-data/ebean/src/main/java/com/baeldung/ebean/model/Address.java b/libraries-data/ebean/src/main/java/com/baeldung/ebean/model/Address.java new file mode 100644 index 0000000000..362e27c32a --- /dev/null +++ b/libraries-data/ebean/src/main/java/com/baeldung/ebean/model/Address.java @@ -0,0 +1,42 @@ +package com.baeldung.ebean.model; + +import javax.persistence.Entity; + +@Entity +public class Address extends BaseModel{ + + public Address(String addressLine1, String addressLine2, String city) { + super(); + this.addressLine1 = addressLine1; + this.addressLine2 = addressLine2; + this.city = city; + } + + private String addressLine1; + private String addressLine2; + private String city; + + public String getAddressLine1() { + return addressLine1; + } + public void setAddressLine1(String addressLine1) { + this.addressLine1 = addressLine1; + } + public String getAddressLine2() { + return addressLine2; + } + public void setAddressLine2(String addressLine2) { + this.addressLine2 = addressLine2; + } + public String getCity() { + return city; + } + public void setCity(String city) { + this.city = city; + } + @Override + public String toString() { + return "Address [id=" + id + ", addressLine1=" + addressLine1 + ", addressLine2=" + addressLine2 + ", city=" + city + "]"; + } + +} From a9d3d8ea07a81f2b8e7e753a2bb9fbe5ceb790a9 Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Fri, 28 Sep 2018 06:18:48 +0530 Subject: [PATCH 06/75] Add files via upload --- .../com/baeldung/ebean/model/BaseModel.java | 59 +++++++++++++++++++ .../com/baeldung/ebean/model/Customer.java | 42 +++++++++++++ 2 files changed, 101 insertions(+) create mode 100644 libraries-data/ebean/src/main/java/com/baeldung/ebean/model/BaseModel.java create mode 100644 libraries-data/ebean/src/main/java/com/baeldung/ebean/model/Customer.java diff --git a/libraries-data/ebean/src/main/java/com/baeldung/ebean/model/BaseModel.java b/libraries-data/ebean/src/main/java/com/baeldung/ebean/model/BaseModel.java new file mode 100644 index 0000000000..7634df7aa0 --- /dev/null +++ b/libraries-data/ebean/src/main/java/com/baeldung/ebean/model/BaseModel.java @@ -0,0 +1,59 @@ +package com.baeldung.ebean.model; + +import java.time.Instant; + +import javax.persistence.Id; +import javax.persistence.MappedSuperclass; +import javax.persistence.Version; + +import io.ebean.annotation.WhenCreated; +import io.ebean.annotation.WhenModified; + +@MappedSuperclass +public abstract class BaseModel { + + @Id + protected long id; + + @Version + protected long version; + + @WhenCreated + protected Instant createdOn; + + @WhenModified + protected Instant modifiedOn; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Instant getCreatedOn() { + return createdOn; + } + + public void setCreatedOn(Instant createdOn) { + this.createdOn = createdOn; + } + + public Instant getModifiedOn() { + return modifiedOn; + } + + public void setModifiedOn(Instant modifiedOn) { + this.modifiedOn = modifiedOn; + } + + public long getVersion() { + return version; + } + + public void setVersion(long version) { + this.version = version; + } + +} diff --git a/libraries-data/ebean/src/main/java/com/baeldung/ebean/model/Customer.java b/libraries-data/ebean/src/main/java/com/baeldung/ebean/model/Customer.java new file mode 100644 index 0000000000..df1db82de4 --- /dev/null +++ b/libraries-data/ebean/src/main/java/com/baeldung/ebean/model/Customer.java @@ -0,0 +1,42 @@ +package com.baeldung.ebean.model; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.OneToOne; + +@Entity +public class Customer extends BaseModel { + + public Customer(String name, Address address) { + super(); + this.name = name; + this.address = address; + } + + private String name; + + @OneToOne(cascade = CascadeType.ALL) + Address address; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + @Override + public String toString() { + return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]"; + } + +} From 9510ca6fa1f066ad4328bfde92d4d8240d641ac5 Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Fri, 28 Sep 2018 06:19:55 +0530 Subject: [PATCH 07/75] Create App.java --- .../main/java/com/baeldung/ebean/app/App.java | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 libraries-data/ebean/src/main/java/com/baeldung/ebean/app/App.java diff --git a/libraries-data/ebean/src/main/java/com/baeldung/ebean/app/App.java b/libraries-data/ebean/src/main/java/com/baeldung/ebean/app/App.java new file mode 100644 index 0000000000..161bf1e820 --- /dev/null +++ b/libraries-data/ebean/src/main/java/com/baeldung/ebean/app/App.java @@ -0,0 +1,75 @@ +package com.baeldung.ebean.app; + +import java.util.Arrays; + +import com.baeldung.ebean.model.Address; +import com.baeldung.ebean.model.Customer; + +import io.ebean.Ebean; +import io.ebean.EbeanServer; +import io.ebean.annotation.Transactional; + +public class App { + + public static void main(String[] args) { + insertAndDeleteInsideTransaction(); + crudOperations(); + queryCustomers(); + } + + @Transactional + public static void insertAndDeleteInsideTransaction() { + + Customer c1 = getCustomer(); + EbeanServer server = Ebean.getDefaultServer(); + server.save(c1); + Customer foundC1 = server.find(Customer.class, c1.getId()); + server.delete(foundC1); + } + + public static void crudOperations() { + + Address a1 = new Address("5, Wide Street", null, "New York"); + Customer c1 = new Customer("John Wide", a1); + + EbeanServer server = Ebean.getDefaultServer(); + server.save(c1); + + c1.setName("Jane Wide"); + c1.setAddress(null); + server.save(c1); + + Customer foundC1 = Ebean.find(Customer.class, c1.getId()); + + Ebean.delete(foundC1); + } + + public static void queryCustomers() { + Address a1 = new Address("1, Big Street", null, "New York"); + Customer c1 = new Customer("Big John", a1); + + Address a2 = new Address("2, Big Street", null, "New York"); + Customer c2 = new Customer("Big John", a2); + + Address a3 = new Address("3, Big Street", null, "San Jose"); + Customer c3 = new Customer("Big Bob", a3); + + Ebean.saveAll(Arrays.asList(c1, c2, c3)); + + Customer customer = Ebean.find(Customer.class) + .select("name") + .fetch("address", "city") + .where() + .eq("city", "San Jose") + .findOne(); + + Ebean.deleteAll(Arrays.asList(c1, c2, c3)); + } + + private static Customer getCustomer() { + Address a1 = new Address("1, Big Street", null, "New York"); + Customer c1 = new Customer("Big John", a1); + return c1; + } + +} From 8b8e3f2650c36840e7a57517dccdd6740a5c7800 Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Fri, 28 Sep 2018 06:20:22 +0530 Subject: [PATCH 08/75] Create App2.java --- .../java/com/baeldung/ebean/app/App2.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 libraries-data/ebean/src/main/java/com/baeldung/ebean/app/App2.java diff --git a/libraries-data/ebean/src/main/java/com/baeldung/ebean/app/App2.java b/libraries-data/ebean/src/main/java/com/baeldung/ebean/app/App2.java new file mode 100644 index 0000000000..fba77007c6 --- /dev/null +++ b/libraries-data/ebean/src/main/java/com/baeldung/ebean/app/App2.java @@ -0,0 +1,26 @@ +package com.baeldung.ebean.app; + +import java.util.Properties; + +import io.ebean.EbeanServer; +import io.ebean.EbeanServerFactory; +import io.ebean.config.ServerConfig; + +public class App2 { + + public static void main(String[] args) { + ServerConfig cfg = new ServerConfig(); + cfg.setDefaultServer(true); + Properties properties = new Properties(); + properties.put("ebean.db.ddl.generate", "true"); + properties.put("ebean.db.ddl.run", "true"); + properties.put("datasource.db.username", "sa"); + properties.put("datasource.db.password", ""); + properties.put("datasource.db.databaseUrl", "jdbc:h2:mem:app2"); + properties.put("datasource.db.databaseDriver", "org.h2.Driver"); + cfg.loadFromProperties(properties); + EbeanServer server = EbeanServerFactory.create(cfg); + + } + +} From 9fcc873f6378cabf35970d31157f918be87c73be Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Fri, 28 Sep 2018 06:20:58 +0530 Subject: [PATCH 09/75] Create application.properties --- .../ebean/src/main/resources/application.properties | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 libraries-data/ebean/src/main/resources/application.properties diff --git a/libraries-data/ebean/src/main/resources/application.properties b/libraries-data/ebean/src/main/resources/application.properties new file mode 100644 index 0000000000..9cc5cc170a --- /dev/null +++ b/libraries-data/ebean/src/main/resources/application.properties @@ -0,0 +1,7 @@ +ebean.db.ddl.generate=true +ebean.db.ddl.run=true + +datasource.db.username=sa +datasource.db.password= +datasource.db.databaseUrl=jdbc:h2:mem:customer +datasource.db.databaseDriver=org.h2.Driver From a22470ac23ebf9a50c5d5aed6e708e3f23078e19 Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Fri, 28 Sep 2018 06:21:19 +0530 Subject: [PATCH 10/75] Create ebean.mf --- libraries-data/ebean/src/main/resources/ebean.mf | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 libraries-data/ebean/src/main/resources/ebean.mf diff --git a/libraries-data/ebean/src/main/resources/ebean.mf b/libraries-data/ebean/src/main/resources/ebean.mf new file mode 100644 index 0000000000..f49fecc717 --- /dev/null +++ b/libraries-data/ebean/src/main/resources/ebean.mf @@ -0,0 +1,3 @@ +entity-packages: com.baeldung.ebean.model +transactional-packages: com.baeldung.ebean.app +querybean-packages: com.baeldung.ebean.app From 772179794686e62ebd6ffba2c3b067a6659c9185 Mon Sep 17 00:00:00 2001 From: josephine-barboza Date: Fri, 28 Sep 2018 06:21:38 +0530 Subject: [PATCH 11/75] Create logback.yml --- libraries-data/ebean/src/main/resources/logback.yml | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 libraries-data/ebean/src/main/resources/logback.yml diff --git a/libraries-data/ebean/src/main/resources/logback.yml b/libraries-data/ebean/src/main/resources/logback.yml new file mode 100644 index 0000000000..c838a19c6c --- /dev/null +++ b/libraries-data/ebean/src/main/resources/logback.yml @@ -0,0 +1,3 @@ + + + From f9065d21b777cc8e29da6138914fc5cd66f59803 Mon Sep 17 00:00:00 2001 From: Dmytro Korniienko Date: Mon, 1 Oct 2018 10:17:39 +0300 Subject: [PATCH 12/75] BAEL-2258 Guide to DateTimeFormatter. Tests added for various formatting patterns and styles --- .../DateTimeFormatterUnitTest.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java b/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java index 4d95bc82e1..cbb84a8783 100644 --- a/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java @@ -3,11 +3,14 @@ package com.baeldung.internationalization; import org.junit.Assert; import org.junit.Test; +import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.LocalTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; +import java.time.temporal.ChronoUnit; import java.util.Locale; import java.util.TimeZone; @@ -43,4 +46,70 @@ public class DateTimeFormatterUnitTest { Assert.assertEquals("Monday, January 1, 2018 10:15:50 AM PST", formattedDateTime); Assert.assertEquals("lundi 1 janvier 2018 10 h 15 PST", frFormattedDateTime); } + + @Test + public void shoulPrintFormattedDate() { + String europeanDatePattern = "dd.MM.yyyy"; + DateTimeFormatter europeanDateFormatter = DateTimeFormatter.ofPattern(europeanDatePattern); + LocalDate summerDay = LocalDate.of(2016, 7, 31); + Assert.assertEquals("31.07.2016", europeanDateFormatter.format(summerDay)); + } + + @Test + public void shouldPrintFormattedTime24() { + String timeColonPattern = "HH:mm:ss"; + DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern); + LocalTime colonTime = LocalTime.of(17, 35, 50); + Assert.assertEquals("17:35:50", timeColonFormatter.format(colonTime)); + } + + @Test + public void shouldPrintFormattedTimeWithMillis() { + String timeColonPattern = "HH:mm:ss SSS"; + DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern); + LocalTime colonTime = LocalTime.of(17, 35, 50).plus(329, ChronoUnit.MILLIS); + Assert.assertEquals("17:35:50 329", timeColonFormatter.format(colonTime)); + } + + @Test + public void shouldPrintFormattedTimePM() { + String timeColonPattern = "hh:mm:ss a"; + DateTimeFormatter timeColonFormatter = DateTimeFormatter.ofPattern(timeColonPattern); + LocalTime colonTime = LocalTime.of(17, 35, 50); + Assert.assertEquals("05:35:50 PM", timeColonFormatter.format(colonTime)); + } + + @Test + public void shouldPrintFormattedUTCRelatedZonedDateTime() { + String newYorkDateTimePattern = "dd.MM.yyyy HH:mm z"; + DateTimeFormatter newYorkDateFormatter = DateTimeFormatter.ofPattern(newYorkDateTimePattern); + LocalDateTime summerDay = LocalDateTime.of(2016, 7, 31, 14, 15); + Assert.assertEquals("31.07.2016 14:15 UTC-04:00", newYorkDateFormatter.format(ZonedDateTime.of(summerDay, ZoneId.of("UTC-4")))); + } + + @Test + public void shouldPrintFormattedNewYorkZonedDateTime() { + String newYorkDateTimePattern = "dd.MM.yyyy HH:mm z"; + DateTimeFormatter newYorkDateFormatter = DateTimeFormatter.ofPattern(newYorkDateTimePattern); + LocalDateTime summerDay = LocalDateTime.of(2016, 7, 31, 14, 15); + Assert.assertEquals("31.07.2016 14:15 EDT", newYorkDateFormatter.format(ZonedDateTime.of(summerDay, ZoneId.of("America/New_York")))); + } + + @Test + public void shouldPrintStyledDate() { + LocalDate anotherSummerDay = LocalDate.of(2016, 8, 23); + Assert.assertEquals("Tuesday, August 23, 2016", DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).format(anotherSummerDay)); + Assert.assertEquals("August 23, 2016", DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).format(anotherSummerDay)); + Assert.assertEquals("Aug 23, 2016", DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).format(anotherSummerDay)); + Assert.assertEquals("8/23/16", DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).format(anotherSummerDay)); + } + + @Test + public void shouldPrintStyledDateTime() { + LocalDateTime anotherSummerDay = LocalDateTime.of(2016, 8, 23, 13, 12, 45); + Assert.assertEquals("Tuesday, August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); + Assert.assertEquals("August 23, 2016 1:12:45 PM EET", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); + Assert.assertEquals("Aug 23, 2016 1:12:45 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); + Assert.assertEquals("8/23/16 1:12 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); + } } From 8ca0e9a84711edfd712bced5b6cf659a53dd783a Mon Sep 17 00:00:00 2001 From: dupirefr Date: Mon, 1 Oct 2018 19:30:04 +0200 Subject: [PATCH 13/75] [BAEL-2183] Arrays manipulations --- .../baeldung/array/ArrayReferenceGuide.java | 159 ++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/array/ArrayReferenceGuide.java diff --git a/core-java/src/main/java/com/baeldung/array/ArrayReferenceGuide.java b/core-java/src/main/java/com/baeldung/array/ArrayReferenceGuide.java new file mode 100644 index 0000000000..7d7dec85b0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/array/ArrayReferenceGuide.java @@ -0,0 +1,159 @@ +package com.baeldung.array; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +public class ArrayReferenceGuide { + + public static void main(String[] args) { + declaration(); + + initialization(); + + access(); + + iterating(); + + varargs(); + + transformIntoList(); + + transformIntoStream(); + + sort(); + + search(); + + merge(); + } + + private static void declaration() { + int[] anArray; + int anotherArray[]; + } + + private static void initialization() { + int[] anArray = new int[10]; + anArray[0] = 10; + anArray[5] = 4; + + int[] anotherArray = new int[] {1, 2, 3, 4, 5}; + } + + private static void access() { + int[] anArray = new int[10]; + anArray[0] = 10; + anArray[5] = 4; + + System.out.println(anArray[0]); + } + + private static void iterating() { + int[] anArray = new int[] {1, 2, 3, 4, 5}; + for (int i = 0; i < anArray.length; i++) { + System.out.println(anArray[i]); + } + + for (int element : anArray) { + System.out.println(element); + } + } + + private static void varargs() { + String[] groceries = new String[] {"Milk", "Tomato", "Chips"}; + varargMethod(groceries); + varargMethod("Milk", "Tomato", "Chips"); + } + + private static void varargMethod(String... varargs) { + for (String element : varargs) { + System.out.println(element); + } + } + + private static void transformIntoList() { + Integer[] anArray = new Integer[] {1, 2, 3, 4, 5}; + + // Naïve implementation + List aList = new ArrayList<>(); // We create an empty list + for (int element : anArray) { + // We iterate over array's elements and add them to the list + aList.add(element); + } + + // Pretty implementation + aList = Arrays.asList(anArray); + + // Drawbacks + try { + aList.remove(0); + } catch (UnsupportedOperationException e) { + System.out.println(e.getMessage()); + } + + try { + aList.add(6); + } catch (UnsupportedOperationException e) { + System.out.println(e.getMessage()); + } + + int[] anotherArray = new int[] {1, 2, 3, 4, 5}; +// List anotherList = Arrays.asList(anotherArray); + } + + private static void transformIntoStream() { + int[] anArray = new int[] {1, 2, 3, 4, 5}; + IntStream aStream = Arrays.stream(anArray); + + Integer[] anotherArray = new Integer[] {1, 2, 3, 4, 5}; + Stream anotherStream = Arrays.stream(anotherArray, 2, 4); + } + + private static void sort() { + int[] anArray = new int[] {5, 2, 1, 4, 8}; + Arrays.sort(anArray); // anArray is now {1, 2, 4, 5, 8} + + Integer[] anotherArray = new Integer[] {5, 2, 1, 4, 8}; + Arrays.sort(anotherArray); // anArray is now {1, 2, 4, 5, 8} + + String[] yetAnotherArray = new String[] {"A", "E", "Z", "B", "C"}; + Arrays.sort(yetAnotherArray, 1, 3, Comparator.comparing(String::toString).reversed()); // yetAnotherArray is now {"A", "Z", "E", "B", "C"} + } + + private static void search() { + int[] anArray = new int[] {5, 2, 1, 4, 8}; + for (int i = 0; i < anArray.length; i++) { + if (anArray[i] == 4) { + System.out.println("Found at index " + i); + break; + } + } + + Arrays.sort(anArray); + int index = Arrays.binarySearch(anArray, 4); + System.out.println("Found at index " + index); + } + + private static void merge() { + int[] anArray = new int[] {5, 2, 1, 4, 8}; + int[] anotherArray = new int[] {10, 4, 9, 11, 2}; + + int[] resultArray = new int[anArray.length + anotherArray.length]; + for (int i = 0; i < resultArray.length; i++) { + resultArray[i] = (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]); + } + for (int element : resultArray) { + System.out.println(element); + } + + Arrays.setAll(resultArray, i -> (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length])); + for (int element : resultArray) { + System.out.println(element); + } + } + +} From 6460e73eb67f514376005258d490ed742f93a60d Mon Sep 17 00:00:00 2001 From: Satyam Date: Tue, 2 Oct 2018 12:06:56 +0530 Subject: [PATCH 14/75] BAEL-2197: Initial Commit --- core-java-8/findItemsBasedOnValues/.gitignore | 1 + .../src/findItems/FindItemsBasedOnValues.java | 114 ++++++++++++++++++ 2 files changed, 115 insertions(+) create mode 100644 core-java-8/findItemsBasedOnValues/.gitignore create mode 100644 core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java diff --git a/core-java-8/findItemsBasedOnValues/.gitignore b/core-java-8/findItemsBasedOnValues/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/core-java-8/findItemsBasedOnValues/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java b/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java new file mode 100644 index 0000000000..5fa15be86e --- /dev/null +++ b/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java @@ -0,0 +1,114 @@ +package findItems; + +import static org.junit.Assert.*; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; +import org.junit.Test; + +public class FindItemsBasedOnValues { + + static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy"); + + public static void main(String[] args) throws ParseException { + FindItemsBasedOnValues findItems = new FindItemsBasedOnValues(); + findItems.findItemsImpl(); + } + + @Test + public void findItemsImpl() throws ParseException { + List expectedList = new ArrayList(); + Client expectedClient = new Client(1001, DATE_FORMAT.parse("01-02-2018")); + expectedList.add(expectedClient); + + List listOfCompanies = new ArrayList(); + List listOfClients = new ArrayList(); + populate(listOfCompanies, listOfClients); + + List filteredList = listOfClients.stream() + .filter(client -> listOfCompanies.stream() + .anyMatch(company -> company.getType() + .equals("eMart") && company.getProjectId() + .equals(client.getProjectId()) && company.getStart() + .after(client.getDate()) && company.getEnd() + .before(client.getDate()))) + .collect(Collectors.toList()); + + assertEquals(expectedClient.getProjectId(), filteredList.get(0) + .getProjectId()); + assertEquals(expectedClient.getDate(), filteredList.get(0) + .getDate()); + } + + private void populate(List companyList, List clientList) throws ParseException { + Company company1 = new Company(1001, DATE_FORMAT.parse("01-03-2018"), DATE_FORMAT.parse("01-01-2018"), "eMart"); + Company company2 = new Company(1002, DATE_FORMAT.parse("01-02-2018"), DATE_FORMAT.parse("01-04-2018"), "commerce"); + Company company3 = new Company(1003, DATE_FORMAT.parse("01-06-2018"), DATE_FORMAT.parse("01-02-2018"), "eMart"); + Company company4 = new Company(1004, DATE_FORMAT.parse("01-03-2018"), DATE_FORMAT.parse("01-06-2018"), "blog"); + + Collections.addAll(companyList, company1, company2, company3, company4); + + Client client1 = new Client(1001, DATE_FORMAT.parse("01-02-2018")); + Client client2 = new Client(1003, DATE_FORMAT.parse("01-04-2018")); + Client client3 = new Client(1005, DATE_FORMAT.parse("01-07-2018")); + Client client4 = new Client(1007, DATE_FORMAT.parse("01-08-2018")); + + Collections.addAll(clientList, client1, client2, client3, client4); + } +} + +class Company { + Long projectId; + Date start; + Date end; + String type; + + public Company(long projectId, Date start, Date end, String type) { + super(); + this.projectId = projectId; + this.start = start; + this.end = end; + this.type = type; + } + + public Long getProjectId() { + return projectId; + } + + public Date getStart() { + return start; + } + + public Date getEnd() { + return end; + } + + public String getType() { + return type; + } + +} + +class Client { + Long projectId; + Date date; + + public Client(long projectId, Date date) { + super(); + this.projectId = projectId; + this.date = date; + } + + public Long getProjectId() { + return projectId; + } + + public Date getDate() { + return date; + } + +} \ No newline at end of file From 7070aae38f951a23463abb3e2545bb7682ef387c Mon Sep 17 00:00:00 2001 From: Satyam Date: Wed, 3 Oct 2018 10:39:58 +0530 Subject: [PATCH 15/75] Updated Test method name --- .../src/findItems/FindItemsBasedOnValues.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java b/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java index 5fa15be86e..d6a320a8ec 100644 --- a/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java +++ b/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java @@ -16,11 +16,11 @@ public class FindItemsBasedOnValues { public static void main(String[] args) throws ParseException { FindItemsBasedOnValues findItems = new FindItemsBasedOnValues(); - findItems.findItemsImpl(); + findItems.givenListOfCompanies_thenListOfClientsIsFilteredCorrectly(); } @Test - public void findItemsImpl() throws ParseException { + public void givenListOfCompanies_thenListOfClientsIsFilteredCorrectly() throws ParseException { List expectedList = new ArrayList(); Client expectedClient = new Client(1001, DATE_FORMAT.parse("01-02-2018")); expectedList.add(expectedClient); From 7f6df18b64e5defb7909d6aa08748bf1cda41fc5 Mon Sep 17 00:00:00 2001 From: Dmytro Korniienko Date: Wed, 3 Oct 2018 23:55:24 +0300 Subject: [PATCH 16/75] BAEL-2258 Guide to DateTimeFormatter. Predefined formatters tests added --- .../internationalization/DateTimeFormatterUnitTest.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java b/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java index cbb84a8783..1260a6db92 100644 --- a/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java @@ -48,7 +48,7 @@ public class DateTimeFormatterUnitTest { } @Test - public void shoulPrintFormattedDate() { + public void shouldPrintFormattedDate() { String europeanDatePattern = "dd.MM.yyyy"; DateTimeFormatter europeanDateFormatter = DateTimeFormatter.ofPattern(europeanDatePattern); LocalDate summerDay = LocalDate.of(2016, 7, 31); @@ -112,4 +112,11 @@ public class DateTimeFormatterUnitTest { Assert.assertEquals("Aug 23, 2016 1:12:45 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); Assert.assertEquals("8/23/16 1:12 PM", DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.of("Europe/Helsinki")).format(anotherSummerDay)); } + + @Test + public void shouldPrintFormattedDateTimeWithPredefined() { + Assert.assertEquals("2018-03-09", DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.of(2018, 3, 9))); + Assert.assertEquals("2018-03-09-03:00", DateTimeFormatter.ISO_OFFSET_DATE.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3")))); + Assert.assertEquals("Fri, 9 Mar 2018 00:00:00 -0300", DateTimeFormatter.RFC_1123_DATE_TIME.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3")))); + } } From 08e902cb26072d8959bbcc191a91d1737d235c7d Mon Sep 17 00:00:00 2001 From: Dmytro Korniienko Date: Thu, 4 Oct 2018 23:14:59 +0300 Subject: [PATCH 17/75] BAEL-2258 Guide to DateTimeFormatter. parse() method usage tests added --- .../DateTimeFormatterUnitTest.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java b/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java index 1260a6db92..36a5f6210b 100644 --- a/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java @@ -9,6 +9,7 @@ import java.time.LocalTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; import java.time.format.FormatStyle; import java.time.temporal.ChronoUnit; import java.util.Locale; @@ -119,4 +120,39 @@ public class DateTimeFormatterUnitTest { Assert.assertEquals("2018-03-09-03:00", DateTimeFormatter.ISO_OFFSET_DATE.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3")))); Assert.assertEquals("Fri, 9 Mar 2018 00:00:00 -0300", DateTimeFormatter.RFC_1123_DATE_TIME.format(LocalDate.of(2018, 3, 9).atStartOfDay(ZoneId.of("UTC-3")))); } + + @Test + public void shouldParseDateTime() { + Assert.assertEquals(LocalDate.of(2018, 3, 12), LocalDate.from(DateTimeFormatter.ISO_LOCAL_DATE.parse("2018-03-09")).plusDays(3)); + } + + @Test + public void shouldParseFormatStyleFull() { + ZonedDateTime dateTime = ZonedDateTime.from(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).parse("Tuesday, August 23, 2016 1:12:45 PM EET")); + Assert.assertEquals(ZonedDateTime.of(LocalDateTime.of(2016, 8, 23, 22, 12, 45), ZoneId.of("Europe/Bucharest")), dateTime.plusHours(9)); + } + + @Test + public void shouldParseDateWithCustomFormatter() { + DateTimeFormatter europeanDateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy"); + Assert.assertFalse(LocalDate.from(europeanDateFormatter.parse("15.08.2014")).isLeapYear()); + } + + @Test + public void shouldParseTimeWithCustomFormatter() { + DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm:ss a"); + Assert.assertTrue(LocalTime.from(timeFormatter.parse("12:25:30 AM")).isBefore(LocalTime.NOON)); + } + + @Test + public void shouldParseZonedDateTimeWithCustomFormatter() { + DateTimeFormatter zonedFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm z"); + Assert.assertEquals(7200, ZonedDateTime.from(zonedFormatter.parse("31.07.2016 14:15 GMT+02:00")).getOffset().getTotalSeconds()); + } + + @Test(expected = DateTimeParseException.class) + public void shouldExpectAnExceptionIfDateTimeStringNotMatchPattern() { + DateTimeFormatter zonedFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm z"); + ZonedDateTime.from(zonedFormatter.parse("31.07.2016 14:15")); + } } From 5022d3fbf95a82d085d992c3b0a3b2f0a9bee486 Mon Sep 17 00:00:00 2001 From: Josephine Barboza Date: Sat, 6 Oct 2018 01:32:25 +0530 Subject: [PATCH 18/75] Ebean Chnages --- libraries-data/ebean/pom.xml | 59 --------- libraries-data/pom.xml | 56 +++++---- .../main/java/com/baeldung/ebean/app/App.java | 0 .../java/com/baeldung/ebean/app/App2.java | 0 .../com/baeldung/ebean/model/Address.java | 0 .../com/baeldung/ebean/model/BaseModel.java | 118 +++++++++--------- .../com/baeldung/ebean/model/Customer.java | 84 ++++++------- .../src/main/resources/application.properties | 0 .../{ebean => }/src/main/resources/ebean.mf | 0 .../src/main/resources/logback.yml | 0 10 files changed, 136 insertions(+), 181 deletions(-) delete mode 100644 libraries-data/ebean/pom.xml rename libraries-data/{ebean => }/src/main/java/com/baeldung/ebean/app/App.java (100%) rename libraries-data/{ebean => }/src/main/java/com/baeldung/ebean/app/App2.java (100%) rename libraries-data/{ebean => }/src/main/java/com/baeldung/ebean/model/Address.java (100%) rename libraries-data/{ebean => }/src/main/java/com/baeldung/ebean/model/BaseModel.java (94%) rename libraries-data/{ebean => }/src/main/java/com/baeldung/ebean/model/Customer.java (95%) rename libraries-data/{ebean => }/src/main/resources/application.properties (100%) rename libraries-data/{ebean => }/src/main/resources/ebean.mf (100%) rename libraries-data/{ebean => }/src/main/resources/logback.yml (100%) diff --git a/libraries-data/ebean/pom.xml b/libraries-data/ebean/pom.xml deleted file mode 100644 index 2e319e1523..0000000000 --- a/libraries-data/ebean/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - 4.0.0 - - com.baeldung - ebean - 0.0.1-SNAPSHOT - jar - - ebean - http://maven.apache.org - - - UTF-8 - - - - - io.ebean - ebean - 11.22.4 - - - com.h2database - h2 - 1.4.196 - - - ch.qos.logback - logback-classic - 1.2.3 - - - - - - - - io.ebean - ebean-maven-plugin - 11.11.2 - - - - main - process-classes - - debug=1 - - - enhance - - - - - - - - diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 5b34a903ce..abbbe9c5de 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -249,6 +249,18 @@ ${awaitility.version} test + + + io.ebean + ebean + 11.22.4 + + + + ch.qos.logback + logback-classic + 1.2.3 + @@ -332,27 +344,7 @@ - - org.datanucleus - datanucleus-maven-plugin - ${datanucleus-maven-plugin.version} - - JDO - ${basedir}/datanucleus.properties - ${basedir}/log4j.properties - true - false - - - - - process-classes - - enhance - - - - + org.apache.maven.plugins @@ -380,6 +372,28 @@ + + + + io.ebean + ebean-maven-plugin + 11.11.2 + + + + main + process-classes + + debug=1 + + + enhance + + + + + + diff --git a/libraries-data/ebean/src/main/java/com/baeldung/ebean/app/App.java b/libraries-data/src/main/java/com/baeldung/ebean/app/App.java similarity index 100% rename from libraries-data/ebean/src/main/java/com/baeldung/ebean/app/App.java rename to libraries-data/src/main/java/com/baeldung/ebean/app/App.java diff --git a/libraries-data/ebean/src/main/java/com/baeldung/ebean/app/App2.java b/libraries-data/src/main/java/com/baeldung/ebean/app/App2.java similarity index 100% rename from libraries-data/ebean/src/main/java/com/baeldung/ebean/app/App2.java rename to libraries-data/src/main/java/com/baeldung/ebean/app/App2.java diff --git a/libraries-data/ebean/src/main/java/com/baeldung/ebean/model/Address.java b/libraries-data/src/main/java/com/baeldung/ebean/model/Address.java similarity index 100% rename from libraries-data/ebean/src/main/java/com/baeldung/ebean/model/Address.java rename to libraries-data/src/main/java/com/baeldung/ebean/model/Address.java diff --git a/libraries-data/ebean/src/main/java/com/baeldung/ebean/model/BaseModel.java b/libraries-data/src/main/java/com/baeldung/ebean/model/BaseModel.java similarity index 94% rename from libraries-data/ebean/src/main/java/com/baeldung/ebean/model/BaseModel.java rename to libraries-data/src/main/java/com/baeldung/ebean/model/BaseModel.java index 7634df7aa0..1390507605 100644 --- a/libraries-data/ebean/src/main/java/com/baeldung/ebean/model/BaseModel.java +++ b/libraries-data/src/main/java/com/baeldung/ebean/model/BaseModel.java @@ -1,59 +1,59 @@ -package com.baeldung.ebean.model; - -import java.time.Instant; - -import javax.persistence.Id; -import javax.persistence.MappedSuperclass; -import javax.persistence.Version; - -import io.ebean.annotation.WhenCreated; -import io.ebean.annotation.WhenModified; - -@MappedSuperclass -public abstract class BaseModel { - - @Id - protected long id; - - @Version - protected long version; - - @WhenCreated - protected Instant createdOn; - - @WhenModified - protected Instant modifiedOn; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public Instant getCreatedOn() { - return createdOn; - } - - public void setCreatedOn(Instant createdOn) { - this.createdOn = createdOn; - } - - public Instant getModifiedOn() { - return modifiedOn; - } - - public void setModifiedOn(Instant modifiedOn) { - this.modifiedOn = modifiedOn; - } - - public long getVersion() { - return version; - } - - public void setVersion(long version) { - this.version = version; - } - -} +package com.baeldung.ebean.model; + +import java.time.Instant; + +import javax.persistence.Id; +import javax.persistence.MappedSuperclass; +import javax.persistence.Version; + +import io.ebean.annotation.WhenCreated; +import io.ebean.annotation.WhenModified; + +@MappedSuperclass +public abstract class BaseModel { + + @Id + protected long id; + + @Version + protected long version; + + @WhenCreated + protected Instant createdOn; + + @WhenModified + protected Instant modifiedOn; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Instant getCreatedOn() { + return createdOn; + } + + public void setCreatedOn(Instant createdOn) { + this.createdOn = createdOn; + } + + public Instant getModifiedOn() { + return modifiedOn; + } + + public void setModifiedOn(Instant modifiedOn) { + this.modifiedOn = modifiedOn; + } + + public long getVersion() { + return version; + } + + public void setVersion(long version) { + this.version = version; + } + +} diff --git a/libraries-data/ebean/src/main/java/com/baeldung/ebean/model/Customer.java b/libraries-data/src/main/java/com/baeldung/ebean/model/Customer.java similarity index 95% rename from libraries-data/ebean/src/main/java/com/baeldung/ebean/model/Customer.java rename to libraries-data/src/main/java/com/baeldung/ebean/model/Customer.java index df1db82de4..4dd629245a 100644 --- a/libraries-data/ebean/src/main/java/com/baeldung/ebean/model/Customer.java +++ b/libraries-data/src/main/java/com/baeldung/ebean/model/Customer.java @@ -1,42 +1,42 @@ -package com.baeldung.ebean.model; - -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.OneToOne; - -@Entity -public class Customer extends BaseModel { - - public Customer(String name, Address address) { - super(); - this.name = name; - this.address = address; - } - - private String name; - - @OneToOne(cascade = CascadeType.ALL) - Address address; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Address getAddress() { - return address; - } - - public void setAddress(Address address) { - this.address = address; - } - - @Override - public String toString() { - return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]"; - } - -} +package com.baeldung.ebean.model; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.OneToOne; + +@Entity +public class Customer extends BaseModel { + + public Customer(String name, Address address) { + super(); + this.name = name; + this.address = address; + } + + private String name; + + @OneToOne(cascade = CascadeType.ALL) + Address address; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + @Override + public String toString() { + return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]"; + } + +} diff --git a/libraries-data/ebean/src/main/resources/application.properties b/libraries-data/src/main/resources/application.properties similarity index 100% rename from libraries-data/ebean/src/main/resources/application.properties rename to libraries-data/src/main/resources/application.properties diff --git a/libraries-data/ebean/src/main/resources/ebean.mf b/libraries-data/src/main/resources/ebean.mf similarity index 100% rename from libraries-data/ebean/src/main/resources/ebean.mf rename to libraries-data/src/main/resources/ebean.mf diff --git a/libraries-data/ebean/src/main/resources/logback.yml b/libraries-data/src/main/resources/logback.yml similarity index 100% rename from libraries-data/ebean/src/main/resources/logback.yml rename to libraries-data/src/main/resources/logback.yml From 62d677ed30e1337e6829a547f59a571889fc94db Mon Sep 17 00:00:00 2001 From: Josephine Barboza Date: Sun, 7 Oct 2018 13:14:31 +0530 Subject: [PATCH 19/75] BAEL-2169 Guide to Ebean --- libraries-data/pom.xml | 207 +++++++++++------- .../main/java/com/baeldung/ebean/app/App.java | 2 +- .../com/baeldung/ebean/model/Address.java | 14 +- .../com/baeldung/ebean/model/BaseModel.java | 8 +- ...pplication.properties => ebean.properties} | 0 libraries-data/src/main/resources/logback.xml | 29 ++- libraries-data/src/main/resources/logback.yml | 3 - 7 files changed, 162 insertions(+), 101 deletions(-) rename libraries-data/src/main/resources/{application.properties => ebean.properties} (100%) delete mode 100644 libraries-data/src/main/resources/logback.yml diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index abbbe9c5de..e1318fd597 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -1,5 +1,6 @@ - 4.0.0 libraries-data @@ -13,6 +14,7 @@ + com.esotericsoftware kryo @@ -99,36 +101,49 @@ org.datanucleus javax.jdo ${javax.jdo.version} + org.datanucleus datanucleus-core ${datanucleus.version} + org.datanucleus datanucleus-api-jdo ${datanucleus.version} + + org.datanucleus datanucleus-rdbms ${datanucleus.version} + org.datanucleus datanucleus-maven-plugin ${datanucleus-maven-plugin.version} + + + log4j + log4j + + org.datanucleus datanucleus-xml ${datanucleus-xml.version} + org.datanucleus datanucleus-jdo-query ${datanucleus-jdo-query.version} + @@ -141,49 +156,55 @@ hazelcast ${hazelcast.version} - + com.googlecode.jmapper-framework jmapper-core ${jmapper.version} - - - org.apache.crunch - crunch-core - ${org.apache.crunch.crunch-core.version} - - - org.apache.hadoop - hadoop-client - ${org.apache.hadoop.hadoop-client} - provided - + + + org.apache.crunch + crunch-core + ${org.apache.crunch.crunch-core.version} + + + org.apache.hadoop + hadoop-client + ${org.apache.hadoop.hadoop-client} + provided + + + log4j + log4j + + + - - commons-cli - commons-cli - 1.2 - provided - - - commons-io - commons-io - 2.1 - provided - - - commons-httpclient - commons-httpclient - 3.0.1 - provided - - - commons-codec - commons-codec - - - + + commons-cli + commons-cli + 1.2 + provided + + + commons-io + commons-io + 2.1 + provided + + + commons-httpclient + commons-httpclient + 3.0.1 + provided + + + commons-codec + commons-codec + + + org.apache.flink flink-connector-kafka-0.11_2.11 @@ -249,19 +270,32 @@ ${awaitility.version} test - - + io.ebean ebean - 11.22.4 + ${ebean.version} - + + org.slf4j + slf4j-api + ${slf4j.version} + + ch.qos.logback logback-classic - 1.2.3 + ${logback.version} + + + ch.qos.logback + logback-core + ${logback.version} + + + org.slf4j + slf4j-log4j12 + ${slf4j.version} - @@ -280,16 +314,28 @@ - - - + + + - - + + - + @@ -344,35 +390,35 @@ - - - org.apache.maven.plugins - maven-assembly-plugin - 2.3 - - - src/main/assembly/hadoop-job.xml - - - - com.baeldung.crunch.WordCount - - - - - - make-assembly - package - - single - - - - + + + org.apache.maven.plugins + maven-assembly-plugin + 2.3 + + + src/main/assembly/hadoop-job.xml + + + + com.baeldung.crunch.WordCount + + + + + + make-assembly + package + + single + + + + - + io.ebean @@ -429,7 +475,10 @@ 5.0.4 1.6.0.1 0.15.0 - 2.2.0 + 2.2.0 + 11.22.4 + 1.7.25 + 1.0.1 diff --git a/libraries-data/src/main/java/com/baeldung/ebean/app/App.java b/libraries-data/src/main/java/com/baeldung/ebean/app/App.java index 161bf1e820..44a4fa8562 100644 --- a/libraries-data/src/main/java/com/baeldung/ebean/app/App.java +++ b/libraries-data/src/main/java/com/baeldung/ebean/app/App.java @@ -28,7 +28,7 @@ public class App { } public static void crudOperations() { - + Address a1 = new Address("5, Wide Street", null, "New York"); Customer c1 = new Customer("John Wide", a1); diff --git a/libraries-data/src/main/java/com/baeldung/ebean/model/Address.java b/libraries-data/src/main/java/com/baeldung/ebean/model/Address.java index 362e27c32a..dfcd90ffa7 100644 --- a/libraries-data/src/main/java/com/baeldung/ebean/model/Address.java +++ b/libraries-data/src/main/java/com/baeldung/ebean/model/Address.java @@ -3,7 +3,7 @@ package com.baeldung.ebean.model; import javax.persistence.Entity; @Entity -public class Address extends BaseModel{ +public class Address extends BaseModel { public Address(String addressLine1, String addressLine2, String city) { super(); @@ -11,32 +11,38 @@ public class Address extends BaseModel{ this.addressLine2 = addressLine2; this.city = city; } - + private String addressLine1; private String addressLine2; private String city; - + public String getAddressLine1() { return addressLine1; } + public void setAddressLine1(String addressLine1) { this.addressLine1 = addressLine1; } + public String getAddressLine2() { return addressLine2; } + public void setAddressLine2(String addressLine2) { this.addressLine2 = addressLine2; } + public String getCity() { return city; } + public void setCity(String city) { this.city = city; } + @Override public String toString() { return "Address [id=" + id + ", addressLine1=" + addressLine1 + ", addressLine2=" + addressLine2 + ", city=" + city + "]"; } - + } diff --git a/libraries-data/src/main/java/com/baeldung/ebean/model/BaseModel.java b/libraries-data/src/main/java/com/baeldung/ebean/model/BaseModel.java index 1390507605..547d5bf075 100644 --- a/libraries-data/src/main/java/com/baeldung/ebean/model/BaseModel.java +++ b/libraries-data/src/main/java/com/baeldung/ebean/model/BaseModel.java @@ -14,13 +14,13 @@ public abstract class BaseModel { @Id protected long id; - + @Version protected long version; - + @WhenCreated protected Instant createdOn; - + @WhenModified protected Instant modifiedOn; @@ -55,5 +55,5 @@ public abstract class BaseModel { public void setVersion(long version) { this.version = version; } - + } diff --git a/libraries-data/src/main/resources/application.properties b/libraries-data/src/main/resources/ebean.properties similarity index 100% rename from libraries-data/src/main/resources/application.properties rename to libraries-data/src/main/resources/ebean.properties diff --git a/libraries-data/src/main/resources/logback.xml b/libraries-data/src/main/resources/logback.xml index 7d900d8ea8..21f797ed71 100644 --- a/libraries-data/src/main/resources/logback.xml +++ b/libraries-data/src/main/resources/logback.xml @@ -1,13 +1,22 @@ - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/libraries-data/src/main/resources/logback.yml b/libraries-data/src/main/resources/logback.yml deleted file mode 100644 index c838a19c6c..0000000000 --- a/libraries-data/src/main/resources/logback.yml +++ /dev/null @@ -1,3 +0,0 @@ - - - From 45da250fffffffae062047e43973416232872624 Mon Sep 17 00:00:00 2001 From: clininger Date: Mon, 8 Oct 2018 07:33:16 +0700 Subject: [PATCH 20/75] BAEL-2184 Converting a Collection to ArrayList --- .../convertcollectiontoarraylist/Foo.java | 52 +++++++ .../FooUnitTest.java | 144 ++++++++++++++++++ 2 files changed, 196 insertions(+) create mode 100644 core-java-collections/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java create mode 100644 core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java diff --git a/core-java-collections/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java b/core-java-collections/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java new file mode 100644 index 0000000000..3123295641 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java @@ -0,0 +1,52 @@ +package com.baeldung.convertcollectiontoarraylist; + +/** + * This POJO is the element type of our collection. It has a deepCopy() method. + * + * @author chris + */ +public class Foo { + + private int id; + private String name; + private Foo parent; + + public Foo() { + } + + public Foo(int id, String name, Foo parent) { + this.id = id; + this.name = name; + this.parent = parent; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Foo getParent() { + return parent; + } + + public void setParent(Foo parent) { + this.parent = parent; + } + + public Foo deepCopy() { + return new Foo(this.id, this.name, + this.parent != null ? this.parent.deepCopy() : null); + } + +} diff --git a/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java b/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java new file mode 100644 index 0000000000..fd07848383 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java @@ -0,0 +1,144 @@ +package com.baeldung.convertcollectiontoarraylist; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import static java.util.stream.Collectors.toCollection; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author chris + */ +public class FooUnitTest { + private static Collection srcCollection = new HashSet<>(); + + public FooUnitTest() { + } + + @BeforeClass + public static void setUpClass() { + int i = 0; + Foo john = new Foo(i++, "John", null); + Foo mary = new Foo(i++, "Mary", null); + Foo sam = new Foo(i++, "Sam", john); + Foo alice = new Foo(i++, "Alice", john); + Foo buffy = new Foo(i++, "Buffy", sam); + srcCollection.add(john); + srcCollection.add(mary); + srcCollection.add(sam); + srcCollection.add(alice); + srcCollection.add(buffy); + } + + /** + * Section 3. Using the ArrayList Constructor + */ + @Test + public void testConstructor() { + ArrayList newList = new ArrayList<>(srcCollection); + verifyShallowCopy(srcCollection, newList); + } + + /** + * Section 4. Using the Streams API + */ + @Test + public void testStream() { + ArrayList newList = srcCollection.stream().collect(toCollection(ArrayList::new)); + verifyShallowCopy(srcCollection, newList); + } + + /** + * Section 5. Deep Copy + */ + @Test + public void testStreamDeepCopy() { + ArrayList newList = srcCollection.stream() + .map(foo -> foo.deepCopy()) + .collect(toCollection(ArrayList::new)); + verifyDeepCopy(srcCollection, newList); + } + + /** + * Section 6. Controlling the List Order + */ + @Test + public void testSortOrder() { + assertFalse("Oops: source collection is already sorted!", isSorted(srcCollection)); + ArrayList newList = srcCollection.stream() + .map(foo -> foo.deepCopy()) + .sorted(Comparator.comparing(Foo::getName)) + .collect(toCollection(ArrayList::new)); + assertTrue("ArrayList is not sorted by name", isSorted(newList)); + } + + /** + * Verify that the contents of the two collections are the same + * @param a + * @param b + */ + private void verifyShallowCopy(Collection a, Collection b) { + assertEquals("Collections have different lengths", a.size(), b.size()); + Iterator iterA = a.iterator(); + Iterator iterB = b.iterator(); + while (iterA.hasNext()) { + // use '==' to test instance identity + assertTrue("Foo instances differ!", iterA.next() == iterB.next()); + } + } + + /** + * Verify that the contents of the two collections are the same + * @param a + * @param b + */ + private void verifyDeepCopy(Collection a, Collection b) { + assertEquals("Collections have different lengths", a.size(), b.size()); + Iterator iterA = a.iterator(); + Iterator iterB = b.iterator(); + while (iterA.hasNext()) { + Foo nextA = iterA.next(); + Foo nextB = iterB.next(); + // should not be same instance + assertFalse("Foo instances are the same!", nextA == nextB); + // but should have same content + assertFalse("Foo instances have different content!", fooDiff(nextA, nextB)); + } + } + + /** + * Return true if the contents of a and b differ. Test parent recursively + * @param a + * @param b + * @return False if the two items are the same + */ + private boolean fooDiff(Foo a, Foo b) { + if (a != null && b != null) { + return a.getId() != b.getId() + || !a.getName().equals(b.getName()) + || fooDiff(a.getParent(), b.getParent()); + } + return !(a == null && b == null); + } + + /** + * @param c collection of Foo + * @return true if the collection is sorted by name + */ + private boolean isSorted(Collection c) { + String prevName = null; + for (Foo foo : c) { + if (prevName == null || foo.getName().compareTo(prevName) > 0) { + prevName = foo.getName(); + } else { + return false; + } + } + return true; + } +} From 7d64241f1634ebf68688a81bb431b7b90d704f68 Mon Sep 17 00:00:00 2001 From: clininger Date: Mon, 8 Oct 2018 08:21:35 +0700 Subject: [PATCH 21/75] BAEL-2184 test names --- .../convertcollectiontoarraylist/FooUnitTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java b/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java index fd07848383..5b46434a0b 100644 --- a/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java +++ b/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java @@ -39,7 +39,7 @@ public class FooUnitTest { * Section 3. Using the ArrayList Constructor */ @Test - public void testConstructor() { + public void whenUsingConstructor_thenVerifyShallowCopy() { ArrayList newList = new ArrayList<>(srcCollection); verifyShallowCopy(srcCollection, newList); } @@ -48,7 +48,7 @@ public class FooUnitTest { * Section 4. Using the Streams API */ @Test - public void testStream() { + public void whenUsingStream_thenVerifyShallowCopy() { ArrayList newList = srcCollection.stream().collect(toCollection(ArrayList::new)); verifyShallowCopy(srcCollection, newList); } @@ -57,7 +57,7 @@ public class FooUnitTest { * Section 5. Deep Copy */ @Test - public void testStreamDeepCopy() { + public void whenUsingDeepCopy_thenVerifyDeepCopy() { ArrayList newList = srcCollection.stream() .map(foo -> foo.deepCopy()) .collect(toCollection(ArrayList::new)); @@ -68,7 +68,7 @@ public class FooUnitTest { * Section 6. Controlling the List Order */ @Test - public void testSortOrder() { + public void whenUsingSortedStream_thenVerifySortOrder() { assertFalse("Oops: source collection is already sorted!", isSorted(srcCollection)); ArrayList newList = srcCollection.stream() .map(foo -> foo.deepCopy()) From 3c0bd8e6e8a5f6db610e65270eb4bcb0c1b8813f Mon Sep 17 00:00:00 2001 From: clininger Date: Mon, 8 Oct 2018 08:42:33 +0700 Subject: [PATCH 22/75] BAEL-2184 formatting --- .../com/baeldung/convertcollectiontoarraylist/Foo.java | 4 ++-- .../convertcollectiontoarraylist/FooUnitTest.java | 9 +++++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/core-java-collections/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java b/core-java-collections/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java index 3123295641..5c9464182e 100644 --- a/core-java-collections/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java +++ b/core-java-collections/src/main/java/com/baeldung/convertcollectiontoarraylist/Foo.java @@ -45,8 +45,8 @@ public class Foo { } public Foo deepCopy() { - return new Foo(this.id, this.name, - this.parent != null ? this.parent.deepCopy() : null); + return new Foo( + this.id, this.name, this.parent != null ? this.parent.deepCopy() : null); } } diff --git a/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java b/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java index 5b46434a0b..2b5751ef9e 100644 --- a/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java +++ b/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java @@ -33,6 +33,9 @@ public class FooUnitTest { srcCollection.add(sam); srcCollection.add(alice); srcCollection.add(buffy); + + // make sure the collection isn't sorted accidentally + assertFalse("Oops: source collection is already sorted!", isSorted(srcCollection)); } /** @@ -50,6 +53,7 @@ public class FooUnitTest { @Test public void whenUsingStream_thenVerifyShallowCopy() { ArrayList newList = srcCollection.stream().collect(toCollection(ArrayList::new)); + verifyShallowCopy(srcCollection, newList); } @@ -61,6 +65,7 @@ public class FooUnitTest { ArrayList newList = srcCollection.stream() .map(foo -> foo.deepCopy()) .collect(toCollection(ArrayList::new)); + verifyDeepCopy(srcCollection, newList); } @@ -69,11 +74,11 @@ public class FooUnitTest { */ @Test public void whenUsingSortedStream_thenVerifySortOrder() { - assertFalse("Oops: source collection is already sorted!", isSorted(srcCollection)); ArrayList newList = srcCollection.stream() .map(foo -> foo.deepCopy()) .sorted(Comparator.comparing(Foo::getName)) .collect(toCollection(ArrayList::new)); + assertTrue("ArrayList is not sorted by name", isSorted(newList)); } @@ -130,7 +135,7 @@ public class FooUnitTest { * @param c collection of Foo * @return true if the collection is sorted by name */ - private boolean isSorted(Collection c) { + private static boolean isSorted(Collection c) { String prevName = null; for (Foo foo : c) { if (prevName == null || foo.getName().compareTo(prevName) > 0) { From 7538a4b534a22993e1f3e3eaa73fc55821bc6198 Mon Sep 17 00:00:00 2001 From: clininger Date: Tue, 9 Oct 2018 02:48:17 +0700 Subject: [PATCH 23/75] BAEL-2184 ignore netbeans project files --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 180462a32f..7fe2778755 100644 --- a/.gitignore +++ b/.gitignore @@ -62,3 +62,5 @@ jmeter/src/main/resources/*-JMeter.csv **/dist **/tmp **/out-tsc +**/nbproject/ +**/nb-configuration.xml \ No newline at end of file From ee1b2cb40bd8158f8f5798d2a04efbd45afca225 Mon Sep 17 00:00:00 2001 From: clininger Date: Tue, 9 Oct 2018 21:20:09 +0700 Subject: [PATCH 24/75] BAEL-2184 sorted test not include deep copy --- .../com/baeldung/convertcollectiontoarraylist/FooUnitTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java b/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java index 2b5751ef9e..5be4121bc7 100644 --- a/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java +++ b/core-java-collections/src/test/java/com/baeldung/convertcollectiontoarraylist/FooUnitTest.java @@ -75,7 +75,6 @@ public class FooUnitTest { @Test public void whenUsingSortedStream_thenVerifySortOrder() { ArrayList newList = srcCollection.stream() - .map(foo -> foo.deepCopy()) .sorted(Comparator.comparing(Foo::getName)) .collect(toCollection(ArrayList::new)); From 12c41c3531c5a00123040825a1e0ee798947b801 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Tue, 9 Oct 2018 20:40:58 +0530 Subject: [PATCH 25/75] BAEL-9148 Fix Java EE Annotations Project - Removed spring security related code from jee-7 project --- jee-7/README.md | 2 - .../springSecurity/ApplicationConfig.java | 13 ------ .../SecurityWebApplicationInitializer.java | 10 ---- .../springSecurity/SpringSecurityConfig.java | 46 ------------------- .../controller/HomeController.java | 28 ----------- .../controller/LoginController.java | 15 ------ .../main/webapp/WEB-INF/spring/security.xml | 23 ---------- jee-7/src/main/webapp/WEB-INF/views/admin.jsp | 12 ----- jee-7/src/main/webapp/WEB-INF/views/home.jsp | 26 ----------- jee-7/src/main/webapp/WEB-INF/views/login.jsp | 26 ----------- jee-7/src/main/webapp/WEB-INF/views/user.jsp | 12 ----- jee-7/src/main/webapp/WEB-INF/web.xml | 5 +- jee-7/src/main/webapp/index.jsp | 11 ----- jee-7/src/main/webapp/secure.jsp | 24 ---------- 14 files changed, 4 insertions(+), 249 deletions(-) delete mode 100755 jee-7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java delete mode 100644 jee-7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java delete mode 100644 jee-7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java delete mode 100644 jee-7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java delete mode 100644 jee-7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java delete mode 100644 jee-7/src/main/webapp/WEB-INF/spring/security.xml delete mode 100644 jee-7/src/main/webapp/WEB-INF/views/admin.jsp delete mode 100644 jee-7/src/main/webapp/WEB-INF/views/home.jsp delete mode 100644 jee-7/src/main/webapp/WEB-INF/views/login.jsp delete mode 100644 jee-7/src/main/webapp/WEB-INF/views/user.jsp delete mode 100644 jee-7/src/main/webapp/index.jsp delete mode 100644 jee-7/src/main/webapp/secure.jsp diff --git a/jee-7/README.md b/jee-7/README.md index f0bd65fdf2..a2493e561b 100644 --- a/jee-7/README.md +++ b/jee-7/README.md @@ -5,5 +5,3 @@ - [Introduction to JAX-WS](http://www.baeldung.com/jax-ws) - [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) -- [Securing Java EE with Spring Security](http://www.baeldung.com/java-ee-spring-security) -- [A Guide to Java EE Web-Related Annotations](https://www.baeldung.com/javaee-web-annotations) \ No newline at end of file diff --git a/jee-7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java b/jee-7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java deleted file mode 100755 index f8e7982253..0000000000 --- a/jee-7/src/main/java/com/baeldung/springSecurity/ApplicationConfig.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.springSecurity; - -import javax.ws.rs.ApplicationPath; -import javax.ws.rs.core.Application; - -/** - * Application class required by JAX-RS. If you don't want to have any - * prefix in the URL, you can set the application path to "/". - */ -@ApplicationPath("/") -public class ApplicationConfig extends Application { - -} diff --git a/jee-7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java b/jee-7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java deleted file mode 100644 index e6a05f7b71..0000000000 --- a/jee-7/src/main/java/com/baeldung/springSecurity/SecurityWebApplicationInitializer.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.springSecurity; - -import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; - -public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { - - public SecurityWebApplicationInitializer() { - super(SpringSecurityConfig.class); - } -} diff --git a/jee-7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java b/jee-7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java deleted file mode 100644 index bda8930f36..0000000000 --- a/jee-7/src/main/java/com/baeldung/springSecurity/SpringSecurityConfig.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.springSecurity; - -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - -@Configuration -@EnableWebSecurity -public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth - .inMemoryAuthentication() - .withUser("user1") - .password("user1Pass") - .roles("USER") - .and() - .withUser("admin") - .password("adminPass") - .roles("ADMIN"); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .csrf() - .disable() - .authorizeRequests() - .antMatchers("/auth/login*") - .anonymous() - .antMatchers("/home/admin*") - .hasRole("ADMIN") - .anyRequest() - .authenticated() - .and() - .formLogin() - .loginPage("/auth/login") - .defaultSuccessUrl("/home", true) - .failureUrl("/auth/login?error=true") - .and() - .logout() - .logoutSuccessUrl("/auth/login"); - } -} \ No newline at end of file diff --git a/jee-7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java b/jee-7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java deleted file mode 100644 index 53fd9f4b81..0000000000 --- a/jee-7/src/main/java/com/baeldung/springSecurity/controller/HomeController.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.springSecurity.controller; - -import javax.mvc.annotation.Controller; -import javax.ws.rs.GET; -import javax.ws.rs.Path; - -@Path("/home") -@Controller -public class HomeController { - - @GET - public String home() { - return "home.jsp"; - } - - @GET - @Path("/user") - public String admin() { - return "user.jsp"; - } - - @GET - @Path("/admin") - public String user() { - return "admin.jsp"; - } - -} diff --git a/jee-7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java b/jee-7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java deleted file mode 100644 index a7e7bb471d..0000000000 --- a/jee-7/src/main/java/com/baeldung/springSecurity/controller/LoginController.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.springSecurity.controller; - -import javax.mvc.annotation.Controller; -import javax.ws.rs.GET; -import javax.ws.rs.Path; - -@Path("/auth/login") -@Controller -public class LoginController { - - @GET - public String login() { - return "login.jsp"; - } -} diff --git a/jee-7/src/main/webapp/WEB-INF/spring/security.xml b/jee-7/src/main/webapp/WEB-INF/spring/security.xml deleted file mode 100644 index 777cd9461f..0000000000 --- a/jee-7/src/main/webapp/WEB-INF/spring/security.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jee-7/src/main/webapp/WEB-INF/views/admin.jsp b/jee-7/src/main/webapp/WEB-INF/views/admin.jsp deleted file mode 100644 index b83ea09f5b..0000000000 --- a/jee-7/src/main/webapp/WEB-INF/views/admin.jsp +++ /dev/null @@ -1,12 +0,0 @@ -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> -<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> - - - - -

Welcome to the ADMIN page

- - ">Logout - - - \ No newline at end of file diff --git a/jee-7/src/main/webapp/WEB-INF/views/home.jsp b/jee-7/src/main/webapp/WEB-INF/views/home.jsp deleted file mode 100644 index c6e129c9ce..0000000000 --- a/jee-7/src/main/webapp/WEB-INF/views/home.jsp +++ /dev/null @@ -1,26 +0,0 @@ -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> -<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> - - - - -

This is the body of the sample view

- - - This text is only visible to a user -

- ">Restricted Admin Page -

-
- - - This text is only visible to an admin -
- ">Admin Page -
-
- - ">Logout - - - \ No newline at end of file diff --git a/jee-7/src/main/webapp/WEB-INF/views/login.jsp b/jee-7/src/main/webapp/WEB-INF/views/login.jsp deleted file mode 100644 index d6f2e56f3a..0000000000 --- a/jee-7/src/main/webapp/WEB-INF/views/login.jsp +++ /dev/null @@ -1,26 +0,0 @@ - - - - -

Login

- -
- - - - - - - - - - - - - -
User:
Password:
- -
- - - \ No newline at end of file diff --git a/jee-7/src/main/webapp/WEB-INF/views/user.jsp b/jee-7/src/main/webapp/WEB-INF/views/user.jsp deleted file mode 100644 index 11b8155da7..0000000000 --- a/jee-7/src/main/webapp/WEB-INF/views/user.jsp +++ /dev/null @@ -1,12 +0,0 @@ -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> -<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> - - - - -

Welcome to the Restricted Admin page

- - ">Logout - - - \ No newline at end of file diff --git a/jee-7/src/main/webapp/WEB-INF/web.xml b/jee-7/src/main/webapp/WEB-INF/web.xml index 1bcbb96e24..e656ffc5be 100644 --- a/jee-7/src/main/webapp/WEB-INF/web.xml +++ b/jee-7/src/main/webapp/WEB-INF/web.xml @@ -1,5 +1,8 @@ - + 3.6.1 - 9 - 9 + 1.9 + 1.9 diff --git a/java-dates/src/test/java/com/baeldung/zoneddatetime/ZonedDateTimeUnitTest.java b/java-dates/src/test/java/com/baeldung/zoneddatetime/ZonedDateTimeUnitTest.java new file mode 100644 index 0000000000..355fef35c6 --- /dev/null +++ b/java-dates/src/test/java/com/baeldung/zoneddatetime/ZonedDateTimeUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.zoneddatetime; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.logging.Logger; + +import org.junit.Test; + +public class ZonedDateTimeUnitTest { + + private static final Logger log = Logger.getLogger(ZonedDateTimeUnitTest.class.getName()); + + @Test + public void testZonedDateTimeToString() { + + ZonedDateTime zonedDateTimeNow = ZonedDateTime.now(ZoneId.of("UTC")); + ZonedDateTime zonedDateTimeOf = ZonedDateTime.of(2018, 01, 01, 0, 0, 0, 0, ZoneId.of("UTC")); + + LocalDateTime localDateTime = LocalDateTime.now(); + ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("UTC")); + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy - hh:mm:ss Z"); + String formattedString = zonedDateTime.format(formatter); + + DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/dd/yyyy - hh:mm:ss z"); + String formattedString2 = zonedDateTime.format(formatter2); + + log.info(formattedString); + log.info(formattedString2); + + } + + @Test + public void testZonedDateTimeFromString() { + + ZonedDateTime zonedDateTime = ZonedDateTime.parse("2011-12-03T10:15:30+01:00", DateTimeFormatter.ISO_ZONED_DATE_TIME); + + log.info(zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME)); + } + +} From f916c468cdc15e9c9e08aff4700fc5406a2a2133 Mon Sep 17 00:00:00 2001 From: Josephine Barboza Date: Wed, 10 Oct 2018 16:51:44 +0530 Subject: [PATCH 34/75] BAEL-2169 Guide to Ebean --- libraries-data/pom.xml | 5 ----- libraries-data/src/main/resources/logback.xml | 12 +++--------- 2 files changed, 3 insertions(+), 14 deletions(-) diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index e1318fd597..4b9701fe68 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -416,10 +416,6 @@ - - - - io.ebean ebean-maven-plugin @@ -439,7 +435,6 @@ - diff --git a/libraries-data/src/main/resources/logback.xml b/libraries-data/src/main/resources/logback.xml index 21f797ed71..9cce5fb855 100644 --- a/libraries-data/src/main/resources/logback.xml +++ b/libraries-data/src/main/resources/logback.xml @@ -7,15 +7,9 @@ - - - - - - - - - + + + From e83b7670548f576c54fc27328b47e53175a4b645 Mon Sep 17 00:00:00 2001 From: Josephine Barboza Date: Wed, 10 Oct 2018 19:12:51 +0530 Subject: [PATCH 35/75] Updated formatting --- libraries-data/pom.xml | 119 ++++++++---------- libraries-data/src/main/resources/logback.xml | 25 ++-- 2 files changed, 65 insertions(+), 79 deletions(-) diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 4b9701fe68..6584ca6b23 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -1,6 +1,5 @@ - 4.0.0 libraries-data @@ -14,7 +13,6 @@ - com.esotericsoftware kryo @@ -101,49 +99,36 @@ org.datanucleus javax.jdo ${javax.jdo.version} - org.datanucleus datanucleus-core ${datanucleus.version} - org.datanucleus datanucleus-api-jdo ${datanucleus.version} - - org.datanucleus datanucleus-rdbms ${datanucleus.version} - org.datanucleus datanucleus-maven-plugin ${datanucleus-maven-plugin.version} - - - log4j - log4j - - org.datanucleus datanucleus-xml ${datanucleus-xml.version} - org.datanucleus datanucleus-jdo-query ${datanucleus-jdo-query.version} - @@ -156,13 +141,13 @@ hazelcast ${hazelcast.version} - + com.googlecode.jmapper-framework jmapper-core ${jmapper.version} - + org.apache.crunch crunch-core @@ -173,12 +158,6 @@ hadoop-client ${org.apache.hadoop.hadoop-client} provided - - - log4j - log4j - - @@ -314,28 +293,16 @@ - - - + + + - - + + - + @@ -390,7 +357,27 @@ - + + org.datanucleus + datanucleus-maven-plugin + ${datanucleus-maven-plugin.version} + + JDO + ${basedir}/datanucleus.properties + ${basedir}/log4j.properties + true + false + + + + + process-classes + + enhance + + + + org.apache.maven.plugins @@ -416,25 +403,25 @@ - - io.ebean - ebean-maven-plugin - 11.11.2 - - - - main - process-classes - - debug=1 - - - enhance - - - - - + + io.ebean + ebean-maven-plugin + 11.11.2 + + + + main + process-classes + + debug=1 + + + enhance + + + + + @@ -473,7 +460,7 @@ 2.2.0 11.22.4 1.7.25 - 1.0.1 + 1.0.1 - + \ No newline at end of file diff --git a/libraries-data/src/main/resources/logback.xml b/libraries-data/src/main/resources/logback.xml index 9cce5fb855..a57d22fcb2 100644 --- a/libraries-data/src/main/resources/logback.xml +++ b/libraries-data/src/main/resources/logback.xml @@ -1,16 +1,15 @@ - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + \ No newline at end of file From 506a973c823f2d7dd0d871c27e1dd457810761b0 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Wed, 10 Oct 2018 19:43:24 +0530 Subject: [PATCH 36/75] BAEL-9148 Fix Java EE Annotations Project - Added new jee-7-security module that contains only security related code previously part of jee-7 module - Added new jee-7-security in parent pom.xml --- jee-7-security/README.md | 2 + jee-7-security/pom.xml | 102 ++++++++++++++++++ .../SecurityWebApplicationInitializer.java | 10 ++ .../springsecurity/SpringSecurityConfig.java | 46 ++++++++ .../controller/HomeController.java | 28 +++++ .../controller/LoginController.java | 16 +++ jee-7-security/src/main/resources/logback.xml | 13 +++ .../src/main/webapp/WEB-INF/beans.xml | 0 .../src/main/webapp/WEB-INF/faces-config.xml | 8 ++ .../main/webapp/WEB-INF/spring/security.xml | 23 ++++ .../src/main/webapp/WEB-INF/views/admin.jsp | 12 +++ .../src/main/webapp/WEB-INF/views/home.jsp | 26 +++++ .../src/main/webapp/WEB-INF/views/login.jsp | 26 +++++ .../src/main/webapp/WEB-INF/views/user.jsp | 12 +++ .../src/main/webapp/WEB-INF/web.xml | 71 ++++++++++++ jee-7-security/src/main/webapp/index.jsp | 11 ++ jee-7-security/src/main/webapp/secure.jsp | 24 +++++ pom.xml | 2 + 18 files changed, 432 insertions(+) create mode 100644 jee-7-security/README.md create mode 100644 jee-7-security/pom.xml create mode 100644 jee-7-security/src/main/java/com/baeldung/springsecurity/SecurityWebApplicationInitializer.java create mode 100644 jee-7-security/src/main/java/com/baeldung/springsecurity/SpringSecurityConfig.java create mode 100644 jee-7-security/src/main/java/com/baeldung/springsecurity/controller/HomeController.java create mode 100644 jee-7-security/src/main/java/com/baeldung/springsecurity/controller/LoginController.java create mode 100644 jee-7-security/src/main/resources/logback.xml create mode 100644 jee-7-security/src/main/webapp/WEB-INF/beans.xml create mode 100644 jee-7-security/src/main/webapp/WEB-INF/faces-config.xml create mode 100644 jee-7-security/src/main/webapp/WEB-INF/spring/security.xml create mode 100644 jee-7-security/src/main/webapp/WEB-INF/views/admin.jsp create mode 100644 jee-7-security/src/main/webapp/WEB-INF/views/home.jsp create mode 100644 jee-7-security/src/main/webapp/WEB-INF/views/login.jsp create mode 100644 jee-7-security/src/main/webapp/WEB-INF/views/user.jsp create mode 100644 jee-7-security/src/main/webapp/WEB-INF/web.xml create mode 100644 jee-7-security/src/main/webapp/index.jsp create mode 100644 jee-7-security/src/main/webapp/secure.jsp diff --git a/jee-7-security/README.md b/jee-7-security/README.md new file mode 100644 index 0000000000..314de6d957 --- /dev/null +++ b/jee-7-security/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Securing Java EE with Spring Security](http://www.baeldung.com/java-ee-spring-security) diff --git a/jee-7-security/pom.xml b/jee-7-security/pom.xml new file mode 100644 index 0000000000..622ca19903 --- /dev/null +++ b/jee-7-security/pom.xml @@ -0,0 +1,102 @@ + + + 4.0.0 + jee-7-security + 1.0-SNAPSHOT + war + jee-7-security + JavaEE 7 Spring Security Application + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + javax + javaee-api + ${javaee_api.version} + provided + + + com.sun.faces + jsf-api + ${com.sun.faces.jsf.version} + + + com.sun.faces + jsf-impl + ${com.sun.faces.jsf.version} + + + javax.servlet + jstl + ${jstl.version} + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + + + javax.servlet.jsp + jsp-api + ${jsp-api.version} + provided + + + taglibs + standard + ${taglibs.standard.version} + + + + javax.mvc + javax.mvc-api + 1.0-pr + + + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + + + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + + + org.springframework.security + spring-security-taglibs + ${org.springframework.security.version} + + + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + src/main/webapp + false + + + + + + + 7.0 + 2.2.14 + 2.2 + 1.1.2 + 4.2.3.RELEASE + + + diff --git a/jee-7-security/src/main/java/com/baeldung/springsecurity/SecurityWebApplicationInitializer.java b/jee-7-security/src/main/java/com/baeldung/springsecurity/SecurityWebApplicationInitializer.java new file mode 100644 index 0000000000..e3e2ed80e6 --- /dev/null +++ b/jee-7-security/src/main/java/com/baeldung/springsecurity/SecurityWebApplicationInitializer.java @@ -0,0 +1,10 @@ +package com.baeldung.springsecurity; + +import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; + +public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { + + public SecurityWebApplicationInitializer() { + super(SpringSecurityConfig.class); + } +} diff --git a/jee-7-security/src/main/java/com/baeldung/springsecurity/SpringSecurityConfig.java b/jee-7-security/src/main/java/com/baeldung/springsecurity/SpringSecurityConfig.java new file mode 100644 index 0000000000..70be1f91ce --- /dev/null +++ b/jee-7-security/src/main/java/com/baeldung/springsecurity/SpringSecurityConfig.java @@ -0,0 +1,46 @@ +package com.baeldung.springsecurity; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth + .inMemoryAuthentication() + .withUser("user1") + .password("user1Pass") + .roles("USER") + .and() + .withUser("admin") + .password("adminPass") + .roles("ADMIN"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .csrf() + .disable() + .authorizeRequests() + .antMatchers("/auth/login*") + .anonymous() + .antMatchers("/home/admin*") + .hasRole("ADMIN") + .anyRequest() + .authenticated() + .and() + .formLogin() + .loginPage("/auth/login") + .defaultSuccessUrl("/home", true) + .failureUrl("/auth/login?error=true") + .and() + .logout() + .logoutSuccessUrl("/auth/login"); + } +} \ No newline at end of file diff --git a/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/HomeController.java b/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/HomeController.java new file mode 100644 index 0000000000..1662f38609 --- /dev/null +++ b/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/HomeController.java @@ -0,0 +1,28 @@ +package com.baeldung.springsecurity.controller; + +import javax.mvc.annotation.Controller; +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +@Path("/home") +@Controller +public class HomeController { + + @GET + public String home() { + return "home.jsp"; + } + + @GET + @Path("/user") + public String admin() { + return "user.jsp"; + } + + @GET + @Path("/admin") + public String user() { + return "admin.jsp"; + } + +} diff --git a/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/LoginController.java b/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/LoginController.java new file mode 100644 index 0000000000..a34abbfd2c --- /dev/null +++ b/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/LoginController.java @@ -0,0 +1,16 @@ +package com.baeldung.springsecurity.controller; + +import javax.mvc.annotation.Controller; +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +@Path("/login") +@Controller +public class LoginController { + + @GET + public String login() { + System.out.println("Login"); + return "login.jsp"; + } +} diff --git a/jee-7-security/src/main/resources/logback.xml b/jee-7-security/src/main/resources/logback.xml new file mode 100644 index 0000000000..c8c077ba1d --- /dev/null +++ b/jee-7-security/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jee-7-security/src/main/webapp/WEB-INF/beans.xml b/jee-7-security/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..e69de29bb2 diff --git a/jee-7-security/src/main/webapp/WEB-INF/faces-config.xml b/jee-7-security/src/main/webapp/WEB-INF/faces-config.xml new file mode 100644 index 0000000000..1f4085458f --- /dev/null +++ b/jee-7-security/src/main/webapp/WEB-INF/faces-config.xml @@ -0,0 +1,8 @@ + + + \ No newline at end of file diff --git a/jee-7-security/src/main/webapp/WEB-INF/spring/security.xml b/jee-7-security/src/main/webapp/WEB-INF/spring/security.xml new file mode 100644 index 0000000000..777cd9461f --- /dev/null +++ b/jee-7-security/src/main/webapp/WEB-INF/spring/security.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jee-7-security/src/main/webapp/WEB-INF/views/admin.jsp b/jee-7-security/src/main/webapp/WEB-INF/views/admin.jsp new file mode 100644 index 0000000000..b83ea09f5b --- /dev/null +++ b/jee-7-security/src/main/webapp/WEB-INF/views/admin.jsp @@ -0,0 +1,12 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> + + + + +

Welcome to the ADMIN page

+ + ">Logout + + + \ No newline at end of file diff --git a/jee-7-security/src/main/webapp/WEB-INF/views/home.jsp b/jee-7-security/src/main/webapp/WEB-INF/views/home.jsp new file mode 100644 index 0000000000..c6e129c9ce --- /dev/null +++ b/jee-7-security/src/main/webapp/WEB-INF/views/home.jsp @@ -0,0 +1,26 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> + + + + +

This is the body of the sample view

+ + + This text is only visible to a user +

+ ">Restricted Admin Page +

+
+ + + This text is only visible to an admin +
+ ">Admin Page +
+
+ + ">Logout + + + \ No newline at end of file diff --git a/jee-7-security/src/main/webapp/WEB-INF/views/login.jsp b/jee-7-security/src/main/webapp/WEB-INF/views/login.jsp new file mode 100644 index 0000000000..d6f2e56f3a --- /dev/null +++ b/jee-7-security/src/main/webapp/WEB-INF/views/login.jsp @@ -0,0 +1,26 @@ + + + + +

Login

+ +
+ + + + + + + + + + + + + +
User:
Password:
+ +
+ + + \ No newline at end of file diff --git a/jee-7-security/src/main/webapp/WEB-INF/views/user.jsp b/jee-7-security/src/main/webapp/WEB-INF/views/user.jsp new file mode 100644 index 0000000000..11b8155da7 --- /dev/null +++ b/jee-7-security/src/main/webapp/WEB-INF/views/user.jsp @@ -0,0 +1,12 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> + + + + +

Welcome to the Restricted Admin page

+ + ">Logout + + + \ No newline at end of file diff --git a/jee-7-security/src/main/webapp/WEB-INF/web.xml b/jee-7-security/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..e656ffc5be --- /dev/null +++ b/jee-7-security/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,71 @@ + + + + + Faces Servlet + javax.faces.webapp.FacesServlet + + + Faces Servlet + *.jsf + + + javax.faces.PROJECT_STAGE + Development + + + State saving method: 'client' or 'server' (default). See JSF Specification section 2.5.2 + javax.faces.STATE_SAVING_METHOD + client + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + index.jsf + welcome.jsf + index.html + index.jsp + + \ No newline at end of file diff --git a/jee-7-security/src/main/webapp/index.jsp b/jee-7-security/src/main/webapp/index.jsp new file mode 100644 index 0000000000..93fef9713d --- /dev/null +++ b/jee-7-security/src/main/webapp/index.jsp @@ -0,0 +1,11 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Index Page + + + Non-secured Index Page +
+ Login + + \ No newline at end of file diff --git a/jee-7-security/src/main/webapp/secure.jsp b/jee-7-security/src/main/webapp/secure.jsp new file mode 100644 index 0000000000..0cadd2cd4f --- /dev/null +++ b/jee-7-security/src/main/webapp/secure.jsp @@ -0,0 +1,24 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> +<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec" %> + + + + + Home Page + + +

Home Page

+ +

+ Hello
+ Roles: +

+ +
+ + +
+ + \ No newline at end of file diff --git a/pom.xml b/pom.xml index ef34881cef..741391e09c 100644 --- a/pom.xml +++ b/pom.xml @@ -399,6 +399,7 @@ javafx jgroups jee-7 + jee-7-security jhipster jjwt jsf @@ -1303,6 +1304,7 @@ javafx jgroups jee-7 + jee-7-security jjwt jsf json-path From 6f619dec41a1ec14cc786c460fd4ab0ab58c01ae Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Wed, 10 Oct 2018 20:20:55 +0530 Subject: [PATCH 37/75] Update LoginController.java --- .../baeldung/springsecurity/controller/LoginController.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/LoginController.java b/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/LoginController.java index a34abbfd2c..45d7ff3d2c 100644 --- a/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/LoginController.java +++ b/jee-7-security/src/main/java/com/baeldung/springsecurity/controller/LoginController.java @@ -4,13 +4,12 @@ import javax.mvc.annotation.Controller; import javax.ws.rs.GET; import javax.ws.rs.Path; -@Path("/login") +@Path("/auth/login") @Controller public class LoginController { @GET public String login() { - System.out.println("Login"); return "login.jsp"; } } From af818fddbf2793ae9dcfe8e324ded960e90b4786 Mon Sep 17 00:00:00 2001 From: Josephine Barboza Date: Wed, 10 Oct 2018 21:27:08 +0530 Subject: [PATCH 38/75] Upadated pom.xml --- libraries-data/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 6584ca6b23..bbf0c7832f 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -457,10 +457,10 @@ 5.0.4 1.6.0.1 0.15.0 - 2.2.0 + 2.2.0 11.22.4 1.7.25 - 1.0.1 + 1.0.1 - \ No newline at end of file + From 50ffa8118657386e61de03a7642033514db83cac Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 10 Oct 2018 20:04:51 +0300 Subject: [PATCH 39/75] add reactor core --- spring-data-mongodb/pom.xml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/spring-data-mongodb/pom.xml b/spring-data-mongodb/pom.xml index ad70d987bb..072ed7a2ac 100644 --- a/spring-data-mongodb/pom.xml +++ b/spring-data-mongodb/pom.xml @@ -34,6 +34,12 @@ ${mongodb-reactivestreams.version} + + io.projectreactor + reactor-core + ${projectreactor.version} + + io.projectreactor reactor-test @@ -109,6 +115,7 @@ 5.1.0.RELEASE 1.9.2 3.2.0.RELEASE + From 5ab63bb07b4fbbdd04932097f35d506590ec07aa Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 10 Oct 2018 20:16:49 +0300 Subject: [PATCH 40/75] fix javax el --- javaxval/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javaxval/pom.xml b/javaxval/pom.xml index 86a7e6955b..0263fb68af 100644 --- a/javaxval/pom.xml +++ b/javaxval/pom.xml @@ -33,7 +33,7 @@ ${javax.el-api.version} - org.glassfish.web + org.glassfish javax.el ${javax.el.version} From 12b1a90a746a341834d831770ad905942ac1e9b8 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Wed, 10 Oct 2018 20:24:43 +0300 Subject: [PATCH 41/75] rebalancing the first and second default profiles --- pom.xml | 53 +++++++++++++++++++++++++++-------------------------- 1 file changed, 27 insertions(+), 26 deletions(-) diff --git a/pom.xml b/pom.xml index 008d0aeac3..e6618da0a2 100644 --- a/pom.xml +++ b/pom.xml @@ -526,31 +526,6 @@ spring-resttemplate - spring-security-acl - spring-security-cache-control - spring-security-client/spring-security-jsp-authentication - spring-security-client/spring-security-jsp-authorize - spring-security-client/spring-security-jsp-config - spring-security-client/spring-security-mvc - spring-security-client/spring-security-thymeleaf-authentication - spring-security-client/spring-security-thymeleaf-authorize - spring-security-client/spring-security-thymeleaf-config - spring-security-core - spring-security-mvc-boot - spring-security-mvc-custom - spring-security-mvc-digest-auth - spring-security-mvc-ldap - spring-security-mvc-login - spring-security-mvc-persisted-remember-me - spring-security-mvc-session - spring-security-mvc-socket - spring-security-openid - - spring-security-rest-basic-auth - spring-security-rest-custom - spring-security-rest - spring-security-sso - spring-security-x509 @@ -719,7 +694,33 @@ - flyway-cdi-extension + flyway-cdi-extension + + spring-security-acl + spring-security-cache-control + spring-security-client/spring-security-jsp-authentication + spring-security-client/spring-security-jsp-authorize + spring-security-client/spring-security-jsp-config + spring-security-client/spring-security-mvc + spring-security-client/spring-security-thymeleaf-authentication + spring-security-client/spring-security-thymeleaf-authorize + spring-security-client/spring-security-thymeleaf-config + spring-security-core + spring-security-mvc-boot + spring-security-mvc-custom + spring-security-mvc-digest-auth + spring-security-mvc-ldap + spring-security-mvc-login + spring-security-mvc-persisted-remember-me + spring-security-mvc-session + spring-security-mvc-socket + spring-security-openid + + spring-security-rest-basic-auth + spring-security-rest-custom + spring-security-rest + spring-security-sso + spring-security-x509 From ee1e3eea89dacdba289f9e054746f4314cda9201 Mon Sep 17 00:00:00 2001 From: DOHA Date: Wed, 10 Oct 2018 20:39:45 +0300 Subject: [PATCH 42/75] cucumber parallel features --- testing-modules/rest-testing/pom.xml | 40 ++++++++++++++++++ .../rest/cucumber/StepDefinition.java | 41 ++++++++++--------- .../test/resources/Feature/cucumber.feature | 10 +++++ 3 files changed, 72 insertions(+), 19 deletions(-) create mode 100644 testing-modules/rest-testing/src/test/resources/Feature/cucumber.feature diff --git a/testing-modules/rest-testing/pom.xml b/testing-modules/rest-testing/pom.xml index 0e54980683..9bfd715682 100644 --- a/testing-modules/rest-testing/pom.xml +++ b/testing-modules/rest-testing/pom.xml @@ -106,6 +106,46 @@ true + + + + maven-failsafe-plugin + ${maven-failsafe-plugin.version} + + classes + 4 + + + + + integration-test + verify + + + + + + com.github.temyers + cucumber-jvm-parallel-plugin + 5.0.0 + + + generateRunners + generate-test-sources + + generateRunners + + + + com.baeldung.rest.cucumber + + src/test/resources/Feature/ + SCENARIO + + + + + diff --git a/testing-modules/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java index b461da8403..35a913ae25 100644 --- a/testing-modules/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java +++ b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java @@ -1,19 +1,5 @@ package com.baeldung.rest.cucumber; -import com.github.tomakehurst.wiremock.WireMockServer; -import cucumber.api.java.en.Then; -import cucumber.api.java.en.When; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Scanner; - import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; import static com.github.tomakehurst.wiremock.client.WireMock.containing; @@ -25,10 +11,27 @@ import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; +import java.io.IOException; +import java.io.InputStream; +import java.util.Scanner; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; + +import com.github.tomakehurst.wiremock.WireMockServer; + +import cucumber.api.java.en.Then; +import cucumber.api.java.en.When; + public class StepDefinition { private static final String CREATE_PATH = "/create"; @@ -37,20 +40,20 @@ public class StepDefinition { private final InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("cucumber.json"); private final String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); - private final WireMockServer wireMockServer = new WireMockServer(); + private final WireMockServer wireMockServer = new WireMockServer(options().dynamicPort()); private final CloseableHttpClient httpClient = HttpClients.createDefault(); @When("^users upload data on a project$") public void usersUploadDataOnAProject() throws IOException { wireMockServer.start(); - configureFor("localhost", 8080); + configureFor("localhost", wireMockServer.port()); stubFor(post(urlEqualTo(CREATE_PATH)) .withHeader("content-type", equalTo(APPLICATION_JSON)) .withRequestBody(containing("testing-framework")) .willReturn(aResponse().withStatus(200))); - HttpPost request = new HttpPost("http://localhost:8080/create"); + HttpPost request = new HttpPost("http://localhost:" + wireMockServer.port() + "/create"); StringEntity entity = new StringEntity(jsonString); request.addHeader("content-type", APPLICATION_JSON); request.setEntity(entity); @@ -67,11 +70,11 @@ public class StepDefinition { public void usersGetInformationOnAProject(String projectName) throws IOException { wireMockServer.start(); - configureFor("localhost", 8080); + configureFor("localhost", wireMockServer.port()); stubFor(get(urlEqualTo("/projects/cucumber")).withHeader("accept", equalTo(APPLICATION_JSON)) .willReturn(aResponse().withBody(jsonString))); - HttpGet request = new HttpGet("http://localhost:8080/projects/" + projectName.toLowerCase()); + HttpGet request = new HttpGet("http://localhost:" + wireMockServer.port() + "/projects/" + projectName.toLowerCase()); request.addHeader("accept", APPLICATION_JSON); HttpResponse httpResponse = httpClient.execute(request); String responseString = convertResponseToString(httpResponse); diff --git a/testing-modules/rest-testing/src/test/resources/Feature/cucumber.feature b/testing-modules/rest-testing/src/test/resources/Feature/cucumber.feature new file mode 100644 index 0000000000..99dd8249fe --- /dev/null +++ b/testing-modules/rest-testing/src/test/resources/Feature/cucumber.feature @@ -0,0 +1,10 @@ +Feature: Testing a REST API + Users should be able to submit GET and POST requests to a web service, represented by WireMock + + Scenario: Data Upload to a web service + When users upload data on a project + Then the server should handle it and return a success status + + Scenario: Data retrieval from a web service + When users want to get information on the Cucumber project + Then the requested data is returned \ No newline at end of file From 26c9bdcc0d3bc2d6271b4c6ba3d0c90f8234bd96 Mon Sep 17 00:00:00 2001 From: eric-martin Date: Wed, 10 Oct 2018 20:23:32 -0500 Subject: [PATCH 43/75] BAEL-2257: Renamed OutputStreamExamplesTest to *UnitTest --- ...tStreamExamplesTest.java => OutputStreamExamplesUnitTest.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename core-java-io/src/test/java/com/baeldung/stream/{OutputStreamExamplesTest.java => OutputStreamExamplesUnitTest.java} (100%) diff --git a/core-java-io/src/test/java/com/baeldung/stream/OutputStreamExamplesTest.java b/core-java-io/src/test/java/com/baeldung/stream/OutputStreamExamplesUnitTest.java similarity index 100% rename from core-java-io/src/test/java/com/baeldung/stream/OutputStreamExamplesTest.java rename to core-java-io/src/test/java/com/baeldung/stream/OutputStreamExamplesUnitTest.java From e908b96eef76af840997567615047664d788aad7 Mon Sep 17 00:00:00 2001 From: eric-martin Date: Wed, 10 Oct 2018 22:09:45 -0500 Subject: [PATCH 44/75] BAEL-2257: Renamed OutputStreamExamplesTest to *UnitTest --- .../java/com/baeldung/stream/OutputStreamExamplesUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-io/src/test/java/com/baeldung/stream/OutputStreamExamplesUnitTest.java b/core-java-io/src/test/java/com/baeldung/stream/OutputStreamExamplesUnitTest.java index 4ae1ce9aa7..aa949259a0 100644 --- a/core-java-io/src/test/java/com/baeldung/stream/OutputStreamExamplesUnitTest.java +++ b/core-java-io/src/test/java/com/baeldung/stream/OutputStreamExamplesUnitTest.java @@ -8,7 +8,7 @@ import java.io.IOException; import org.junit.Before; import org.junit.Test; -public class OutputStreamExamplesTest { +public class OutputStreamExamplesUnitTest { StringBuilder filePath = new StringBuilder(); From ef61b86af31c3d5c5186905fff2ec2046c483348 Mon Sep 17 00:00:00 2001 From: Satyam Date: Thu, 11 Oct 2018 20:55:55 +0530 Subject: [PATCH 45/75] BAEL-2197:Code rework --- .../src/findItems/FindItemsBasedOnValues.java | 111 +++++++----------- 1 file changed, 45 insertions(+), 66 deletions(-) diff --git a/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java b/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java index d6a320a8ec..a0dcdddd85 100644 --- a/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java +++ b/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java @@ -1,114 +1,93 @@ package findItems; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; + import java.text.ParseException; -import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; -import java.util.Date; import java.util.List; import java.util.stream.Collectors; + import org.junit.Test; public class FindItemsBasedOnValues { - static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy"); + List EmplList = new ArrayList(); + List deptList = new ArrayList(); public static void main(String[] args) throws ParseException { FindItemsBasedOnValues findItems = new FindItemsBasedOnValues(); - findItems.givenListOfCompanies_thenListOfClientsIsFilteredCorrectly(); + findItems.givenDepartmentList_thenEmployeeListIsFilteredCorrectly(); } @Test - public void givenListOfCompanies_thenListOfClientsIsFilteredCorrectly() throws ParseException { - List expectedList = new ArrayList(); - Client expectedClient = new Client(1001, DATE_FORMAT.parse("01-02-2018")); - expectedList.add(expectedClient); + public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() { + Integer expectedId = 1002; - List listOfCompanies = new ArrayList(); - List listOfClients = new ArrayList(); - populate(listOfCompanies, listOfClients); + populate(EmplList, deptList); - List filteredList = listOfClients.stream() - .filter(client -> listOfCompanies.stream() - .anyMatch(company -> company.getType() - .equals("eMart") && company.getProjectId() - .equals(client.getProjectId()) && company.getStart() - .after(client.getDate()) && company.getEnd() - .before(client.getDate()))) + List filteredList = EmplList.stream() + .filter(empl -> deptList.stream() + .anyMatch(dept -> dept.getDepartment() + .equals("sales") && empl.getEmployeeId() + .equals(dept.getEmployeeId()))) .collect(Collectors.toList()); - assertEquals(expectedClient.getProjectId(), filteredList.get(0) - .getProjectId()); - assertEquals(expectedClient.getDate(), filteredList.get(0) - .getDate()); + assertEquals(expectedId, filteredList.get(0) + .getEmployeeId()); } - private void populate(List companyList, List clientList) throws ParseException { - Company company1 = new Company(1001, DATE_FORMAT.parse("01-03-2018"), DATE_FORMAT.parse("01-01-2018"), "eMart"); - Company company2 = new Company(1002, DATE_FORMAT.parse("01-02-2018"), DATE_FORMAT.parse("01-04-2018"), "commerce"); - Company company3 = new Company(1003, DATE_FORMAT.parse("01-06-2018"), DATE_FORMAT.parse("01-02-2018"), "eMart"); - Company company4 = new Company(1004, DATE_FORMAT.parse("01-03-2018"), DATE_FORMAT.parse("01-06-2018"), "blog"); + private void populate(List EmplList, List deptList) { + Employee employee1 = new Employee(1001, "empl1"); + Employee employee2 = new Employee(1002, "empl2"); + Employee employee3 = new Employee(1003, "empl3"); - Collections.addAll(companyList, company1, company2, company3, company4); + Collections.addAll(EmplList, employee1, employee2, employee3); - Client client1 = new Client(1001, DATE_FORMAT.parse("01-02-2018")); - Client client2 = new Client(1003, DATE_FORMAT.parse("01-04-2018")); - Client client3 = new Client(1005, DATE_FORMAT.parse("01-07-2018")); - Client client4 = new Client(1007, DATE_FORMAT.parse("01-08-2018")); + Department department1 = new Department(1002, "sales"); + Department department2 = new Department(1003, "marketing"); + Department department3 = new Department(1004, "sales"); - Collections.addAll(clientList, client1, client2, client3, client4); + Collections.addAll(deptList, department1, department2, department3); } } -class Company { - Long projectId; - Date start; - Date end; - String type; +class Employee { + Integer employeeId; + String employeeName; - public Company(long projectId, Date start, Date end, String type) { + public Employee(Integer employeeId, String employeeName) { super(); - this.projectId = projectId; - this.start = start; - this.end = end; - this.type = type; + this.employeeId = employeeId; + this.employeeName = employeeName; } - public Long getProjectId() { - return projectId; + public Integer getEmployeeId() { + return employeeId; } - public Date getStart() { - return start; - } - - public Date getEnd() { - return end; - } - - public String getType() { - return type; + public String getEmployeeName() { + return employeeName; } } -class Client { - Long projectId; - Date date; +class Department { + Integer employeeId; + String department; - public Client(long projectId, Date date) { + public Department(Integer employeeId, String department) { super(); - this.projectId = projectId; - this.date = date; + this.employeeId = employeeId; + this.department = department; } - public Long getProjectId() { - return projectId; + public Integer getEmployeeId() { + return employeeId; } - public Date getDate() { - return date; + public String getDepartment() { + return department; } } \ No newline at end of file From a915063c44f0d99966ba2e75ab8fd0e11453222a Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 11 Oct 2018 21:12:07 +0300 Subject: [PATCH 46/75] Update README.md --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index adb17ca7e5..8e0a5eb9ee 100644 --- a/README.md +++ b/README.md @@ -21,3 +21,8 @@ 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` + + +Building a single module +==================== +To build a specific module run the command: `mvn clean install -Dgib.enabled=false` in the module directory From 01819fe1bac8d3bf7dbd016a77a0f42a87ba16f5 Mon Sep 17 00:00:00 2001 From: Johan Janssen Date: Thu, 11 Oct 2018 21:40:30 +0200 Subject: [PATCH 47/75] BAEL-2263 Using JUnit 5 with Gradle --- gradle/junit5/build.gradle | 25 +++++++++++++ .../com/example/CalculatorJUnit4Test.java | 12 +++++++ .../com/example/CalculatorJUnit5Test.java | 36 +++++++++++++++++++ gradle/settings.gradle | 2 +- 4 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 gradle/junit5/build.gradle create mode 100644 gradle/junit5/src/test/java/com/example/CalculatorJUnit4Test.java create mode 100644 gradle/junit5/src/test/java/com/example/CalculatorJUnit5Test.java diff --git a/gradle/junit5/build.gradle b/gradle/junit5/build.gradle new file mode 100644 index 0000000000..5f056d8c23 --- /dev/null +++ b/gradle/junit5/build.gradle @@ -0,0 +1,25 @@ +plugins { + // Apply the java-library plugin to add support for Java Library + id 'java-library' +} + +dependencies { + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.1' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.1' + + // Only necessary for JUnit 3 and 4 tests + testCompileOnly 'junit:junit:4.12' + testRuntimeOnly 'org.junit.vintage:junit-vintage-engine:5.3.1' + +} + +repositories { + jcenter() +} + +test { + useJUnitPlatform { + includeTags 'fast' + excludeTags 'slow' + } +} \ No newline at end of file diff --git a/gradle/junit5/src/test/java/com/example/CalculatorJUnit4Test.java b/gradle/junit5/src/test/java/com/example/CalculatorJUnit4Test.java new file mode 100644 index 0000000000..4cf63642ee --- /dev/null +++ b/gradle/junit5/src/test/java/com/example/CalculatorJUnit4Test.java @@ -0,0 +1,12 @@ +package com.example; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class CalculatorJUnit4Test { + @Test + public void testAdd() { + assertEquals(42, Integer.sum(19, 23)); + } +} diff --git a/gradle/junit5/src/test/java/com/example/CalculatorJUnit5Test.java b/gradle/junit5/src/test/java/com/example/CalculatorJUnit5Test.java new file mode 100644 index 0000000000..59fdb0f8ae --- /dev/null +++ b/gradle/junit5/src/test/java/com/example/CalculatorJUnit5Test.java @@ -0,0 +1,36 @@ +package com.example; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test;; + +public class CalculatorJUnit5Test { + + @Tag("fast") + @Test + public void testAdd() { + assertEquals(42, Integer.sum(19, 23)); + } + + @Tag("slow") + @Test + public void testAddMaxInteger() { + assertEquals(2147483646, Integer.sum(2147183646, 300000)); + } + + @Tag("fast") + @Test + public void testAddZero() { + assertEquals(21, Integer.sum(21, 0)); + } + + @Tag("fast") + @Test + public void testDivide() { + assertThrows(ArithmeticException.class, () -> { + Integer.divideUnsigned(42, 0); + }); + } +} diff --git a/gradle/settings.gradle b/gradle/settings.gradle index 38704681bd..f1d64de58a 100644 --- a/gradle/settings.gradle +++ b/gradle/settings.gradle @@ -5,6 +5,6 @@ include 'greeting-library' include 'greeting-library-java' include 'greeter' include 'gradletaskdemo' - +include 'junit5' println 'This will be executed during the initialization phase.' From f824da90ba31a87f1331a3f4c36ae0f4fffc846e Mon Sep 17 00:00:00 2001 From: Priyesh Mashelkar Date: Fri, 12 Oct 2018 05:59:44 +0100 Subject: [PATCH 48/75] Converting DOM Document to File Issue: BAEL-2167 --- .../com/baeldung/xml/XMLDocumentWriter.java | 41 +++++++++++++++ .../xml/XMLDocumentWriterUnitTest.java | 52 +++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 xml/src/main/java/com/baeldung/xml/XMLDocumentWriter.java create mode 100644 xml/src/test/java/com/baeldung/xml/XMLDocumentWriterUnitTest.java diff --git a/xml/src/main/java/com/baeldung/xml/XMLDocumentWriter.java b/xml/src/main/java/com/baeldung/xml/XMLDocumentWriter.java new file mode 100644 index 0000000000..e33fc5fe1d --- /dev/null +++ b/xml/src/main/java/com/baeldung/xml/XMLDocumentWriter.java @@ -0,0 +1,41 @@ +package com.baeldung.xml; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Document; + +public class XMLDocumentWriter { + + public void write(Document document, String fileName, boolean excludeDeclaration, boolean prettyPrint) { + try(FileWriter writer = new FileWriter(new File(fileName))) { + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + if(excludeDeclaration) { + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + } + if(prettyPrint) { + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); + } + DOMSource source = new DOMSource(document); + StreamResult result = new StreamResult(writer); + transformer.transform(source, result); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } catch (TransformerConfigurationException e) { + throw new IllegalStateException(e); + } catch (TransformerException e) { + throw new IllegalArgumentException(e); + } + } +} diff --git a/xml/src/test/java/com/baeldung/xml/XMLDocumentWriterUnitTest.java b/xml/src/test/java/com/baeldung/xml/XMLDocumentWriterUnitTest.java new file mode 100644 index 0000000000..68f787a054 --- /dev/null +++ b/xml/src/test/java/com/baeldung/xml/XMLDocumentWriterUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.xml; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.commons.io.FileUtils; +import org.junit.After; +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import java.io.File; + +public class XMLDocumentWriterUnitTest { + + @Test + public void givenXMLDocumentWhenWriteIsCalledThenXMLIsWrittenToFile() throws Exception { + Document document = createSampleDocument(); + new XMLDocumentWriter().write(document, "company_simple.xml", false, false); + } + + @Test + public void givenXMLDocumentWhenWriteIsCalledWithPrettyPrintThenFormattedXMLIsWrittenToFile() throws Exception { + Document document = createSampleDocument(); + new XMLDocumentWriter().write(document, "company_prettyprinted.xml", false, true); + } + + private Document createSampleDocument() throws ParserConfigurationException { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document document = documentBuilder.newDocument(); + Element companyElement = document.createElement("Company"); + document.appendChild(companyElement); + Element departmentElement = document.createElement("Department"); + departmentElement.setAttribute("name", "Sales"); + companyElement.appendChild(departmentElement); + Element employee1 = document.createElement("Employee"); + employee1.setAttribute("name", "John Smith"); + departmentElement.appendChild(employee1); + Element employee2 = document.createElement("Employee"); + employee2.setAttribute("name", "Tim Dellor"); + departmentElement.appendChild(employee2); + return document; + } + + @After + public void cleanUp() throws Exception { + FileUtils.deleteQuietly(new File("company_simple.xml")); + FileUtils.deleteQuietly(new File("company_prettyprinted.xml")); + } +} From 44a3d36bd981f581bc97c85036fe25288744510b Mon Sep 17 00:00:00 2001 From: Andrey Shcherbakov Date: Fri, 12 Oct 2018 07:16:54 +0200 Subject: [PATCH 49/75] Implement a binary tree (#5431) * Add code for the article 'Java Primitives versus Objects' * Use JMH for benchmarking the primitive and wrapper classes * Uncomment the benchmarks and remove unused class * Add a binary search tree implementation * Add an example of how to use the binary tree class * Adjust the print statements --- .../com/baeldung/datastructures/Main.kt | 19 ++ .../com/baeldung/datastructures/Node.kt | 167 +++++++++ .../com/baeldung/datastructures/NodeTest.kt | 319 ++++++++++++++++++ 3 files changed, 505 insertions(+) create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/datastructures/Node.kt create mode 100644 core-kotlin/src/test/kotlin/com/baeldung/datastructures/NodeTest.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt b/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt new file mode 100644 index 0000000000..4fd8aa27c7 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Main.kt @@ -0,0 +1,19 @@ +package com.baeldung.datastructures + +/** + * Example of how to use the {@link Node} class. + * + */ +fun main(args: Array) { + val tree = Node(4) + val keys = arrayOf(8, 15, 21, 3, 7, 2, 5, 10, 2, 3, 4, 6, 11) + for (key in keys) { + tree.insert(key) + } + val node = tree.find(4)!! + println("Node with value ${node.key} [left = ${node.left?.key}, right = ${node.right?.key}]") + println("Delete node with key = 3") + node.delete(3) + print("Tree content after the node elimination: ") + println(tree.visit().joinToString { it.toString() }) +} diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Node.kt b/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Node.kt new file mode 100644 index 0000000000..b81afe1e4c --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/datastructures/Node.kt @@ -0,0 +1,167 @@ +package com.baeldung.datastructures + +/** + * An ADT for a binary search tree. + * Note that this data type is neither immutable nor thread safe. + */ +class Node( + var key: Int, + var left: Node? = null, + var right: Node? = null) { + + /** + * Return a node with given value. If no such node exists, return null. + * @param value + */ + fun find(value: Int): Node? = when { + this.key > value -> left?.find(value) + this.key < value -> right?.find(value) + else -> this + + } + + /** + * Insert a given value into the tree. + * After insertion, the tree should contain a node with the given value. + * If the tree already contains the given value, nothing is performed. + * @param value + */ + fun insert(value: Int) { + if (value > this.key) { + if (this.right == null) { + this.right = Node(value) + } else { + this.right?.insert(value) + } + } else if (value < this.key) { + if (this.left == null) { + this.left = Node(value) + } else { + this.left?.insert(value) + } + } + } + + /** + * Delete the value from the given tree. If the tree does not contain the value, the tree remains unchanged. + * @param value + */ + fun delete(value: Int) { + when { + value > key -> scan(value, this.right, this) + value < key -> scan(value, this.left, this) + else -> removeNode(this, null) + } + } + + /** + * Scan the tree in the search of the given value. + * @param value + * @param node sub-tree that potentially might contain the sought value + * @param parent node's parent + */ + private fun scan(value: Int, node: Node?, parent: Node?) { + if (node == null) { + System.out.println("value " + value + + " seems not present in the tree.") + return + } + when { + value > node.key -> scan(value, node.right, node) + value < node.key -> scan(value, node.left, node) + value == node.key -> removeNode(node, parent) + } + + } + + /** + * Remove the node. + * + * Removal process depends on how many children the node has. + * + * @param node node that is to be removed + * @param parent parent of the node to be removed + */ + private fun removeNode(node: Node, parent: Node?) { + node.left?.let { leftChild -> + run { + node.right?.let { + removeTwoChildNode(node) + } ?: removeSingleChildNode(node, leftChild) + } + } ?: run { + node.right?.let { rightChild -> removeSingleChildNode(node, rightChild) } ?: removeNoChildNode(node, parent) + } + + + } + + /** + * Remove the node without children. + * @param node + * @param parent + */ + private fun removeNoChildNode(node: Node, parent: Node?) { + parent?.let { p -> + if (node == p.left) { + p.left = null + } else if (node == p.right) { + p.right = null + } + } ?: throw IllegalStateException( + "Can not remove the root node without child nodes") + + } + + /** + * Remove a node that has two children. + * + * The process of elimination is to find the biggest key in the left sub-tree and replace the key of the + * node that is to be deleted with that key. + */ + private fun removeTwoChildNode(node: Node) { + val leftChild = node.left!! + leftChild.right?.let { + val maxParent = findParentOfMaxChild(leftChild) + maxParent.right?.let { + node.key = it.key + maxParent.right = null + } ?: throw IllegalStateException("Node with max child must have the right child!") + + } ?: run { + node.key = leftChild.key + node.left = leftChild.left + } + + } + + /** + * Return a node whose right child contains the biggest value in the given sub-tree. + * Assume that the node n has a non-null right child. + * + * @param n + */ + private fun findParentOfMaxChild(n: Node): Node { + return n.right?.let { r -> r.right?.let { findParentOfMaxChild(r) } ?: n } + ?: throw IllegalArgumentException("Right child must be non-null") + + } + + /** + * Remove a parent that has only one child. + * Removal is effectively is just coping the data from the child parent to the parent parent. + * @param parent Node to be deleted. Assume that it has just one child + * @param child Assume it is a child of the parent + */ + private fun removeSingleChildNode(parent: Node, child: Node) { + parent.key = child.key + parent.left = child.left + parent.right = child.right + } + + fun visit(): Array { + val a = left?.visit() ?: emptyArray() + val b = right?.visit() ?: emptyArray() + return a + arrayOf(key) + b + } +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/datastructures/NodeTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/datastructures/NodeTest.kt new file mode 100644 index 0000000000..8a46c5f6ec --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/datastructures/NodeTest.kt @@ -0,0 +1,319 @@ +package com.baeldung.datastructures + +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test + +class NodeTest { + + @Before + fun setUp() { + } + + @After + fun tearDown() { + } + + /** + * Test suit for finding the node by value + * Partition the tests as follows: + * 1. tree depth: 0, 1, > 1 + * 2. pivot depth location: not present, 0, 1, 2, > 2 + */ + + /** + * Find the node by value + * 1. tree depth: 0 + * 2. pivot depth location: not present + */ + @Test + fun givenDepthZero_whenPivotNotPresent_thenNull() { + val n = Node(1) + assertNull(n.find(2)) + } + + /** + * Find the node by value + * 1. tree depth: 0 + * 2. pivot depth location: 0 + */ + @Test + fun givenDepthZero_whenPivotDepthZero_thenReturnNodeItself() { + val n = Node(1) + assertEquals(n, n.find(1)) + } + + /** + * Find the node by value + * 1. tree depth: 1 + * 2. pivot depth location: not present + */ + @Test + fun givenDepthOne_whenPivotNotPresent_thenNull() { + val n = Node(1, Node(0)) + assertNull(n.find(2)) + } + + /** + * Find the node by value + * 1. tree depth: 1 + * 2. pivot depth location: not present + */ + @Test + fun givenDepthOne_whenPivotAtDepthOne_thenSuccess() { + val n = Node(1, Node(0)) + assertEquals(n.left, n.find(0) + ) + } + + @Test + fun givenDepthTwo_whenPivotAtDepth2_then_Success() { + val left = Node(1, Node(0), Node(2)) + val right = Node(5, Node(4), Node(6)) + val n = Node(3, left, right) + assertEquals(left.left, n.find(0)) + } + + + /** + * Test suit for inserting a value + * Partition the test as follows: + * 1. tree depth: 0, 1, 2, > 2 + * 2. depth to insert: 0, 1, > 1 + * 3. is duplicate: no, yes + * 4. sub-tree: left, right + */ + /** + * Test for inserting a value + * 1. tree depth: 0 + * 2. depth to insert: 1 + * 3. is duplicate: no + * 4. sub-tree: right + */ + @Test + fun givenTreeDepthZero_whenInsertNoDuplicateToRight_thenAddNode() { + val n = Node(1) + n.insert(2) + assertEquals(1, n.key) + with(n.right!!) { + assertEquals(2, key) + assertNull(left) + assertNull(right) + } + assertNull(n.left) + } + + /** + * Test for inserting a value + * 1. tree depth: 0 + * 2. depth to insert: 1 + * 3. is duplicate: no + * 4. sub-tree: right + */ + @Test + fun givenTreeDepthZero_whenInsertNoDuplicateToLeft_thenSuccess() { + val n = Node(1) + n.insert(0) + assertEquals(1, n.key) + with(n.left!!) { + assertEquals(0, key) + assertNull(left) + assertNull(right) + } + assertNull(n.right) + } + + /** + * Test for inserting a value + * 1. tree depth: 0 + * 2. depth to insert: 1 + * 3. is duplicate: yes + */ + @Test + fun givenTreeDepthZero_whenInsertDuplicate_thenSuccess() { + val n = Node(1) + n.insert(1) + assertEquals(1, n.key) + assertNull(n.right) + assertNull(n.left) + } + + + /** + * Test suit for inserting a value + * Partition the test as follows: + * 1. tree depth: 0, 1, 2, > 2 + * 2. depth to insert: 0, 1, > 1 + * 3. is duplicate: no, yes + * 4. sub-tree: left, right + */ + /** + * Test for inserting a value + * 1. tree depth: 1 + * 2. depth to insert: 1 + * 3. is duplicate: no + * 4. sub-tree: right + */ + @Test + fun givenTreeDepthOne_whenInsertNoDuplicateToRight_thenSuccess() { + val n = Node(10, Node(3)) + n.insert(15) + assertEquals(10, n.key) + with(n.right!!) { + assertEquals(15, key) + assertNull(left) + assertNull(right) + } + with(n.left!!) { + assertEquals(3, key) + assertNull(left) + assertNull(right) + } + } + + /** + * Test for inserting a value + * 1. tree depth: 1 + * 2. depth to insert: 1 + * 3. is duplicate: no + * 4. sub-tree: left + */ + @Test + fun givenTreeDepthOne_whenInsertNoDuplicateToLeft_thenAddNode() { + val n = Node(10, null, Node(15)) + n.insert(3) + assertEquals(10, n.key) + with(n.right!!) { + assertEquals(15, key) + assertNull(left) + assertNull(right) + } + with(n.left!!) { + assertEquals(3, key) + assertNull(left) + assertNull(right) + } + } + + /** + * Test for inserting a value + * 1. tree depth: 1 + * 2. depth to insert: 1 + * 3. is duplicate: yes + */ + @Test + fun givenTreeDepthOne_whenInsertDuplicate_thenNoChange() { + val n = Node(10, null, Node(15)) + n.insert(15) + assertEquals(10, n.key) + with(n.right!!) { + assertEquals(15, key) + assertNull(left) + assertNull(right) + } + assertNull(n.left) + } + + /** + * Test suit for removal + * Partition the input as follows: + * 1. tree depth: 0, 1, 2, > 2 + * 2. value to delete: absent, present + * 3. # child nodes: 0, 1, 2 + */ + /** + * Test for removal value + * 1. tree depth: 0 + * 2. value to delete: absent + */ + @Test + fun givenTreeDepthZero_whenValueAbsent_thenNoChange() { + val n = Node(1) + n.delete(0) + assertEquals(1, n.key) + assertNull(n.left) + assertNull(n.right) + } + + /** + * Test for removal + * 1. tree depth: 1 + * 2. value to delete: absent + */ + @Test + fun givenTreeDepthOne_whenValueAbsent_thenNoChange() { + val n = Node(1, Node(0), Node(2)) + n.delete(3) + assertEquals(1, n.key) + assertEquals(2, n.right!!.key) + with(n.left!!) { + assertEquals(0, key) + assertNull(left) + assertNull(right) + } + with(n.right!!) { + assertNull(left) + assertNull(right) + } + } + + /** + * Test suit for removal + * 1. tree depth: 1 + * 2. value to delete: present + * 3. # child nodes: 0 + */ + @Test + fun givenTreeDepthOne_whenNodeToDeleteHasNoChildren_thenChangeTree() { + val n = Node(1, Node(0)) + n.delete(0) + assertEquals(1, n.key) + assertNull(n.left) + assertNull(n.right) + } + + /** + * Test suit for removal + * 1. tree depth: 2 + * 2. value to delete: present + * 3. # child nodes: 1 + */ + @Test + fun givenTreeDepthTwo_whenNodeToDeleteHasOneChild_thenChangeTree() { + val n = Node(2, Node(0, null, Node(1)), Node(3)) + n.delete(0) + assertEquals(2, n.key) + with(n.right!!) { + assertEquals(3, key) + assertNull(left) + assertNull(right) + } + with(n.left!!) { + assertEquals(1, key) + assertNull(left) + assertNull(right) + } + } + + @Test + fun givenTreeDepthThree_whenNodeToDeleteHasTwoChildren_thenChangeTree() { + val l = Node(2, Node(1), Node(5, Node(4), Node(6))) + val r = Node(10, Node(9), Node(11)) + val n = Node(8, l, r) + n.delete(8) + assertEquals(6, n.key) + with(n.left!!) { + assertEquals(2, key) + assertEquals(1, left!!.key) + assertEquals(5, right!!.key) + assertEquals(4, right!!.left!!.key) + } + with(n.right!!) { + assertEquals(10, key) + assertEquals(9, left!!.key) + assertEquals(11, right!!.key) + } + } + +} From 15b7eacd4310b871769afe12a363f231fb924052 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Fri, 12 Oct 2018 10:21:35 +0300 Subject: [PATCH 50/75] cleanup work --- core-java-collections/pom.xml | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml index 694d2da5eb..b4a6e26d13 100644 --- a/core-java-collections/pom.xml +++ b/core-java-collections/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung core-java-collections 0.1.0-SNAPSHOT jar @@ -63,11 +62,17 @@ jmh-generator-annprocess ${openjdk.jmh.version} - - org.apache.commons - commons-exec - 1.3 - + + org.apache.commons + commons-exec + 1.3 + + + + one.util + streamex + 0.6.5 + From bae7a74acd987defc018c79852b88417f8c3a931 Mon Sep 17 00:00:00 2001 From: Kumar Chandrakant Date: Fri, 12 Oct 2018 10:54:04 +0100 Subject: [PATCH 51/75] Adding files for the article BAEL-2206 --- .../interfaces/ConflictingInterfaces.kt | 23 +++++++++++++ .../interfaces/InterfaceDelegation.kt | 13 ++++++++ .../baeldung/interfaces/MultipleInterfaces.kt | 29 +++++++++++++++++ .../baeldung/interfaces/SimpleInterface.kt | 24 ++++++++++++++ .../interfaces/InterfaceExamplesUnitTest.kt | 32 +++++++++++++++++++ 5 files changed, 121 insertions(+) create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt create mode 100644 core-kotlin/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt create mode 100644 core-kotlin/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt diff --git a/core-kotlin/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt b/core-kotlin/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt new file mode 100644 index 0000000000..630afbdae7 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/interfaces/ConflictingInterfaces.kt @@ -0,0 +1,23 @@ +package com.baeldung.interfaces + +interface BaseInterface { + fun someMethod(): String +} + +interface FirstChildInterface : BaseInterface { + override fun someMethod(): String { + return("Hello, from someMethod in FirstChildInterface") + } +} + +interface SecondChildInterface : BaseInterface { + override fun someMethod(): String { + return("Hello, from someMethod in SecondChildInterface") + } +} + +class ChildClass : FirstChildInterface, SecondChildInterface { + override fun someMethod(): String { + return super.someMethod() + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt b/core-kotlin/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt new file mode 100644 index 0000000000..591fde0689 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/interfaces/InterfaceDelegation.kt @@ -0,0 +1,13 @@ +package com.baeldung.interfaces + +interface MyInterface { + fun someMethod(): String +} + +class MyClass() : MyInterface { + override fun someMethod(): String { + return("Hello, World!") + } +} + +class MyDerivedClass(myInterface: MyInterface) : MyInterface by myInterface \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt b/core-kotlin/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt new file mode 100644 index 0000000000..105a85cbb3 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/interfaces/MultipleInterfaces.kt @@ -0,0 +1,29 @@ +package com.baeldung.interfaces + +interface FirstInterface { + fun someMethod(): String + + fun anotherMethod(): String { + return("Hello, from anotherMethod in FirstInterface") + } +} + +interface SecondInterface { + fun someMethod(): String { + return("Hello, from someMethod in SecondInterface") + } + + fun anotherMethod(): String { + return("Hello, from anotherMethod in SecondInterface") + } +} + +class SomeClass: FirstInterface, SecondInterface { + override fun someMethod(): String { + return("Hello, from someMethod in SomeClass") + } + + override fun anotherMethod(): String { + return("Hello, from anotherMethod in SomeClass") + } +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt b/core-kotlin/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt new file mode 100644 index 0000000000..0758549dde --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/interfaces/SimpleInterface.kt @@ -0,0 +1,24 @@ +package com.baeldung.interfaces + +interface SimpleInterface { + val firstProp: String + val secondProp: String + get() = "Second Property" + fun firstMethod(): String + fun secondMethod(): String { + println("Hello, from: " + secondProp) + return "" + } +} + +class SimpleClass: SimpleInterface { + override val firstProp: String = "First Property" + override val secondProp: String + get() = "Second Property, Overridden!" + override fun firstMethod(): String { + return("Hello, from: " + firstProp) + } + override fun secondMethod(): String { + return("Hello, from: " + secondProp + firstProp) + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt new file mode 100644 index 0000000000..96b99948b7 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/interfaces/InterfaceExamplesUnitTest.kt @@ -0,0 +1,32 @@ +package com.baeldung.interfaces + +import org.junit.Test +import kotlin.test.assertEquals + +class InterfaceExamplesUnitTest { + @Test + fun givenAnInterface_whenImplemented_thenBehavesAsOverridden() { + val simpleClass = SimpleClass() + assertEquals("Hello, from: First Property", simpleClass.firstMethod()) + assertEquals("Hello, from: Second Property, Overridden!First Property", simpleClass.secondMethod()) + } + + @Test + fun givenMultipleInterfaces_whenImplemented_thenBehavesAsOverridden() { + val someClass = SomeClass() + assertEquals("Hello, from someMethod in SomeClass", someClass.someMethod()) + assertEquals("Hello, from anotherMethod in SomeClass", someClass.anotherMethod()) + } + + @Test + fun givenConflictingInterfaces_whenImplemented_thenBehavesAsOverridden() { + val childClass = ChildClass() + assertEquals("Hello, from someMethod in SecondChildInterface", childClass.someMethod()) + } + + @Test + fun givenAnInterface_whenImplemented_thenBehavesAsDelegated() { + val myClass = MyClass() + assertEquals("Hello, World!", MyDerivedClass(myClass).someMethod()) + } +} \ No newline at end of file From fe8488a8d5e773e7e657a85c477bbfa7f3af68a0 Mon Sep 17 00:00:00 2001 From: Akash Pandey Date: Sat, 13 Oct 2018 01:20:33 +0530 Subject: [PATCH 52/75] Bael 2189: Convert Byte Array To/From hex String (#5396) * BAEL-2159: Mini Article on "Separate double into integer and decimal parts" * BAEL-2189: Tutorial to convert Byte Array to/from hex String. * BEAL-2189: Code review comments incorporated. * 1. Added validations for Non-Hex String characters in hex String. 2. Moved classes to algorithms module. 3. Renamed unit test class name ends with *UnitTest. * 1. Added validations for Non-Hex String characters in hex String. 2. Moved classes to algorithms module. 3. Renamed unit test class name ends with *UnitTest. * removed: redundant property added for local testing. --- algorithms/pom.xml | 6 + .../conversion/HexStringConverter.java | 110 +++++++++++++++ .../ByteArrayConverterUnitTest.java | 127 ++++++++++++++++++ 3 files changed, 243 insertions(+) create mode 100644 algorithms/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java create mode 100644 algorithms/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java diff --git a/algorithms/pom.xml b/algorithms/pom.xml index eda87d6c75..db4a1c2eff 100644 --- a/algorithms/pom.xml +++ b/algorithms/pom.xml @@ -17,6 +17,11 @@ commons-math3 ${commons-math3.version} + + commons-codec + commons-codec + ${commons-codec.version} + org.projectlombok lombok @@ -85,6 +90,7 @@ 3.7.0 1.0.1 3.9.0 + 1.11 \ No newline at end of file diff --git a/algorithms/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java b/algorithms/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java new file mode 100644 index 0000000000..d3e251d3fd --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java @@ -0,0 +1,110 @@ +package com.baeldung.algorithms.conversion; + +import java.math.BigInteger; + +import javax.xml.bind.DatatypeConverter; + +import org.apache.commons.codec.DecoderException; +import org.apache.commons.codec.binary.Hex; + +import com.google.common.io.BaseEncoding; + +public class HexStringConverter { + + /** + * Create a byte Array from String of hexadecimal digits using Character conversion + * @param hexString - Hexadecimal digits as String + * @return Desired byte Array + */ + public byte[] decodeHexString(String hexString) { + if (hexString.length() % 2 == 1) { + throw new IllegalArgumentException("Invalid hexadecimal String supplied."); + } + byte[] bytes = new byte[hexString.length() / 2]; + + for (int i = 0; i < hexString.length(); i += 2) { + bytes[i / 2] = hexToByte(hexString.substring(i, i + 2)); + } + return bytes; + } + + /** + * Create a String of hexadecimal digits from a byte Array using Character conversion + * @param byteArray - The byte Array + * @return Desired String of hexadecimal digits in lower case + */ + public String encodeHexString(byte[] byteArray) { + StringBuffer hexStringBuffer = new StringBuffer(); + for (int i = 0; i < byteArray.length; i++) { + hexStringBuffer.append(byteToHex(byteArray[i])); + } + return hexStringBuffer.toString(); + } + + public String byteToHex(byte num) { + char[] hexDigits = new char[2]; + hexDigits[0] = Character.forDigit((num >> 4) & 0xF, 16); + hexDigits[1] = Character.forDigit((num & 0xF), 16); + return new String(hexDigits); + } + + public byte hexToByte(String hexString) { + int firstDigit = toDigit(hexString.charAt(0)); + int secondDigit = toDigit(hexString.charAt(1)); + return (byte) ((firstDigit << 4) + secondDigit); + } + + private int toDigit(char hexChar) { + int digit = Character.digit(hexChar, 16); + if(digit == -1) { + throw new IllegalArgumentException("Invalid Hexadecimal Character: "+ hexChar); + } + return digit; + } + + public String encodeUsingBigIntegerToString(byte[] bytes) { + BigInteger bigInteger = new BigInteger(1, bytes); + return bigInteger.toString(16); + } + + public String encodeUsingBigIntegerStringFormat(byte[] bytes) { + BigInteger bigInteger = new BigInteger(1, bytes); + return String.format("%0" + (bytes.length << 1) + "x", bigInteger); + } + + public byte[] decodeUsingBigInteger(String hexString) { + byte[] byteArray = new BigInteger(hexString, 16).toByteArray(); + if (byteArray[0] == 0) { + byte[] output = new byte[byteArray.length - 1]; + System.arraycopy(byteArray, 1, output, 0, output.length); + return output; + } + return byteArray; + } + + public String encodeUsingDataTypeConverter(byte[] bytes) { + return DatatypeConverter.printHexBinary(bytes); + } + + public byte[] decodeUsingDataTypeConverter(String hexString) { + return DatatypeConverter.parseHexBinary(hexString); + } + + public String encodeUsingApacheCommons(byte[] bytes) throws DecoderException { + return Hex.encodeHexString(bytes); + } + + public byte[] decodeUsingApacheCommons(String hexString) throws DecoderException { + return Hex.decodeHex(hexString); + } + + public String encodeUsingGuava(byte[] bytes) { + return BaseEncoding.base16() + .encode(bytes); + } + + public byte[] decodeUsingGuava(String hexString) { + return BaseEncoding.base16() + .decode(hexString.toUpperCase()); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java new file mode 100644 index 0000000000..be61802705 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java @@ -0,0 +1,127 @@ +package com.baeldung.algorithms.conversion; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import org.apache.commons.codec.DecoderException; +import org.hamcrest.text.IsEqualIgnoringCase; +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.algorithms.conversion.HexStringConverter; + +public class ByteArrayConverterUnitTest { + + private HexStringConverter hexStringConverter; + + @Before + public void setup() { + hexStringConverter = new HexStringConverter(); + } + + @Test + public void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + if(hexString.charAt(0) == '0') { + hexString = hexString.substring(1); + } + String output = hexStringConverter.encodeUsingBigIntegerToString(bytes); + assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); + } + + @Test + public void shouldEncodeByteArrayToHexStringUsingBigIntegerStringFormat() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + String output = hexStringConverter.encodeUsingBigIntegerStringFormat(bytes); + assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); + } + + @Test + public void shouldDecodeHexStringToByteArrayUsingBigInteger() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + byte[] output = hexStringConverter.decodeUsingBigInteger(hexString); + assertArrayEquals(bytes, output); + } + + @Test + public void shouldEncodeByteArrayToHexStringUsingCharacterConversion() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + String output = hexStringConverter.encodeHexString(bytes); + assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); + } + + @Test + public void shouldDecodeHexStringToByteArrayUsingCharacterConversion() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + byte[] output = hexStringConverter.decodeHexString(hexString); + assertArrayEquals(bytes, output); + } + + @Test(expected=IllegalArgumentException.class) + public void shouldDecodeHexToByteWithInvalidHexCharacter() { + hexStringConverter.hexToByte("fg"); + } + + @Test + public void shouldEncodeByteArrayToHexStringDataTypeConverter() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + String output = hexStringConverter.encodeUsingDataTypeConverter(bytes); + assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); + } + + @Test + public void shouldDecodeHexStringToByteArrayUsingDataTypeConverter() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + byte[] output = hexStringConverter.decodeUsingDataTypeConverter(hexString); + assertArrayEquals(bytes, output); + } + + @Test + public void shouldEncodeByteArrayToHexStringUsingGuava() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + String output = hexStringConverter.encodeUsingGuava(bytes); + assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); + } + + @Test + public void shouldDecodeHexStringToByteArrayUsingGuava() { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + byte[] output = hexStringConverter.decodeUsingGuava(hexString); + assertArrayEquals(bytes, output); + } + + @Test + public void shouldEncodeByteArrayToHexStringUsingApacheCommons() throws DecoderException { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + String output = hexStringConverter.encodeUsingApacheCommons(bytes); + assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString)); + } + + @Test + public void shouldDecodeHexStringToByteArrayUsingApacheCommons() throws DecoderException { + byte[] bytes = getSampleBytes(); + String hexString = getSampleHexString(); + byte[] output = hexStringConverter.decodeUsingApacheCommons(hexString); + assertArrayEquals(bytes, output); + } + + private String getSampleHexString() { + return "0af50c0e2d10"; + } + + private byte[] getSampleBytes() { + return new byte[] { 10, -11, 12, 14, 45, 16 }; + } + +} From 3c35e25015dd5e7b7943c8e77fab9b8345c37191 Mon Sep 17 00:00:00 2001 From: Rokon Uddin Ahmed Date: Sat, 13 Oct 2018 02:22:56 +0600 Subject: [PATCH 53/75] BAEL-9344 (#5435) * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.MD * Update README.md * Update README.md * Update README.md * Create README.md * Update README.md * Update README.md --- algorithms/README.md | 3 +++ aws/README.md | 2 +- core-java-9/README.md | 1 + core-java-collections/README.md | 3 +++ core-java-concurrency/README.md | 1 + core-java/README.md | 6 ++++++ core-kotlin/README.md | 2 ++ hibernate5/README.md | 1 + java-streams/README.md | 1 + java-strings/README.md | 2 ++ libraries-security/README.md | 3 +++ libraries/README.md | 2 ++ spring-5-mvc/README.md | 1 + spring-boot-bootstrap/README.md | 1 + spring-cloud/README.md | 2 ++ spring-core/README.md | 2 ++ spring-data-jpa/README.md | 1 + spring-security-mvc-boot/README.MD | 1 + testing-modules/spring-testing/README.md | 3 ++- 19 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 libraries-security/README.md diff --git a/algorithms/README.md b/algorithms/README.md index 9b3bbcdee5..9d347869bd 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -28,3 +28,6 @@ - [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points) - [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines) - [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters) +- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred) +- [Merge Sort in Java](https://www.baeldung.com/java-merge-sort) +- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage) diff --git a/aws/README.md b/aws/README.md index d23937a419..2c61928095 100644 --- a/aws/README.md +++ b/aws/README.md @@ -9,4 +9,4 @@ - [Integration Testing with a Local DynamoDB Instance](http://www.baeldung.com/dynamodb-local-integration-tests) - [Using the JetS3t Java Client With Amazon S3](http://www.baeldung.com/jets3t-amazon-s3) - [Managing Amazon SQS Queues in Java](http://www.baeldung.com/aws-queues-java) - +- [Guide to AWS Aurora RDS with Java](https://www.baeldung.com/aws-aurora-rds-java) diff --git a/core-java-9/README.md b/core-java-9/README.md index bf07cfcc86..38816471aa 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -26,3 +26,4 @@ - [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range) - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) - [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api) +- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api) diff --git a/core-java-collections/README.md b/core-java-collections/README.md index d9d768961c..aef640634e 100644 --- a/core-java-collections/README.md +++ b/core-java-collections/README.md @@ -52,3 +52,6 @@ - [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance) - [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value) - [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity) +- [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort) +- [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max) +- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream) diff --git a/core-java-concurrency/README.md b/core-java-concurrency/README.md index d775d24dff..eeb9a83748 100644 --- a/core-java-concurrency/README.md +++ b/core-java-concurrency/README.md @@ -29,3 +29,4 @@ - [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer) - [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle) - [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable) +- [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield) diff --git a/core-java/README.md b/core-java/README.md index a117d1843d..9e38dfc47d 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -150,3 +150,9 @@ - [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception) - [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string) - [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic) +- [Convert Double to String, Removing Decimal Places](https://www.baeldung.com/java-double-to-string) +- [Different Ways to Capture Java Heap Dumps](https://www.baeldung.com/java-heap-dump-capture) +- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts) +- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset) +- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing) +- [Java Switch Statement](https://www.baeldung.com/java-switch) diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 7d8d5213d1..523f5b6e78 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -37,3 +37,5 @@ - [Kotlin with Ktor](https://www.baeldung.com/kotlin-ktor) - [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel) - [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant) +- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class) +- [Concatenate Strings in Kotlin](https://www.baeldung.com/kotlin-concatenate-strings) diff --git a/hibernate5/README.md b/hibernate5/README.md index b90f885c78..fbf46eed50 100644 --- a/hibernate5/README.md +++ b/hibernate5/README.md @@ -16,3 +16,4 @@ - [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle) - [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class) - [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column) +- [Hibernate 5 Naming Strategy Configuration](https://www.baeldung.com/hibernate-naming-strategy) diff --git a/java-streams/README.md b/java-streams/README.md index 548d4b6a33..2550f08650 100644 --- a/java-streams/README.md +++ b/java-streams/README.md @@ -13,3 +13,4 @@ - [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices) - [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams) - [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering) +- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack) diff --git a/java-strings/README.md b/java-strings/README.md index b12fc75f30..ff833a5cda 100644 --- a/java-strings/README.md +++ b/java-strings/README.md @@ -31,3 +31,5 @@ - [Converting a Stack Trace to a String in Java](https://www.baeldung.com/java-stacktrace-to-string) - [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically) - [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis) +- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty) +- [String Performance Hints](https://www.baeldung.com/java-string-performance) diff --git a/libraries-security/README.md b/libraries-security/README.md new file mode 100644 index 0000000000..c42e91a888 --- /dev/null +++ b/libraries-security/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Guide to ScribeJava](https://www.baeldung.com/scribejava) diff --git a/libraries/README.md b/libraries/README.md index c2c4b2718a..fcf687d806 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -81,6 +81,8 @@ - [Guide to Resilience4j](http://www.baeldung.com/resilience4j) - [Parsing YAML with SnakeYAML](http://www.baeldung.com/java-snake-yaml) - [Guide to JMapper](http://www.baeldung.com/jmapper) +- [An Introduction to Apache Commons Lang 3](https://www.baeldung.com/java-commons-lang-3) +- [Exactly Once Processing in Kafka](https://www.baeldung.com/kafka-exactly-once) The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/spring-5-mvc/README.md b/spring-5-mvc/README.md index 7e83077f54..fa9d48ab72 100644 --- a/spring-5-mvc/README.md +++ b/spring-5-mvc/README.md @@ -2,3 +2,4 @@ - [Spring Boot and Kotlin](http://www.baeldung.com/spring-boot-kotlin) - [Spring MVC Streaming and SSE Request Processing](https://www.baeldung.com/spring-mvc-sse-streams) - [Overview and Need for DelegatingFilterProxy in Spring](https://www.baeldung.com/spring-delegating-filter-proxy) +- [A Controller, Service and DAO Example with Spring Boot and JSF](https://www.baeldung.com/jsf-spring-boot-controller-service-dao) diff --git a/spring-boot-bootstrap/README.md b/spring-boot-bootstrap/README.md index 4b09f11714..08fdb1bdc9 100644 --- a/spring-boot-bootstrap/README.md +++ b/spring-boot-bootstrap/README.md @@ -3,3 +3,4 @@ - [Spring Boot Dependency Management with a Custom Parent](http://www.baeldung.com/spring-boot-dependency-management-custom-parent) - [Thin JARs with Spring Boot](http://www.baeldung.com/spring-boot-thin-jar) - [Deploying a Spring Boot Application to Cloud Foundry](https://www.baeldung.com/spring-boot-app-deploy-to-cloud-foundry) +- [Deploy a Spring Boot Application to Google App Engine](https://www.baeldung.com/spring-boot-google-app-engine) diff --git a/spring-cloud/README.md b/spring-cloud/README.md index 805052e4db..16bc2d110a 100644 --- a/spring-cloud/README.md +++ b/spring-cloud/README.md @@ -28,3 +28,5 @@ - [An Intro to Spring Cloud Task](http://www.baeldung.com/spring-cloud-task) - [Running Spring Boot Applications With Minikube](http://www.baeldung.com/spring-boot-minikube) - [Introduction to Netflix Archaius with Spring Cloud](https://www.baeldung.com/netflix-archaius-spring-cloud-integration) +- [An Intro to Spring Cloud Vault](https://www.baeldung.com/spring-cloud-vault) +- [Netflix Archaius with Various Database Configurations](https://www.baeldung.com/netflix-archaius-database-configurations) diff --git a/spring-core/README.md b/spring-core/README.md index c0577b4ebc..e5c359c11b 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -20,3 +20,5 @@ - [Controlling Bean Creation Order with @DependsOn Annotation](http://www.baeldung.com/spring-depends-on) - [Spring Autowiring of Generic Types](https://www.baeldung.com/spring-autowire-generics) - [Spring Application Context Events](https://www.baeldung.com/spring-context-events) +- [Unsatisfied Dependency in Spring](https://www.baeldung.com/spring-unsatisfied-dependency) +- [What is a Spring Bean?](https://www.baeldung.com/spring-bean) diff --git a/spring-data-jpa/README.md b/spring-data-jpa/README.md index 8817020eec..44ce240da3 100644 --- a/spring-data-jpa/README.md +++ b/spring-data-jpa/README.md @@ -14,6 +14,7 @@ - [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa) - [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) - [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) +- [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/spring-security-mvc-boot/README.MD b/spring-security-mvc-boot/README.MD index 6bd9b9295c..6f01bfdc65 100644 --- a/spring-security-mvc-boot/README.MD +++ b/spring-security-mvc-boot/README.MD @@ -11,3 +11,4 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com - [Granted Authority Versus Role in Spring Security](http://www.baeldung.com/spring-security-granted-authority-vs-role) - [Spring Data with Spring Security](https://www.baeldung.com/spring-data-security) - [Spring Security – Whitelist IP Range](https://www.baeldung.com/spring-security-whitelist-ip-range) +- [Find the Registered Spring Security Filters](https://www.baeldung.com/spring-security-registered-filters) diff --git a/testing-modules/spring-testing/README.md b/testing-modules/spring-testing/README.md index aed330d260..e22c3e84e7 100644 --- a/testing-modules/spring-testing/README.md +++ b/testing-modules/spring-testing/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: -* [Mockito.mock() vs @Mock vs @MockBean](http://www.baeldung.com/java-spring-mockito-mock-mockbean) +- [Mockito.mock() vs @Mock vs @MockBean](http://www.baeldung.com/java-spring-mockito-mock-mockbean) +- [A Quick Guide to @TestPropertySource](https://www.baeldung.com/spring-test-property-source) From ac8742cfff0f11b7e2b7f9fcae0f8a3bacaf71a3 Mon Sep 17 00:00:00 2001 From: DOHA Date: Sat, 13 Oct 2018 01:47:27 +0300 Subject: [PATCH 54/75] fix MockitoJUnitRunner deprecated import --- .../calculator/NthRootCalculatorUnitTest.java | 6 +++--- .../app/rest/FlowerControllerUnitTest.java | 13 ++++++------ .../app/rest/MessageControllerUnitTest.java | 21 ++++++++++--------- .../creditcard/CreditCardEditorUnitTest.java | 5 +---- .../mockito/MockitoSpyIntegrationTest.java | 12 +++++------ .../mockito/MockitoVoidMethodsUnitTest.java | 18 +++++++++++----- 6 files changed, 41 insertions(+), 34 deletions(-) diff --git a/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java b/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java index 388bceef49..286dffb56a 100644 --- a/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java @@ -1,11 +1,11 @@ package com.baeldung.nth.root.calculator; +import static org.junit.Assert.assertEquals; + import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.junit.Assert.assertEquals; +import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class NthRootCalculatorUnitTest { diff --git a/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java b/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java index f30af140af..aeec57d136 100644 --- a/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java +++ b/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java @@ -1,17 +1,18 @@ package com.baeldung.app.rest; -import com.baeldung.app.api.Flower; -import com.baeldung.domain.service.FlowerService; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.when; +import com.baeldung.app.api.Flower; +import com.baeldung.domain.service.FlowerService; @RunWith(MockitoJUnitRunner.class) public class FlowerControllerUnitTest { diff --git a/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java b/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java index e303c85caf..15e91d86b5 100644 --- a/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java +++ b/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java @@ -1,18 +1,19 @@ package com.baeldung.app.rest; +import static org.mockito.Mockito.times; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + import com.baeldung.app.api.MessageApi; import com.baeldung.domain.model.Message; import com.baeldung.domain.service.MessageService; import com.baeldung.domain.util.MessageMatcher; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.mockito.Mockito.times; @RunWith(MockitoJUnitRunner.class) public class MessageControllerUnitTest { @@ -37,6 +38,6 @@ public class MessageControllerUnitTest { message.setTo("you"); message.setText("Hello, you!"); - Mockito.verify(messageService, times(1)).deliverMessage(Matchers.argThat(new MessageMatcher(message))); + Mockito.verify(messageService, times(1)).deliverMessage(ArgumentMatchers.argThat(new MessageMatcher(message))); } } diff --git a/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java b/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java index a84f866dfe..814efc112a 100644 --- a/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java +++ b/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java @@ -4,10 +4,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; - -import com.baeldung.propertyeditor.creditcard.CreditCard; -import com.baeldung.propertyeditor.creditcard.CreditCardEditor; +import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class CreditCardEditorUnitTest { diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoSpyIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoSpyIntegrationTest.java index 206e0f4daf..118d50ea40 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoSpyIntegrationTest.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoSpyIntegrationTest.java @@ -1,15 +1,15 @@ package org.baeldung.mockito; +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.Spy; -import org.mockito.runners.MockitoJUnitRunner; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; +import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class MockitoSpyIntegrationTest { diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsUnitTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsUnitTest.java index 49360f8d6c..b020338fd9 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsUnitTest.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsUnitTest.java @@ -1,14 +1,22 @@ package org.baeldung.mockito; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doCallRealMethod; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + import org.junit.Test; import org.junit.runner.RunWith; -import static org.junit.Assert.assertEquals; - -import static org.mockito.Mockito.*; import org.mockito.ArgumentCaptor; -import static org.mockito.Matchers.any; +import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; -import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class MockitoVoidMethodsUnitTest { From 435af770b3a7538cb7debee70628aa64520546b9 Mon Sep 17 00:00:00 2001 From: Marcos Lopez Gonzalez Date: Sat, 13 Oct 2018 13:04:22 +0200 Subject: [PATCH 55/75] BAEL-2259 - Guide to EnumSet (#5423) * EnumSet * enumset operations * formatting --- .../java/com/baeldung/enumset/EnumSets.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 core-java-collections/src/main/java/com/baeldung/enumset/EnumSets.java diff --git a/core-java-collections/src/main/java/com/baeldung/enumset/EnumSets.java b/core-java-collections/src/main/java/com/baeldung/enumset/EnumSets.java new file mode 100644 index 0000000000..7b93ed8737 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/enumset/EnumSets.java @@ -0,0 +1,45 @@ +package com.baeldung.enumset; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; + +public class EnumSets { + + public enum Color { + RED, YELLOW, GREEN, BLUE, BLACK, WHITE + } + + public static void main(String[] args) { + EnumSet allColors = EnumSet.allOf(Color.class); + System.out.println(allColors); + + EnumSet noColors = EnumSet.noneOf(Color.class); + System.out.println(noColors); + + EnumSet blackAndWhite = EnumSet.of(Color.BLACK, Color.WHITE); + System.out.println(blackAndWhite); + + EnumSet noBlackOrWhite = EnumSet.complementOf(blackAndWhite); + System.out.println(noBlackOrWhite); + + EnumSet range = EnumSet.range(Color.YELLOW, Color.BLUE); + System.out.println(range); + + EnumSet blackAndWhiteCopy = EnumSet.copyOf(EnumSet.of(Color.BLACK, Color.WHITE)); + System.out.println(blackAndWhiteCopy); + + List colorsList = new ArrayList<>(); + colorsList.add(Color.RED); + EnumSet listCopy = EnumSet.copyOf(colorsList); + System.out.println(listCopy); + + EnumSet set = EnumSet.noneOf(Color.class); + set.add(Color.RED); + set.add(Color.YELLOW); + set.contains(Color.RED); + set.forEach(System.out::println); + set.remove(Color.RED); + } + +} From 03e0627cffc0e8b674f0050951eebddeb5c2664f Mon Sep 17 00:00:00 2001 From: Kuba Date: Sat, 13 Oct 2018 17:02:22 +0200 Subject: [PATCH 56/75] BAEL-2200 Sample application for auto-configuration report. (#5335) * BAEL-2200 Sample application for auto-configuration report. * BAEL-2200 Sample application for auto-configuration report fixes. * Fix formatting. --- .../auto/configuration/AutoConfigurationDemo.java | 14 ++++++++++++++ .../src/main/resources/application.properties | 3 ++- 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java new file mode 100644 index 0000000000..87a191554b --- /dev/null +++ b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java @@ -0,0 +1,14 @@ +package com.baeldung.h2db.auto.configuration; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication(scanBasePackages = "com.baeldung.h2db.auto-configuration") +public class AutoConfigurationDemo { + + public static void main(String[] args) { + SpringApplication.run(AutoConfigurationDemo.class, args); + } + +} diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties b/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties index 0591cc9e0f..5e425a3550 100644 --- a/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties +++ b/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties @@ -4,4 +4,5 @@ spring.datasource.username=sa spring.datasource.password= spring.jpa.hibernate.ddl-auto=create spring.h2.console.enabled=true -spring.h2.console.path=/h2-console \ No newline at end of file +spring.h2.console.path=/h2-console +debug=true \ No newline at end of file From b3a6a60100be49fea9925d1c17e8c02b5ff49119 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sat, 13 Oct 2018 19:15:02 +0300 Subject: [PATCH 57/75] add txt files for zip --- core-java-io/src/main/resources/zipTest/test1.txt | 1 + core-java-io/src/main/resources/zipTest/test2.txt | 1 + 2 files changed, 2 insertions(+) create mode 100644 core-java-io/src/main/resources/zipTest/test1.txt create mode 100644 core-java-io/src/main/resources/zipTest/test2.txt diff --git a/core-java-io/src/main/resources/zipTest/test1.txt b/core-java-io/src/main/resources/zipTest/test1.txt new file mode 100644 index 0000000000..e88ded96ab --- /dev/null +++ b/core-java-io/src/main/resources/zipTest/test1.txt @@ -0,0 +1 @@ +Test1 \ No newline at end of file diff --git a/core-java-io/src/main/resources/zipTest/test2.txt b/core-java-io/src/main/resources/zipTest/test2.txt new file mode 100644 index 0000000000..da8f209890 --- /dev/null +++ b/core-java-io/src/main/resources/zipTest/test2.txt @@ -0,0 +1 @@ +Test2 \ No newline at end of file From ca4b6200a74a860fc0c4cc26a47c15215584d70c Mon Sep 17 00:00:00 2001 From: Jonathan Cook Date: Sat, 13 Oct 2018 20:19:14 +0200 Subject: [PATCH 58/75] BAEL-2268 - Guide to JerseyTest (#5443) * BAEL-2268 - Guide to JerseyTest - second attempt without formatting changes * BAEL-2268 - Guide to JerseyTest - Add line break to end of file --- .../baeldung/jersey/server/model/Fruit.java | 5 +++ .../jersey/server/rest/FruitResource.java | 12 +++++++ .../GreetingsResourceIntegrationTest.java | 33 +++++++++++++++++++ .../rest/FruitResourceIntegrationTest.java | 27 +++++++++++++++ 4 files changed, 77 insertions(+) create mode 100644 jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java b/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java index c55362487b..1a648290a3 100644 --- a/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java +++ b/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java @@ -54,4 +54,9 @@ public class Fruit { public void setSerial(String serial) { this.serial = serial; } + + @Override + public String toString() { + return "Fruit [name: " + getName() + " colour: " + getColour() + "]"; + } } diff --git a/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java b/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java index ee34cdd3ca..88692dcc55 100644 --- a/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java +++ b/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java @@ -16,6 +16,8 @@ import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; import org.glassfish.jersey.server.mvc.ErrorTemplate; import org.glassfish.jersey.server.mvc.Template; @@ -86,6 +88,16 @@ public class FruitResource { public void createFruit(@Valid Fruit fruit) { SimpleStorageService.storeFruit(fruit); } + + @POST + @Path("/created") + @Consumes(MediaType.APPLICATION_JSON) + public Response createNewFruit(@Valid Fruit fruit) { + String result = "Fruit saved : " + fruit; + return Response.status(Status.CREATED.getStatusCode()) + .entity(result) + .build(); + } @GET @Valid diff --git a/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java b/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java new file mode 100644 index 0000000000..8953f4161c --- /dev/null +++ b/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java @@ -0,0 +1,33 @@ +package com.baeldung.jersey.server; + +import static org.junit.Assert.assertEquals; + +import javax.ws.rs.core.Application; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.Test; + +public class GreetingsResourceIntegrationTest extends JerseyTest { + + @Override + protected Application configure() { + return new ResourceConfig(Greetings.class); + } + + @Test + public void givenGetHiGreeting_whenCorrectRequest_thenResponseIsOkAndContainsHi() { + Response response = target("/greetings/hi").request() + .get(); + + assertEquals("Http Response should be 200: ", Status.OK.getStatusCode(), response.getStatus()); + assertEquals("Http Content-Type should be: ", MediaType.TEXT_HTML, response.getHeaderString(HttpHeaders.CONTENT_TYPE)); + + String content = response.readEntity(String.class); + assertEquals("Content of ressponse is: ", "hi", content); + } +} 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 2eeb5710cb..376c8c1e75 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 @@ -10,6 +10,7 @@ import javax.ws.rs.core.Application; import javax.ws.rs.core.Form; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; import org.glassfish.jersey.test.JerseyTest; import org.glassfish.jersey.test.TestProperties; @@ -63,6 +64,15 @@ public class FruitResourceIntegrationTest extends JerseyTest { assertEquals("Http Response should be 400 ", 400, response.getStatus()); assertThat(response.readEntity(String.class), containsString("Fruit colour must not be null")); } + + @Test + public void givenCreateFruit_whenJsonIsCorrect_thenResponseCodeIsCreated() { + Response response = target("fruit/created").request() + .post(Entity.json("{\"name\":\"strawberry\",\"weight\":20}")); + + assertEquals("Http Response should be 201 ", Status.CREATED.getStatusCode(), response.getStatus()); + assertThat(response.readEntity(String.class), containsString("Fruit saved : Fruit [name: strawberry colour: null]")); + } @Test public void givenUpdateFruit_whenFormContainsBadSerialParam_thenResponseCodeIsBadRequest() { @@ -102,6 +112,23 @@ public class FruitResourceIntegrationTest extends JerseyTest { .get(String.class); assertThat(json, containsString("{\"name\":\"strawberry\",\"weight\":20}")); } + + @Test + public void givenFruitExists_whenSearching_thenResponseContainsFruitEntity() { + Fruit fruit = new Fruit(); + fruit.setName("strawberry"); + fruit.setWeight(20); + Response response = target("fruit/create").request(MediaType.APPLICATION_JSON_TYPE) + .post(Entity.entity(fruit, MediaType.APPLICATION_JSON_TYPE)); + + assertEquals("Http Response should be 204 ", 204, response.getStatus()); + + final Fruit entity = target("fruit/search/strawberry").request() + .get(Fruit.class); + + assertEquals("Fruit name: ", "strawberry", entity.getName()); + assertEquals("Fruit weight: ", Integer.valueOf(20), entity.getWeight()); + } @Test public void givenFruit_whenFruitIsInvalid_thenReponseContainsCustomExceptions() { From 1820b2c37ff5d2167e34edd3d67754b3189226c2 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sat, 13 Oct 2018 16:29:52 +0530 Subject: [PATCH 59/75] [BAEL-9514] - Added Junit 5 @DisplayName annotation example --- .../customtestname/CustomNameUnitTest.java | 17 +++++++ .../ParameterizedUnitTest.java | 48 +++++++++++++++++++ .../suite/SelectClassesSuiteUnitTest.java | 13 +++++ .../suite/SelectPackagesSuiteUnitTest.java | 11 +++++ .../suite/childpackage1/Class1UnitTest.java | 15 ++++++ .../suite/childpackage2/Class2UnitTest.java | 14 ++++++ 6 files changed, 118 insertions(+) create mode 100644 core-java/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java create mode 100644 core-java/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java create mode 100644 core-java/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java create mode 100644 core-java/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java create mode 100644 core-java/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java create mode 100644 core-java/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java diff --git a/core-java/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java b/core-java/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java new file mode 100644 index 0000000000..f04b825c89 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java @@ -0,0 +1,17 @@ +package org.baeldung.java.customtestname; + +import static org.junit.Assert.assertNotNull; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +public class CustomNameUnitTest { + + @ParameterizedTest + @ValueSource(strings = { "Hello", "World" }) + @DisplayName("Test Method to check that the inputs are not nullable") + void givenString_TestNullOrNot(String word) { + assertNotNull(word); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java b/core-java/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java new file mode 100644 index 0000000000..af9ad870b9 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java @@ -0,0 +1,48 @@ +package org.baeldung.java.parameterisedsource; + +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.EnumSet; +import java.util.stream.Stream; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +import com.baeldung.enums.PizzaDeliveryStrategy; + +public class ParameterizedUnitTest { + + @ParameterizedTest + @ValueSource(strings = { "Hello", "World" }) + void givenString_TestNullOrNot(String word) { + assertNotNull(word); + } + + @ParameterizedTest + @EnumSource(value = PizzaDeliveryStrategy.class, names = {"EXPRESS", "NORMAL"}) + void givenEnum_TestContainsOrNot(PizzaDeliveryStrategy timeUnit) { + assertTrue(EnumSet.of(PizzaDeliveryStrategy.EXPRESS, PizzaDeliveryStrategy.NORMAL).contains(timeUnit)); + } + + @ParameterizedTest + @MethodSource("wordDataProvider") + void givenMethodSource_TestInputStream(String argument) { + assertNotNull(argument); + } + + static Stream wordDataProvider() { + return Stream.of("foo", "bar"); + } + + @ParameterizedTest + @CsvSource({ "1, Car", "2, House", "3, Train" }) + void givenCSVSource_TestContent(int id, String word) { + assertNotNull(id); + assertNotNull(word); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java b/core-java/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java new file mode 100644 index 0000000000..220897eae7 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java @@ -0,0 +1,13 @@ +package org.baeldung.java.suite; + +import org.baeldung.java.suite.childpackage1.Class1UnitTest; +import org.baeldung.java.suite.childpackage2.Class2UnitTest; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.SelectClasses; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@SelectClasses({Class1UnitTest.class, Class2UnitTest.class}) +public class SelectClassesSuiteUnitTest { + +} diff --git a/core-java/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java b/core-java/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java new file mode 100644 index 0000000000..ae887ae43b --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java @@ -0,0 +1,11 @@ +package org.baeldung.java.suite; + +import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@SelectPackages({ "org.baeldung.java.suite.childpackage1", "org.baeldung.java.suite.childpackage2" }) +public class SelectPackagesSuiteUnitTest { + +} diff --git a/core-java/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java b/core-java/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java new file mode 100644 index 0000000000..78469cb971 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java @@ -0,0 +1,15 @@ +package org.baeldung.java.suite.childpackage1; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.Test; + + +public class Class1UnitTest { + + @Test + public void testCase_InClass1UnitTest() { + assertTrue(true); + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java b/core-java/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java new file mode 100644 index 0000000000..4463ecfad9 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java @@ -0,0 +1,14 @@ +package org.baeldung.java.suite.childpackage2; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.Test; + +public class Class2UnitTest { + + @Test + public void testCase_InClass2UnitTest() { + assertTrue(true); + } + +} From c9f2162f984a2f36f91406c1d2b9fa431b53fad3 Mon Sep 17 00:00:00 2001 From: Shreyash Date: Sun, 14 Oct 2018 11:34:09 +0530 Subject: [PATCH 60/75] Spring Data Reactive Redis examples Issue: BAEL-1868 --- .../log4j2/${sys:logging.folder.path} | 0 persistence-modules/spring-data-redis/pom.xml | 87 +++++++++++-------- .../redis/SpringRedisReactiveApplication.java | 13 +++ .../reactive/redis/config/RedisConfig.java | 56 ++++++++++++ .../data/reactive/redis/model/Employee.java | 21 +++++ .../spring/data/redis/config/RedisConfig.java | 8 +- .../RedisKeyCommandsIntegrationTest.java | 51 +++++++++++ .../RedisTemplateListOpsIntegrationTest.java | 49 +++++++++++ .../RedisTemplateValueOpsIntegrationTest.java | 71 +++++++++++++++ .../RedisMessageListenerIntegrationTest.java | 2 +- .../StudentRepositoryIntegrationTest.java | 2 +- pom.xml | 1 + 12 files changed, 318 insertions(+), 43 deletions(-) create mode 100755 logging-modules/log4j2/${sys:logging.folder.path} create mode 100644 persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/SpringRedisReactiveApplication.java create mode 100644 persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/config/RedisConfig.java create mode 100644 persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/model/Employee.java create mode 100644 persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java create mode 100644 persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java create mode 100644 persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java diff --git a/logging-modules/log4j2/${sys:logging.folder.path} b/logging-modules/log4j2/${sys:logging.folder.path} new file mode 100755 index 0000000000..e69de29bb2 diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index 5981bf41e0..bee3d683b8 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -7,17 +7,61 @@ jar + parent-boot-2 com.baeldung - parent-spring-5 0.0.1-SNAPSHOT - ../../parent-spring-5 + ../../parent-boot-2 - org.springframework.data - spring-data-redis - ${spring-data-redis} + org.springframework.boot + spring-boot-starter-data-redis-reactive + + + org.springframework.boot + spring-boot-starter-web + + + org.projectlombok + lombok + + + io.projectreactor + reactor-test + test + + + + org.springframework + spring-test + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.junit.jupiter + junit-jupiter-api + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test @@ -33,42 +77,12 @@ jar - - org.springframework - spring-core - ${spring.version} - - - commons-logging - commons-logging - - - - - - org.springframework - spring-context - ${spring.version} - - - - org.springframework - spring-test - ${spring.version} - test - - com.lordofthejars nosqlunit-redis ${nosqlunit.version} - - org.springframework.data - spring-data-commons - ${spring-data-commons.version} - com.github.kstyrc embedded-redis @@ -77,12 +91,13 @@ - 2.0.3.RELEASE 3.2.4 2.9.0 0.10.0 2.0.3.RELEASE 0.6 + 1.0.0 + 5.0.2 diff --git a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/SpringRedisReactiveApplication.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/SpringRedisReactiveApplication.java new file mode 100644 index 0000000000..8b1f892f67 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/SpringRedisReactiveApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.data.reactive.redis; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringRedisReactiveApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringRedisReactiveApplication.class, args); + } + +} diff --git a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/config/RedisConfig.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/config/RedisConfig.java new file mode 100644 index 0000000000..d23d0092eb --- /dev/null +++ b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/config/RedisConfig.java @@ -0,0 +1,56 @@ +package com.baeldung.spring.data.reactive.redis.config; + + +import com.baeldung.spring.data.reactive.redis.model.Employee; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.ReactiveKeyCommands; +import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; +import org.springframework.data.redis.connection.ReactiveStringCommands; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.ReactiveRedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import javax.annotation.PreDestroy; + +@Configuration +public class RedisConfig { + + @Autowired + RedisConnectionFactory factory; + + @Bean + public ReactiveRedisTemplate reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) { + Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(Employee.class); + RedisSerializationContext.RedisSerializationContextBuilder builder = RedisSerializationContext.newSerializationContext(new StringRedisSerializer()); + RedisSerializationContext context = builder.value(serializer) + .build(); + return new ReactiveRedisTemplate<>(factory, context); + } + + @Bean + public ReactiveRedisTemplate reactiveRedisTemplateString(ReactiveRedisConnectionFactory connectionFactory) { + return new ReactiveRedisTemplate<>(connectionFactory, RedisSerializationContext.string()); + } + + @Bean + public ReactiveKeyCommands keyCommands(final ReactiveRedisConnectionFactory reactiveRedisConnectionFactory) { + return reactiveRedisConnectionFactory.getReactiveConnection() + .keyCommands(); + } + + @Bean + public ReactiveStringCommands stringCommands(final ReactiveRedisConnectionFactory reactiveRedisConnectionFactory) { + return reactiveRedisConnectionFactory.getReactiveConnection() + .stringCommands(); + } + + @PreDestroy + public void cleanRedis() { + factory.getConnection() + .flushDb(); + } +} diff --git a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/model/Employee.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/model/Employee.java new file mode 100644 index 0000000000..9178f6e112 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/reactive/redis/model/Employee.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.data.reactive.redis.model; + +import java.io.Serializable; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.ToString; + +@Data +@ToString +@AllArgsConstructor +@NoArgsConstructor +@EqualsAndHashCode +public class Employee implements Serializable { + private static final long serialVersionUID = 1603714798906422731L; + private String id; + private String name; + private String department; +} diff --git a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java index 62a7886f46..6fdb3c5bef 100644 --- a/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java +++ b/persistence-modules/spring-data-redis/src/main/java/com/baeldung/spring/data/redis/config/RedisConfig.java @@ -1,6 +1,8 @@ package com.baeldung.spring.data.redis.config; -import org.springframework.beans.factory.annotation.Value; +import com.baeldung.spring.data.redis.queue.MessagePublisher; +import com.baeldung.spring.data.redis.queue.RedisMessagePublisher; +import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -13,10 +15,6 @@ import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; import org.springframework.data.redis.repository.configuration.EnableRedisRepositories; import org.springframework.data.redis.serializer.GenericToStringSerializer; -import com.baeldung.spring.data.redis.queue.MessagePublisher; -import com.baeldung.spring.data.redis.queue.RedisMessagePublisher; -import com.baeldung.spring.data.redis.queue.RedisMessageSubscriber; - @Configuration @ComponentScan("com.baeldung.spring.data.redis") @EnableRedisRepositories(basePackages = "com.baeldung.spring.data.redis.repo") 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 new file mode 100644 index 0000000000..e48aa1e06a --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisKeyCommandsIntegrationTest.java @@ -0,0 +1,51 @@ +package com.baeldung.spring.data.reactive.redis.template; + + +import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication; +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.connection.ReactiveKeyCommands; +import org.springframework.data.redis.connection.ReactiveStringCommands; +import org.springframework.data.redis.connection.ReactiveStringCommands.SetCommand; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.nio.ByteBuffer; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class) +public class RedisKeyCommandsIntegrationTest { + + @Autowired + private ReactiveKeyCommands keyCommands; + + @Autowired + private ReactiveStringCommands stringCommands; + + @Test + public void givenFluxOfKeys_whenPerformOperations_thenPerformOperations() { + Flux keys = Flux.just("key1", "key2", "key3", "key4"); + + Flux generator = keys.map(String::getBytes) + .map(ByteBuffer::wrap) + .map(key -> SetCommand.set(key) + .value(key)); + + StepVerifier.create(stringCommands.set(generator)) + .expectNextCount(4L) + .verifyComplete(); + + Mono keyCount = keyCommands.keys(ByteBuffer.wrap("key*".getBytes())) + .flatMapMany(Flux::fromIterable) + .count(); + + StepVerifier.create(keyCount) + .expectNext(4L) + .verifyComplete(); + + } +} 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 new file mode 100644 index 0000000000..3ebeff87b1 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateListOpsIntegrationTest.java @@ -0,0 +1,49 @@ +package com.baeldung.spring.data.reactive.redis.template; + + +import com.baeldung.spring.data.reactive.redis.SpringRedisReactiveApplication; +import org.junit.Before; +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.context.junit4.SpringRunner; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class) +public class RedisTemplateListOpsIntegrationTest { + + private static final String LIST_NAME = "demo_list"; + + @Autowired + private ReactiveRedisTemplate redisTemplate; + + private ReactiveListOperations reactiveListOps; + + @Before + public void setup() { + reactiveListOps = redisTemplate.opsForList(); + } + + @Test + public void givenListAndValues_whenLeftPushAndLeftPop_thenLeftPushAndLeftPop() { + Mono lPush = reactiveListOps.leftPushAll(LIST_NAME, "first", "second") + .log("Pushed"); + + StepVerifier.create(lPush) + .expectNext(2L) + .verifyComplete(); + + Mono lPop = reactiveListOps.leftPop(LIST_NAME) + .log("Popped"); + + StepVerifier.create(lPop) + .expectNext("second") + .verifyComplete(); + } + +} 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 new file mode 100644 index 0000000000..9490568089 --- /dev/null +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/spring/data/reactive/redis/template/RedisTemplateValueOpsIntegrationTest.java @@ -0,0 +1,71 @@ +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 org.junit.Before; +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.context.junit4.SpringRunner; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.time.Duration; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisReactiveApplication.class) +public class RedisTemplateValueOpsIntegrationTest { + + @Autowired + private ReactiveRedisTemplate redisTemplate; + + private ReactiveValueOperations reactiveValueOps; + + @Before + public void setup() { + reactiveValueOps = redisTemplate.opsForValue(); + } + + @Test + public void givenEmployee_whenSet_thenSet() { + + Mono result = reactiveValueOps.set("123", new Employee("123", "Bill", "Accounts")); + + StepVerifier.create(result) + .expectNext(true) + .verifyComplete(); + } + + @Test + public void givenEmployeeId_whenGet_thenReturnsEmployee() { + + Mono fetchedEmployee = reactiveValueOps.get("123"); + + StepVerifier.create(fetchedEmployee) + .expectNext(new Employee("123", "Bill", "Accounts")) + .verifyComplete(); + } + + @Test + public void givenEmployee_whenSetWithExpiry_thenSetsWithExpiryTime() throws InterruptedException { + + Mono result = reactiveValueOps.set("129", new Employee("129", "John", "Programming"), Duration.ofSeconds(1)); + + Mono fetchedEmployee = reactiveValueOps.get("129"); + + StepVerifier.create(result) + .expectNext(true) + .verifyComplete(); + + Thread.sleep(2000L); + + StepVerifier.create(fetchedEmployee) + .expectNextCount(0L) + .verifyComplete(); + } + +} 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 5bc70069c5..99febb6430 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 @@ -31,7 +31,7 @@ public class RedisMessageListenerIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new redis.embedded.RedisServer(6379); + redisServer = new redis.embedded.RedisServer(6380); 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 48832a8de9..43aadefc01 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 @@ -32,7 +32,7 @@ public class StudentRepositoryIntegrationTest { @BeforeClass public static void startRedisServer() throws IOException { - redisServer = new redis.embedded.RedisServer(6379); + redisServer = new redis.embedded.RedisServer(6380); redisServer.start(); } diff --git a/pom.xml b/pom.xml index 6c77ede1c2..28a6dd358e 100644 --- a/pom.xml +++ b/pom.xml @@ -451,6 +451,7 @@ spring-5 spring-5-data-reactive spring-5-reactive + spring-data-5-reactive/spring-5-data-reactive-redis spring-5-reactive-security spring-5-reactive-client spring-5-mvc From 79285e3cc60f28359c1429bc4ca15a4faf5a8a8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dar=C3=ADo=20Carrasquel?= Date: Sun, 14 Oct 2018 01:33:39 -0500 Subject: [PATCH 61/75] BAEL-2234 Dates difference with ZonedDateTimes (#5445) --- .../test/java/com/baeldung/date/DateDiffUnitTest.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java b/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java index 58d192bfdb..92da22cc95 100644 --- a/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/date/DateDiffUnitTest.java @@ -51,6 +51,15 @@ public class DateDiffUnitTest { assertEquals(diff, 6); } + @Test + public void givenTwoZonedDateTimesInJava8_whenDifferentiating_thenWeGetSix() { + LocalDateTime ldt = LocalDateTime.now(); + ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal")); + ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore")).minusDays(6); + long diff = ChronoUnit.DAYS.between(sixDaysBehind, now); + assertEquals(diff, 6); + } + @Test public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix() { org.joda.time.LocalDate now = org.joda.time.LocalDate.now(); From ee5fe8faab1b2bdc4c81d840a5545765e2f7260a Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 14 Oct 2018 15:13:39 +0530 Subject: [PATCH 62/75] [BAEL-9461] - Added code examples for difference between thenApply() and thenCompose() --- .../CompletableFutureLongRunningUnitTest.java | 20 +++++++++++++++++++ .../log4j2/${sys:logging.folder.path} | 0 2 files changed, 20 insertions(+) delete mode 100755 logging-modules/log4j2/${sys:logging.folder.path} diff --git a/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java index 45d2ec68e4..d9cf8ae019 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java @@ -184,5 +184,25 @@ public class CompletableFutureLongRunningUnitTest { assertEquals("Hello World", future.get()); } + + @Test + public void whenPassingTransformation_thenFunctionExecutionWithThenApply() throws InterruptedException, ExecutionException { + CompletableFuture finalResult = compute().thenApply(s -> s + 1); + assertTrue(finalResult.get() == 11); + } + + @Test + public void whenPassingPreviousStage_thenFunctionExecutionWithThenCompose() throws InterruptedException, ExecutionException { + CompletableFuture finalResult = compute().thenCompose(this::computeAnother); + assertTrue(finalResult.get() == 20); + } + + public CompletableFuture compute(){ + return CompletableFuture.supplyAsync(() -> 10); + } + + public CompletableFuture computeAnother(Integer i){ + return CompletableFuture.supplyAsync(() -> 10 + i); + } } \ No newline at end of file diff --git a/logging-modules/log4j2/${sys:logging.folder.path} b/logging-modules/log4j2/${sys:logging.folder.path} deleted file mode 100755 index e69de29bb2..0000000000 From b5dcb13c41cae9374210dfe4c178b11a242a04de Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 14 Oct 2018 18:13:40 +0530 Subject: [PATCH 63/75] [BAEL-9635] - Moved Junit vs TestNg junit code examples to junit-5 module from core-java --- .../customtestname/CustomNameUnitTest.java | 17 ------ .../ParameterizedUnitTest.java | 48 ----------------- .../suite/SelectClassesSuiteUnitTest.java | 13 ----- .../suite/SelectPackagesSuiteUnitTest.java | 11 ---- .../suite/childpackage1/Class1UnitTest.java | 15 ------ .../suite/childpackage2/Class2UnitTest.java | 14 ----- .../log4j2/${sys:logging.folder.path} | 0 pom.xml | 6 +++ .../baeldung/throwsexception/Calculator.java | 0 .../DivideByZeroException.java | 0 .../junit4vstestng/SortedUnitTest.java | 0 .../SummationServiceIntegrationTest.java | 0 .../SummationServiceIntegrationTest.java | 53 +++++++++++++++++++ .../throwsexception/CalculatorUnitTest.java | 0 14 files changed, 59 insertions(+), 118 deletions(-) delete mode 100644 core-java/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java delete mode 100644 core-java/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java delete mode 100644 core-java/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java delete mode 100644 core-java/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java delete mode 100644 core-java/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java delete mode 100644 core-java/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java delete mode 100755 logging-modules/log4j2/${sys:logging.folder.path} rename {core-java => testing-modules/junit-5}/src/main/java/com/baeldung/throwsexception/Calculator.java (100%) rename {core-java => testing-modules/junit-5}/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java (100%) rename {core-java => testing-modules/junit-5}/src/test/java/com/baeldung/junit4vstestng/SortedUnitTest.java (100%) rename {core-java => testing-modules/junit-5}/src/test/java/com/baeldung/junit4vstestng/SummationServiceIntegrationTest.java (100%) create mode 100644 testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SummationServiceIntegrationTest.java rename {core-java => testing-modules/junit-5}/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java (100%) diff --git a/core-java/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java b/core-java/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java deleted file mode 100644 index f04b825c89..0000000000 --- a/core-java/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.java.customtestname; - -import static org.junit.Assert.assertNotNull; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -public class CustomNameUnitTest { - - @ParameterizedTest - @ValueSource(strings = { "Hello", "World" }) - @DisplayName("Test Method to check that the inputs are not nullable") - void givenString_TestNullOrNot(String word) { - assertNotNull(word); - } -} diff --git a/core-java/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java b/core-java/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java deleted file mode 100644 index af9ad870b9..0000000000 --- a/core-java/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.baeldung.java.parameterisedsource; - -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.EnumSet; -import java.util.stream.Stream; - -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; -import org.junit.jupiter.params.provider.EnumSource; -import org.junit.jupiter.params.provider.MethodSource; -import org.junit.jupiter.params.provider.ValueSource; - -import com.baeldung.enums.PizzaDeliveryStrategy; - -public class ParameterizedUnitTest { - - @ParameterizedTest - @ValueSource(strings = { "Hello", "World" }) - void givenString_TestNullOrNot(String word) { - assertNotNull(word); - } - - @ParameterizedTest - @EnumSource(value = PizzaDeliveryStrategy.class, names = {"EXPRESS", "NORMAL"}) - void givenEnum_TestContainsOrNot(PizzaDeliveryStrategy timeUnit) { - assertTrue(EnumSet.of(PizzaDeliveryStrategy.EXPRESS, PizzaDeliveryStrategy.NORMAL).contains(timeUnit)); - } - - @ParameterizedTest - @MethodSource("wordDataProvider") - void givenMethodSource_TestInputStream(String argument) { - assertNotNull(argument); - } - - static Stream wordDataProvider() { - return Stream.of("foo", "bar"); - } - - @ParameterizedTest - @CsvSource({ "1, Car", "2, House", "3, Train" }) - void givenCSVSource_TestContent(int id, String word) { - assertNotNull(id); - assertNotNull(word); - } -} diff --git a/core-java/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java b/core-java/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java deleted file mode 100644 index 220897eae7..0000000000 --- a/core-java/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung.java.suite; - -import org.baeldung.java.suite.childpackage1.Class1UnitTest; -import org.baeldung.java.suite.childpackage2.Class2UnitTest; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.platform.suite.api.SelectClasses; -import org.junit.runner.RunWith; - -@RunWith(JUnitPlatform.class) -@SelectClasses({Class1UnitTest.class, Class2UnitTest.class}) -public class SelectClassesSuiteUnitTest { - -} diff --git a/core-java/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java b/core-java/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java deleted file mode 100644 index ae887ae43b..0000000000 --- a/core-java/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.baeldung.java.suite; - -import org.junit.platform.runner.JUnitPlatform; -import org.junit.platform.suite.api.SelectPackages; -import org.junit.runner.RunWith; - -@RunWith(JUnitPlatform.class) -@SelectPackages({ "org.baeldung.java.suite.childpackage1", "org.baeldung.java.suite.childpackage2" }) -public class SelectPackagesSuiteUnitTest { - -} diff --git a/core-java/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java b/core-java/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java deleted file mode 100644 index 78469cb971..0000000000 --- a/core-java/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.baeldung.java.suite.childpackage1; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.Test; - - -public class Class1UnitTest { - - @Test - public void testCase_InClass1UnitTest() { - assertTrue(true); - } - -} diff --git a/core-java/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java b/core-java/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java deleted file mode 100644 index 4463ecfad9..0000000000 --- a/core-java/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.java.suite.childpackage2; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.Test; - -public class Class2UnitTest { - - @Test - public void testCase_InClass2UnitTest() { - assertTrue(true); - } - -} diff --git a/logging-modules/log4j2/${sys:logging.folder.path} b/logging-modules/log4j2/${sys:logging.folder.path} deleted file mode 100755 index e69de29bb2..0000000000 diff --git a/pom.xml b/pom.xml index 28a6dd358e..da1733d2b2 100644 --- a/pom.xml +++ b/pom.xml @@ -46,6 +46,12 @@ ${junit-jupiter.version} test + + org.junit.jupiter + junit-jupiter-params + ${junit-jupiter.version} + test + org.junit.jupiter junit-jupiter-api diff --git a/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java b/testing-modules/junit-5/src/main/java/com/baeldung/throwsexception/Calculator.java similarity index 100% rename from core-java/src/main/java/com/baeldung/throwsexception/Calculator.java rename to testing-modules/junit-5/src/main/java/com/baeldung/throwsexception/Calculator.java diff --git a/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java b/testing-modules/junit-5/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java similarity index 100% rename from core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java rename to testing-modules/junit-5/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/SortedUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit4vstestng/SortedUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/junit4vstestng/SortedUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit4vstestng/SortedUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/SummationServiceIntegrationTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit4vstestng/SummationServiceIntegrationTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/junit4vstestng/SummationServiceIntegrationTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit4vstestng/SummationServiceIntegrationTest.java diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SummationServiceIntegrationTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SummationServiceIntegrationTest.java new file mode 100644 index 0000000000..92e7a6f5db --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5vstestng/SummationServiceIntegrationTest.java @@ -0,0 +1,53 @@ +package com.baeldung.junit5vstestng; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class SummationServiceIntegrationTest { + private static List numbers; + + @BeforeAll + public static void initialize() { + numbers = new ArrayList<>(); + } + + @AfterAll + public static void tearDown() { + numbers = null; + } + + @BeforeEach + public void runBeforeEachTest() { + numbers.add(1); + numbers.add(2); + numbers.add(3); + } + + @AfterEach + public void runAfterEachTest() { + numbers.clear(); + } + + @Test + public void givenNumbers_sumEquals_thenCorrect() { + int sum = numbers.stream() + .reduce(0, Integer::sum); + Assert.assertEquals(6, sum); + } + + @Ignore + @Test + public void givenEmptyList_sumEqualsZero_thenCorrect() { + int sum = numbers.stream() + .reduce(0, Integer::sum); + Assert.assertEquals(6, sum); + } +} diff --git a/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java similarity index 100% rename from core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java From 29cee792a889d72c211251ee31a5052bf118c7ac Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 14 Oct 2018 20:02:51 +0530 Subject: [PATCH 64/75] [BAEL-9601] - Upgraded groovy-all version in libraries module --- libraries/pom.xml | 3 ++- logging-modules/log4j2/{${sys:logging.folder.path} => ${sys} | 0 2 files changed, 2 insertions(+), 1 deletion(-) rename logging-modules/log4j2/{${sys:logging.folder.path} => ${sys} (100%) mode change 100755 => 100644 diff --git a/libraries/pom.xml b/libraries/pom.xml index 91c54b6113..6bbe8e6f1c 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -358,6 +358,7 @@ org.codehaus.groovy groovy-all + pom ${groovy.version} @@ -922,7 +923,7 @@ 2.3.0 0.9.12 1.19 - 2.4.10 + 2.5.2 1.1.0 3.9.0 2.0.4 diff --git a/logging-modules/log4j2/${sys:logging.folder.path} b/logging-modules/log4j2/${sys old mode 100755 new mode 100644 similarity index 100% rename from logging-modules/log4j2/${sys:logging.folder.path} rename to logging-modules/log4j2/${sys From 38ddcc6477ca324e248173a102be6fd63276a7d9 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 14 Oct 2018 19:26:46 +0300 Subject: [PATCH 65/75] rename test to manual --- ...{SystemsUtilsUnitTest.java => SystemsUtilsManualTest.java} | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) rename libraries/src/test/java/com/baeldung/commons/lang3/test/{SystemsUtilsUnitTest.java => SystemsUtilsManualTest.java} (86%) diff --git a/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java similarity index 86% rename from libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsUnitTest.java rename to libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java index 0efe97f912..cb45ebc24d 100644 --- a/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsUnitTest.java +++ b/libraries/src/test/java/com/baeldung/commons/lang3/test/SystemsUtilsManualTest.java @@ -6,8 +6,10 @@ import org.apache.commons.lang3.SystemUtils; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -public class SystemsUtilsUnitTest { +public class SystemsUtilsManualTest { + // the paths depend on the OS and installed version of Java + @Test public void givenSystemUtilsClass_whenCalledgetJavaHome_thenCorrect() { assertThat(SystemUtils.getJavaHome()).isEqualTo(new File("/usr/lib/jvm/java-8-oracle/jre")); From 23b1323446c2c535ab8fdf3aef19761e0649bc98 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sun, 14 Oct 2018 11:37:16 -0500 Subject: [PATCH 66/75] BAEL-2200: Spring Boot auto-configuration report (#5453) * BAEL-1766: Update README * BAEL-1853: add link to article * BAEL-1801: add link to article * Added links back to articles * Add links back to articles * BAEL-1795: Update README * BAEL-1901 and BAEL-1555 add links back to article * BAEL-2026 add link back to article * BAEL-2029: add link back to article * BAEL-1898: Add link back to article * BAEL-2102 and BAEL-2131 Add links back to articles * BAEL-2132 Add link back to article * BAEL-1980: add link back to article * BAEL-2200: Display auto-configuration report in Spring Boot --- .../baeldung/h2db/auto/configuration/AutoConfigurationDemo.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java index 87a191554b..8d92e18754 100644 --- a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java +++ b/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java @@ -4,7 +4,7 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; -@SpringBootApplication(scanBasePackages = "com.baeldung.h2db.auto-configuration") +@SpringBootApplication public class AutoConfigurationDemo { public static void main(String[] args) { From 285219c54c3ffe993e9bb9e7819d5b4cb9802de3 Mon Sep 17 00:00:00 2001 From: fanatixan Date: Sun, 14 Oct 2018 19:08:11 +0200 Subject: [PATCH 67/75] Bael-2210 - Heap Sort (#5446) * implementing heap * Heap sort refactor --- .../main/java/com/baeldung/heapsort/Heap.java | 136 ++++++++++++++++++ .../com/baeldung/heapsort/HeapUnitTest.java | 36 +++++ 2 files changed, 172 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/heapsort/Heap.java create mode 100644 core-java/src/test/java/com/baeldung/heapsort/HeapUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/heapsort/Heap.java b/core-java/src/main/java/com/baeldung/heapsort/Heap.java new file mode 100644 index 0000000000..95e0e1d8cd --- /dev/null +++ b/core-java/src/main/java/com/baeldung/heapsort/Heap.java @@ -0,0 +1,136 @@ +package com.baeldung.heapsort; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Heap> { + + private List elements = new ArrayList<>(); + + public static > List sort(Iterable elements) { + Heap heap = of(elements); + + List result = new ArrayList<>(); + + while (!heap.isEmpty()) { + result.add(heap.pop()); + } + + return result; + } + + public static > Heap of(E... elements) { + return of(Arrays.asList(elements)); + } + + public static > Heap of(Iterable elements) { + Heap result = new Heap<>(); + for (E element : elements) { + result.add(element); + } + return result; + } + + public void add(E e) { + elements.add(e); + int elementIndex = elements.size() - 1; + while (!isRoot(elementIndex) && !isCorrectChild(elementIndex)) { + int parentIndex = parentIndex(elementIndex); + swap(elementIndex, parentIndex); + elementIndex = parentIndex; + } + } + + public E pop() { + if (isEmpty()) { + throw new IllegalStateException("You cannot pop from an empty heap"); + } + + E result = elementAt(0); + + int lasElementIndex = elements.size() - 1; + swap(0, lasElementIndex); + elements.remove(lasElementIndex); + + int elementIndex = 0; + while (!isLeaf(elementIndex) && !isCorrectParent(elementIndex)) { + int smallerChildIndex = smallerChildIndex(elementIndex); + swap(elementIndex, smallerChildIndex); + elementIndex = smallerChildIndex; + } + + return result; + } + + public boolean isEmpty() { + return elements.isEmpty(); + } + + private boolean isRoot(int index) { + return index == 0; + } + + private int smallerChildIndex(int index) { + int leftChildIndex = leftChildIndex(index); + int rightChildIndex = rightChildIndex(index); + + if (!isValidIndex(rightChildIndex)) { + return leftChildIndex; + } + + if (elementAt(leftChildIndex).compareTo(elementAt(rightChildIndex)) < 0) { + return leftChildIndex; + } + + return rightChildIndex; + } + + private boolean isLeaf(int index) { + return !isValidIndex(leftChildIndex(index)); + } + + private boolean isCorrectParent(int index) { + return isCorrect(index, leftChildIndex(index)) && isCorrect(index, rightChildIndex(index)); + } + + private boolean isCorrectChild(int index) { + return isCorrect(parentIndex(index), index); + } + + private boolean isCorrect(int parentIndex, int childIndex) { + if (!isValidIndex(parentIndex) || !isValidIndex(childIndex)) { + return true; + } + + return elementAt(parentIndex).compareTo(elementAt(childIndex)) < 0; + } + + private boolean isValidIndex(int index) { + return index < elements.size(); + } + + private void swap(int index1, int index2) { + E element1 = elementAt(index1); + E element2 = elementAt(index2); + elements.set(index1, element2); + elements.set(index2, element1); + } + + private E elementAt(int index) { + return elements.get(index); + } + + private int parentIndex(int index) { + return (index - 1) / 2; + } + + private int leftChildIndex(int index) { + return 2 * index + 1; + } + + private int rightChildIndex(int index) { + return 2 * index + 2; + } + +} diff --git a/core-java/src/test/java/com/baeldung/heapsort/HeapUnitTest.java b/core-java/src/test/java/com/baeldung/heapsort/HeapUnitTest.java new file mode 100644 index 0000000000..cc3e49b6c9 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/heapsort/HeapUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.heapsort; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +public class HeapUnitTest { + + @Test + public void givenNotEmptyHeap_whenPopCalled_thenItShouldReturnSmallestElement() { + // given + Heap heap = Heap.of(3, 5, 1, 4, 2); + + // when + int head = heap.pop(); + + // then + assertThat(head).isEqualTo(1); + } + + @Test + public void givenNotEmptyIterable_whenSortCalled_thenItShouldReturnElementsInSortedList() { + // given + List elements = Arrays.asList(3, 5, 1, 4, 2); + + // when + List sortedElements = Heap.sort(elements); + + // then + assertThat(sortedElements).isEqualTo(Arrays.asList(1, 2, 3, 4, 5)); + } + +} From edff9132ee617922b52a12be0d8b35c4e2ffd7d2 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 14 Oct 2018 23:05:11 +0530 Subject: [PATCH 68/75] [BAEL-9635] - Added missing classes --- .../customtestname/CustomNameUnitTest.java | 17 +++++++ .../ParameterizedUnitTest.java | 45 +++++++++++++++++++ .../PizzaDeliveryStrategy.java | 6 +++ .../suite/SelectClassesSuiteUnitTest.java | 13 ++++++ .../suite/SelectPackagesSuiteUnitTest.java | 11 +++++ .../suite/childpackage1/Class1UnitTest.java | 15 +++++++ .../suite/childpackage2/Class2UnitTest.java | 14 ++++++ 7 files changed, 121 insertions(+) create mode 100644 testing-modules/junit-5/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java create mode 100644 testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java create mode 100644 testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/PizzaDeliveryStrategy.java create mode 100644 testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java create mode 100644 testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java create mode 100644 testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java create mode 100644 testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java b/testing-modules/junit-5/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java new file mode 100644 index 0000000000..f04b825c89 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/org/baeldung/java/customtestname/CustomNameUnitTest.java @@ -0,0 +1,17 @@ +package org.baeldung.java.customtestname; + +import static org.junit.Assert.assertNotNull; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +public class CustomNameUnitTest { + + @ParameterizedTest + @ValueSource(strings = { "Hello", "World" }) + @DisplayName("Test Method to check that the inputs are not nullable") + void givenString_TestNullOrNot(String word) { + assertNotNull(word); + } +} diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java b/testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java new file mode 100644 index 0000000000..8d09161176 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/ParameterizedUnitTest.java @@ -0,0 +1,45 @@ +package org.baeldung.java.parameterisedsource; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.EnumSet; +import java.util.stream.Stream; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +public class ParameterizedUnitTest { + + @ParameterizedTest + @ValueSource(strings = { "Hello", "World" }) + void givenString_TestNullOrNot(String word) { + assertNotNull(word); + } + + @ParameterizedTest + @EnumSource(value = PizzaDeliveryStrategy.class, names = {"EXPRESS", "NORMAL"}) + void givenEnum_TestContainsOrNot(PizzaDeliveryStrategy timeUnit) { + assertTrue(EnumSet.of(PizzaDeliveryStrategy.EXPRESS, PizzaDeliveryStrategy.NORMAL).contains(timeUnit)); + } + + @ParameterizedTest + @MethodSource("wordDataProvider") + void givenMethodSource_TestInputStream(String argument) { + assertNotNull(argument); + } + + static Stream wordDataProvider() { + return Stream.of("foo", "bar"); + } + + @ParameterizedTest + @CsvSource({ "1, Car", "2, House", "3, Train" }) + void givenCSVSource_TestContent(int id, String word) { + assertNotNull(id); + assertNotNull(word); + } +} diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/PizzaDeliveryStrategy.java b/testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/PizzaDeliveryStrategy.java new file mode 100644 index 0000000000..ecfc7b4627 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/org/baeldung/java/parameterisedsource/PizzaDeliveryStrategy.java @@ -0,0 +1,6 @@ +package org.baeldung.java.parameterisedsource; + +public enum PizzaDeliveryStrategy { + EXPRESS, + NORMAL; +} diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java b/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java new file mode 100644 index 0000000000..220897eae7 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectClassesSuiteUnitTest.java @@ -0,0 +1,13 @@ +package org.baeldung.java.suite; + +import org.baeldung.java.suite.childpackage1.Class1UnitTest; +import org.baeldung.java.suite.childpackage2.Class2UnitTest; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.SelectClasses; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@SelectClasses({Class1UnitTest.class, Class2UnitTest.class}) +public class SelectClassesSuiteUnitTest { + +} diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java b/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java new file mode 100644 index 0000000000..ae887ae43b --- /dev/null +++ b/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/SelectPackagesSuiteUnitTest.java @@ -0,0 +1,11 @@ +package org.baeldung.java.suite; + +import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.SelectPackages; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +@SelectPackages({ "org.baeldung.java.suite.childpackage1", "org.baeldung.java.suite.childpackage2" }) +public class SelectPackagesSuiteUnitTest { + +} diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java b/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java new file mode 100644 index 0000000000..78469cb971 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage1/Class1UnitTest.java @@ -0,0 +1,15 @@ +package org.baeldung.java.suite.childpackage1; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.Test; + + +public class Class1UnitTest { + + @Test + public void testCase_InClass1UnitTest() { + assertTrue(true); + } + +} diff --git a/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java b/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java new file mode 100644 index 0000000000..4463ecfad9 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/org/baeldung/java/suite/childpackage2/Class2UnitTest.java @@ -0,0 +1,14 @@ +package org.baeldung.java.suite.childpackage2; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.Test; + +public class Class2UnitTest { + + @Test + public void testCase_InClass2UnitTest() { + assertTrue(true); + } + +} From 3a14ed0ff35556766c700a51c1d2004350db6a27 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Sun, 14 Oct 2018 23:46:10 +0530 Subject: [PATCH 69/75] [BAEL-9515] - Added latest version of spring 1.5 --- parent-boot-1/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parent-boot-1/pom.xml b/parent-boot-1/pom.xml index 7742841d07..d220b4a6b7 100644 --- a/parent-boot-1/pom.xml +++ b/parent-boot-1/pom.xml @@ -17,7 +17,7 @@ org.springframework.boot spring-boot-dependencies - 1.5.15.RELEASE + 1.5.16.RELEASE pom import From 6d79649b5610243216333224222bb88ce9cf6d50 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Mon, 15 Oct 2018 01:32:54 +0530 Subject: [PATCH 70/75] [BAEL-9547] - Splitted guava module and introduced guava-collections module --- guava-collections/.gitignore | 13 ++++ guava-collections/README.md | 20 ++++++ guava-collections/pom.xml | 66 ++++++++++++++++++ .../src/main/resources/logback.xml | 19 +++++ .../baeldung/guava/EvictingQueueUnitTest.java | 0 .../guava/GuavaCollectionTypesUnitTest.java | 0 .../GuavaCollectionsExamplesUnitTest.java | 0 ...avaFilterTransformCollectionsUnitTest.java | 0 .../org/baeldung/guava/GuavaMapFromSet.java | 0 .../guava/GuavaMapFromSetUnitTest.java | 0 .../guava/GuavaMapInitializeUnitTest.java | 0 .../baeldung/guava/GuavaMultiMapUnitTest.java | 0 .../guava/GuavaOrderingExamplesUnitTest.java | 0 .../baeldung/guava/GuavaOrderingUnitTest.java | 0 .../baeldung/guava/GuavaRangeMapUnitTest.java | 0 .../baeldung/guava/GuavaRangeSetUnitTest.java | 0 .../baeldung/guava/GuavaStringUnitTest.java | 0 .../guava/MinMaxPriorityQueueUnitTest.java | 0 .../hamcrest/HamcrestExamplesUnitTest.java | 0 .../CollectionApachePartitionUnitTest.java | 0 .../CollectionGuavaPartitionUnitTest.java | 0 .../java/CollectionJavaPartitionUnitTest.java | 0 .../src/test/resources/.gitignore | 13 ++++ guava-collections/src/test/resources/test.out | 1 + guava-collections/src/test/resources/test1.in | 1 + .../src/test/resources/test1_1.in | 1 + guava-collections/src/test/resources/test2.in | 4 ++ .../src/test/resources/test_copy.in | 1 + .../src/test/resources/test_le.txt | Bin 0 -> 4 bytes guava/README.md | 14 ---- guava/pom.xml | 7 -- pom.xml | 2 + 32 files changed, 141 insertions(+), 21 deletions(-) create mode 100644 guava-collections/.gitignore create mode 100644 guava-collections/README.md create mode 100644 guava-collections/pom.xml create mode 100644 guava-collections/src/main/resources/logback.xml rename {guava => guava-collections}/src/test/java/org/baeldung/guava/EvictingQueueUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaCollectionTypesUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaCollectionsExamplesUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaFilterTransformCollectionsUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaMapFromSet.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaMultiMapUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaOrderingExamplesUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaOrderingUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaRangeMapUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/GuavaStringUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/guava/MinMaxPriorityQueueUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/hamcrest/HamcrestExamplesUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/java/CollectionApachePartitionUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/java/CollectionGuavaPartitionUnitTest.java (100%) rename {guava => guava-collections}/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java (100%) create mode 100644 guava-collections/src/test/resources/.gitignore create mode 100644 guava-collections/src/test/resources/test.out create mode 100644 guava-collections/src/test/resources/test1.in create mode 100644 guava-collections/src/test/resources/test1_1.in create mode 100644 guava-collections/src/test/resources/test2.in create mode 100644 guava-collections/src/test/resources/test_copy.in create mode 100644 guava-collections/src/test/resources/test_le.txt diff --git a/guava-collections/.gitignore b/guava-collections/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/guava-collections/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/guava-collections/README.md b/guava-collections/README.md new file mode 100644 index 0000000000..eb1eb1d35c --- /dev/null +++ b/guava-collections/README.md @@ -0,0 +1,20 @@ +========= + +## Guava and Hamcrest Cookbooks and Examples + + +### Relevant Articles: +- [Guava Collections Cookbook](http://www.baeldung.com/guava-collections) +- [Guava Ordering Cookbook](http://www.baeldung.com/guava-order) +- [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays) +- [Partition a List in Java](http://www.baeldung.com/java-list-split) +- [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection) +- [Guava – Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial) +- [Guava – Lists](http://www.baeldung.com/guava-lists) +- [Guava – Sets](http://www.baeldung.com/guava-sets) +- [Guava – Maps](http://www.baeldung.com/guava-maps) +- [Guide to Guava Multimap](http://www.baeldung.com/guava-multimap) +- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset) +- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap) +- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue) +- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) \ No newline at end of file diff --git a/guava-collections/pom.xml b/guava-collections/pom.xml new file mode 100644 index 0000000000..a717023156 --- /dev/null +++ b/guava-collections/pom.xml @@ -0,0 +1,66 @@ + + 4.0.0 + com.baeldung + guava-collections + 0.1.0-SNAPSHOT + guava-collections + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + org.hamcrest + java-hamcrest + ${java-hamcrest.version} + test + + + + + guava + + + src/main/resources + true + + + + + + + 24.0-jre + 3.5 + 4.1 + + + 3.6.1 + 2.0.0.0 + + + \ No newline at end of file diff --git a/guava-collections/src/main/resources/logback.xml b/guava-collections/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/guava-collections/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/guava/src/test/java/org/baeldung/guava/EvictingQueueUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/EvictingQueueUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/EvictingQueueUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/EvictingQueueUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaCollectionTypesUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaCollectionTypesUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCollectionsExamplesUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaCollectionsExamplesUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaCollectionsExamplesUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaCollectionsExamplesUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaFilterTransformCollectionsUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaFilterTransformCollectionsUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaFilterTransformCollectionsUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaFilterTransformCollectionsUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapFromSet.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaMapFromSet.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaMapFromSet.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaMapFromSet.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaMapFromSetUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMultiMapUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaMultiMapUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaMultiMapUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaMultiMapUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaOrderingExamplesUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaOrderingExamplesUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaOrderingExamplesUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaOrderingExamplesUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaOrderingUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaOrderingUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaOrderingUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaOrderingUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaRangeMapUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaRangeMapUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaRangeMapUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaRangeMapUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaRangeSetUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/GuavaStringUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaStringUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/GuavaStringUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/GuavaStringUnitTest.java diff --git a/guava/src/test/java/org/baeldung/guava/MinMaxPriorityQueueUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/MinMaxPriorityQueueUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/guava/MinMaxPriorityQueueUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/MinMaxPriorityQueueUnitTest.java diff --git a/guava/src/test/java/org/baeldung/hamcrest/HamcrestExamplesUnitTest.java b/guava-collections/src/test/java/org/baeldung/hamcrest/HamcrestExamplesUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/hamcrest/HamcrestExamplesUnitTest.java rename to guava-collections/src/test/java/org/baeldung/hamcrest/HamcrestExamplesUnitTest.java diff --git a/guava/src/test/java/org/baeldung/java/CollectionApachePartitionUnitTest.java b/guava-collections/src/test/java/org/baeldung/java/CollectionApachePartitionUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/java/CollectionApachePartitionUnitTest.java rename to guava-collections/src/test/java/org/baeldung/java/CollectionApachePartitionUnitTest.java diff --git a/guava/src/test/java/org/baeldung/java/CollectionGuavaPartitionUnitTest.java b/guava-collections/src/test/java/org/baeldung/java/CollectionGuavaPartitionUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/java/CollectionGuavaPartitionUnitTest.java rename to guava-collections/src/test/java/org/baeldung/java/CollectionGuavaPartitionUnitTest.java diff --git a/guava/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java b/guava-collections/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java similarity index 100% rename from guava/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java rename to guava-collections/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java diff --git a/guava-collections/src/test/resources/.gitignore b/guava-collections/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/guava-collections/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/guava-collections/src/test/resources/test.out b/guava-collections/src/test/resources/test.out new file mode 100644 index 0000000000..7a79da3803 --- /dev/null +++ b/guava-collections/src/test/resources/test.out @@ -0,0 +1 @@ +John Jane Adam Tom \ No newline at end of file diff --git a/guava-collections/src/test/resources/test1.in b/guava-collections/src/test/resources/test1.in new file mode 100644 index 0000000000..70c379b63f --- /dev/null +++ b/guava-collections/src/test/resources/test1.in @@ -0,0 +1 @@ +Hello world \ No newline at end of file diff --git a/guava-collections/src/test/resources/test1_1.in b/guava-collections/src/test/resources/test1_1.in new file mode 100644 index 0000000000..8318c86b35 --- /dev/null +++ b/guava-collections/src/test/resources/test1_1.in @@ -0,0 +1 @@ +Test \ No newline at end of file diff --git a/guava-collections/src/test/resources/test2.in b/guava-collections/src/test/resources/test2.in new file mode 100644 index 0000000000..622efea9e6 --- /dev/null +++ b/guava-collections/src/test/resources/test2.in @@ -0,0 +1,4 @@ +John +Jane +Adam +Tom \ No newline at end of file diff --git a/guava-collections/src/test/resources/test_copy.in b/guava-collections/src/test/resources/test_copy.in new file mode 100644 index 0000000000..70c379b63f --- /dev/null +++ b/guava-collections/src/test/resources/test_copy.in @@ -0,0 +1 @@ +Hello world \ No newline at end of file diff --git a/guava-collections/src/test/resources/test_le.txt b/guava-collections/src/test/resources/test_le.txt new file mode 100644 index 0000000000000000000000000000000000000000..f7cc484bf45e18b3fe4dea78290abf122bedbad1 GIT binary patch literal 4 LcmYdcU|;|M0h9n` literal 0 HcmV?d00001 diff --git a/guava/README.md b/guava/README.md index fe1a347d72..7501bf08de 100644 --- a/guava/README.md +++ b/guava/README.md @@ -4,33 +4,19 @@ ### Relevant Articles: -- [Guava Collections Cookbook](http://www.baeldung.com/guava-collections) -- [Guava Ordering Cookbook](http://www.baeldung.com/guava-order) - [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates) -- [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays) -- [Partition a List in Java](http://www.baeldung.com/java-list-split) -- [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection) -- [Guava – Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial) - [Guava – Write to File, Read from File](http://www.baeldung.com/guava-write-to-file-read-from-file) -- [Guava – Lists](http://www.baeldung.com/guava-lists) -- [Guava – Sets](http://www.baeldung.com/guava-sets) -- [Guava – Maps](http://www.baeldung.com/guava-maps) - [Guava Set + Function = Map](http://www.baeldung.com/guava-set-function-map-tutorial) - [Guide to Guava’s Ordering](http://www.baeldung.com/guava-ordering) - [Guide to Guava’s PreConditions](http://www.baeldung.com/guava-preconditions) - [Introduction to Guava CacheLoader](http://www.baeldung.com/guava-cacheloader) - [Introduction to Guava Memoizer](http://www.baeldung.com/guava-memoizer) - [Guide to Guava’s EventBus](http://www.baeldung.com/guava-eventbus) -- [Guide to Guava Multimap](http://www.baeldung.com/guava-multimap) -- [Guide to Guava RangeSet](http://www.baeldung.com/guava-rangeset) -- [Guide to Guava RangeMap](http://www.baeldung.com/guava-rangemap) - [Guide to Guava Table](http://www.baeldung.com/guava-table) - [Guide to Guava’s Reflection Utilities](http://www.baeldung.com/guava-reflection) - [Guide to Guava ClassToInstanceMap](http://www.baeldung.com/guava-class-to-instance-map) -- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](http://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue) - [Guide to Mathematical Utilities in Guava](http://www.baeldung.com/guava-math) - [Bloom Filter in Java using Guava](http://www.baeldung.com/guava-bloom-filter) - [Using Guava CountingOutputStream](http://www.baeldung.com/guava-counting-outputstream) - [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers) - [Quick Guide to the Guava RateLimiter](http://www.baeldung.com/guava-rate-limiter) -- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) diff --git a/guava/pom.xml b/guava/pom.xml index 60678608dd..1d37a79ab6 100644 --- a/guava/pom.xml +++ b/guava/pom.xml @@ -14,12 +14,6 @@ - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - org.apache.commons commons-lang3 @@ -56,7 +50,6 @@ 24.0-jre 3.5 - 4.1 3.6.1 diff --git a/pom.xml b/pom.xml index 28a6dd358e..d48ec6b7cb 100644 --- a/pom.xml +++ b/pom.xml @@ -372,6 +372,7 @@ google-web-toolkit gson guava + guava-collections guava-modules/guava-18 guava-modules/guava-19 guava-modules/guava-21 @@ -1279,6 +1280,7 @@ google-cloud gson guava + guava-collections guava-modules/guava-18 guava-modules/guava-19 guava-modules/guava-21 From 3d51a0f86aa42ffd32ba9233af1537be9ba2353a Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Sun, 14 Oct 2018 22:19:23 -0500 Subject: [PATCH 71/75] BAEL-2253 Update README (#5460) * BAEL-1766: Update README * BAEL-1853: add link to article * BAEL-1801: add link to article * Added links back to articles * Add links back to articles * BAEL-1795: Update README * BAEL-1901 and BAEL-1555 add links back to article * BAEL-2026 add link back to article * BAEL-2029: add link back to article * BAEL-1898: Add link back to article * BAEL-2102 and BAEL-2131 Add links back to articles * BAEL-2132 Add link back to article * BAEL-1980: add link back to article * BAEL-2200: Display auto-configuration report in Spring Boot * BAEL-2253: Add link back to article --- javaxval/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/javaxval/README.md b/javaxval/README.md index 3153546c7d..3a975022ad 100644 --- a/javaxval/README.md +++ b/javaxval/README.md @@ -9,3 +9,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Java Bean Validation Basics](http://www.baeldung.com/javax-validation) - [Validating Container Elements with Bean Validation 2.0](http://www.baeldung.com/bean-validation-container-elements) - [Method Constraints with Bean Validation 2.0](http://www.baeldung.com/javax-validation-method-constraints) +- [Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation](https://www.baeldung.com/java-bean-validation-not-null-empty-blank) From eeb5e0892b759661283d187bb800cdce6d6844a9 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Mon, 15 Oct 2018 21:40:00 +0200 Subject: [PATCH 72/75] removed unnecessary Mockito and refactored test method name --- .../FindItemsBasedOnOtherStreamUnitTest.java | 180 +++++++++--------- 1 file changed, 88 insertions(+), 92 deletions(-) rename core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java => core-java-collections/src/test/java/com/baeldung/findItems/FindItemsBasedOnOtherStreamUnitTest.java (63%) diff --git a/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java b/core-java-collections/src/test/java/com/baeldung/findItems/FindItemsBasedOnOtherStreamUnitTest.java similarity index 63% rename from core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java rename to core-java-collections/src/test/java/com/baeldung/findItems/FindItemsBasedOnOtherStreamUnitTest.java index a0dcdddd85..326ea9fbe4 100644 --- a/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java +++ b/core-java-collections/src/test/java/com/baeldung/findItems/FindItemsBasedOnOtherStreamUnitTest.java @@ -1,93 +1,89 @@ -package findItems; - -import static org.junit.Assert.assertEquals; - -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import org.junit.Test; - -public class FindItemsBasedOnValues { - - List EmplList = new ArrayList(); - List deptList = new ArrayList(); - - public static void main(String[] args) throws ParseException { - FindItemsBasedOnValues findItems = new FindItemsBasedOnValues(); - findItems.givenDepartmentList_thenEmployeeListIsFilteredCorrectly(); - } - - @Test - public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() { - Integer expectedId = 1002; - - populate(EmplList, deptList); - - List filteredList = EmplList.stream() - .filter(empl -> deptList.stream() - .anyMatch(dept -> dept.getDepartment() - .equals("sales") && empl.getEmployeeId() - .equals(dept.getEmployeeId()))) - .collect(Collectors.toList()); - - assertEquals(expectedId, filteredList.get(0) - .getEmployeeId()); - } - - private void populate(List EmplList, List deptList) { - Employee employee1 = new Employee(1001, "empl1"); - Employee employee2 = new Employee(1002, "empl2"); - Employee employee3 = new Employee(1003, "empl3"); - - Collections.addAll(EmplList, employee1, employee2, employee3); - - Department department1 = new Department(1002, "sales"); - Department department2 = new Department(1003, "marketing"); - Department department3 = new Department(1004, "sales"); - - Collections.addAll(deptList, department1, department2, department3); - } -} - -class Employee { - Integer employeeId; - String employeeName; - - public Employee(Integer employeeId, String employeeName) { - super(); - this.employeeId = employeeId; - this.employeeName = employeeName; - } - - public Integer getEmployeeId() { - return employeeId; - } - - public String getEmployeeName() { - return employeeName; - } - -} - -class Department { - Integer employeeId; - String department; - - public Department(Integer employeeId, String department) { - super(); - this.employeeId = employeeId; - this.department = department; - } - - public Integer getEmployeeId() { - return employeeId; - } - - public String getDepartment() { - return department; - } - +package com.baeldung.findItems; + +import static org.junit.Assert.assertEquals; + +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.Test; + +public class FindItemsBasedOnOtherStreamUnitTest { + + private List employeeList = new ArrayList(); + + private List departmentList = new ArrayList(); + + @Test + public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() { + Integer expectedId = 1002; + + populate(employeeList, departmentList); + + List filteredList = employeeList.stream() + .filter(empl -> departmentList.stream() + .anyMatch(dept -> dept.getDepartment() + .equals("sales") && empl.getEmployeeId() + .equals(dept.getEmployeeId()))) + .collect(Collectors.toList()); + + assertEquals(expectedId, filteredList.get(0) + .getEmployeeId()); + } + + private void populate(List EmplList, List deptList) { + Employee employee1 = new Employee(1001, "empl1"); + Employee employee2 = new Employee(1002, "empl2"); + Employee employee3 = new Employee(1003, "empl3"); + + Collections.addAll(EmplList, employee1, employee2, employee3); + + Department department1 = new Department(1002, "sales"); + Department department2 = new Department(1003, "marketing"); + Department department3 = new Department(1004, "sales"); + + Collections.addAll(deptList, department1, department2, department3); + } +} + +class Employee { + private Integer employeeId; + private String employeeName; + + Employee(Integer employeeId, String employeeName) { + super(); + this.employeeId = employeeId; + this.employeeName = employeeName; + } + + Integer getEmployeeId() { + return employeeId; + } + + public String getEmployeeName() { + return employeeName; + } + +} + +class Department { + private Integer employeeId; + private String department; + + Department(Integer employeeId, String department) { + super(); + this.employeeId = employeeId; + this.department = department; + } + + Integer getEmployeeId() { + return employeeId; + } + + String getDepartment() { + return department; + } + } \ No newline at end of file From 8cfa575f5d80ae73bafa9abe4bc4253dbe72db90 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Mon, 15 Oct 2018 21:40:50 +0200 Subject: [PATCH 73/75] removed unneccessary folder --- core-java-8/findItemsBasedOnValues/.gitignore | 1 - 1 file changed, 1 deletion(-) delete mode 100644 core-java-8/findItemsBasedOnValues/.gitignore diff --git a/core-java-8/findItemsBasedOnValues/.gitignore b/core-java-8/findItemsBasedOnValues/.gitignore deleted file mode 100644 index ae3c172604..0000000000 --- a/core-java-8/findItemsBasedOnValues/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/bin/ From 5e791c56a1a5e8165a332c0f9ac83358a0706441 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Mon, 15 Oct 2018 23:12:19 +0200 Subject: [PATCH 74/75] removed unneccessary folder --- .../com/baeldung/modulo/ModuloUnitTest.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/modulo/ModuloUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/modulo/ModuloUnitTest.java b/core-java/src/test/java/com/baeldung/modulo/ModuloUnitTest.java new file mode 100644 index 0000000000..8b3685adf3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/modulo/ModuloUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.modulo; + +import org.junit.Test; +import static org.assertj.core.api.Java6Assertions.*; + +public class ModuloUnitTest { + + @Test + public void whenIntegerDivision_thenLosesRemainder(){ + assertThat(11 / 4).isEqualTo(2); + } + + @Test + public void whenDoubleDivision_thenKeepsRemainder(){ + assertThat(11 / 4.0).isEqualTo(2.75); + } + + @Test + public void whenModulo_thenReturnsRemainder(){ + assertThat(11 % 4).isEqualTo(3); + } + + @Test(expected = ArithmeticException.class) + public void whenDivisionByZero_thenArithmeticException(){ + double result = 1 / 0; + } + + @Test(expected = ArithmeticException.class) + public void whenModuloByZero_thenArithmeticException(){ + double result = 1 % 0; + } + + @Test + public void whenDivisorIsOddAndModulusIs2_thenResultIs1(){ + assertThat(3 % 2).isEqualTo(1); + } + + @Test + public void whenDivisorIsEvenAndModulusIs2_thenResultIs0(){ + assertThat(4 % 2).isEqualTo(0); + } + + @Test + public void whenItemsIsAddedToCircularQueue_thenNoArrayIndexOutOfBounds(){ + int QUEUE_CAPACITY= 10; + int[] circularQueue = new int[QUEUE_CAPACITY]; + int itemsInserted = 0; + for (int value = 0; value < 1000; value++) { + int writeIndex = ++itemsInserted % QUEUE_CAPACITY; + circularQueue[writeIndex] = value; + } + } + +} From 45194b5edc1b18ca785aeaf62e0530cc4ed21293 Mon Sep 17 00:00:00 2001 From: rozagerardo Date: Tue, 16 Oct 2018 02:22:19 -0300 Subject: [PATCH 75/75] [BAEL-1502] spring-5-reactive | Validation for Functional Endpoints (#5437) * Added validation for functional endpoints scenarios: * validating in handler explicitly * created abstract handler with validation steps * using validation handlers with two implementations * * added annotated entity to be used with springvalidator * * added tests and cleaning the code slightly --- .../FunctionalValidationsApplication.java | 12 ++ .../handlers/AbstractValidationHandler.java | 45 +++++++ .../handlers/FunctionalHandler.java | 43 +++++++ ...notatedRequestEntityValidationHandler.java | 30 +++++ .../CustomRequestEntityValidationHandler.java | 37 ++++++ .../impl/OtherEntityValidationHandler.java | 28 +++++ .../model/AnnotatedRequestEntity.java | 23 ++++ .../functional/model/CustomRequestEntity.java | 17 +++ .../functional/model/OtherEntity.java | 17 +++ .../routers/ValidationsRouters.java | 29 +++++ .../CustomRequestEntityValidator.java | 29 +++++ .../validators/OtherEntityValidator.java | 27 +++++ ...FunctionalEndpointValidationsLiveTest.java | 111 ++++++++++++++++++ 13 files changed, 448 insertions(+) create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/AbstractValidationHandler.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/FunctionalHandler.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/AnnotatedRequestEntityValidationHandler.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/CustomRequestEntityValidationHandler.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/OtherEntityValidationHandler.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/AnnotatedRequestEntity.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/CustomRequestEntity.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/OtherEntity.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/validators/CustomRequestEntityValidator.java create mode 100644 spring-5-reactive/src/main/java/com/baeldung/validations/functional/validators/OtherEntityValidator.java create mode 100644 spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java new file mode 100644 index 0000000000..e548e33c85 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.validations.functional; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class FunctionalValidationsApplication { + + public static void main(String[] args) { + SpringApplication.run(FunctionalValidationsApplication.class, args); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/AbstractValidationHandler.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/AbstractValidationHandler.java new file mode 100644 index 0000000000..f34c1ee8d8 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/AbstractValidationHandler.java @@ -0,0 +1,45 @@ +package com.baeldung.validations.functional.handlers; + +import org.springframework.http.HttpStatus; +import org.springframework.validation.BeanPropertyBindingResult; +import org.springframework.validation.Errors; +import org.springframework.validation.Validator; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; +import org.springframework.web.server.ResponseStatusException; + +import reactor.core.publisher.Mono; + +public abstract class AbstractValidationHandler { + + private final Class validationClass; + + private final U validator; + + protected AbstractValidationHandler(Class clazz, U validator) { + this.validationClass = clazz; + this.validator = validator; + } + + abstract protected Mono processBody(T validBody, final ServerRequest originalRequest); + + public final Mono handleRequest(final ServerRequest request) { + return request.bodyToMono(this.validationClass) + .flatMap(body -> { + Errors errors = new BeanPropertyBindingResult(body, this.validationClass.getName()); + this.validator.validate(body, errors); + + if (errors == null || errors.getAllErrors() + .isEmpty()) { + return processBody(body, request); + } else { + return onValidationErrors(errors, body, request); + } + }); + } + + protected Mono onValidationErrors(Errors errors, T invalidBody, final ServerRequest request) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, errors.getAllErrors() + .toString()); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/FunctionalHandler.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/FunctionalHandler.java new file mode 100644 index 0000000000..d7e3bd0bc0 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/FunctionalHandler.java @@ -0,0 +1,43 @@ +package com.baeldung.validations.functional.handlers; + +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.validation.BeanPropertyBindingResult; +import org.springframework.validation.Errors; +import org.springframework.validation.Validator; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; +import org.springframework.web.server.ResponseStatusException; + +import com.baeldung.validations.functional.model.CustomRequestEntity; +import com.baeldung.validations.functional.validators.CustomRequestEntityValidator; + +import reactor.core.publisher.Mono; + +@Component +public class FunctionalHandler { + + public Mono handleRequest(final ServerRequest request) { + Validator validator = new CustomRequestEntityValidator(); + Mono responseBody = request.bodyToMono(CustomRequestEntity.class) + .map(body -> { + Errors errors = new BeanPropertyBindingResult(body, CustomRequestEntity.class.getName()); + validator.validate(body, errors); + + if (errors == null || errors.getAllErrors() + .isEmpty()) { + return String.format("Hi, %s [%s]!", body.getName(), body.getCode()); + + } else { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, errors.getAllErrors() + .toString()); + } + + }); + return ServerResponse.ok() + .contentType(MediaType.APPLICATION_JSON) + .body(responseBody, String.class); + + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/AnnotatedRequestEntityValidationHandler.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/AnnotatedRequestEntityValidationHandler.java new file mode 100644 index 0000000000..2011679741 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/AnnotatedRequestEntityValidationHandler.java @@ -0,0 +1,30 @@ +package com.baeldung.validations.functional.handlers.impl; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.validation.Validator; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.validations.functional.handlers.AbstractValidationHandler; +import com.baeldung.validations.functional.model.AnnotatedRequestEntity; + +import reactor.core.publisher.Mono; + +@Component +public class AnnotatedRequestEntityValidationHandler extends AbstractValidationHandler { + + private AnnotatedRequestEntityValidationHandler(@Autowired Validator validator) { + super(AnnotatedRequestEntity.class, validator); + } + + @Override + protected Mono processBody(AnnotatedRequestEntity validBody, ServerRequest originalRequest) { + String responseBody = String.format("Hi, %s. Password: %s!", validBody.getUser(), validBody.getPassword()); + return ServerResponse.ok() + .contentType(MediaType.APPLICATION_JSON) + .body(Mono.just(responseBody), String.class); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/CustomRequestEntityValidationHandler.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/CustomRequestEntityValidationHandler.java new file mode 100644 index 0000000000..34630c60b2 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/CustomRequestEntityValidationHandler.java @@ -0,0 +1,37 @@ +package com.baeldung.validations.functional.handlers.impl; + +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.validation.Errors; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.validations.functional.handlers.AbstractValidationHandler; +import com.baeldung.validations.functional.model.CustomRequestEntity; +import com.baeldung.validations.functional.validators.CustomRequestEntityValidator; + +import reactor.core.publisher.Mono; + +@Component +public class CustomRequestEntityValidationHandler extends AbstractValidationHandler { + + private CustomRequestEntityValidationHandler() { + super(CustomRequestEntity.class, new CustomRequestEntityValidator()); + } + + @Override + protected Mono processBody(CustomRequestEntity validBody, ServerRequest originalRequest) { + String responseBody = String.format("Hi, %s [%s]!", validBody.getName(), validBody.getCode()); + return ServerResponse.ok() + .contentType(MediaType.APPLICATION_JSON) + .body(Mono.just(responseBody), String.class); + } + + @Override + protected Mono onValidationErrors(Errors errors, CustomRequestEntity invalidBody, final ServerRequest request) { + return ServerResponse.badRequest() + .contentType(MediaType.APPLICATION_JSON) + .body(Mono.just(String.format("Custom message showing the errors: %s", errors.getAllErrors() + .toString())), String.class); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/OtherEntityValidationHandler.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/OtherEntityValidationHandler.java new file mode 100644 index 0000000000..0196287d13 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/handlers/impl/OtherEntityValidationHandler.java @@ -0,0 +1,28 @@ +package com.baeldung.validations.functional.handlers.impl; + +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.web.reactive.function.server.ServerRequest; +import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.validations.functional.handlers.AbstractValidationHandler; +import com.baeldung.validations.functional.model.OtherEntity; +import com.baeldung.validations.functional.validators.OtherEntityValidator; + +import reactor.core.publisher.Mono; + +@Component +public class OtherEntityValidationHandler extends AbstractValidationHandler { + + private OtherEntityValidationHandler() { + super(OtherEntity.class, new OtherEntityValidator()); + } + + @Override + protected Mono processBody(OtherEntity validBody, ServerRequest originalRequest) { + String responseBody = String.format("Other object with item %s and quantity %s!", validBody.getItem(), validBody.getQuantity()); + return ServerResponse.ok() + .contentType(MediaType.APPLICATION_JSON) + .body(Mono.just(responseBody), String.class); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/AnnotatedRequestEntity.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/AnnotatedRequestEntity.java new file mode 100644 index 0000000000..992f07481c --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/AnnotatedRequestEntity.java @@ -0,0 +1,23 @@ +package com.baeldung.validations.functional.model; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@AllArgsConstructor +@NoArgsConstructor +@Getter +@Setter +public class AnnotatedRequestEntity { + @NotNull + private String user; + + @NotNull + @Size(min = 4, max = 7) + private String password; + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/CustomRequestEntity.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/CustomRequestEntity.java new file mode 100644 index 0000000000..ed459f121b --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/CustomRequestEntity.java @@ -0,0 +1,17 @@ +package com.baeldung.validations.functional.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@AllArgsConstructor +@NoArgsConstructor +@Getter +@Setter +public class CustomRequestEntity { + + private String name; + private String code; + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/OtherEntity.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/OtherEntity.java new file mode 100644 index 0000000000..78667cb13d --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/model/OtherEntity.java @@ -0,0 +1,17 @@ +package com.baeldung.validations.functional.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@AllArgsConstructor +@NoArgsConstructor +@Getter +@Setter +public class OtherEntity { + + private String item; + private Integer quantity; + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java new file mode 100644 index 0000000000..efbdbe3f99 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/routers/ValidationsRouters.java @@ -0,0 +1,29 @@ +package com.baeldung.validations.functional.routers; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.function.server.RequestPredicates; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; + +import com.baeldung.validations.functional.handlers.FunctionalHandler; +import com.baeldung.validations.functional.handlers.impl.AnnotatedRequestEntityValidationHandler; +import com.baeldung.validations.functional.handlers.impl.CustomRequestEntityValidationHandler; +import com.baeldung.validations.functional.handlers.impl.OtherEntityValidationHandler; + +@Configuration +public class ValidationsRouters { + + @Bean + public RouterFunction responseHeaderRoute(@Autowired CustomRequestEntityValidationHandler dryHandler, + @Autowired FunctionalHandler complexHandler, + @Autowired OtherEntityValidationHandler otherHandler, + @Autowired AnnotatedRequestEntityValidationHandler annotatedEntityHandler) { + return RouterFunctions.route(RequestPredicates.POST("/complex-handler-functional-validation"), complexHandler::handleRequest) + .andRoute(RequestPredicates.POST("/dry-functional-validation"), dryHandler::handleRequest) + .andRoute(RequestPredicates.POST("/other-dry-functional-validation"), otherHandler::handleRequest) + .andRoute(RequestPredicates.POST("/annotated-functional-validation"), annotatedEntityHandler::handleRequest); + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/validators/CustomRequestEntityValidator.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/validators/CustomRequestEntityValidator.java new file mode 100644 index 0000000000..085d477318 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/validators/CustomRequestEntityValidator.java @@ -0,0 +1,29 @@ +package com.baeldung.validations.functional.validators; + +import org.springframework.validation.Errors; +import org.springframework.validation.ValidationUtils; +import org.springframework.validation.Validator; + +import com.baeldung.validations.functional.model.CustomRequestEntity; + +public class CustomRequestEntityValidator implements Validator { + + private static final int MINIMUM_CODE_LENGTH = 6; + + @Override + public boolean supports(Class clazz) { + return CustomRequestEntity.class.isAssignableFrom(clazz); + } + + @Override + public void validate(Object target, Errors errors) { + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "field.required"); + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "code", "field.required"); + CustomRequestEntity request = (CustomRequestEntity) target; + if (request.getCode() != null && request.getCode() + .trim() + .length() < MINIMUM_CODE_LENGTH) { + errors.rejectValue("code", "field.min.length", new Object[] { Integer.valueOf(MINIMUM_CODE_LENGTH) }, "The code must be at least [" + MINIMUM_CODE_LENGTH + "] characters in length."); + } + } +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/validations/functional/validators/OtherEntityValidator.java b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/validators/OtherEntityValidator.java new file mode 100644 index 0000000000..18c2c28cfe --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/validations/functional/validators/OtherEntityValidator.java @@ -0,0 +1,27 @@ +package com.baeldung.validations.functional.validators; + +import org.springframework.validation.Errors; +import org.springframework.validation.ValidationUtils; +import org.springframework.validation.Validator; + +import com.baeldung.validations.functional.model.OtherEntity; + +public class OtherEntityValidator implements Validator { + + private static final int MIN_ITEM_QUANTITY = 1; + + @Override + public boolean supports(Class clazz) { + return OtherEntity.class.isAssignableFrom(clazz); + } + + @Override + public void validate(Object target, Errors errors) { + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "item", "field.required"); + ValidationUtils.rejectIfEmptyOrWhitespace(errors, "quantity", "field.required"); + OtherEntity request = (OtherEntity) target; + if (request.getQuantity() != null && request.getQuantity() < MIN_ITEM_QUANTITY) { + errors.rejectValue("quantity", "field.min.length", new Object[] { Integer.valueOf(MIN_ITEM_QUANTITY) }, "There must be at least one item"); + } + } +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java b/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java new file mode 100644 index 0000000000..5fe764bf8f --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/validations/functional/FunctionalEndpointValidationsLiveTest.java @@ -0,0 +1,111 @@ +package com.baeldung.validations.functional; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; + +import com.baeldung.validations.functional.model.AnnotatedRequestEntity; +import com.baeldung.validations.functional.model.CustomRequestEntity; + +import reactor.core.publisher.Mono; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class FunctionalEndpointValidationsLiveTest { + + private static final String BASE_URL = "http://localhost:8080"; + private static final String COMPLEX_EP_URL = BASE_URL + "/complex-handler-functional-validation"; + private static final String DRY_EP_URL = BASE_URL + "/dry-functional-validation"; + private static final String ANNOTATIONS_EP_URL = BASE_URL + "/annotated-functional-validation"; + + private static WebTestClient client; + + @BeforeAll + public static void setup() { + client = WebTestClient.bindToServer() + .baseUrl(BASE_URL) + .build(); + } + + @Test + public void whenRequestingDryEPWithInvalidBody_thenObtainBadRequest() { + CustomRequestEntity body = new CustomRequestEntity("name", "123"); + + ResponseSpec response = client.post() + .uri(DRY_EP_URL) + .body(Mono.just(body), CustomRequestEntity.class) + .exchange(); + + response.expectStatus() + .isBadRequest(); + } + + @Test + public void whenRequestingComplexEPWithInvalidBody_thenObtainBadRequest() { + CustomRequestEntity body = new CustomRequestEntity("name", "123"); + + ResponseSpec response = client.post() + .uri(COMPLEX_EP_URL) + .body(Mono.just(body), CustomRequestEntity.class) + .exchange(); + + response.expectStatus() + .isBadRequest(); + } + + @Test + public void whenRequestingAnnotatedEPWithInvalidBody_thenObtainBadRequest() { + AnnotatedRequestEntity body = new AnnotatedRequestEntity("user", "passwordlongerthan7digits"); + + ResponseSpec response = client.post() + .uri(ANNOTATIONS_EP_URL) + .body(Mono.just(body), AnnotatedRequestEntity.class) + .exchange(); + + response.expectStatus() + .isBadRequest(); + } + + @Test + public void whenRequestingDryEPWithValidBody_thenObtainBadRequest() { + CustomRequestEntity body = new CustomRequestEntity("name", "1234567"); + + ResponseSpec response = client.post() + .uri(DRY_EP_URL) + .body(Mono.just(body), CustomRequestEntity.class) + .exchange(); + + response.expectStatus() + .isOk(); + } + + @Test + public void whenRequestingComplexEPWithValidBody_thenObtainBadRequest() { + CustomRequestEntity body = new CustomRequestEntity("name", "1234567"); + + ResponseSpec response = client.post() + .uri(COMPLEX_EP_URL) + .body(Mono.just(body), CustomRequestEntity.class) + .exchange(); + + response.expectStatus() + .isOk(); + } + + @Test + public void whenRequestingAnnotatedEPWithValidBody_thenObtainBadRequest() { + AnnotatedRequestEntity body = new AnnotatedRequestEntity("user", "12345"); + + ResponseSpec response = client.post() + .uri(ANNOTATIONS_EP_URL) + .body(Mono.just(body), AnnotatedRequestEntity.class) + .exchange(); + + response.expectStatus() + .isOk(); + } +}