From 0dab47c76d3a5c8e6a8239929301e86b7a993545 Mon Sep 17 00:00:00 2001 From: Senthil Kumar Subramanian Date: Sun, 25 Mar 2018 21:06:38 +0530 Subject: [PATCH 01/46] Spring-dependency injection --- Spring-DependencyInjection/pom.xml | 30 +++++++++ .../src/main/java/beans.xml | 31 ++++++++++ .../com/baeldung/spring/core/Address.java | 53 ++++++++++++++++ .../java/com/baeldung/spring/core/Car.java | 30 +++++++++ .../com/baeldung/spring/core/Customer.java | 61 +++++++++++++++++++ .../com/baeldung/spring/core/Department.java | 31 ++++++++++ .../com/baeldung/spring/core/Employee.java | 23 +++++++ .../com/baeldung/spring/core/Product.java | 48 +++++++++++++++ .../com/baeldung/spring/core/Student.java | 40 ++++++++++++ .../com/baeldung/spring/core/Subject.java | 30 +++++++++ .../spring/core/config/AppConfig.java | 30 +++++++++ .../AnnotationApplicationContextTest.java | 17 ++++++ .../JavaConfigApplicationContextTest.java | 23 +++++++ ...MLConfigurationApplicationContextTest.java | 28 +++++++++ .../Spring_DependencyInjection/AppTest.java | 38 ++++++++++++ 15 files changed, 513 insertions(+) create mode 100644 Spring-DependencyInjection/pom.xml create mode 100644 Spring-DependencyInjection/src/main/java/beans.xml create mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Address.java create mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Car.java create mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Customer.java create mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Department.java create mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Employee.java create mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Product.java create mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Student.java create mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Subject.java create mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/config/AppConfig.java create mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/AnnotationApplicationContextTest.java create mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/JavaConfigApplicationContextTest.java create mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/XMLConfigurationApplicationContextTest.java create mode 100644 Spring-DependencyInjection/src/test/java/com/spring/core/Spring_DependencyInjection/AppTest.java diff --git a/Spring-DependencyInjection/pom.xml b/Spring-DependencyInjection/pom.xml new file mode 100644 index 0000000000..cc818f948b --- /dev/null +++ b/Spring-DependencyInjection/pom.xml @@ -0,0 +1,30 @@ + + 4.0.0 + + com.spring.core + Spring-DependencyInjection + 0.0.1-SNAPSHOT + jar + + Spring-DependencyInjection + http://maven.apache.org + + + UTF-8 + + + + + org.springframework + spring-context + 4.3.14.RELEASE + + + junit + junit + 3.8.1 + test + + + diff --git a/Spring-DependencyInjection/src/main/java/beans.xml b/Spring-DependencyInjection/src/main/java/beans.xml new file mode 100644 index 0000000000..71de8d3293 --- /dev/null +++ b/Spring-DependencyInjection/src/main/java/beans.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Address.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Address.java new file mode 100644 index 0000000000..9e6fe29c0c --- /dev/null +++ b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Address.java @@ -0,0 +1,53 @@ +package com.baeldung.spring.core; + +import org.springframework.stereotype.Component; + +@Component +public class Address { + + private String address1; + + private String city; + + private String state; + + private String country; + + public String getAddress1() { + return address1; + } + + public void setAddress1(String address1) { + this.address1 = address1; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + @Override + public String toString() { + return "Address [address1=" + address1 + ", city=" + city + ", state=" + state + ", country=" + country + "]"; + } + +} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Car.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Car.java new file mode 100644 index 0000000000..3f940e1e28 --- /dev/null +++ b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Car.java @@ -0,0 +1,30 @@ +package com.baeldung.spring.core; + +public class Car { + + private String carName; + + private String carType; + + public String getCarName() { + return carName; + } + + public void setCarName(String carName) { + this.carName = carName; + } + + public String getCarType() { + return carType; + } + + public void setCarType(String carType) { + this.carType = carType; + } + + @Override + public String toString() { + return "Car [carName=" + carName + ", carType=" + carType + "]"; + } + +} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Customer.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Customer.java new file mode 100644 index 0000000000..da9ac13021 --- /dev/null +++ b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Customer.java @@ -0,0 +1,61 @@ +package com.baeldung.spring.core; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class Customer { + + @Value("Thomas") + private String customerName; + + @Value("Cust123") + private String customerId; + + private Product product; + + private Address address; + + @Autowired + public Customer(Address address) { + super(); + this.address = address; + } + + public String getCustomerName() { + return customerName; + } + + public void setCustomerName(String customerName) { + this.customerName = customerName; + } + + public String getCustomerId() { + return customerId; + } + + public void setCustomerId(String customerId) { + this.customerId = customerId; + } + + public Product getProduct() { + return product; + } + + @Autowired + public void setProduct(Product product) { + this.product = product; + } + + public Address getAddress() { + return address; + } + + @Override + public String toString() { + return "Customer [customerName=" + customerName + ", customerId=" + customerId + ", product=" + product + + ", address=" + address + "]"; + } + +} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Department.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Department.java new file mode 100644 index 0000000000..f7da2d560a --- /dev/null +++ b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Department.java @@ -0,0 +1,31 @@ +package com.baeldung.spring.core; + +import org.springframework.stereotype.Component; + +@Component +public class Department { + + private String departmentName; + + private String departmentId; + + public Department(String departmentName, String departmentNumber) { + super(); + this.departmentName = departmentName; + this.departmentId = departmentNumber; + } + + public String getDepartmentName() { + return departmentName; + } + + public String getDepartmentId() { + return departmentId; + } + + @Override + public String toString() { + return "Department [departmentName=" + departmentName + ", departmentNumber=" + departmentId + "]"; + } + +} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Employee.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Employee.java new file mode 100644 index 0000000000..de450b8e6b --- /dev/null +++ b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Employee.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.core; + +import org.springframework.stereotype.Component; + +@Component +public class Employee { + + private Department department; + + public Employee(Department department) { + super(); + this.department = department; + } + + public Department getDepartment() { + return department; + } + + @Override + public String toString() { + return "Employee [department=" + department + "]"; + } +} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Product.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Product.java new file mode 100644 index 0000000000..162c9b3429 --- /dev/null +++ b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Product.java @@ -0,0 +1,48 @@ +package com.baeldung.spring.core; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class Product { + + @Value("product1") + private String productName; + + @Value("Pro123") + private String productId; + + @Value("100") + private String productCost; + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public String getProductCost() { + return productCost; + } + + public void setProductCost(String productCost) { + this.productCost = productCost; + } + + @Override + public String toString() { + return "Product [productName=" + productName + ", productId=" + productId + ", productCost=" + productCost + + "]"; + } + +} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Student.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Student.java new file mode 100644 index 0000000000..f2563f01ec --- /dev/null +++ b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Student.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.core; + +public class Student { + + private String studentName; + + private String studentId; + + private Subject subject; + + public String getStudentName() { + return studentName; + } + + public void setStudentName(String studentName) { + this.studentName = studentName; + } + + public String getStudentId() { + return studentId; + } + + public void setStudentId(String studentId) { + this.studentId = studentId; + } + + public Subject getSubject() { + return subject; + } + + public void setSubject(Subject subject) { + this.subject = subject; + } + + @Override + public String toString() { + return "Student [studentName=" + studentName + ", studentId=" + studentId + ", subject=" + subject + "]"; + } + +} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Subject.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Subject.java new file mode 100644 index 0000000000..b160bbef18 --- /dev/null +++ b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Subject.java @@ -0,0 +1,30 @@ +package com.baeldung.spring.core; + +public class Subject { + + private String subjectName; + + private String subjectId; + + public String getSubjectName() { + return subjectName; + } + + public void setSubjectName(String subjectName) { + this.subjectName = subjectName; + } + + public String getSubjectId() { + return subjectId; + } + + public void setSubjectId(String subjectId) { + this.subjectId = subjectId; + } + + @Override + public String toString() { + return "Subject [subjectName=" + subjectName + ", subjectId=" + subjectId + "]"; + } + +} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/config/AppConfig.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/config/AppConfig.java new file mode 100644 index 0000000000..496191d758 --- /dev/null +++ b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/config/AppConfig.java @@ -0,0 +1,30 @@ +package com.baeldung.spring.core.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.spring.core.Car; +import com.baeldung.spring.core.Department; +import com.baeldung.spring.core.Employee; + +@Configuration +public class AppConfig { + + @Bean + public Department getDepartment() { + return new Department("Sales", "S01"); + } + + @Bean + public Employee getEmployee() { + return new Employee(getDepartment()); + } + + @Bean + public Car getCar() { + Car car = new Car(); + car.setCarName("Honda"); + car.setCarType("SUV"); + return car; + } +} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/AnnotationApplicationContextTest.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/AnnotationApplicationContextTest.java new file mode 100644 index 0000000000..02daf26eb2 --- /dev/null +++ b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/AnnotationApplicationContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.core.test; + +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import com.baeldung.spring.core.Customer; + +public class AnnotationApplicationContextTest { + + public static void main(String[] args) { + AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); + Customer customer = applicationContext.getBean(Customer.class); + System.out.println("Customer is :: " + customer); + System.out.println("Product is :: " + customer.getProduct()); + applicationContext.close(); + } +} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/JavaConfigApplicationContextTest.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/JavaConfigApplicationContextTest.java new file mode 100644 index 0000000000..01b0c67675 --- /dev/null +++ b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/JavaConfigApplicationContextTest.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.core.test; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.support.AbstractApplicationContext; + +import com.baeldung.spring.core.Car; +import com.baeldung.spring.core.Department; +import com.baeldung.spring.core.Employee; +import com.baeldung.spring.core.config.AppConfig; + +public class JavaConfigApplicationContextTest { + + public static void main(String[] args) { + AbstractApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); + Department department = applicationContext.getBean(Department.class); + Employee employee = applicationContext.getBean(Employee.class); + System.out.println("Department is :: " + department); + System.out.println("Employee is :: " + employee); + Car car = applicationContext.getBean(Car.class); + System.out.println("Car is :: " + car); + applicationContext.close(); + } +} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/XMLConfigurationApplicationContextTest.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/XMLConfigurationApplicationContextTest.java new file mode 100644 index 0000000000..ead4226f1b --- /dev/null +++ b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/XMLConfigurationApplicationContextTest.java @@ -0,0 +1,28 @@ +package com.baeldung.spring.core.test; + +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import com.baeldung.spring.core.Department; +import com.baeldung.spring.core.Employee; +import com.baeldung.spring.core.Student; +import com.baeldung.spring.core.Subject; + +public class XMLConfigurationApplicationContextTest { + + public static void main(String[] args) { + AbstractApplicationContext abstractApplicationContext = new ClassPathXmlApplicationContext("beans.xml"); + // Constructor Injection + Department department = (Department) abstractApplicationContext.getBean("department"); + Employee employee = (Employee) abstractApplicationContext.getBean("employee"); + System.out.println("Department is :: " + department); + System.out.println("Employee is :: " + employee); + + // Setter Injection + Subject subject = (Subject) abstractApplicationContext.getBean("subject"); + Student student = (Student) abstractApplicationContext.getBean("student"); + System.out.println("Subject is :: " + subject); + System.out.println("Student is :: " + student); + abstractApplicationContext.close(); + } +} diff --git a/Spring-DependencyInjection/src/test/java/com/spring/core/Spring_DependencyInjection/AppTest.java b/Spring-DependencyInjection/src/test/java/com/spring/core/Spring_DependencyInjection/AppTest.java new file mode 100644 index 0000000000..5b3c551257 --- /dev/null +++ b/Spring-DependencyInjection/src/test/java/com/spring/core/Spring_DependencyInjection/AppTest.java @@ -0,0 +1,38 @@ +package com.spring.core.Spring_DependencyInjection; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Unit test for simple App. + */ +public class AppTest + extends TestCase +{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public AppTest( String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( AppTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + assertTrue( true ); + } +} From f4feab9212a4bce79c79530960a139eced155fd9 Mon Sep 17 00:00:00 2001 From: Denis Zhdanov Date: Mon, 2 Apr 2018 00:36:53 +0300 Subject: [PATCH 02/46] BAEL-1423 Java Concurrency Utility with JCTools Library --- jctools/README.md | 11 ++ jctools/pom.xml | 108 ++++++++++++++++++ .../com/baeldung/jctools/MpmcBenchmark.java | 98 ++++++++++++++++ .../com/baeldung/jctools/JCToolsUnitTest.java | 86 ++++++++++++++ 4 files changed, 303 insertions(+) create mode 100644 jctools/README.md create mode 100644 jctools/pom.xml create mode 100644 jctools/src/main/java/com/baeldung/jctools/MpmcBenchmark.java create mode 100644 jctools/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java diff --git a/jctools/README.md b/jctools/README.md new file mode 100644 index 0000000000..181e45c1ca --- /dev/null +++ b/jctools/README.md @@ -0,0 +1,11 @@ +## Overview + +This project holds a [couple of tests](./src/test/java/com/baeldung/jctools/JCToolsUnitTest.java) which illustrate JCTools specifics and a [benchmark](./src/main/java/com/baeldung/jctools/MpmcBenchmark.java) in the [JMH](http://openjdk.java.net/projects/code-tools/jmh/) format. + +## How to build and run the JMH benchmark + +Execute the following from the project's root: +```bash +mvn clean install +java -jar ./target/benchmarks.jar MpmcBenchmark -si true +``` \ No newline at end of file diff --git a/jctools/pom.xml b/jctools/pom.xml new file mode 100644 index 0000000000..8a21c610de --- /dev/null +++ b/jctools/pom.xml @@ -0,0 +1,108 @@ + + 4.0.0 + + com.baeldung + jctools + 0.0.1-SNAPSHOT + + jctools + + + + org.jctools + jctools-core + ${jctools.version} + + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + provided + + + + junit + junit + 4.12 + test + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + 2.1.2 + 3.9.1 + 1.20 + + 1.8 + + benchmarks + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${javac.target} + ${javac.target} + ${javac.target} + + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.2 + + + package + + shade + + + ${uberjar.name} + + + org.openjdk.jmh.Main + + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + + + + + \ No newline at end of file diff --git a/jctools/src/main/java/com/baeldung/jctools/MpmcBenchmark.java b/jctools/src/main/java/com/baeldung/jctools/MpmcBenchmark.java new file mode 100644 index 0000000000..0e543fa609 --- /dev/null +++ b/jctools/src/main/java/com/baeldung/jctools/MpmcBenchmark.java @@ -0,0 +1,98 @@ +package com.baeldung.jctools; + +import org.jctools.queues.MpmcArrayQueue; +import org.jctools.queues.atomic.MpmcAtomicArrayQueue; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Control; + +import java.util.Queue; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.SampleTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Fork(1) +@Warmup(iterations = 1) +@Measurement(iterations = 3) +public class MpmcBenchmark { + + public static final String GROUP_UNSAFE = "MpmcArrayQueue"; + public static final String GROUP_AFU = "MpmcAtomicArrayQueue"; + public static final String GROUP_JDK = "ArrayBlockingQueue"; + + public static final int PRODUCER_THREADS_NUMBER = 32; + public static final int CONSUMER_THREADS_NUMBER = 32; + + public static final int CAPACITY = 128; + + @State(Scope.Group) + public static class Mpmc { + public final Queue queue = new MpmcArrayQueue<>(CAPACITY); + } + + @State(Scope.Group) + public static class MpmcAtomic { + public final Queue queue = new MpmcAtomicArrayQueue<>(CAPACITY); + } + + @State(Scope.Group) + public static class Jdk { + public final Queue queue = new ArrayBlockingQueue<>(CAPACITY); + } + + @Benchmark + @Group(GROUP_UNSAFE) + @GroupThreads(PRODUCER_THREADS_NUMBER) + public void mpmcWrite(Control control, Mpmc state) { + write(control, state.queue); + } + + @Benchmark + @Group(GROUP_UNSAFE) + @GroupThreads(CONSUMER_THREADS_NUMBER) + public void mpmcRead(Control control, Mpmc state) { + read(control, state.queue); + } + + @Benchmark + @Group(GROUP_AFU) + @GroupThreads(PRODUCER_THREADS_NUMBER) + public void mpmcAtomicWrite(Control control, MpmcAtomic state) { + write(control, state.queue); + } + + @Benchmark + @Group(GROUP_AFU) + @GroupThreads(CONSUMER_THREADS_NUMBER) + public void mpmcAtomicRead(Control control, MpmcAtomic state) { + read(control, state.queue); + } + + @Benchmark + @Group(GROUP_JDK) + @GroupThreads(PRODUCER_THREADS_NUMBER) + public void jdkWrite(Control control, Jdk state) { + write(control, state.queue); + } + + @Benchmark + @Group(GROUP_JDK) + @GroupThreads(CONSUMER_THREADS_NUMBER) + public void jdkRead(Control control, Jdk state) { + read(control, state.queue); + } + + private void write(Control control, Queue queue) { + //noinspection StatementWithEmptyBody + while (!control.stopMeasurement && !queue.offer(1L)) { + // Is intentionally left blank + } + } + + private void read(Control control, Queue queue) { + //noinspection StatementWithEmptyBody + while (!control.stopMeasurement && queue.poll() == null) { + // Is intentionally left blank + } + } +} diff --git a/jctools/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java b/jctools/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java new file mode 100644 index 0000000000..4a9d0fadb2 --- /dev/null +++ b/jctools/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java @@ -0,0 +1,86 @@ +package com.baeldung.jctools; + +import org.jctools.queues.SpscArrayQueue; +import org.jctools.queues.SpscChunkedArrayQueue; +import org.junit.Test; + +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.IntConsumer; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +public class JCToolsUnitTest { + + @Test + public void givenMultipleProducers_whenSpscQueueUsed_thenNoWarningOccurs() throws InterruptedException { + SpscArrayQueue queue = new SpscArrayQueue(2); + + Thread producer1 = new Thread(() -> { + queue.offer(1); + }); + producer1.start(); + producer1.join(); + + Thread producer2 = new Thread(() -> { + queue.offer(2); + }); + producer2.start(); + producer2.join(); + + Set fromQueue = new HashSet<>(); + Thread consumer = new Thread(() -> queue.drain(fromQueue::add)); + consumer.start(); + consumer.join(); + + assertThat(fromQueue).containsOnly(1, 2); + } + + @Test + public void whenQueueIsFull_thenNoMoreElementsCanBeAdded() throws InterruptedException { + SpscChunkedArrayQueue queue = new SpscChunkedArrayQueue<>(8, 16); + assertThat(queue.capacity()).isEqualTo(16); + + CountDownLatch startConsuming = new CountDownLatch(1); + CountDownLatch awakeProducer = new CountDownLatch(1); + AtomicReference error = new AtomicReference<>(); + Thread producer = new Thread(() -> { + IntStream.range(0, queue.capacity()).forEach(i -> { + assertThat(queue.offer(i)).isTrue(); + }); + assertThat(queue.offer(queue.capacity())).isFalse(); + startConsuming.countDown(); + try { + awakeProducer.await(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + + assertThat(queue.offer(queue.capacity())).isTrue(); + }); + producer.setUncaughtExceptionHandler((t, e) -> { + error.set(e); + startConsuming.countDown(); + }); + producer.start(); + + startConsuming.await(); + + if (error.get() != null) { + fail("Producer's assertion failed", error.get()); + } + + Set fromQueue = new HashSet<>(); + queue.drain(fromQueue::add); + awakeProducer.countDown(); + producer.join(); + queue.drain(fromQueue::add); + + assertThat(fromQueue).containsAll(IntStream.range(0, 17).boxed().collect(Collectors.toSet())); + } +} From b296e9a4962fe598913c23945a45c181f29fb4d2 Mon Sep 17 00:00:00 2001 From: Denis Zhdanov Date: Mon, 2 Apr 2018 04:32:05 +0300 Subject: [PATCH 03/46] BAEL-1423 Java Concurrency Utility with JCTools Library Refactored JMH benchmark after digging deeper into its features --- .../com/baeldung/jctools/MpmcBenchmark.java | 89 +++++++------------ 1 file changed, 32 insertions(+), 57 deletions(-) diff --git a/jctools/src/main/java/com/baeldung/jctools/MpmcBenchmark.java b/jctools/src/main/java/com/baeldung/jctools/MpmcBenchmark.java index 0e543fa609..7b754bf709 100644 --- a/jctools/src/main/java/com/baeldung/jctools/MpmcBenchmark.java +++ b/jctools/src/main/java/com/baeldung/jctools/MpmcBenchmark.java @@ -14,82 +14,57 @@ import java.util.concurrent.TimeUnit; @Fork(1) @Warmup(iterations = 1) @Measurement(iterations = 3) +@State(Scope.Group) public class MpmcBenchmark { - public static final String GROUP_UNSAFE = "MpmcArrayQueue"; - public static final String GROUP_AFU = "MpmcAtomicArrayQueue"; - public static final String GROUP_JDK = "ArrayBlockingQueue"; + public static final String PARAM_UNSAFE = "MpmcArrayQueue"; + public static final String PARAM_AFU = "MpmcAtomicArrayQueue"; + public static final String PARAM_JDK = "ArrayBlockingQueue"; public static final int PRODUCER_THREADS_NUMBER = 32; public static final int CONSUMER_THREADS_NUMBER = 32; + public static final String GROUP_NAME = "MyGroup"; + public static final int CAPACITY = 128; - @State(Scope.Group) - public static class Mpmc { - public final Queue queue = new MpmcArrayQueue<>(CAPACITY); + @Param({PARAM_UNSAFE, PARAM_AFU, PARAM_JDK}) + public volatile String implementation; + + public volatile Queue queue; + + @Setup(Level.Trial) + public void setUp() { + switch (implementation) { + case PARAM_UNSAFE: + queue = new MpmcArrayQueue<>(CAPACITY); + break; + case PARAM_AFU: + queue = new MpmcAtomicArrayQueue<>(CAPACITY); + break; + case PARAM_JDK: + queue = new ArrayBlockingQueue<>(CAPACITY); + break; + default: + throw new UnsupportedOperationException("Unsupported implementation " + implementation); + } } - @State(Scope.Group) - public static class MpmcAtomic { - public final Queue queue = new MpmcAtomicArrayQueue<>(CAPACITY); - } - - @State(Scope.Group) - public static class Jdk { - public final Queue queue = new ArrayBlockingQueue<>(CAPACITY); - } @Benchmark - @Group(GROUP_UNSAFE) + @Group(GROUP_NAME) @GroupThreads(PRODUCER_THREADS_NUMBER) - public void mpmcWrite(Control control, Mpmc state) { - write(control, state.queue); - } - - @Benchmark - @Group(GROUP_UNSAFE) - @GroupThreads(CONSUMER_THREADS_NUMBER) - public void mpmcRead(Control control, Mpmc state) { - read(control, state.queue); - } - - @Benchmark - @Group(GROUP_AFU) - @GroupThreads(PRODUCER_THREADS_NUMBER) - public void mpmcAtomicWrite(Control control, MpmcAtomic state) { - write(control, state.queue); - } - - @Benchmark - @Group(GROUP_AFU) - @GroupThreads(CONSUMER_THREADS_NUMBER) - public void mpmcAtomicRead(Control control, MpmcAtomic state) { - read(control, state.queue); - } - - @Benchmark - @Group(GROUP_JDK) - @GroupThreads(PRODUCER_THREADS_NUMBER) - public void jdkWrite(Control control, Jdk state) { - write(control, state.queue); - } - - @Benchmark - @Group(GROUP_JDK) - @GroupThreads(CONSUMER_THREADS_NUMBER) - public void jdkRead(Control control, Jdk state) { - read(control, state.queue); - } - - private void write(Control control, Queue queue) { + public void write(Control control) { //noinspection StatementWithEmptyBody while (!control.stopMeasurement && !queue.offer(1L)) { // Is intentionally left blank } } - private void read(Control control, Queue queue) { + @Benchmark + @Group(GROUP_NAME) + @GroupThreads(CONSUMER_THREADS_NUMBER) + public void read(Control control) { //noinspection StatementWithEmptyBody while (!control.stopMeasurement && queue.poll() == null) { // Is intentionally left blank From b2dfcd9469ea94c3d339e145d6df5aa17d79d63f Mon Sep 17 00:00:00 2001 From: Senthil Kumar Subramanian Date: Sun, 8 Apr 2018 16:39:10 +0530 Subject: [PATCH 04/46] BAEL-1683-Guide to Java Clock class --- .../java/com/baeldung/clock/ClockExample.java | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/clock/ClockExample.java diff --git a/core-java/src/main/java/com/baeldung/clock/ClockExample.java b/core-java/src/main/java/com/baeldung/clock/ClockExample.java new file mode 100644 index 0000000000..c28f9102a6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/clock/ClockExample.java @@ -0,0 +1,83 @@ +package com.baeldung.clock; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; + +public class ClockExample { + + public static void main(String[] args) { + + // gets systemUTC + Clock clockUTC = Clock.systemUTC(); + System.out.println("UTC time :: " + clockUTC.instant()); + + // using system() + Clock clockSystem = Clock.system(ZoneId.of("Asia/Kolkata")); + System.out.println(clockSystem.instant()); + + // gets systemDefaultZone + Clock clockSystemDefault = Clock.systemDefaultZone(); + System.out.println(clockSystemDefault); + clockSystemDefault = Clock.system(ZoneId.systemDefault()); + System.out.println(clockSystemDefault); + + // gets instant from system default zone + Clock clockInstant = Clock.systemDefaultZone(); + Instant instant = clockInstant.instant(); + System.out.println(instant); + + // gets millis + Clock millis = Clock.systemDefaultZone(); + System.out.println(millis.millis()); + System.out.println(System.currentTimeMillis()); + + // using offset + + Clock baseClock = Clock.systemDefaultZone(); + // result clock will be later than baseClock + Clock clock5 = Clock.offset(baseClock, Duration.ofHours(72)); + System.out.println(clock5.instant()); + + // result clock will be same as baseClock + clock5 = Clock.offset(baseClock, Duration.ZERO); + System.out.println(clock5.instant()); + + // result clock will be earlier than baseClock + clock5 = Clock.offset(baseClock, Duration.ofHours(-72)); + System.out.println(clock5.instant()); + + // using tick + Clock clockDefaultZone = Clock.systemDefaultZone(); + Clock clocktick = Clock.tick(clockDefaultZone, Duration.ofSeconds(30)); + System.out.println("Clock Default Zone : " + clockDefaultZone.instant()); + System.out.println("Clock tick : " + clocktick.instant()); + + // using tickMinutes + Clock tickMinutes = Clock.tickMinutes(ZoneId.of("Asia/Kolkata")); + System.out.println(tickMinutes.instant()); + tickMinutes = Clock.tick(Clock.system(ZoneId.of("Asia/Kolkata")), Duration.ofMinutes(1)); + System.out.println(tickMinutes.instant()); + + // using tickSeconds + ZoneId zoneId = ZoneId.of("Asia/Calcutta"); + Clock tickSeconds = Clock.tickSeconds(zoneId); + System.out.println(tickSeconds.instant()); + tickSeconds = Clock.tick(Clock.system(ZoneId.of("Asia/Kolkata")), Duration.ofSeconds(1)); + System.out.println(tickSeconds.instant()); + + // using withZone + ZoneId zone1 = ZoneId.of("Asia/Singapore"); + Clock clock11 = Clock.system(zone1); + System.out.println(clock11.instant()); + + ZoneId zone2 = ZoneId.of("Asia/Kolkata"); + Clock clock21 = clock11.withZone(zone2); + System.out.println(clock21.instant()); + + ZoneId zone = clockDefaultZone.getZone(); + System.out.println(zone.getId()); + + } +} From b9d21e3210738acd9ea80da2c247f0ff0305dbd7 Mon Sep 17 00:00:00 2001 From: Senthil Kumar Subramanian Date: Thu, 12 Apr 2018 07:42:42 +0530 Subject: [PATCH 05/46] BAEL-1683-Guide to Java Clock class --- .../java/com/baeldung/clock/ClockExample.java | 83 --------- .../baeldung/java/clock/ClockUnitTest.java | 159 ++++++++++++++++++ 2 files changed, 159 insertions(+), 83 deletions(-) delete mode 100644 core-java/src/main/java/com/baeldung/clock/ClockExample.java create mode 100644 core-java/src/test/java/com/baeldung/java/clock/ClockUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/clock/ClockExample.java b/core-java/src/main/java/com/baeldung/clock/ClockExample.java deleted file mode 100644 index c28f9102a6..0000000000 --- a/core-java/src/main/java/com/baeldung/clock/ClockExample.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.baeldung.clock; - -import java.time.Clock; -import java.time.Duration; -import java.time.Instant; -import java.time.ZoneId; - -public class ClockExample { - - public static void main(String[] args) { - - // gets systemUTC - Clock clockUTC = Clock.systemUTC(); - System.out.println("UTC time :: " + clockUTC.instant()); - - // using system() - Clock clockSystem = Clock.system(ZoneId.of("Asia/Kolkata")); - System.out.println(clockSystem.instant()); - - // gets systemDefaultZone - Clock clockSystemDefault = Clock.systemDefaultZone(); - System.out.println(clockSystemDefault); - clockSystemDefault = Clock.system(ZoneId.systemDefault()); - System.out.println(clockSystemDefault); - - // gets instant from system default zone - Clock clockInstant = Clock.systemDefaultZone(); - Instant instant = clockInstant.instant(); - System.out.println(instant); - - // gets millis - Clock millis = Clock.systemDefaultZone(); - System.out.println(millis.millis()); - System.out.println(System.currentTimeMillis()); - - // using offset - - Clock baseClock = Clock.systemDefaultZone(); - // result clock will be later than baseClock - Clock clock5 = Clock.offset(baseClock, Duration.ofHours(72)); - System.out.println(clock5.instant()); - - // result clock will be same as baseClock - clock5 = Clock.offset(baseClock, Duration.ZERO); - System.out.println(clock5.instant()); - - // result clock will be earlier than baseClock - clock5 = Clock.offset(baseClock, Duration.ofHours(-72)); - System.out.println(clock5.instant()); - - // using tick - Clock clockDefaultZone = Clock.systemDefaultZone(); - Clock clocktick = Clock.tick(clockDefaultZone, Duration.ofSeconds(30)); - System.out.println("Clock Default Zone : " + clockDefaultZone.instant()); - System.out.println("Clock tick : " + clocktick.instant()); - - // using tickMinutes - Clock tickMinutes = Clock.tickMinutes(ZoneId.of("Asia/Kolkata")); - System.out.println(tickMinutes.instant()); - tickMinutes = Clock.tick(Clock.system(ZoneId.of("Asia/Kolkata")), Duration.ofMinutes(1)); - System.out.println(tickMinutes.instant()); - - // using tickSeconds - ZoneId zoneId = ZoneId.of("Asia/Calcutta"); - Clock tickSeconds = Clock.tickSeconds(zoneId); - System.out.println(tickSeconds.instant()); - tickSeconds = Clock.tick(Clock.system(ZoneId.of("Asia/Kolkata")), Duration.ofSeconds(1)); - System.out.println(tickSeconds.instant()); - - // using withZone - ZoneId zone1 = ZoneId.of("Asia/Singapore"); - Clock clock11 = Clock.system(zone1); - System.out.println(clock11.instant()); - - ZoneId zone2 = ZoneId.of("Asia/Kolkata"); - Clock clock21 = clock11.withZone(zone2); - System.out.println(clock21.instant()); - - ZoneId zone = clockDefaultZone.getZone(); - System.out.println(zone.getId()); - - } -} diff --git a/core-java/src/test/java/com/baeldung/java/clock/ClockUnitTest.java b/core-java/src/test/java/com/baeldung/java/clock/ClockUnitTest.java new file mode 100644 index 0000000000..e83ba7afc8 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/clock/ClockUnitTest.java @@ -0,0 +1,159 @@ +package com.baeldung.java.clock; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.time.Clock; +import java.time.Duration; +import java.time.ZoneId; +import java.time.ZoneOffset; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ClockUnitTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(ClockUnitTest.class); + + @Test + public void givenClock_withSytemUTC_retrievesInstant() { + + Clock clockUTC = Clock.systemUTC(); + + assertEquals(clockUTC.getZone(), ZoneOffset.UTC); + assertEquals(clockUTC.instant().equals(null), false); + + LOGGER.debug("UTC instant :: " + clockUTC.instant()); + } + + @Test + public void givenClock_withSytem_retrievesInstant() { + + Clock clockSystem = Clock.system(ZoneId.of("Asia/Calcutta")); + + assertEquals(clockSystem.getZone(), ZoneId.of("Asia/Calcutta")); + assertEquals(clockSystem.instant().equals(null), false); + + LOGGER.debug("System zone :: " + clockSystem.getZone()); + } + + @Test + public void givenClock_withSytemDefaultZone_retrievesInstant() { + + Clock clockSystemDefault = Clock.systemDefaultZone(); + + assertEquals(clockSystemDefault.getZone().equals(null), false); + assertEquals(clockSystemDefault.instant().equals(null), false); + + LOGGER.debug("System Default instant :: " + clockSystemDefault.instant()); + } + + @Test + public void givenClock_withSytemUTC_retrievesTimeInMillis() { + + Clock clockMillis = Clock.systemDefaultZone(); + + assertEquals(clockMillis.instant().equals(null), false); + assertTrue(clockMillis.millis() > 0); + + LOGGER.debug("System Default millis :: " + clockMillis.millis()); + } + + @Test + public void givenClock_usingOffset_retrievesFutureDate() { + + Clock baseClock = Clock.systemDefaultZone(); + + // result clock will be later than baseClock + Clock futureClock = Clock.offset(baseClock, Duration.ofHours(72)); + + assertEquals(futureClock.instant().equals(null), false); + assertTrue(futureClock.millis() > baseClock.millis()); + + LOGGER.debug("Future Clock instant :: " + futureClock.instant()); + } + + @Test + public void givenClock_usingOffset_retrievesPastDate() { + Clock baseClock = Clock.systemDefaultZone(); + + // result clock will be later than baseClock + Clock pastClock = Clock.offset(baseClock, Duration.ofHours(-72)); + + assertEquals(pastClock.instant().equals(null), false); + assertTrue(pastClock.millis() < baseClock.millis()); + + LOGGER.debug("Past Clock instant :: " + pastClock.instant()); + } + + @Test + public void givenClock_usingTick_retrievesInstant() { + Clock clockDefaultZone = Clock.systemDefaultZone(); + Clock clocktick = Clock.tick(clockDefaultZone, Duration.ofSeconds(300)); + + assertEquals(clockDefaultZone.instant().equals(null), false); + assertEquals(clocktick.instant().equals(null), false); + assertTrue(clockDefaultZone.millis() > clocktick.millis()); + + LOGGER.debug("Clock Default Zone instant : " + clockDefaultZone.instant()); + LOGGER.debug("Clock tick instant: " + clocktick.instant()); + } + + @Test(expected=IllegalArgumentException.class) + public void givenClock_usingTickDurationNegative_throwsException() { + + Clock clockDefaultZone = Clock.systemDefaultZone(); + Clock.tick(clockDefaultZone, Duration.ofSeconds(-300)); + + } + + @Test + public void givenClock_usingTickSeconds_retrievesInstant() { + ZoneId zoneId = ZoneId.of("Asia/Calcutta"); + Clock tickSeconds = Clock.tickSeconds(zoneId); + + assertEquals(tickSeconds.instant().equals(null), false); + LOGGER.debug("Clock tick seconds instant :: " + tickSeconds.instant()); + + tickSeconds = Clock.tick(Clock.system(ZoneId.of("Asia/Calcutta")), Duration.ofSeconds(100)); + assertEquals(tickSeconds.instant().equals(null), false); + } + + @Test + public void givenClock_usingTickMinutes_retrievesInstant() { + + Clock tickMinutes = Clock.tickMinutes(ZoneId.of("Asia/Calcutta")); + + assertEquals(tickMinutes.instant().equals(null), false); + LOGGER.debug("Clock tick seconds instant :: " + tickMinutes.instant()); + + tickMinutes = Clock.tick(Clock.system(ZoneId.of("Asia/Calcutta")), Duration.ofMinutes(5)); + assertEquals(tickMinutes.instant().equals(null), false); + } + + @Test + public void givenClock_usingWithZone_retrievesInstant() { + + ZoneId zoneSingapore = ZoneId.of("Asia/Singapore"); + Clock clockSingapore = Clock.system(zoneSingapore); + + assertEquals(clockSingapore.instant().equals(null), false); + LOGGER.debug("clockSingapore instant : " + clockSingapore.instant()); + + ZoneId zoneCalcutta = ZoneId.of("Asia/Calcutta"); + Clock clockCalcutta = clockSingapore.withZone(zoneCalcutta); + assertEquals(clockCalcutta.instant().equals(null), false); + LOGGER.debug("clockCalcutta instant : " + clockSingapore.instant()); + } + + @Test + public void givenClock_usingGetZone_retrievesZoneId() { + + Clock clockDefaultZone = Clock.systemDefaultZone(); + ZoneId zone = clockDefaultZone.getZone(); + + assertEquals(zone.getId().equals(null), false); + LOGGER.debug("Default zone instant : " + clockDefaultZone.instant()); + } +} From 4073b10bbecef1feda641f291d312071d6675f17 Mon Sep 17 00:00:00 2001 From: Denis Zhdanov Date: Mon, 16 Apr 2018 01:39:16 +0300 Subject: [PATCH 06/46] BAEL-1423 Java Concurrency Utility with JCTools library Addressed editor's comments --- jctools/README.md | 11 -- jctools/pom.xml | 108 ------------------ libraries/pom.xml | 45 ++++++++ .../com/baeldung/jctools/MpmcBenchmark.java | 0 .../main/java/com/baeldung/jctools/README.md | 7 ++ .../com/baeldung/jctools/JCToolsUnitTest.java | 0 6 files changed, 52 insertions(+), 119 deletions(-) delete mode 100644 jctools/README.md delete mode 100644 jctools/pom.xml rename {jctools => libraries}/src/main/java/com/baeldung/jctools/MpmcBenchmark.java (100%) create mode 100644 libraries/src/main/java/com/baeldung/jctools/README.md rename {jctools => libraries}/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java (100%) diff --git a/jctools/README.md b/jctools/README.md deleted file mode 100644 index 181e45c1ca..0000000000 --- a/jctools/README.md +++ /dev/null @@ -1,11 +0,0 @@ -## Overview - -This project holds a [couple of tests](./src/test/java/com/baeldung/jctools/JCToolsUnitTest.java) which illustrate JCTools specifics and a [benchmark](./src/main/java/com/baeldung/jctools/MpmcBenchmark.java) in the [JMH](http://openjdk.java.net/projects/code-tools/jmh/) format. - -## How to build and run the JMH benchmark - -Execute the following from the project's root: -```bash -mvn clean install -java -jar ./target/benchmarks.jar MpmcBenchmark -si true -``` \ No newline at end of file diff --git a/jctools/pom.xml b/jctools/pom.xml deleted file mode 100644 index 8a21c610de..0000000000 --- a/jctools/pom.xml +++ /dev/null @@ -1,108 +0,0 @@ - - 4.0.0 - - com.baeldung - jctools - 0.0.1-SNAPSHOT - - jctools - - - - org.jctools - jctools-core - ${jctools.version} - - - - org.openjdk.jmh - jmh-core - ${jmh.version} - - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh.version} - provided - - - - junit - junit - 4.12 - test - - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - 2.1.2 - 3.9.1 - 1.20 - - 1.8 - - benchmarks - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - ${javac.target} - ${javac.target} - ${javac.target} - - - - - - org.apache.maven.plugins - maven-shade-plugin - 2.2 - - - package - - shade - - - ${uberjar.name} - - - org.openjdk.jmh.Main - - - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - - - - - - - - - - - \ No newline at end of file diff --git a/libraries/pom.xml b/libraries/pom.xml index 6ff06d7285..8a3a27cec4 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -661,6 +661,12 @@ fugue 4.5.1 + + + org.jctools + jctools-core + ${jctools.version} + @@ -780,6 +786,44 @@ 1.8 + + + + org.apache.maven.plugins + maven-shade-plugin + 2.2 + + + package + + shade + + + benchmarks + + + org.openjdk.jmh.Main + + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + + @@ -850,6 +894,7 @@ 2.2.0 9.1.5.Final 1.4.9 + 2.1.2 diff --git a/jctools/src/main/java/com/baeldung/jctools/MpmcBenchmark.java b/libraries/src/main/java/com/baeldung/jctools/MpmcBenchmark.java similarity index 100% rename from jctools/src/main/java/com/baeldung/jctools/MpmcBenchmark.java rename to libraries/src/main/java/com/baeldung/jctools/MpmcBenchmark.java diff --git a/libraries/src/main/java/com/baeldung/jctools/README.md b/libraries/src/main/java/com/baeldung/jctools/README.md new file mode 100644 index 0000000000..3c1b3c1c1e --- /dev/null +++ b/libraries/src/main/java/com/baeldung/jctools/README.md @@ -0,0 +1,7 @@ +## How to build and run the JMH benchmark + +Execute the following from the project's root: +```bash +mvn clean install +java -jar ./target/benchmarks.jar MpmcBenchmark -si true +``` \ No newline at end of file diff --git a/jctools/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java b/libraries/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java similarity index 100% rename from jctools/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java rename to libraries/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java From 5b22ce4687cd02ec201b03dea44e8aa211552dc0 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Mon, 16 Apr 2018 22:21:35 +0200 Subject: [PATCH 07/46] added article link --- spring-boot/README.MD | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 028fde5056..fa9ce64a1e 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -1,4 +1,4 @@ -###The Course +### The Course The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: @@ -33,4 +33,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Quick Guide to Maven Wrapper](http://www.baeldung.com/maven-wrapper) - [An Introduction to Kong](http://www.baeldung.com/kong) - [Spring Boot Customize Whitelabel Error Page](http://www.baeldung.com/spring-boot-custom-error-page) +- [http://www.baeldung.com/spring-boot-main-class](http://www.baeldung.com/spring-boot-main-class) From 20b0a214e6bcc0abadc40b42f17a217a2dee8548 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Mon, 16 Apr 2018 22:22:38 +0200 Subject: [PATCH 08/46] added article link --- spring-boot-gradle/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 spring-boot-gradle/README.md diff --git a/spring-boot-gradle/README.md b/spring-boot-gradle/README.md new file mode 100644 index 0000000000..f96aa9ccf8 --- /dev/null +++ b/spring-boot-gradle/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Spring Boot: Configuring a Main Class](http://www.baeldung.com/spring-boot-main-class) From e62fb43d7b542eadf0da7c7320981c653c95becd Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Mon, 16 Apr 2018 22:23:11 +0200 Subject: [PATCH 09/46] fixed link --- spring-boot/README.MD | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot/README.MD b/spring-boot/README.MD index fa9ce64a1e..080c4d6353 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -33,5 +33,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [A Quick Guide to Maven Wrapper](http://www.baeldung.com/maven-wrapper) - [An Introduction to Kong](http://www.baeldung.com/kong) - [Spring Boot Customize Whitelabel Error Page](http://www.baeldung.com/spring-boot-custom-error-page) -- [http://www.baeldung.com/spring-boot-main-class](http://www.baeldung.com/spring-boot-main-class) +- [Spring Boot: Configuring a Main Class](http://www.baeldung.com/spring-boot-main-class) From 6a03f1a9fdafa18f5046182f89b14688e52e8bcc Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Wed, 18 Apr 2018 21:42:20 +0400 Subject: [PATCH 10/46] spring-data final --- libraries-data/pom.xml | 4 +- .../com/baeldung/ignite/spring/IgniteApp.java | 53 +++++++++++++++++++ .../spring/config/SpringDataConfig.java | 34 ++++++++++++ .../ignite/spring/dto/EmployeeDTO.java | 48 +++++++++++++++++ .../spring/repository/EmployeeRepository.java | 13 +++++ 5 files changed, 150 insertions(+), 2 deletions(-) create mode 100644 libraries-data/src/main/java/com/baeldung/ignite/spring/IgniteApp.java create mode 100644 libraries-data/src/main/java/com/baeldung/ignite/spring/config/SpringDataConfig.java create mode 100644 libraries-data/src/main/java/com/baeldung/ignite/spring/dto/EmployeeDTO.java create mode 100644 libraries-data/src/main/java/com/baeldung/ignite/spring/repository/EmployeeRepository.java diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 55bf02ae16..0e34e8f35b 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -72,7 +72,7 @@ org.apache.ignite - ignite-spring + ignite-spring-data ${ignite.version} @@ -201,7 +201,7 @@ 3.7.0 5.0 1.0.0 - 2.3.0 + 2.4.0 2.8.2 \ No newline at end of file diff --git a/libraries-data/src/main/java/com/baeldung/ignite/spring/IgniteApp.java b/libraries-data/src/main/java/com/baeldung/ignite/spring/IgniteApp.java new file mode 100644 index 0000000000..c181cdbb3c --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/ignite/spring/IgniteApp.java @@ -0,0 +1,53 @@ +package com.baeldung.ignite.spring; + +import com.baeldung.ignite.spring.config.SpringDataConfig; +import com.baeldung.ignite.spring.dto.EmployeeDTO; +import com.baeldung.ignite.spring.repository.EmployeeRepository; +import org.apache.ignite.Ignite; +import org.apache.ignite.IgniteCache; +import org.apache.ignite.Ignition; +import org.apache.ignite.cache.query.QueryCursor; +import org.apache.ignite.cache.query.SqlFieldsQuery; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import java.util.List; + +/** + * Created by Gebruiker on 4/12/2018. + */ +public class IgniteApp { + + public static void main (String[] args) { + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.register(SpringDataConfig.class); + context.refresh(); + + EmployeeRepository repository = context.getBean(EmployeeRepository.class); + + EmployeeDTO employeeDTO = new EmployeeDTO(); + employeeDTO.setId(1); + employeeDTO.setName("John"); + employeeDTO.setEmployed(true); + + repository.save(employeeDTO.getId(), employeeDTO); + + EmployeeDTO employee = repository.getEmployeeDTOById(employeeDTO.getId()); + System.out.println(employee); + } + + private void getUsingTheCache(Integer employeeId) { + + Ignite ignite = Ignition.ignite(); + + IgniteCache cache = ignite.cache("baeldungCache"); + + EmployeeDTO employeeDTO = cache.get(employeeId); + + System.out.println(employeeDTO); + + SqlFieldsQuery sql = new SqlFieldsQuery( + "select * from EmployeeDTO where isEmployed = 'true'"); + + QueryCursor> cursor = cache.query(sql); + } +} diff --git a/libraries-data/src/main/java/com/baeldung/ignite/spring/config/SpringDataConfig.java b/libraries-data/src/main/java/com/baeldung/ignite/spring/config/SpringDataConfig.java new file mode 100644 index 0000000000..20a00a0285 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/ignite/spring/config/SpringDataConfig.java @@ -0,0 +1,34 @@ +package com.baeldung.ignite.spring.config; + +import com.baeldung.ignite.spring.dto.EmployeeDTO; +import com.baeldung.ignite.spring.repository.EmployeeRepository; +import org.apache.ignite.Ignite; +import org.apache.ignite.Ignition; +import org.apache.ignite.configuration.CacheConfiguration; +import org.apache.ignite.configuration.IgniteConfiguration; +import org.apache.ignite.springdata.repository.config.EnableIgniteRepositories; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableIgniteRepositories(basePackageClasses = EmployeeRepository.class) +@ComponentScan(basePackages = "com.baeldung.ignite.spring.repository") +public class SpringDataConfig { + + @Bean + public Ignite igniteInstance() { + IgniteConfiguration config = new IgniteConfiguration(); + // Setting some custom name for the node. + //config.setIgniteInstanceName("springDataNode"); + // Enabling peer-class loading feature. + //config.setPeerClassLoadingEnabled(true); + // Defining and creating a new cache to be used by Ignite Spring Data + // repository. + CacheConfiguration cache = new CacheConfiguration("baeldungCache"); + // Setting SQL schema for the cache. + cache.setIndexedTypes(Integer.class, EmployeeDTO.class); + config.setCacheConfiguration(cache); + return Ignition.start(config); + } +} diff --git a/libraries-data/src/main/java/com/baeldung/ignite/spring/dto/EmployeeDTO.java b/libraries-data/src/main/java/com/baeldung/ignite/spring/dto/EmployeeDTO.java new file mode 100644 index 0000000000..5dbf860fe7 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/ignite/spring/dto/EmployeeDTO.java @@ -0,0 +1,48 @@ +package com.baeldung.ignite.spring.dto; + +import org.apache.ignite.cache.query.annotations.QuerySqlField; + +import java.io.Serializable; + +public class EmployeeDTO implements Serializable { + + @QuerySqlField(index = true) + private Integer id; + @QuerySqlField(index = true) + private String name; + @QuerySqlField(index = true) + private boolean isEmployed; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isEmployed() { + return isEmployed; + } + + public void setEmployed(boolean employed) { + isEmployed = employed; + } + + @Override + public String toString() { + return "EmployeeDTO{" + + "id=" + id + + ", name='" + name + '\'' + + ", isEmployed=" + isEmployed + + '}'; + } +} diff --git a/libraries-data/src/main/java/com/baeldung/ignite/spring/repository/EmployeeRepository.java b/libraries-data/src/main/java/com/baeldung/ignite/spring/repository/EmployeeRepository.java new file mode 100644 index 0000000000..cdcd23a58a --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/ignite/spring/repository/EmployeeRepository.java @@ -0,0 +1,13 @@ +package com.baeldung.ignite.spring.repository; + +import com.baeldung.ignite.spring.dto.EmployeeDTO; +import org.apache.ignite.springdata.repository.IgniteRepository; +import org.apache.ignite.springdata.repository.config.RepositoryConfig; +import org.springframework.stereotype.Repository; + +@Repository +@RepositoryConfig(cacheName = "baeldungCache") +public interface EmployeeRepository extends IgniteRepository { + + EmployeeDTO getEmployeeDTOById(Integer id); +} From 5e822b28962c9634b248d56730b066f6b7bdeac0 Mon Sep 17 00:00:00 2001 From: Fabio Pereira Date: Wed, 18 Apr 2018 23:14:58 -0300 Subject: [PATCH 11/46] refactoring packages and using generics --- .../{filter => filters}/ExampleHandlerFilterFunction.java | 6 +++--- .../reactive/{filter => filters}/ExampleWebFilter.java | 2 +- .../reactive/{handler => filters}/PlayerHandler.java | 6 +++--- .../baeldung/reactive/{router => filters}/PlayerRouter.java | 6 ++---- .../reactive/{controller => filters}/UserController.java | 2 +- .../reactive/{handler => filters}/PlayerHandlerTest.java | 2 +- .../{controller => filters}/UserControllerTest.java | 2 +- 7 files changed, 12 insertions(+), 14 deletions(-) rename spring-5-reactive/src/main/java/com/baeldung/reactive/{filter => filters}/ExampleHandlerFilterFunction.java (77%) rename spring-5-reactive/src/main/java/com/baeldung/reactive/{filter => filters}/ExampleWebFilter.java (93%) rename spring-5-reactive/src/main/java/com/baeldung/reactive/{handler => filters}/PlayerHandler.java (77%) rename spring-5-reactive/src/main/java/com/baeldung/reactive/{router => filters}/PlayerRouter.java (74%) rename spring-5-reactive/src/main/java/com/baeldung/reactive/{controller => filters}/UserController.java (90%) rename spring-5-reactive/src/test/java/com/baeldung/reactive/{handler => filters}/PlayerHandlerTest.java (97%) rename spring-5-reactive/src/test/java/com/baeldung/reactive/{controller => filters}/UserControllerTest.java (96%) diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/filter/ExampleHandlerFilterFunction.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/ExampleHandlerFilterFunction.java similarity index 77% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/filter/ExampleHandlerFilterFunction.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/filters/ExampleHandlerFilterFunction.java index e55f5ce2fe..36b3c2ff6e 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/filter/ExampleHandlerFilterFunction.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/ExampleHandlerFilterFunction.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.filter; +package com.baeldung.reactive.filters; import org.springframework.web.reactive.function.server.HandlerFilterFunction; import org.springframework.web.reactive.function.server.HandlerFunction; @@ -8,10 +8,10 @@ import reactor.core.publisher.Mono; import static org.springframework.http.HttpStatus.FORBIDDEN; -public class ExampleHandlerFilterFunction implements HandlerFilterFunction { +public class ExampleHandlerFilterFunction implements HandlerFilterFunction { @Override - public Mono filter(ServerRequest serverRequest, HandlerFunction handlerFunction) { + public Mono filter(ServerRequest serverRequest, HandlerFunction handlerFunction) { if (serverRequest.pathVariable("name").equalsIgnoreCase("test")) { return ServerResponse.status(FORBIDDEN).build(); } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/filter/ExampleWebFilter.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/ExampleWebFilter.java similarity index 93% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/filter/ExampleWebFilter.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/filters/ExampleWebFilter.java index 99bc9f7fc3..8fe3550a7e 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/filter/ExampleWebFilter.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/ExampleWebFilter.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.filter; +package com.baeldung.reactive.filters; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/handler/PlayerHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/PlayerHandler.java similarity index 77% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/handler/PlayerHandler.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/filters/PlayerHandler.java index 51b4e166d1..20a08570ae 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/handler/PlayerHandler.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/PlayerHandler.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.handler; +package com.baeldung.reactive.filters; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.server.ServerRequest; @@ -8,9 +8,9 @@ import reactor.core.publisher.Mono; import static org.springframework.web.reactive.function.server.ServerResponse.ok; @Component -public class PlayerHandler { +class PlayerHandler { - public Mono getName(ServerRequest request) { + Mono getName(ServerRequest request) { Mono name = Mono.just(request.pathVariable("name")); return ok().body(name, String.class); } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/router/PlayerRouter.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/PlayerRouter.java similarity index 74% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/router/PlayerRouter.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/filters/PlayerRouter.java index be721964ca..753991782c 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/router/PlayerRouter.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/PlayerRouter.java @@ -1,7 +1,5 @@ -package com.baeldung.reactive.router; +package com.baeldung.reactive.filters; -import com.baeldung.reactive.filter.ExampleHandlerFilterFunction; -import com.baeldung.reactive.handler.PlayerHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.function.server.RouterFunction; @@ -17,6 +15,6 @@ public class PlayerRouter { public RouterFunction route(PlayerHandler playerHandler) { return RouterFunctions .route(GET("/players/{name}"), playerHandler::getName) - .filter(new ExampleHandlerFilterFunction()::filter); + .filter(new ExampleHandlerFilterFunction()); } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/UserController.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/UserController.java similarity index 90% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/controller/UserController.java rename to spring-5-reactive/src/main/java/com/baeldung/reactive/filters/UserController.java index f51a674fe8..38c9210f88 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/controller/UserController.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/UserController.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.controller; +package com.baeldung.reactive.filters; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/handler/PlayerHandlerTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerTest.java similarity index 97% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/handler/PlayerHandlerTest.java rename to spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerTest.java index de9b326874..8189802248 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/handler/PlayerHandlerTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerTest.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.handler; +package com.baeldung.reactive.filters; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/controller/UserControllerTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerTest.java similarity index 96% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/controller/UserControllerTest.java rename to spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerTest.java index 131a3d812b..d32a9d478f 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/controller/UserControllerTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerTest.java @@ -1,4 +1,4 @@ -package com.baeldung.reactive.controller; +package com.baeldung.reactive.filters; import org.junit.Test; import org.junit.runner.RunWith; From 7ae3babd59f4f3b1548f169ad4a2421e406117d3 Mon Sep 17 00:00:00 2001 From: amit2103 Date: Thu, 19 Apr 2018 13:11:39 +0530 Subject: [PATCH 12/46] Bael 5927 (#4042) * Added parent module on poms that have no parent defined * Removed dependency reduced pom from undertow module * Defined the integration profile in the parent --- apache-fop/pom.xml | 36 ---------------- cdi/pom.xml | 36 +--------------- core-java-8/pom.xml | 35 ---------------- core-java-concurrency/pom.xml | 35 ---------------- disruptor/pom.xml | 27 ------------ ethereumj/pom.xml | 30 ------------- hystrix/pom.xml | 36 ---------------- jhipster/jhipster-monolithic/pom.xml | 27 ------------ jjwt/pom.xml | 35 ---------------- mapstruct/pom.xml | 35 ---------------- parent-boot-5/pom.xml | 42 ++++++++++++++++++- persistence-modules/java-cassandra/pom.xml | 35 ---------------- persistence-modules/java-cockroachdb/pom.xml | 35 ---------------- persistence-modules/java-mongodb/pom.xml | 35 ---------------- persistence-modules/querydsl/pom.xml | 36 ---------------- .../spring-data-cassandra/pom.xml | 35 ---------------- persistence-modules/spring-data-neo4j/pom.xml | 35 ---------------- .../spring-hibernate-3/pom.xml | 35 ---------------- pom.xml | 36 ++++++++++++++++ spring-akka/pom.xml | 35 ---------------- spring-all/pom.xml | 35 ---------------- spring-boot-bootstrap/pom.xml | 33 --------------- spring-boot/pom.xml | 33 --------------- spring-cloud-data-flow/log-sink/pom.xml | 39 +---------------- spring-cloud-data-flow/time-processor/pom.xml | 35 ---------------- spring-cloud-data-flow/time-source/pom.xml | 35 ---------------- .../spring-cloud-ribbon-client/pom.xml | 39 +---------------- spring-core/pom.xml | 37 +--------------- spring-cucumber/pom.xml | 35 ---------------- spring-custom-aop/spring-custom-aop/pom.xml | 38 +---------------- spring-data-mongodb/pom.xml | 35 ---------------- spring-integration/pom.xml | 35 ---------------- spring-jenkins-pipeline/pom.xml | 20 --------- spring-jooq/pom.xml | 35 ---------------- spring-mockito/pom.xml | 35 ---------------- spring-mvc-java/pom.xml | 32 -------------- spring-mvc-velocity/pom.xml | 34 --------------- spring-protobuf/pom.xml | 38 +---------------- spring-rest-angular/pom.xml | 38 +---------------- spring-rest-full/pom.xml | 33 --------------- spring-rest-query-language/pom.xml | 33 --------------- spring-rest/pom.xml | 31 -------------- spring-security-mvc-boot/pom.xml | 33 --------------- .../spring-security-x509-basic-auth/pom.xml | 35 ---------------- spring-social-login/pom.xml | 35 ---------------- spring-spel/pom.xml | 35 ---------------- spring-thymeleaf/pom.xml | 35 ---------------- spring-userservice/pom.xml | 35 ---------------- testing-modules/mockito-2/pom.xml | 35 ---------------- testing-modules/rest-assured/pom.xml | 37 ---------------- testing-modules/rest-testing/pom.xml | 36 ---------------- 51 files changed, 84 insertions(+), 1681 deletions(-) diff --git a/apache-fop/pom.xml b/apache-fop/pom.xml index f7439dc244..c9522e2b75 100644 --- a/apache-fop/pom.xml +++ b/apache-fop/pom.xml @@ -82,42 +82,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - - - **/*IntegrationTest.java - **/*LiveTest.java - - - - - - - json - - - - - - - - 1.1 4.3 diff --git a/cdi/pom.xml b/cdi/pom.xml index da0672afde..e96c3fc44e 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -44,41 +44,7 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - + 4.3.4.RELEASE 1.8.9 diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index 924773cd02..cd71a9c123 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -236,41 +236,6 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - diff --git a/core-java-concurrency/pom.xml b/core-java-concurrency/pom.xml index bf858047e9..11a111a245 100644 --- a/core-java-concurrency/pom.xml +++ b/core-java-concurrency/pom.xml @@ -183,41 +183,6 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - diff --git a/disruptor/pom.xml b/disruptor/pom.xml index 33eb7bb50a..c384347e91 100644 --- a/disruptor/pom.xml +++ b/disruptor/pom.xml @@ -139,33 +139,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - - - json - - - - - - - - 3.5 diff --git a/ethereumj/pom.xml b/ethereumj/pom.xml index 8b6d3677c9..283b84c197 100644 --- a/ethereumj/pom.xml +++ b/ethereumj/pom.xml @@ -77,36 +77,6 @@ ethereumj - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - none - - - */EthControllerTestOne.java - - - - - - - - - - UTF-8 1.8 diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 19da678eb7..c201e87210 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -78,40 +78,4 @@ test - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml index eb4c2ca2d3..a1bb74a3b5 100644 --- a/jhipster/jhipster-monolithic/pom.xml +++ b/jhipster/jhipster-monolithic/pom.xml @@ -994,32 +994,5 @@ - - integration - - true - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*IntTest.java - - - - - - - - diff --git a/jjwt/pom.xml b/jjwt/pom.xml index cd2dd9f97e..7b90110b8f 100644 --- a/jjwt/pom.xml +++ b/jjwt/pom.xml @@ -45,39 +45,4 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - diff --git a/mapstruct/pom.xml b/mapstruct/pom.xml index ba67ccc2df..cacfa6ccfc 100644 --- a/mapstruct/pom.xml +++ b/mapstruct/pom.xml @@ -58,39 +58,4 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - diff --git a/parent-boot-5/pom.xml b/parent-boot-5/pom.xml index 0e3936a73a..a7ae818960 100644 --- a/parent-boot-5/pom.xml +++ b/parent-boot-5/pom.xml @@ -75,5 +75,45 @@ - + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + **/*LiveTest.java + **/AutoconfigurationTest.java + **/*UnitTest.java + + + **/*IntegrationTest.java + */EthControllerTestOne.java + **/*IntTest.java + **/*EntryPointsTest.java + + + + + + + json + + + + + + + \ No newline at end of file diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml index 81e072c3a7..1937b1c5d8 100644 --- a/persistence-modules/java-cassandra/pom.xml +++ b/persistence-modules/java-cassandra/pom.xml @@ -43,41 +43,6 @@ java-cassandra - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - UTF-8 diff --git a/persistence-modules/java-cockroachdb/pom.xml b/persistence-modules/java-cockroachdb/pom.xml index 2b6f9651bc..1a0231f4a4 100644 --- a/persistence-modules/java-cockroachdb/pom.xml +++ b/persistence-modules/java-cockroachdb/pom.xml @@ -28,41 +28,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - Central diff --git a/persistence-modules/java-mongodb/pom.xml b/persistence-modules/java-mongodb/pom.xml index 9784b2c5a8..b09e96262d 100644 --- a/persistence-modules/java-mongodb/pom.xml +++ b/persistence-modules/java-mongodb/pom.xml @@ -32,41 +32,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*ManualTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 1.8 1.8 diff --git a/persistence-modules/querydsl/pom.xml b/persistence-modules/querydsl/pom.xml index c2943875f1..0ae38a5323 100644 --- a/persistence-modules/querydsl/pom.xml +++ b/persistence-modules/querydsl/pom.xml @@ -163,40 +163,4 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-data-cassandra/pom.xml b/persistence-modules/spring-data-cassandra/pom.xml index 1358210a45..82fcc073cd 100644 --- a/persistence-modules/spring-data-cassandra/pom.xml +++ b/persistence-modules/spring-data-cassandra/pom.xml @@ -87,39 +87,4 @@ true - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - diff --git a/persistence-modules/spring-data-neo4j/pom.xml b/persistence-modules/spring-data-neo4j/pom.xml index bdd51e9659..7bd531638a 100644 --- a/persistence-modules/spring-data-neo4j/pom.xml +++ b/persistence-modules/spring-data-neo4j/pom.xml @@ -117,41 +117,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 1.8 1.8 diff --git a/persistence-modules/spring-hibernate-3/pom.xml b/persistence-modules/spring-hibernate-3/pom.xml index f1873a84d3..67ff243f73 100644 --- a/persistence-modules/spring-hibernate-3/pom.xml +++ b/persistence-modules/spring-hibernate-3/pom.xml @@ -98,41 +98,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 4.3.4.RELEASE diff --git a/pom.xml b/pom.xml index f0cb72e4d0..4183a3db49 100644 --- a/pom.xml +++ b/pom.xml @@ -482,4 +482,40 @@ + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*ManualTest.java + **/*LiveTest.java + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + \ No newline at end of file diff --git a/spring-akka/pom.xml b/spring-akka/pom.xml index 5efd111c35..551240ba73 100644 --- a/spring-akka/pom.xml +++ b/spring-akka/pom.xml @@ -51,41 +51,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 4.3.4.RELEASE 2.4.14 diff --git a/spring-all/pom.xml b/spring-all/pom.xml index b04ffae9c8..6c95817973 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -227,41 +227,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - org.baeldung.sample.App diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 07466c76f2..00b6068bee 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -87,39 +87,6 @@ - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/AutoconfigurationTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - autoconfiguration diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index f10fe5a909..936ea59fe7 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -200,39 +200,6 @@ - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - **/AutoconfigurationTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - autoconfiguration diff --git a/spring-cloud-data-flow/log-sink/pom.xml b/spring-cloud-data-flow/log-sink/pom.xml index c07380de56..128402926f 100644 --- a/spring-cloud-data-flow/log-sink/pom.xml +++ b/spring-cloud-data-flow/log-sink/pom.xml @@ -40,42 +40,5 @@ - - - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - + diff --git a/spring-cloud-data-flow/time-processor/pom.xml b/spring-cloud-data-flow/time-processor/pom.xml index 08d5e2b9be..4c9b50040e 100644 --- a/spring-cloud-data-flow/time-processor/pom.xml +++ b/spring-cloud-data-flow/time-processor/pom.xml @@ -40,40 +40,5 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - diff --git a/spring-cloud-data-flow/time-source/pom.xml b/spring-cloud-data-flow/time-source/pom.xml index 4d35e30be2..adf6b1e151 100644 --- a/spring-cloud-data-flow/time-source/pom.xml +++ b/spring-cloud-data-flow/time-source/pom.xml @@ -41,39 +41,4 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - diff --git a/spring-cloud/spring-cloud-ribbon-client/pom.xml b/spring-cloud/spring-cloud-ribbon-client/pom.xml index 85baff12cd..aba98d05e4 100644 --- a/spring-cloud/spring-cloud-ribbon-client/pom.xml +++ b/spring-cloud/spring-cloud-ribbon-client/pom.xml @@ -60,42 +60,5 @@ - - - - integration - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - + \ No newline at end of file diff --git a/spring-core/pom.xml b/spring-core/pom.xml index deffaf41db..ae1b93a403 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -90,42 +90,7 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - + 1.10.19 1.4.4.RELEASE diff --git a/spring-cucumber/pom.xml b/spring-cucumber/pom.xml index df4723484d..f24d0318d3 100644 --- a/spring-cucumber/pom.xml +++ b/spring-cucumber/pom.xml @@ -66,39 +66,4 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - diff --git a/spring-custom-aop/spring-custom-aop/pom.xml b/spring-custom-aop/spring-custom-aop/pom.xml index 95c1b7419f..b65e4c9f9b 100644 --- a/spring-custom-aop/spring-custom-aop/pom.xml +++ b/spring-custom-aop/spring-custom-aop/pom.xml @@ -138,43 +138,7 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - - + org.baeldung.boot.DemoApplication diff --git a/spring-data-mongodb/pom.xml b/spring-data-mongodb/pom.xml index 7060ec5b36..9d772ee6ca 100644 --- a/spring-data-mongodb/pom.xml +++ b/spring-data-mongodb/pom.xml @@ -75,41 +75,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - UTF-8 diff --git a/spring-integration/pom.xml b/spring-integration/pom.xml index e3dd0d3f9a..a3cdfa172f 100644 --- a/spring-integration/pom.xml +++ b/spring-integration/pom.xml @@ -131,39 +131,4 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - diff --git a/spring-jenkins-pipeline/pom.xml b/spring-jenkins-pipeline/pom.xml index 071f6e6e36..545d36e2b2 100644 --- a/spring-jenkins-pipeline/pom.xml +++ b/spring-jenkins-pipeline/pom.xml @@ -55,26 +55,6 @@ - - integration - - - - maven-surefire-plugin - - - **/*UnitTest.java - - - - **/*IntegrationTest.java - - - - - - - unit diff --git a/spring-jooq/pom.xml b/spring-jooq/pom.xml index 763465be8c..a3dad5802f 100644 --- a/spring-jooq/pom.xml +++ b/spring-jooq/pom.xml @@ -185,41 +185,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 3.8.6 1.4.193 diff --git a/spring-mockito/pom.xml b/spring-mockito/pom.xml index 8c2949275c..8e8636edf7 100644 --- a/spring-mockito/pom.xml +++ b/spring-mockito/pom.xml @@ -30,41 +30,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 1.10.19 diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 9b2981a747..9a4dc4870d 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -199,38 +199,6 @@ - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - live diff --git a/spring-mvc-velocity/pom.xml b/spring-mvc-velocity/pom.xml index 7c517e2006..38edbe0aae 100644 --- a/spring-mvc-velocity/pom.xml +++ b/spring-mvc-velocity/pom.xml @@ -127,40 +127,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - diff --git a/spring-protobuf/pom.xml b/spring-protobuf/pom.xml index 1771c3e1f2..6f999f795d 100644 --- a/spring-protobuf/pom.xml +++ b/spring-protobuf/pom.xml @@ -51,41 +51,5 @@ - - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - + diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 255aa840e7..34babbcf2c 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -72,43 +72,7 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - **/*UnitTest.java - - - - - - - json - - - - - - - - + 19.0 3.5 diff --git a/spring-rest-full/pom.xml b/spring-rest-full/pom.xml index 3bd7ec07f6..02cab262d1 100644 --- a/spring-rest-full/pom.xml +++ b/spring-rest-full/pom.xml @@ -270,39 +270,6 @@ - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - live diff --git a/spring-rest-query-language/pom.xml b/spring-rest-query-language/pom.xml index b329bec07e..1ef3f924ad 100644 --- a/spring-rest-query-language/pom.xml +++ b/spring-rest-query-language/pom.xml @@ -289,39 +289,6 @@ - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - live diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index ebf174fb50..9a2169d46d 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -241,37 +241,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - none - - - **/*IntegrationTest.java - **/*UnitTest.java - - - - - - - - - - live diff --git a/spring-security-mvc-boot/pom.xml b/spring-security-mvc-boot/pom.xml index b717a1366d..c3af96ebfc 100644 --- a/spring-security-mvc-boot/pom.xml +++ b/spring-security-mvc-boot/pom.xml @@ -169,39 +169,6 @@ - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - live diff --git a/spring-security-x509/spring-security-x509-basic-auth/pom.xml b/spring-security-x509/spring-security-x509-basic-auth/pom.xml index e46629f44d..1f680a8b89 100644 --- a/spring-security-x509/spring-security-x509-basic-auth/pom.xml +++ b/spring-security-x509/spring-security-x509-basic-auth/pom.xml @@ -37,39 +37,4 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - diff --git a/spring-social-login/pom.xml b/spring-social-login/pom.xml index 50e2abfbfc..19bfad89b1 100644 --- a/spring-social-login/pom.xml +++ b/spring-social-login/pom.xml @@ -95,41 +95,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 3.3.2 diff --git a/spring-spel/pom.xml b/spring-spel/pom.xml index 4262482617..9bf1478f58 100644 --- a/spring-spel/pom.xml +++ b/spring-spel/pom.xml @@ -30,39 +30,4 @@ test - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - \ No newline at end of file diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index 5ce2a4b637..f6e7997da8 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -172,39 +172,4 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - \ No newline at end of file diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml index 72a4f0edac..67acd386f1 100644 --- a/spring-userservice/pom.xml +++ b/spring-userservice/pom.xml @@ -213,41 +213,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 4.2.0.RELEASE diff --git a/testing-modules/mockito-2/pom.xml b/testing-modules/mockito-2/pom.xml index 2d119ae8af..62c338bcc9 100644 --- a/testing-modules/mockito-2/pom.xml +++ b/testing-modules/mockito-2/pom.xml @@ -15,41 +15,6 @@ ../../ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - UTF-8 diff --git a/testing-modules/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index 1006e9a373..b0d8c591fd 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -176,43 +176,6 @@ - - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - - 2.8.5 1.8 diff --git a/testing-modules/rest-testing/pom.xml b/testing-modules/rest-testing/pom.xml index ea63ee0e58..b888cfa329 100644 --- a/testing-modules/rest-testing/pom.xml +++ b/testing-modules/rest-testing/pom.xml @@ -115,42 +115,6 @@ - - - integration - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*UnitTest.java - **/*LiveTest.java - - - **/*IntegrationTest.java - - - - - - - json - - - - - - - - 2.8.5 From ed9f3fa2e2a2bcb5c318db67a4f8476f9f6a3f57 Mon Sep 17 00:00:00 2001 From: tamasradu Date: Fri, 20 Apr 2018 00:28:38 +0300 Subject: [PATCH 13/46] Using assertThatThrownBy (#4047) --- .../netty/EmbeddedChannelUnitTest.java | 30 +++++++------------ 1 file changed, 11 insertions(+), 19 deletions(-) diff --git a/libraries/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java b/libraries/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java index ca723a7b7f..2818bb96a2 100644 --- a/libraries/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java +++ b/libraries/src/test/java/com/baeldung/netty/EmbeddedChannelUnitTest.java @@ -52,16 +52,12 @@ public class EmbeddedChannelUnitTest { "/calculate?a=10&b=5"); wrongHttpRequest.headers().add("Operator", "Add"); - Throwable thrownException = catchThrowable(() -> { - // send invalid HTTP request to server and expect and error - channel.pipeline().fireChannelRead(wrongHttpRequest); - channel.checkException(); - Assertions.failBecauseExceptionWasNotThrown(UnsupportedOperationException.class); - }); - - assertThat(thrownException) - .isInstanceOf(UnsupportedOperationException.class) - .hasMessage("HTTP method not supported"); + assertThatThrownBy(() -> { + // send invalid HTTP request to server and expect and error + channel.pipeline().fireChannelRead(wrongHttpRequest); + channel.checkException(); + }).isInstanceOf(UnsupportedOperationException.class) + .hasMessage("HTTP method not supported"); FullHttpResponse errorHttpResponse = channel.readOutbound(); String errorHttpResponseContent = errorHttpResponse.content().toString(Charset.defaultCharset()); @@ -77,15 +73,11 @@ public class EmbeddedChannelUnitTest { "/calculate?a=10&b=5"); wrongHttpRequest.headers().add("Operator", "Invalid_operation"); - Throwable thrownException = catchThrowable(() -> { - // send invalid HTTP request to server and expect and error - channel.writeInbound(wrongHttpRequest); - Assertions.failBecauseExceptionWasNotThrown(IllegalArgumentException.class); - }); - - // the HttpMessageHandler does not handle the exception and throws it down the - // pipeline - assertThat(thrownException).isInstanceOf(IllegalArgumentException.class).hasMessage("Operation not defined"); + // the HttpMessageHandler does not handle the exception and throws it down the pipeline + assertThatThrownBy(() -> { + channel.writeInbound(wrongHttpRequest); + }).isInstanceOf(IllegalArgumentException.class) + .hasMessage("Operation not defined"); // the outbound message is a HTTP response with the status code 500 FullHttpResponse errorHttpResponse = channel.readOutbound(); From 5e78d679d8ac2a1402a6823165417bd50007cf97 Mon Sep 17 00:00:00 2001 From: gautamshetty Date: Sat, 21 Apr 2018 05:06:11 -0500 Subject: [PATCH 14/46] BAEL-717: Singleton Session Bean. (#4046) * BAEL-717: Singleton EJB Bean Files for BAEL-717:Singleton EJB Bean. * BAEL-717: Singleton EJB Bean Corrected Indentation. * BAEL-717: Singleton EJB Bean Corrected Indentation. * BAEL-717: Singleton EJB Bean Corrected Indentation. * BAEL-717: Singleton EJB Bean Corrected Indentation. * BAEL-717: Singleton EJB Bean Changed artifactId value. * BAEL-717: Singleton EJB Bean. Added module for Singleton EJB Bean. * BAEL-717: Singleton EJB Bean. Removed Singleton EJB Bean Module. * BAEL-717: Singleton EJB Bean Changed the JNDI Lookup name. * BAEL-717: Singleton EJB Bean. Added the "singleton-ejb-bean" module. * BAEL-717: Singleton EJB Bean. Corrected Indentation. * BAEL-717: Singleton EJB Bean Corrected Indentation. * BAEL-717: Singleton EJB Bean. Corrected Indentation. * BAEL-717: Singleton EJB Bean. Corrected Indentation. * BAEL-717:Singleton EJB Bean. Corrected Indentation. * BAEL-717:Singleton EJB Bean. Corrected Indentation. * BAEL-717: Singleton Session Bean. Added class for Bean-Managed concurrrency. Changed class name from CountryStateCacheBean to CountryStateContainerManagedBean. * BAEL-717: Singleton Session Bean. Changing the name of the class to CountryStateContainerManagedBean. * BAEL-717: Singleton Session Bean. Added method to test Bean-Managed concurrency. * Get Latest. * deleting CountryStateBeanManagedBean for new file. * deleting CountryStateCacheBean for new file. * deleting CountryStateContainerManagedBean for new file. * BAEL-717: Singleton Session Bean. Adding file for Bean with Bean-Managed concurrency. Changing file name for original file to CountryStateContainerManagedBean with Container-Managed concurrency. * Deleting file for new checkin. * BAEL-717: Singleton Session Bean. Added test case for Bean-Manged concurrency. Change in JNDI names. * BAEL-717: Singleton Session Bean. Changed the assert method parameter order and null check in test cases. * BAEL-717:Singleton Session Bean Removed volatile keyword for the variable countryStatesMap. Marking it as final. --- .../baeldung/singletonbean/CountryStateBeanManagedBean.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryStateBeanManagedBean.java b/spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryStateBeanManagedBean.java index b437dc4d7f..ee2c1f005a 100644 --- a/spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryStateBeanManagedBean.java +++ b/spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryStateBeanManagedBean.java @@ -8,8 +8,6 @@ import java.util.Map; import javax.annotation.PostConstruct; import javax.ejb.ConcurrencyManagement; import javax.ejb.ConcurrencyManagementType; -import javax.ejb.Lock; -import javax.ejb.LockType; import javax.ejb.Singleton; import javax.ejb.Startup; @@ -18,7 +16,7 @@ import javax.ejb.Startup; @ConcurrencyManagement(ConcurrencyManagementType.BEAN) public class CountryStateBeanManagedBean implements CountryState { - private volatile Map> countryStatesMap = new HashMap>(); + private final Map> countryStatesMap = new HashMap>(); @PostConstruct public synchronized void initialize() { From 5b5386636b6c3a0e64d2b35deff1614e0d4006b7 Mon Sep 17 00:00:00 2001 From: Jorge Date: Sat, 21 Apr 2018 15:45:15 +0200 Subject: [PATCH 15/46] [BAEL-1641] Find all pairs of numbers in an array that add up to a given sum (#3890) * [BAEL-1641] Find all pairs of numbers in an array that add up to a given sum * Commiting editor's suggested changes * Commiting article Spring Data Reactive Mongo DB microservice in Kotlin * Revert commit for BAEL 1687 - Moving those files to a new branch * Use AssertJ and BDD-style on unit testing --- .../com/baeldung/algorithms/RunAlgorithm.java | 8 ++ .../pairsaddupnumber/DifferentPairs.java | 72 ++++++++++++++++++ .../pairsaddupnumber/ExistingPairs.java | 51 +++++++++++++ .../pairsaddupnumber/FindPairs.java | 74 +++++++++++++++++++ .../DifferentPairsUnitTest.java | 39 ++++++++++ .../ExistingPairsUnitTest.java | 34 +++++++++ 6 files changed, 278 insertions(+) create mode 100644 algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairs.java create mode 100644 algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairs.java create mode 100644 algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/FindPairs.java create mode 100644 algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairsUnitTest.java create mode 100644 algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairsUnitTest.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java b/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java index 6ab7dbb4e5..c82883425d 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java @@ -6,6 +6,7 @@ import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing; import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization; import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; import com.baeldung.algorithms.slope_one.SlopeOne; +import com.baeldung.algorithms.pairsaddupnumber.FindPairs; public class RunAlgorithm { @@ -17,6 +18,7 @@ public class RunAlgorithm { System.out.println("3 - Simple Genetic Algorithm"); System.out.println("4 - Ant Colony"); System.out.println("5 - Dijkstra"); + System.out.println("6 - All pairs in an array that add up to a given sum"); int decision = in.nextInt(); switch (decision) { case 1: @@ -37,6 +39,12 @@ public class RunAlgorithm { case 5: System.out.println("Please run the DijkstraAlgorithmTest."); break; + case 6: + final FindPairs findPairs = new FindPairs(); + final int[] input = {1, 4, 3, 2, 1, 4, 4, 3, 3}; + final int sum = 6; + findPairs.execute(input, sum); + break; default: System.out.println("Unknown option"); break; diff --git a/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairs.java b/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairs.java new file mode 100644 index 0000000000..e86e1d5a22 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairs.java @@ -0,0 +1,72 @@ +package com.baeldung.algorithms.pairsaddupnumber; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.IntStream; + +/** + * Find all different pairs of numbers in an array that add up to a given sum - Complexity O(n) + */ +public class DifferentPairs { + + /** + * Show all different pairs using traditional "for" loop + * + * @param input - number's array + * @param sum - given sum + * @return - number's array with all existing pairs. This list will contain just one pair's element because + * the other one can be calculated with SUM - element_1 = element_2 + */ + public static List findPairsWithForLoop(int[] input, int sum) { + final List allDifferentPairs = new ArrayList<>(); + // Aux. hash map + final Map pairs = new HashMap(); + for (int i : input) { + if (pairs.containsKey(i)) { + if (pairs.get(i) != null) { + // Add pair to returned list + allDifferentPairs.add(i); + } + // Mark pair as added to prevent duplicates + pairs.put(sum - i, null); + } else if (!pairs.containsValue(i)) { + // Add pair to aux. hash map + pairs.put(sum - i, i); + } + } + return allDifferentPairs; + } + + /** + * Show all different pairs using Java 8 stream API + * + * @param input - number's array + * @param sum - given sum + * @return - number's array with all existing pairs. This list will contain just one pair's element because + * the other one can be calculated with SUM - element_1 = element_2 + */ + public static List findPairsWithStreamApi(int[] input, int sum) { + final List allDifferentPairs = new ArrayList<>(); + // Aux. hash map + final Map pairs = new HashMap(); + IntStream.range(0, input.length).forEach(i -> { + if (pairs.containsKey(input[i])) { + if (pairs.get(input[i]) != null) { + // Add pair to returned list + allDifferentPairs.add(input[i]); + } + // Mark pair as added to prevent duplicates + pairs.put(sum - input[i], null); + } else if (!pairs.containsValue(input[i])) { + // Add pair to aux. hash map + pairs.put(sum - input[i], input[i]); + } + } + ); + return allDifferentPairs; + } +} + diff --git a/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairs.java b/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairs.java new file mode 100644 index 0000000000..6b10c73bcf --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairs.java @@ -0,0 +1,51 @@ +package com.baeldung.algorithms.pairsaddupnumber; + + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.IntStream; + +/** + * Find all existing pairs of numbers in an array that add up to a given sum - Complexity O(n^2) "Brute force" + */ +public class ExistingPairs { + + /** + * Show all existing pairs using traditional "for" loop + * + * @param input - number's array + * @param sum - given sum + * @return - number's array with all existing pairs. This list will contain just one pair's element because + * the other one can be calculated with SUM - element_1 = element_2 + */ + public static List findPairsWithForLoop(int[] input, int sum) { + final List allExistingPairs = new ArrayList<>(); + for (int i = 0; i < input.length; i++) { + for (int j = 0; j < input.length; j++) { + if (j != i && (input[i] + input[j]) == sum) { + allExistingPairs.add(input[i]); + } + } + } + return allExistingPairs; + } + + /** + * Show all existing pairs using Java 8 stream API + * + * @param input - number's array + * @param sum - given sum + * @return - number's array with all existing pairs. This list will contain just one pair's element because + * the other one can be calculated with SUM - element_1 = element_2 + */ + public static List findPairsWithStreamApi(int[] input, int sum) { + final List allExistingPairs = new ArrayList<>(); + IntStream.range(0, input.length).forEach(i -> + IntStream.range(0, input.length) + .filter(j -> i != j && input[i] + input[j] == sum) + .forEach(j -> allExistingPairs.add(input[i])) + ); + return allExistingPairs; + } +} + diff --git a/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/FindPairs.java b/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/FindPairs.java new file mode 100644 index 0000000000..4b309332ae --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/pairsaddupnumber/FindPairs.java @@ -0,0 +1,74 @@ +package com.baeldung.algorithms.pairsaddupnumber; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.IntStream; + + +public class FindPairs { + + public void execute(int[] input, int sum) { + final StringBuilder inputArray = new StringBuilder(); + inputArray.append("{"); + IntStream.range(0, input.length).forEach(i -> inputArray.append(input[i] + ", ")); + inputArray.append("}"); + System.out.println(" Given number array: " + inputArray.toString()); + System.out.println(" Given sum: " + sum); + /* Call services */ + getDifferentPairs(input, sum); + getExistingPairs(input, sum); + } + + /** + * Print all existing pairs for the given inputs: input array & sum number + */ + private static void getExistingPairs(int[] input, int sum) { + List pairs = new ArrayList<>(); + System.out.println("~ All existing pairs ~"); + + /* Traditional FOR loop */ + // Call method + pairs = ExistingPairs.findPairsWithForLoop(input, sum); + // Create a pretty printing + final StringBuilder output1 = new StringBuilder(); + pairs.forEach((pair) -> output1.append("{" + pair + ", " + (sum - pair) + "}, ")); + // Print result + System.out.println("Traditional \"for\" loop: " + output1.toString().substring(0, output1.length() - 2)); + + /* Java 8 stream API */ + // Call the method + pairs = ExistingPairs.findPairsWithStreamApi(input, sum); + // Create a pretty printing + final StringBuilder output2 = new StringBuilder(); + pairs.forEach((pair) -> output2.append("{" + pair + ", " + (sum - pair) + "}, ")); + // Print result + System.out.println("Java 8 streams API: " + output2.toString().substring(0, output2.length() - 2)); + } + + /** + * Print all different pairs for the given inputs: input array & sum number + */ + private static void getDifferentPairs(int[] input, int sum) { + List pairs = new ArrayList<>(); + System.out.println("~ All different pairs ~"); + + /* Traditional FOR loop */ + // Call method + pairs = DifferentPairs.findPairsWithForLoop(input, sum); + // Create a pretty printing + final StringBuilder output3 = new StringBuilder(); + pairs.forEach((pair) -> output3.append("{" + pair + ", " + (sum - pair) + "}, ")); + // Print result + System.out.println("Traditional \"for\" loop: " + output3.toString().substring(0, output3.length() - 2)); + + /* Java 8 stream API */ + // Call method + pairs = DifferentPairs.findPairsWithStreamApi(input, sum); + // Create a pretty printing + final StringBuilder output4 = new StringBuilder(); + pairs.forEach((pair) -> output4.append("{" + pair + ", " + (sum - pair) + "}, ")); + // Print result + System.out.println("Java 8 streams API: " + output4.toString().substring(0, output4.length() - 2)); + } +} + diff --git a/algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairsUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairsUnitTest.java new file mode 100644 index 0000000000..48fcfb871c --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/DifferentPairsUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.algorithms.pairsaddupnumber; + +import org.junit.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class DifferentPairsUnitTest { + + /* All different pairs */ + + @Test + public void whenTraditionalLoop_thenReturnAllDifferentPairs() { + /* Data */ + final int[] input = {2, 4, 3, 3, 8}; + final int sum = 6; + /* Call service */ + final List pairs = DifferentPairs.findPairsWithForLoop(input, sum); + /* Check results */ + assertThat(pairs).hasSize(2).contains(4,3).doesNotContain(8); + } + + @Test + public void whenStreamApi_thenReturnAllDifferentPairs() { + /* Data */ + final int[] input = {2, 4, 3, 3, 8}; + final int sum = 6; + /* Call service */ + final List pairs = DifferentPairs.findPairsWithStreamApi(input, sum); + /* Check results */ + assertNotNull(pairs); + assertEquals(pairs.size(),2); + assertEquals(pairs.get(0), new Integer(4)); + assertThat(pairs).hasSize(2).contains(4,3).doesNotContain(8); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairsUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairsUnitTest.java new file mode 100644 index 0000000000..ac6d6cc885 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/pairsaddupnumber/ExistingPairsUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.algorithms.pairsaddupnumber; + +import org.junit.Test; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + + +public class ExistingPairsUnitTest { + + /* All existing pairs */ + + @Test + public void whenTraditionalLoop_thenReturnAllExistingPairs() { + /* Data */ + final int[] input = {2, 4, 3, 3, 8}; + final int sum = 6; + /* Call service */ + final List pairs = ExistingPairs.findPairsWithForLoop(input, sum); + /* Check results */ + assertThat(pairs).hasSize(4).contains(2,4,3,3).doesNotContain(8); + } + + @Test + public void whenStreamApi_thenReturnAllExistingPairs() { + /* Data */ + final int[] input = {2, 4, 3, 3, 8}; + final int sum = 6; + /* Call service */ + final List pairs = ExistingPairs.findPairsWithStreamApi(input, sum); + /* Check results */ + assertThat(pairs).hasSize(4).contains(2,4,3,3).doesNotContain(8); + } +} From 5f839803635f13e8f912803d2474416754f05d75 Mon Sep 17 00:00:00 2001 From: Donato Rimenti Date: Sat, 21 Apr 2018 18:51:14 +0200 Subject: [PATCH 16/46] BAEL 1639: added singleton examples and test. (#3977) --- .../synchronization/DclSingleton.java | 38 ++++++ .../synchronization/DraconianSingleton.java | 34 +++++ .../synchronization/EarlyInitSingleton.java | 31 +++++ .../synchronization/EnumSingleton.java | 16 +++ .../InitOnDemandSingleton.java | 41 ++++++ .../SingletonSynchronizationUnitTest.java | 119 ++++++++++++++++++ 6 files changed, 279 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/DclSingleton.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/DraconianSingleton.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/EarlyInitSingleton.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/EnumSingleton.java create mode 100644 core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/InitOnDemandSingleton.java create mode 100644 core-java/src/test/java/com/baeldung/designpatterns/singleton/synchronization/SingletonSynchronizationUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/DclSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/DclSingleton.java new file mode 100644 index 0000000000..e10f111a56 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/DclSingleton.java @@ -0,0 +1,38 @@ +package com.baeldung.designpatterns.singleton.synchronization; + +/** + * Double-checked locking design pattern applied to a singleton. + * + * @author Donato Rimenti + * + */ +public class DclSingleton { + + /** + * Current instance of the singleton. + */ + private static volatile DclSingleton instance; + + /** + * Private constructor to avoid instantiation. + */ + private DclSingleton() { + } + + /** + * Returns the current instance of the singleton. + * + * @return the current instance of the singleton + */ + public static DclSingleton getInstance() { + if (instance == null) { + synchronized (DclSingleton.class) { + if (instance == null) { + instance = new DclSingleton(); + } + } + } + return instance; + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/DraconianSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/DraconianSingleton.java new file mode 100644 index 0000000000..1d01c49b13 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/DraconianSingleton.java @@ -0,0 +1,34 @@ +package com.baeldung.designpatterns.singleton.synchronization; + +/** + * Draconian singleton. The method to get the instance is synchronized. + * + * @author Donato Rimenti + * + */ +public class DraconianSingleton { + + /** + * Current instance of the singleton. + */ + private static DraconianSingleton instance; + + /** + * Private constructor to avoid instantiation. + */ + private DraconianSingleton() { + } + + /** + * Returns the current instance of the singleton. + * + * @return the current instance of the singleton + */ + public static synchronized DraconianSingleton getInstance() { + if (instance == null) { + instance = new DraconianSingleton(); + } + return instance; + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/EarlyInitSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/EarlyInitSingleton.java new file mode 100644 index 0000000000..18c4b7cdce --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/EarlyInitSingleton.java @@ -0,0 +1,31 @@ +package com.baeldung.designpatterns.singleton.synchronization; + +/** + * Singleton with early initialization. Inlines the singleton instance + * initialization. + * + * @author Donato Rimenti + * + */ +public class EarlyInitSingleton { + + /** + * Current instance of the singleton. + */ + private static final EarlyInitSingleton INSTANCE = new EarlyInitSingleton(); + + /** + * Private constructor to avoid instantiation. + */ + private EarlyInitSingleton() { + } + + /** + * Returns the current instance of the singleton. + * + * @return the current instance of the singleton + */ + public static EarlyInitSingleton getInstance() { + return INSTANCE; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/EnumSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/EnumSingleton.java new file mode 100644 index 0000000000..b7ff7f50b1 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/EnumSingleton.java @@ -0,0 +1,16 @@ +package com.baeldung.designpatterns.singleton.synchronization; + +/** + * Enum singleton pattern. Uses an enum to hold a reference to the singleton + * instance. + * + * @author Donato Rimenti + * + */ +public enum EnumSingleton { + + /** + * Current instance of the singleton. + */ + INSTANCE; +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/InitOnDemandSingleton.java b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/InitOnDemandSingleton.java new file mode 100644 index 0000000000..d76bada786 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/designpatterns/singleton/synchronization/InitOnDemandSingleton.java @@ -0,0 +1,41 @@ +package com.baeldung.designpatterns.singleton.synchronization; + +/** + * Initialization on demand singleton pattern. Uses a nested static class to + * hold a reference to the singleton instance. + * + * @author Donato Rimenti + * + */ +public class InitOnDemandSingleton { + + /** + * Holder for a singleton instance. + * + * @author Donato Rimenti + * + */ + private static class InstanceHolder { + + /** + * Current instance of the singleton. + */ + private static final InitOnDemandSingleton INSTANCE = new InitOnDemandSingleton(); + } + + /** + * Private constructor to avoid instantiation. + */ + private InitOnDemandSingleton() { + } + + /** + * Returns the current instance of the singleton. + * + * @return the current instance of the singleton + */ + public static InitOnDemandSingleton getInstance() { + return InstanceHolder.INSTANCE; + } + +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/designpatterns/singleton/synchronization/SingletonSynchronizationUnitTest.java b/core-java/src/test/java/com/baeldung/designpatterns/singleton/synchronization/SingletonSynchronizationUnitTest.java new file mode 100644 index 0000000000..2c1a3fe093 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/designpatterns/singleton/synchronization/SingletonSynchronizationUnitTest.java @@ -0,0 +1,119 @@ +package com.baeldung.designpatterns.singleton.synchronization; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Unit tests for the singleton synchronization package with the same name. + * + * @author Donato Rimenti + * + */ +public class SingletonSynchronizationUnitTest { + + /** + * Size of the thread pools used. + */ + private static final int POOL_SIZE = 1_000; + + /** + * Number of tasks to submit. + */ + private static final int TASKS_TO_SUBMIT = 1_000_000; + + /** + * Tests the thread-safety of {@link DraconianSingleton}. + */ + @Test + public void givenDraconianSingleton_whenMultithreadInstancesEquals_thenTrue() { + ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); + Set resultSet = Collections.synchronizedSet(new HashSet()); + + // Submits the instantiation tasks. + for (int i = 0; i < TASKS_TO_SUBMIT; i++) { + executor.submit(() -> resultSet.add(DraconianSingleton.getInstance())); + } + + // Since the instance of the object we inserted into the set is always + // the same, the size should be one. + Assert.assertEquals(1, resultSet.size()); + } + + /** + * Tests the thread-safety of {@link DclSingleton}. + */ + @Test + public void givenDclSingleton_whenMultithreadInstancesEquals_thenTrue() { + ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); + Set resultSet = Collections.synchronizedSet(new HashSet()); + + // Submits the instantiation tasks. + for (int i = 0; i < TASKS_TO_SUBMIT; i++) { + executor.submit(() -> resultSet.add(DclSingleton.getInstance())); + } + + // Since the instance of the object we inserted into the set is always + // the same, the size should be one. + Assert.assertEquals(1, resultSet.size()); + } + + /** + * Tests the thread-safety of {@link EarlyInitSingleton}. + */ + @Test + public void givenEarlyInitSingleton_whenMultithreadInstancesEquals_thenTrue() { + ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); + Set resultSet = Collections.synchronizedSet(new HashSet()); + + // Submits the instantiation tasks. + for (int i = 0; i < TASKS_TO_SUBMIT; i++) { + executor.submit(() -> resultSet.add(EarlyInitSingleton.getInstance())); + } + + // Since the instance of the object we inserted into the set is always + // the same, the size should be one. + Assert.assertEquals(1, resultSet.size()); + } + + /** + * Tests the thread-safety of {@link InitOnDemandSingleton}. + */ + @Test + public void givenInitOnDemandSingleton_whenMultithreadInstancesEquals_thenTrue() { + ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); + Set resultSet = Collections.synchronizedSet(new HashSet()); + + // Submits the instantiation tasks. + for (int i = 0; i < TASKS_TO_SUBMIT; i++) { + executor.submit(() -> resultSet.add(InitOnDemandSingleton.getInstance())); + } + + // Since the instance of the object we inserted into the set is always + // the same, the size should be one. + Assert.assertEquals(1, resultSet.size()); + } + + /** + * Tests the thread-safety of {@link EnumSingleton}. + */ + @Test + public void givenEnumSingleton_whenMultithreadInstancesEquals_thenTrue() { + ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); + Set resultSet = Collections.synchronizedSet(new HashSet()); + + // Submits the instantiation tasks. + for (int i = 0; i < TASKS_TO_SUBMIT; i++) { + executor.submit(() -> resultSet.add(EnumSingleton.INSTANCE)); + } + + // Since the instance of the object we inserted into the set is always + // the same, the size should be one. + Assert.assertEquals(1, resultSet.size()); + } +} From 83a8344e4ea1f024b1da42c57ccf15125e664316 Mon Sep 17 00:00:00 2001 From: Orry Date: Sat, 21 Apr 2018 20:29:32 +0200 Subject: [PATCH 17/46] BAEL-1701 (#4012) * BAEL-1701: Create SQSApplication, add most functionality (still need to format, and add queue monitoring) * BAEL-1701: Complete examples --- .../java/com/baeldung/sqs/SQSApplication.java | 146 ++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 aws/src/main/java/com/baeldung/sqs/SQSApplication.java diff --git a/aws/src/main/java/com/baeldung/sqs/SQSApplication.java b/aws/src/main/java/com/baeldung/sqs/SQSApplication.java new file mode 100644 index 0000000000..978506a24f --- /dev/null +++ b/aws/src/main/java/com/baeldung/sqs/SQSApplication.java @@ -0,0 +1,146 @@ +package com.baeldung.sqs; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.amazonaws.auth.AWSCredentials; +import com.amazonaws.auth.AWSStaticCredentialsProvider; +import com.amazonaws.auth.BasicAWSCredentials; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.sqs.AmazonSQSClientBuilder; +import com.amazonaws.services.sqs.model.CreateQueueRequest; +import com.amazonaws.services.sqs.model.DeleteMessageRequest; +import com.amazonaws.services.sqs.model.GetQueueAttributesRequest; +import com.amazonaws.services.sqs.model.GetQueueAttributesResult; +import com.amazonaws.services.sqs.model.MessageAttributeValue; +import com.amazonaws.services.sqs.model.ReceiveMessageRequest; +import com.amazonaws.services.sqs.model.SendMessageBatchRequest; +import com.amazonaws.services.sqs.model.SendMessageRequest; +import com.amazonaws.services.sqs.model.SetQueueAttributesRequest; +import com.amazonaws.services.sqs.model.SendMessageBatchRequestEntry; +import com.amazonaws.services.sqs.model.Message; +import com.amazonaws.services.sqs.AmazonSQS; + +public class SQSApplication { + + private static final AWSCredentials credentials; + + static { + // put your accesskey and secretkey here + credentials = new BasicAWSCredentials( + "", + "" + ); + } + + public static void main(String[] args) { + + // Set up the client + AmazonSQS sqs = AmazonSQSClientBuilder.standard() + .withCredentials(new AWSStaticCredentialsProvider(credentials)) + .withRegion(Regions.US_EAST_1) + .build(); + + // Create a standard queue + + CreateQueueRequest createStandardQueueRequest = new CreateQueueRequest("baeldung-queue"); + String standardQueueUrl = sqs.createQueue(createStandardQueueRequest) + .getQueueUrl(); + + System.out.println(standardQueueUrl); + + // Create a fifo queue + + Map queueAttributes = new HashMap(); + queueAttributes.put("FifoQueue", "true"); + queueAttributes.put("ContentBasedDeduplication", "true"); + + CreateQueueRequest createFifoQueueRequest = new CreateQueueRequest("baeldung-queue.fifo").withAttributes(queueAttributes); + String fifoQueueUrl = sqs.createQueue(createFifoQueueRequest) + .getQueueUrl(); + + System.out.println(fifoQueueUrl); + + // Set up a dead letter queue + + String deadLetterQueueUrl = sqs.createQueue("baeldung-dead-letter-queue") + .getQueueUrl(); + + GetQueueAttributesResult deadLetterQueueAttributes = sqs.getQueueAttributes(new GetQueueAttributesRequest(deadLetterQueueUrl).withAttributeNames("QueueArn")); + + String deadLetterQueueARN = deadLetterQueueAttributes.getAttributes() + .get("QueueArn"); + + SetQueueAttributesRequest queueAttributesRequest = new SetQueueAttributesRequest().withQueueUrl(standardQueueUrl) + .addAttributesEntry("RedrivePolicy", "{\"maxReceiveCount\":\"2\", " + "\"deadLetterTargetArn\":\"" + deadLetterQueueARN + "\"}"); + + sqs.setQueueAttributes(queueAttributesRequest); + + // Send a message to a standard queue + + Map messageAttributes = new HashMap<>(); + + messageAttributes.put("AttributeOne", new MessageAttributeValue().withStringValue("This is an attribute") + .withDataType("String")); + + SendMessageRequest sendMessageStandardQueue = new SendMessageRequest().withQueueUrl(standardQueueUrl) + .withMessageBody("A simple message.") + .withDelaySeconds(30) // Message will arrive in the queue after 30 seconds. We can use this only in standard queues + .withMessageAttributes(messageAttributes); + + sqs.sendMessage(sendMessageStandardQueue); + + // Send a message to a fifo queue + + SendMessageRequest sendMessageFifoQueue = new SendMessageRequest().withQueueUrl(fifoQueueUrl) + .withMessageBody("FIFO Queue") + .withMessageGroupId("baeldung-group-1") + .withMessageAttributes(messageAttributes); + + sqs.sendMessage(sendMessageFifoQueue); + + // Send multiple messages + + List messageEntries = new ArrayList<>(); + messageEntries.add(new SendMessageBatchRequestEntry().withId("id-1") + .withMessageBody("batch-1") + .withMessageGroupId("baeldung-group-1")); + messageEntries.add(new SendMessageBatchRequestEntry().withId("id-2") + .withMessageBody("batch-2") + .withMessageGroupId("baeldung-group-1")); + + SendMessageBatchRequest sendMessageBatchRequest = new SendMessageBatchRequest(fifoQueueUrl, messageEntries); + sqs.sendMessageBatch(sendMessageBatchRequest); + + // Read a message from a queue + + ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(fifoQueueUrl).withWaitTimeSeconds(10) // Long polling; + .withMaxNumberOfMessages(1); // Max is 10 + + List sqsMessages = sqs.receiveMessage(receiveMessageRequest) + .getMessages(); + + sqsMessages.get(0) + .getAttributes(); + sqsMessages.get(0) + .getBody(); + + // Delete a message from a queue + + sqs.deleteMessage(new DeleteMessageRequest().withQueueUrl(fifoQueueUrl) + .withReceiptHandle(sqsMessages.get(0) + .getReceiptHandle())); + + // Monitoring + GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest(standardQueueUrl).withAttributeNames("All"); + GetQueueAttributesResult getQueueAttributesResult = sqs.getQueueAttributes(getQueueAttributesRequest); + System.out.println(String.format("The number of messages on the queue: %s", getQueueAttributesResult.getAttributes() + .get("ApproximateNumberOfMessages"))); + System.out.println(String.format("The number of messages in flight: %s", getQueueAttributesResult.getAttributes() + .get("ApproximateNumberOfMessagesNotVisible"))); + + } + +} From fb744e25a53b704ba6790ec13ae37cefc00b1dc7 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Sat, 21 Apr 2018 22:38:45 +0200 Subject: [PATCH 18/46] added article links --- maven/README.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 maven/README.md diff --git a/maven/README.md b/maven/README.md new file mode 100644 index 0000000000..7c3779143a --- /dev/null +++ b/maven/README.md @@ -0,0 +1,9 @@ +### Relevant Articles + +- [Guide to the Core Maven Plugins](http://www.baeldung.com/core-maven-plugins) +- [Maven Resources Plugin](http://www.baeldung.com/maven-resources-plugin) +- [Maven Compiler Plugin](http://www.baeldung.com/maven-compiler-plugin) +- [Quick Guide to the Maven Surefire Plugin](http://www.baeldung.com/maven-surefire-plugin) +- [The Maven Failsafe Plugin](http://www.baeldung.com/maven-failsafe-plugin) +- [The Maven Verifier Plugin](http://www.baeldung.com/maven-verifier-plugin) +- [The Maven Clean Plugin](http://www.baeldung.com/maven-clean-plugin) From 8e0b36a8f90a93d91512185139e6efa573d2b626 Mon Sep 17 00:00:00 2001 From: Tom Hombergs Date: Sat, 21 Apr 2018 22:49:05 +0200 Subject: [PATCH 19/46] removed folder "SpringDependencyInjection" e Please enter the commit message for your changes. Lines starting --- Spring-DependencyInjection/pom.xml | 30 --------- .../src/main/java/beans.xml | 31 ---------- .../com/baeldung/spring/core/Address.java | 53 ---------------- .../java/com/baeldung/spring/core/Car.java | 30 --------- .../com/baeldung/spring/core/Customer.java | 61 ------------------- .../com/baeldung/spring/core/Department.java | 31 ---------- .../com/baeldung/spring/core/Employee.java | 23 ------- .../com/baeldung/spring/core/Product.java | 48 --------------- .../com/baeldung/spring/core/Student.java | 40 ------------ .../com/baeldung/spring/core/Subject.java | 30 --------- .../spring/core/config/AppConfig.java | 30 --------- .../AnnotationApplicationContextTest.java | 17 ------ .../JavaConfigApplicationContextTest.java | 23 ------- ...MLConfigurationApplicationContextTest.java | 28 --------- .../Spring_DependencyInjection/AppTest.java | 38 ------------ 15 files changed, 513 deletions(-) delete mode 100644 Spring-DependencyInjection/pom.xml delete mode 100644 Spring-DependencyInjection/src/main/java/beans.xml delete mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Address.java delete mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Car.java delete mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Customer.java delete mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Department.java delete mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Employee.java delete mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Product.java delete mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Student.java delete mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Subject.java delete mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/config/AppConfig.java delete mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/AnnotationApplicationContextTest.java delete mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/JavaConfigApplicationContextTest.java delete mode 100644 Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/XMLConfigurationApplicationContextTest.java delete mode 100644 Spring-DependencyInjection/src/test/java/com/spring/core/Spring_DependencyInjection/AppTest.java diff --git a/Spring-DependencyInjection/pom.xml b/Spring-DependencyInjection/pom.xml deleted file mode 100644 index cc818f948b..0000000000 --- a/Spring-DependencyInjection/pom.xml +++ /dev/null @@ -1,30 +0,0 @@ - - 4.0.0 - - com.spring.core - Spring-DependencyInjection - 0.0.1-SNAPSHOT - jar - - Spring-DependencyInjection - http://maven.apache.org - - - UTF-8 - - - - - org.springframework - spring-context - 4.3.14.RELEASE - - - junit - junit - 3.8.1 - test - - - diff --git a/Spring-DependencyInjection/src/main/java/beans.xml b/Spring-DependencyInjection/src/main/java/beans.xml deleted file mode 100644 index 71de8d3293..0000000000 --- a/Spring-DependencyInjection/src/main/java/beans.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Address.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Address.java deleted file mode 100644 index 9e6fe29c0c..0000000000 --- a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Address.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.spring.core; - -import org.springframework.stereotype.Component; - -@Component -public class Address { - - private String address1; - - private String city; - - private String state; - - private String country; - - public String getAddress1() { - return address1; - } - - public void setAddress1(String address1) { - this.address1 = address1; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - @Override - public String toString() { - return "Address [address1=" + address1 + ", city=" + city + ", state=" + state + ", country=" + country + "]"; - } - -} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Car.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Car.java deleted file mode 100644 index 3f940e1e28..0000000000 --- a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Car.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.spring.core; - -public class Car { - - private String carName; - - private String carType; - - public String getCarName() { - return carName; - } - - public void setCarName(String carName) { - this.carName = carName; - } - - public String getCarType() { - return carType; - } - - public void setCarType(String carType) { - this.carType = carType; - } - - @Override - public String toString() { - return "Car [carName=" + carName + ", carType=" + carType + "]"; - } - -} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Customer.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Customer.java deleted file mode 100644 index da9ac13021..0000000000 --- a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Customer.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.spring.core; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -@Component -public class Customer { - - @Value("Thomas") - private String customerName; - - @Value("Cust123") - private String customerId; - - private Product product; - - private Address address; - - @Autowired - public Customer(Address address) { - super(); - this.address = address; - } - - public String getCustomerName() { - return customerName; - } - - public void setCustomerName(String customerName) { - this.customerName = customerName; - } - - public String getCustomerId() { - return customerId; - } - - public void setCustomerId(String customerId) { - this.customerId = customerId; - } - - public Product getProduct() { - return product; - } - - @Autowired - public void setProduct(Product product) { - this.product = product; - } - - public Address getAddress() { - return address; - } - - @Override - public String toString() { - return "Customer [customerName=" + customerName + ", customerId=" + customerId + ", product=" + product - + ", address=" + address + "]"; - } - -} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Department.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Department.java deleted file mode 100644 index f7da2d560a..0000000000 --- a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Department.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.spring.core; - -import org.springframework.stereotype.Component; - -@Component -public class Department { - - private String departmentName; - - private String departmentId; - - public Department(String departmentName, String departmentNumber) { - super(); - this.departmentName = departmentName; - this.departmentId = departmentNumber; - } - - public String getDepartmentName() { - return departmentName; - } - - public String getDepartmentId() { - return departmentId; - } - - @Override - public String toString() { - return "Department [departmentName=" + departmentName + ", departmentNumber=" + departmentId + "]"; - } - -} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Employee.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Employee.java deleted file mode 100644 index de450b8e6b..0000000000 --- a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Employee.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.spring.core; - -import org.springframework.stereotype.Component; - -@Component -public class Employee { - - private Department department; - - public Employee(Department department) { - super(); - this.department = department; - } - - public Department getDepartment() { - return department; - } - - @Override - public String toString() { - return "Employee [department=" + department + "]"; - } -} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Product.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Product.java deleted file mode 100644 index 162c9b3429..0000000000 --- a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Product.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.spring.core; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -@Component -public class Product { - - @Value("product1") - private String productName; - - @Value("Pro123") - private String productId; - - @Value("100") - private String productCost; - - public String getProductName() { - return productName; - } - - public void setProductName(String productName) { - this.productName = productName; - } - - public String getProductId() { - return productId; - } - - public void setProductId(String productId) { - this.productId = productId; - } - - public String getProductCost() { - return productCost; - } - - public void setProductCost(String productCost) { - this.productCost = productCost; - } - - @Override - public String toString() { - return "Product [productName=" + productName + ", productId=" + productId + ", productCost=" + productCost - + "]"; - } - -} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Student.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Student.java deleted file mode 100644 index f2563f01ec..0000000000 --- a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Student.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.spring.core; - -public class Student { - - private String studentName; - - private String studentId; - - private Subject subject; - - public String getStudentName() { - return studentName; - } - - public void setStudentName(String studentName) { - this.studentName = studentName; - } - - public String getStudentId() { - return studentId; - } - - public void setStudentId(String studentId) { - this.studentId = studentId; - } - - public Subject getSubject() { - return subject; - } - - public void setSubject(Subject subject) { - this.subject = subject; - } - - @Override - public String toString() { - return "Student [studentName=" + studentName + ", studentId=" + studentId + ", subject=" + subject + "]"; - } - -} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Subject.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Subject.java deleted file mode 100644 index b160bbef18..0000000000 --- a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/Subject.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.spring.core; - -public class Subject { - - private String subjectName; - - private String subjectId; - - public String getSubjectName() { - return subjectName; - } - - public void setSubjectName(String subjectName) { - this.subjectName = subjectName; - } - - public String getSubjectId() { - return subjectId; - } - - public void setSubjectId(String subjectId) { - this.subjectId = subjectId; - } - - @Override - public String toString() { - return "Subject [subjectName=" + subjectName + ", subjectId=" + subjectId + "]"; - } - -} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/config/AppConfig.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/config/AppConfig.java deleted file mode 100644 index 496191d758..0000000000 --- a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/config/AppConfig.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.spring.core.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.baeldung.spring.core.Car; -import com.baeldung.spring.core.Department; -import com.baeldung.spring.core.Employee; - -@Configuration -public class AppConfig { - - @Bean - public Department getDepartment() { - return new Department("Sales", "S01"); - } - - @Bean - public Employee getEmployee() { - return new Employee(getDepartment()); - } - - @Bean - public Car getCar() { - Car car = new Car(); - car.setCarName("Honda"); - car.setCarType("SUV"); - return car; - } -} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/AnnotationApplicationContextTest.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/AnnotationApplicationContextTest.java deleted file mode 100644 index 02daf26eb2..0000000000 --- a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/AnnotationApplicationContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.spring.core.test; - -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.baeldung.spring.core.Customer; - -public class AnnotationApplicationContextTest { - - public static void main(String[] args) { - AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); - Customer customer = applicationContext.getBean(Customer.class); - System.out.println("Customer is :: " + customer); - System.out.println("Product is :: " + customer.getProduct()); - applicationContext.close(); - } -} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/JavaConfigApplicationContextTest.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/JavaConfigApplicationContextTest.java deleted file mode 100644 index 01b0c67675..0000000000 --- a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/JavaConfigApplicationContextTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.spring.core.test; - -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.support.AbstractApplicationContext; - -import com.baeldung.spring.core.Car; -import com.baeldung.spring.core.Department; -import com.baeldung.spring.core.Employee; -import com.baeldung.spring.core.config.AppConfig; - -public class JavaConfigApplicationContextTest { - - public static void main(String[] args) { - AbstractApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); - Department department = applicationContext.getBean(Department.class); - Employee employee = applicationContext.getBean(Employee.class); - System.out.println("Department is :: " + department); - System.out.println("Employee is :: " + employee); - Car car = applicationContext.getBean(Car.class); - System.out.println("Car is :: " + car); - applicationContext.close(); - } -} diff --git a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/XMLConfigurationApplicationContextTest.java b/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/XMLConfigurationApplicationContextTest.java deleted file mode 100644 index ead4226f1b..0000000000 --- a/Spring-DependencyInjection/src/main/java/com/baeldung/spring/core/test/XMLConfigurationApplicationContextTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.spring.core.test; - -import org.springframework.context.support.AbstractApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.baeldung.spring.core.Department; -import com.baeldung.spring.core.Employee; -import com.baeldung.spring.core.Student; -import com.baeldung.spring.core.Subject; - -public class XMLConfigurationApplicationContextTest { - - public static void main(String[] args) { - AbstractApplicationContext abstractApplicationContext = new ClassPathXmlApplicationContext("beans.xml"); - // Constructor Injection - Department department = (Department) abstractApplicationContext.getBean("department"); - Employee employee = (Employee) abstractApplicationContext.getBean("employee"); - System.out.println("Department is :: " + department); - System.out.println("Employee is :: " + employee); - - // Setter Injection - Subject subject = (Subject) abstractApplicationContext.getBean("subject"); - Student student = (Student) abstractApplicationContext.getBean("student"); - System.out.println("Subject is :: " + subject); - System.out.println("Student is :: " + student); - abstractApplicationContext.close(); - } -} diff --git a/Spring-DependencyInjection/src/test/java/com/spring/core/Spring_DependencyInjection/AppTest.java b/Spring-DependencyInjection/src/test/java/com/spring/core/Spring_DependencyInjection/AppTest.java deleted file mode 100644 index 5b3c551257..0000000000 --- a/Spring-DependencyInjection/src/test/java/com/spring/core/Spring_DependencyInjection/AppTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.spring.core.Spring_DependencyInjection; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - -/** - * Unit test for simple App. - */ -public class AppTest - extends TestCase -{ - /** - * Create the test case - * - * @param testName name of the test case - */ - public AppTest( String testName ) - { - super( testName ); - } - - /** - * @return the suite of tests being tested - */ - public static Test suite() - { - return new TestSuite( AppTest.class ); - } - - /** - * Rigourous Test :-) - */ - public void testApp() - { - assertTrue( true ); - } -} From 57a4f160aae3accd8217ef349a5b99d03a4d8904 Mon Sep 17 00:00:00 2001 From: chrisoberle Date: Sun, 22 Apr 2018 17:55:00 -0400 Subject: [PATCH 20/46] BAEL-1706 - optional parameters in java (#4050) * BAEL-1706 - optional parameters in java * minor adjustments per review * add tests * fix formatting * fix constructor issue with MultiVitaminOverloading * BAEL-1706 Test name change, formatting --- .../baeldung/optionalparams/MultiVitamin.java | 50 ++++++++++ .../MultiVitaminAllowingNulls.java | 38 ++++++++ .../MultiVitaminOverloading.java | 56 +++++++++++ .../MultiVitaminStaticFactoryMethods.java | 52 ++++++++++ .../MultiVitaminWithBuilder.java | 77 +++++++++++++++ .../OptionalParamsUnitTest.java | 96 +++++++++++++++++++ 6 files changed, 369 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/optionalparams/MultiVitamin.java create mode 100644 core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminAllowingNulls.java create mode 100644 core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminOverloading.java create mode 100644 core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminStaticFactoryMethods.java create mode 100644 core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminWithBuilder.java create mode 100644 core-java/src/test/java/com/baeldung/optionalparams/OptionalParamsUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/optionalparams/MultiVitamin.java b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitamin.java new file mode 100644 index 0000000000..709e74eac0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitamin.java @@ -0,0 +1,50 @@ +package com.baeldung.optionalparams; + +public class MultiVitamin { + + private String name; // required + private int vitaminA; // in mcg + private int vitaminC; // in mg + private int calcium; // in mg + private int iron; // in mg + + public MultiVitamin(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public int getVitaminA() { + return vitaminA; + } + + public void setVitaminA(int vitaminA) { + this.vitaminA = vitaminA; + } + + public int getVitaminC() { + return vitaminC; + } + + public void setVitaminC(int vitaminC) { + this.vitaminC = vitaminC; + } + + public int getCalcium() { + return calcium; + } + + public void setCalcium(int calcium) { + this.calcium = calcium; + } + + public int getIron() { + return iron; + } + + public void setIron(int iron) { + this.iron = iron; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminAllowingNulls.java b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminAllowingNulls.java new file mode 100644 index 0000000000..36d178783a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminAllowingNulls.java @@ -0,0 +1,38 @@ +package com.baeldung.optionalparams; + +public class MultiVitaminAllowingNulls { + + private String name; // required + private Integer vitaminA; // in mcg + private Integer vitaminC; // in mg + private Integer calcium; // in mg + private Integer iron; // in mg + + public MultiVitaminAllowingNulls(String name, Integer vitaminA, Integer vitaminC, Integer calcium, Integer iron) { + this.name = name; + this.vitaminA = vitaminA; + this.vitaminC = vitaminC; + this.calcium = calcium; + this.iron = iron; + } + + public String getName() { + return name; + } + + public Integer getVitaminA() { + return vitaminA; + } + + public Integer getVitaminC() { + return vitaminC; + } + + public Integer getCalcium() { + return calcium; + } + + public Integer getIron() { + return iron; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminOverloading.java b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminOverloading.java new file mode 100644 index 0000000000..e1d3032fd3 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminOverloading.java @@ -0,0 +1,56 @@ +package com.baeldung.optionalparams; + +public class MultiVitaminOverloading { + + static final int DEFAULT_IRON_AMOUNT = 20; + + private final String name; // required + private final int vitaminA; // in mcg + private final int vitaminC; // in mg + private final int calcium; // in mg + private final int iron; // in mg + + public MultiVitaminOverloading(String name) { + this(name, 0); + } + + public MultiVitaminOverloading(String name, int vitaminA) { + this(name, vitaminA, 0); + } + + public MultiVitaminOverloading(String name, int vitaminA, int vitaminC) { + this(name, vitaminA, vitaminC, 0); + } + + public MultiVitaminOverloading(String name, int vitaminA, int vitaminC, int calcium) { + this(name, vitaminA, vitaminC, calcium, DEFAULT_IRON_AMOUNT); + } + + public MultiVitaminOverloading(String name, int vitaminA, int vitaminC, int calcium, int iron) { + this.name = name; + this.vitaminA = vitaminA; + this.vitaminC = vitaminC; + this.calcium = calcium; + this.iron = iron; + } + + public String getName() { + return name; + } + + public int getVitaminA() { + return vitaminA; + } + + public int getVitaminC() { + return vitaminC; + } + + public int getCalcium() { + return calcium; + } + + public int getIron() { + return iron; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminStaticFactoryMethods.java b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminStaticFactoryMethods.java new file mode 100644 index 0000000000..ca7ab0f6cf --- /dev/null +++ b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminStaticFactoryMethods.java @@ -0,0 +1,52 @@ +package com.baeldung.optionalparams; + +public class MultiVitaminStaticFactoryMethods { + + static final int IRON_AMT_DEF = 20; + static final int IRON_AMT_MEN = 30; + + static final int CALCIUM_AMT_DEF = 100; + static final int CALCIUM_AMT_WOMEN = 120; + + private final String name; // required + private final int vitaminA; // in mcg + private final int vitaminC; // in mg + private final int calcium; // in mg + private final int iron; // in mg + + public static MultiVitaminStaticFactoryMethods forMen(String name) { + return new MultiVitaminStaticFactoryMethods(name, 5000, 60, CALCIUM_AMT_DEF, IRON_AMT_MEN); + } + + public static MultiVitaminStaticFactoryMethods forWomen(String name) { + return new MultiVitaminStaticFactoryMethods(name, 5000, 60, CALCIUM_AMT_WOMEN, IRON_AMT_DEF); + } + + private MultiVitaminStaticFactoryMethods(String name, int vitaminA, int vitaminC, int calcium, int iron) { + this.name = name; + this.vitaminA = vitaminA; + this.vitaminC = vitaminC; + this.calcium = calcium; + this.iron = iron; + } + + public String getName() { + return name; + } + + public int getVitaminA() { + return vitaminA; + } + + public int getVitaminC() { + return vitaminC; + } + + public int getCalcium() { + return calcium; + } + + public int getIron() { + return iron; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminWithBuilder.java b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminWithBuilder.java new file mode 100644 index 0000000000..e1b2920e9a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/optionalparams/MultiVitaminWithBuilder.java @@ -0,0 +1,77 @@ +package com.baeldung.optionalparams; + +public class MultiVitaminWithBuilder { + + private final String name; // required + private final int vitaminA; // in mcg + private final int vitaminC; // in mg + private final int calcium; // in mg + private final int iron; // in mg + + private MultiVitaminWithBuilder(MultiVitaminBuilder builder) { + this.name = builder.name; + this.vitaminA = builder.vitaminA; + this.vitaminC = builder.vitaminC; + this.calcium = builder.calcium; + this.iron = builder.iron; + } + + public String getName() { + return name; + } + + public int getVitaminA() { + return vitaminA; + } + + public int getVitaminC() { + return vitaminC; + } + + public int getCalcium() { + return calcium; + } + + public int getIron() { + return iron; + } + + public static class MultiVitaminBuilder { + + private static final int ZERO = 0; + + private final String name; // required + private int vitaminA = ZERO; + private int vitaminC = ZERO; + private int calcium = ZERO; + private int iron = ZERO; + + public MultiVitaminBuilder(String name) { + this.name = name; + } + + public MultiVitaminBuilder withVitaminA(int vitaminA) { + this.vitaminA = vitaminA; + return this; + } + + public MultiVitaminBuilder withVitaminC(int vitaminC) { + this.vitaminC = vitaminC; + return this; + } + + public MultiVitaminBuilder withCalcium(int calcium) { + this.calcium = calcium; + return this; + } + + public MultiVitaminBuilder withIron(int iron) { + this.iron = iron; + return this; + } + + public MultiVitaminWithBuilder build() { + return new MultiVitaminWithBuilder(this); + } + } +} diff --git a/core-java/src/test/java/com/baeldung/optionalparams/OptionalParamsUnitTest.java b/core-java/src/test/java/com/baeldung/optionalparams/OptionalParamsUnitTest.java new file mode 100644 index 0000000000..4f3c31822b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/optionalparams/OptionalParamsUnitTest.java @@ -0,0 +1,96 @@ +package com.baeldung.optionalparams; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.math.BigDecimal; + +import org.assertj.core.util.Arrays; +import org.junit.Test; + +public class OptionalParamsUnitTest { + + @Test + public void whenCreateMultiVitaminWithOverloading_thenOk() { + MultiVitaminOverloading multiVitamin = new MultiVitaminOverloading("Default Multivitamin"); + + assertThat(multiVitamin.getName()).isEqualTo("Default Multivitamin"); + assertThat(multiVitamin.getVitaminA()).isEqualTo(0); + assertThat(multiVitamin.getVitaminC()).isEqualTo(0); + assertThat(multiVitamin.getCalcium()).isEqualTo(0); + assertThat(multiVitamin.getIron()).isEqualTo(MultiVitaminOverloading.DEFAULT_IRON_AMOUNT); + } + + @Test + public void whenCreateMultiVitaminWithStaticFactoryMethods_thenOk() { + MultiVitaminStaticFactoryMethods mensMultiVitamin = MultiVitaminStaticFactoryMethods.forMen("Complete for Men"); + + assertThat(mensMultiVitamin.getName()).isEqualTo("Complete for Men"); + assertThat(mensMultiVitamin.getCalcium()).isEqualTo(MultiVitaminStaticFactoryMethods.CALCIUM_AMT_DEF); + assertThat(mensMultiVitamin.getIron()).isEqualTo(MultiVitaminStaticFactoryMethods.IRON_AMT_MEN); + + MultiVitaminStaticFactoryMethods womensMultiVitamin = MultiVitaminStaticFactoryMethods.forWomen("Complete for Women"); + + assertThat(womensMultiVitamin.getName()).isEqualTo("Complete for Women"); + assertThat(womensMultiVitamin.getCalcium()).isEqualTo(MultiVitaminStaticFactoryMethods.CALCIUM_AMT_WOMEN); + assertThat(womensMultiVitamin.getIron()).isEqualTo(MultiVitaminStaticFactoryMethods.IRON_AMT_DEF); + } + + @Test + public void whenCreateMultiVitaminWithBuilder_thenOk() { + MultiVitaminWithBuilder vitamin = new MultiVitaminWithBuilder.MultiVitaminBuilder("Maximum Strength") + .withCalcium(100) + .withIron(200) + .withVitaminA(50) + .withVitaminC(1000) + .build(); + + assertThat(vitamin.getName()).isEqualTo("Maximum Strength"); + assertThat(vitamin.getCalcium()).isEqualTo(100); + assertThat(vitamin.getIron()).isEqualTo(200); + assertThat(vitamin.getVitaminA()).isEqualTo(50); + assertThat(vitamin.getVitaminC()).isEqualTo(1000); + } + + @Test + public void whenCreateMutliVitaminWithAccessors_thenOk() { + MultiVitamin vitamin = new MultiVitamin("Generic"); + vitamin.setVitaminA(50); + vitamin.setVitaminC(1000); + vitamin.setCalcium(100); + vitamin.setIron(200); + + assertThat(vitamin.getName()).isEqualTo("Generic"); + assertThat(vitamin.getCalcium()).isEqualTo(100); + assertThat(vitamin.getIron()).isEqualTo(200); + assertThat(vitamin.getVitaminA()).isEqualTo(50); + assertThat(vitamin.getVitaminC()).isEqualTo(1000); + } + + @Test + public void whenCreateMultiVitaminWithNulls_thenOk() { + MultiVitamin vitamin = new MultiVitamin(null); + + assertThat(vitamin.getName()).isNull(); + } + + public void varArgsDemo() { + Object[] args = Arrays.array(Long.valueOf(1), Integer.valueOf(2), BigDecimal.valueOf(3)); + + processVarArgsWithCastingAntiPattern(args); + } + + private void processVarArgsWithCastingAntiPattern(Object... args) { + String message = "processing %s as %s"; + + // never do this sort of thing + for (Object arg : args) { + if (arg instanceof Long) { + System.out.println(String.format(message, arg, "Long")); + } else if (arg instanceof Integer) { + System.out.println(String.format(message, arg, "Integer")); + } else if (arg instanceof BigDecimal) { + System.out.println(String.format(message, arg, "BigDecimal")); + } + } + } +} From 0c81d77e1b0e0a33f0c2f3a3a36279a06cb963ac Mon Sep 17 00:00:00 2001 From: Felipe Santiago Corro Date: Sun, 22 Apr 2018 19:31:27 -0300 Subject: [PATCH 21/46] Spring MVC @PathVariable dot (.) get truncated --- .../CustomWebMvcConfigurationSupport.java | 17 +++++++++++ .../web/controller/SiteController.java | 30 +++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 spring-mvc-java/src/main/java/com/baeldung/spring/web/config/CustomWebMvcConfigurationSupport.java create mode 100644 spring-mvc-java/src/main/java/com/baeldung/web/controller/SiteController.java diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/CustomWebMvcConfigurationSupport.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/CustomWebMvcConfigurationSupport.java new file mode 100644 index 0000000000..4a9f6a3431 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/CustomWebMvcConfigurationSupport.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.web.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +@Configuration +public class CustomWebMvcConfigurationSupport extends WebMvcConfigurationSupport { + + @Bean + public RequestMappingHandlerMapping requestMappingHandlerMapping() { + RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping(); + handlerMapping.setUseSuffixPatternMatch(false); + return handlerMapping; + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/SiteController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/SiteController.java new file mode 100644 index 0000000000..3867380665 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/SiteController.java @@ -0,0 +1,30 @@ +package com.baeldung.web.controller; + +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@RequestMapping("/site") +public class SiteController { + + @RequestMapping(value = "/{firstValue}/{secondValue}", method = RequestMethod.GET) + public String requestWithError(@PathVariable("firstValue") String firstValue, + @PathVariable("secondValue") String secondValue) { + + return firstValue + " - " + secondValue; + } + + @RequestMapping(value = "/{firstValue}/{secondValue:.+}", method = RequestMethod.GET) + public String requestWithRegex(@PathVariable("firstValue") String firstValue, + @PathVariable("secondValue") String secondValue) { + + return firstValue + " - " + secondValue; + } + + @RequestMapping(value = "/{firstValue}/{secondValue}/", method = RequestMethod.GET) + public String requestWithSlash(@PathVariable("firstValue") String firstValue, + @PathVariable("secondValue") String secondValue) { + + return firstValue + " - " + secondValue; + } +} From dba41e16b0a31346cd527404e4b99cc99fecd7b7 Mon Sep 17 00:00:00 2001 From: fanatixan Date: Mon, 23 Apr 2018 06:37:12 +0200 Subject: [PATCH 22/46] working with booleans in thymeleaf (#4061) --- spring-thymeleaf/README.md | 10 +- .../BooleanExpressionsController.java | 45 +++++ .../main/webapp/WEB-INF/views/booleans.html | 179 ++++++++++++++++++ 3 files changed, 230 insertions(+), 4 deletions(-) create mode 100644 spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BooleanExpressionsController.java create mode 100644 spring-thymeleaf/src/main/webapp/WEB-INF/views/booleans.html diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index 2c37e73ada..4d152aee8a 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -10,6 +10,7 @@ - [Spring MVC + Thymeleaf 3.0: New Features](http://www.baeldung.com/spring-thymeleaf-3) - [How to Work with Dates in Thymeleaef](http://www.baeldung.com/dates-in-thymeleaf) - [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven) +- [Working with Booleans in Thymeleaf](http://www.baeldung.com/working-with-booleans-in-thymeleaf) ### Build the Project @@ -22,11 +23,12 @@ mvn cargo:run Access the pages using the URLs: -http://localhost:8082/spring-thymeleaf/ -http://localhost:8082/spring-thymeleaf/addStudent/ -http://localhost:8082/spring-thymeleaf/listStudents/ + - http://localhost:8082/spring-thymeleaf/ + - http://localhost:8082/spring-thymeleaf/addStudent/ + - http://localhost:8082/spring-thymeleaf/listStudents/ + - http://localhost:8082/spring-thymeleaf/booleans/ -The first URL is the home page of the application. The home page has links to the other two pages. +The first URL is the home page of the application. The home page has links to the second and third pages. ### Security The user/password required is: user1/user1Pass diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BooleanExpressionsController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BooleanExpressionsController.java new file mode 100644 index 0000000000..3a640e1499 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BooleanExpressionsController.java @@ -0,0 +1,45 @@ +package com.baeldung.thymeleaf.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +/** + * Controller to test boolean expressions + * + */ +@Controller +public class BooleanExpressionsController { + + @RequestMapping(value = "/booleans", method = RequestMethod.GET) + public String getDates(Model model) { + // "truthy" values + model.addAttribute("trueValue", true); + model.addAttribute("one", 1); + model.addAttribute("nonZeroCharacter", 'a'); + model.addAttribute("emptyString", ""); + model.addAttribute("foo", "foo"); + model.addAttribute("object", new Object()); + model.addAttribute("arrayOfZeros", new Integer[] { 0, 0 }); + model.addAttribute("arrayOfZeroAndOne", new Integer[] { 0, 1 }); + model.addAttribute("arrayOfOnes", new Integer[] { 1, 1 }); + + // "falsy" values + model.addAttribute("nullValue", null); + model.addAttribute("falseValue", false); + model.addAttribute("zero", 0); + model.addAttribute("zeroCharacter", '\0'); + model.addAttribute("falseString", "false"); + model.addAttribute("no", "no"); + model.addAttribute("off", "off"); + + model.addAttribute("isRaining", true); + model.addAttribute("isSunny", true); + model.addAttribute("isCold", false); + model.addAttribute("isWarm", true); + + return "booleans.html"; + } + +} diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/booleans.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/booleans.html new file mode 100644 index 0000000000..63d894421b --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/booleans.html @@ -0,0 +1,179 @@ + + + + +Expression utility objects + + + +

'Truthy' and 'falsy' expressions

+
    +
  • 'true' is evaluated to
  • +
  • '1' is evaluated to
  • +
  • non zero character is evaluated to
  • +
  • empty string is evaluated to
  • +
  • the string "foo" is evaluated to
  • +
  • an object is evaluated to
  • +
  • the array [0, 0] is evaluated to
  • +
  • the array [0, 1] is evaluated to
  • +
  • the array [1, 1] is evaluated to
  • + +
  • null value is evaluated to
  • +
  • 'false' is evaluated to
  • +
  • '0' is evaluated to
  • +
  • zero character is evaluated to
  • +
  • the string "false" is evaluated to
  • +
  • the string "no" is evaluated to
  • +
  • the string "off" is evaluated to
  • +
+ +

Using booleans as rendering conditions

+ + + + + + + + + + + + + + + + +
th:ifth:unless
truewill be renderedwon't be rendered
falsewon't be renderedwill be rendered
+ +

Boolean and conditional operators

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AB${A or B}${A} or ${B}${A and B}${A} and ${B}${!A}!${A}${not A}not ${A}
truetrue
truefalse
falsetrue
falsefalse
+ +
    +
  • the result of "true ? 'then'" is
  • +
  • the result of "false ? 'then'" is
  • +
  • the result of "true ? 'then' : 'else'" is
  • +
  • the result of "false ? 'then' : 'else'" is
  • +
  • the result of "'foo' ?: 'bar'" is
  • +
  • the result of "null ?: 'bar'" is
  • +
  • the result of "0 ?: 'bar'" is
  • +
  • the result of "1 ?: 'bar'" is
  • +
+ +
    +
  • The weather is bad
  • +
  • The weather is bad
  • +
  • The weather is good
  • +
  • The weather is good
  • +
  • It's warm
  • +
  • It's warm
  • +
  • It's warm
  • +
  • It's warm
  • +
  • It's
  • +
  • +
+ +

#bools utility object

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Array#bools.arrayIsTrue()#bools.arrayIsFalse()#bools.arrayAnd()#bools.arrayOr()
[0, 0]
[0, 1]
[1, 1]
+ + \ No newline at end of file From 5f1b1b0b0decc94cf8cb4cb2a1d8003c3c013f16 Mon Sep 17 00:00:00 2001 From: ramansahasi Date: Mon, 23 Apr 2018 20:27:02 +0530 Subject: [PATCH 23/46] BAEL-1725 Java Pass-by-reference vs Pass-by-value - First commit (#4058) * BAEL-1725 Java Pass-by-reference vs Pass-by-value - First commit * updated test cases --- .../parameterpassing/NonPrimitives.java | 27 ++++++++++++++ .../baeldung/parameterpassing/Primitives.java | 17 +++++++++ .../NonPrimitivesUnitTest.java | 37 +++++++++++++++++++ .../parameterpassing/PrimitivesUnitTest.java | 28 ++++++++++++++ 4 files changed, 109 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/parameterpassing/NonPrimitives.java create mode 100644 core-java/src/main/java/com/baeldung/parameterpassing/Primitives.java create mode 100644 core-java/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java create mode 100644 core-java/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java diff --git a/core-java/src/main/java/com/baeldung/parameterpassing/NonPrimitives.java b/core-java/src/main/java/com/baeldung/parameterpassing/NonPrimitives.java new file mode 100644 index 0000000000..0e1746fc38 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/parameterpassing/NonPrimitives.java @@ -0,0 +1,27 @@ +package com.baeldung.parameterpassing; + +public class NonPrimitives { + public static void main(String[] args) { + FooClass a = new FooClass(1); + FooClass b = new FooClass(1); + + System.out.printf("Before Modification: a = %d and b = %d ", a.num, b.num); + modify(a, b); + System.out.printf("\nAfter Modification: a = %d and b = %d ", a.num, b.num); + } + + public static void modify(FooClass a1, FooClass b1) { + a1.num++; + + b1 = new FooClass(1); + b1.num++; + } +} + +class FooClass { + public int num; + + public FooClass(int num) { + this.num = num; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/parameterpassing/Primitives.java b/core-java/src/main/java/com/baeldung/parameterpassing/Primitives.java new file mode 100644 index 0000000000..f63229d7de --- /dev/null +++ b/core-java/src/main/java/com/baeldung/parameterpassing/Primitives.java @@ -0,0 +1,17 @@ +package com.baeldung.parameterpassing; + +public class Primitives { + public static void main(String[] args) { + int x = 1; + int y = 2; + + System.out.printf("Before Modification: x = %d and y = %d ", x, y); + modify(x, y); + System.out.printf("\nAfter Modification: x = %d and y = %d ", x, y); + } + + public static void modify(int x1, int y1) { + x1 = 5; + y1 = 10; + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java b/core-java/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java new file mode 100644 index 0000000000..62f891d11b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/parameterpassing/NonPrimitivesUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.parameterpassing; + +import org.junit.Assert; +import org.junit.Test; + +public class NonPrimitivesUnitTest { + @Test + public void whenModifyingObjects_thenOriginalObjectChanged() { + Foo a = new Foo(1); + Foo b = new Foo(1); + + // Before Modification + Assert.assertEquals(a.num, 1); + Assert.assertEquals(b.num, 1); + + modify(a, b); + + // After Modification + Assert.assertEquals(a.num, 2); + Assert.assertEquals(b.num, 1); + } + + public static void modify(Foo a1, Foo b1) { + a1.num++; + + b1 = new Foo(1); + b1.num++; + } +} + +class Foo { + public int num; + + public Foo(int num) { + this.num = num; + } +} \ No newline at end of file diff --git a/core-java/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java b/core-java/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java new file mode 100644 index 0000000000..496cd1d205 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/parameterpassing/PrimitivesUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.parameterpassing; + +import org.junit.Assert; +import org.junit.Test; + +public class PrimitivesUnitTest { + @Test + public void whenModifyingPrimitives_thenOriginalValuesNotModified() { + + int x = 1; + int y = 2; + + // Before Modification + Assert.assertEquals(x, 1); + Assert.assertEquals(y, 2); + + modify(x, y); + + // After Modification + Assert.assertEquals(x, 1); + Assert.assertEquals(y, 2); + } + + public static void modify(int x1, int y1) { + x1 = 5; + y1 = 10; + } +} From b7a7a80968526d3b76acd500d11754f5df2b21ac Mon Sep 17 00:00:00 2001 From: Eugen Date: Mon, 23 Apr 2018 21:55:33 +0300 Subject: [PATCH 24/46] Update README.md --- vavr/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/vavr/README.md b/vavr/README.md index 373f897486..4bef25b625 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -1,8 +1,8 @@ ### Relevant Articles: -- [Introduction to Vavr](http://www.baeldung.com/javaslang) -- [Guide to Try in Vavr](http://www.baeldung.com/javaslang-try) -- [Guide to Pattern Matching in Vavr](http://www.baeldung.com/javaslang-pattern-matching) -- [Property Testing Example With Vavr](http://www.baeldung.com/javaslang-property-testing) +- [Introduction to Vavr](http://www.baeldung.com/vavr) +- [Guide to Try in Vavr](http://www.baeldung.com/vavr-try) +- [Guide to Pattern Matching in Vavr](http://www.baeldung.com/vavr-pattern-matching) +- [Property Testing Example With Vavr](http://www.baeldung.com/vavr-property-testing) - [Exceptions in Lambda Expression Using Vavr](http://www.baeldung.com/exceptions-using-vavr) - [Vavr (ex-Javaslang) Support in Spring Data](http://www.baeldung.com/spring-vavr) - [Introduction to Vavr’s Validation API](http://www.baeldung.com/vavr-validation-api) From 79fa4592e0009467439d133ed484f77b7bf3f01e Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Mon, 23 Apr 2018 22:14:53 +0000 Subject: [PATCH 25/46] Demonstration of Java assert --- .../com/baeldung/assertion/Assertion.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/assertion/Assertion.java diff --git a/core-java/src/main/java/com/baeldung/assertion/Assertion.java b/core-java/src/main/java/com/baeldung/assertion/Assertion.java new file mode 100644 index 0000000000..795728757c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/assertion/Assertion.java @@ -0,0 +1,26 @@ +package com.baeldung.assertion; + +/** + * Simple demonstration of using Java assert keyword. + */ +public class Assertion { + + public static void main(String[] args) { + Assertion assertion = new Assertion(); + assertion.setup(); + } + + public void setup() { + Object conn = getConnection(); + assert conn != null : "Connection is null"; + + // continue with other setup ... + } + + // Simulate failure to get a connection; using Object + // to avoid dependencies on JDBC or some other heavy + // 3rd party library + public Object getConnection() { + return null; + } +} From 274745e3bbcbc38f6c44abdd448acd4db1b0942e Mon Sep 17 00:00:00 2001 From: abialas Date: Tue, 24 Apr 2018 03:58:19 +0200 Subject: [PATCH 26/46] BAEL-1679 (#3959) * BAEL-1412 add java 8 spring data features * BAEL-21 new HTTP API overview * BAEL-21 fix executor * BAEL-1432 add custom gradle task * BAEL-1567 add samples of cookie and session in serlvet * BAEL-1567 use stream api * BAEL-1567 fix optional * BAEL-1679 add query annotation jpa spring data * BAEL-1679 added new junits * BAEL-1679 use assertJ, use givenWhenThen naming convention --- .../main/java/org/baeldung/model/User.java | 8 + .../baeldung/repository/UserRepository.java | 60 ++++ .../UserRepositoryIntegrationTest.java | 300 +++++++++++++++++- 3 files changed, 353 insertions(+), 15 deletions(-) diff --git a/spring-boot/src/main/java/org/baeldung/model/User.java b/spring-boot/src/main/java/org/baeldung/model/User.java index 61936584c4..eb886338a0 100644 --- a/spring-boot/src/main/java/org/baeldung/model/User.java +++ b/spring-boot/src/main/java/org/baeldung/model/User.java @@ -15,6 +15,14 @@ public class User { private String name; private Integer status; + public User() { + } + + public User(String name, Integer status) { + this.name = name; + this.status = status; + } + public Integer getId() { return id; } diff --git a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java index c9a06b5bab..a5cf6a0c24 100644 --- a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java +++ b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java @@ -1,10 +1,20 @@ package org.baeldung.repository; import org.baeldung.model.User; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import java.util.Collection; +import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.stream.Stream; @@ -21,4 +31,54 @@ public interface UserRepository extends JpaRepository { @Async CompletableFuture findOneByStatus(Integer status); + @Query("SELECT u FROM User u WHERE u.status = 1") + Collection findAllActiveUsers(); + + @Query(value = "SELECT * FROM USERS u WHERE u.status = 1", nativeQuery = true) + Collection findAllActiveUsersNative(); + + @Query("SELECT u FROM User u WHERE u.status = ?1") + User findUserByStatus(Integer status); + + @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true) + User findUserByStatusNative(Integer status); + + @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") + User findUserByStatusAndName(Integer status, String name); + + @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") + User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); + + @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) + User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); + + @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") + User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName); + + @Query("SELECT u FROM User u WHERE u.name like ?1%") + User findUserByNameLike(String name); + + @Query("SELECT u FROM User u WHERE u.name like :name%") + User findUserByNameLikeNamedParam(@Param("name") String name); + + @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true) + User findUserByNameLikeNative(String name); + + @Query(value = "SELECT u FROM User u") + List findAllUsers(Sort sort); + + @Query(value = "SELECT u FROM User u ORDER BY id") + Page findAllUsersWithPagination(Pageable pageable); + + @Query(value = "SELECT * FROM Users ORDER BY id \n-- #pageable\n", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) + Page findAllUsersWithPaginationNative(Pageable pageable); + + @Modifying + @Query("update User u set u.status = :status where u.name = :name") + int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); + + @Modifying + @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) + int updateUserSetStatusForNameNative(Integer status, String name); + } diff --git a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java index 2b61aa6252..f1e1ecce55 100644 --- a/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java @@ -1,58 +1,65 @@ package org.baeldung.repository; -import org.baeldung.boot.Application; +import org.baeldung.boot.config.H2JpaConfig; import org.baeldung.model.User; import org.junit.After; 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.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.domain.JpaSort; +import org.springframework.data.mapping.PropertyReferenceException; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; +import java.util.Collection; +import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Stream; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Created by adam. */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) +@SpringBootTest(classes = H2JpaConfig.class) public class UserRepositoryIntegrationTest { private final String USER_NAME_ADAM = "Adam"; + private final String USER_NAME_PETER = "Peter"; + private final Integer INACTIVE_STATUS = 0; private final Integer ACTIVE_STATUS = 1; - @Autowired - private UserRepository userRepository; + @Autowired private UserRepository userRepository; @Test - public void shouldReturnEmptyOptionalWhenSearchByNameInEmptyDB() { + public void givenEmptyDBWhenFindOneByNameThenReturnEmptyOptional() { Optional foundUser = userRepository.findOneByName(USER_NAME_ADAM); - assertThat(foundUser.isPresent(), equalTo(false)); + assertThat(foundUser.isPresent()).isEqualTo(false); } @Test - public void shouldReturnOptionalWithPresentUserWhenExistsWithGivenName() { + public void givenUserInDBWhenFindOneByNameThenReturnOptionalWithUser() { User user = new User(); user.setName(USER_NAME_ADAM); userRepository.save(user); Optional foundUser = userRepository.findOneByName(USER_NAME_ADAM); - assertThat(foundUser.isPresent(), equalTo(true)); - assertThat(foundUser.get().getName(), equalTo(USER_NAME_ADAM)); + assertThat(foundUser.isPresent()).isEqualTo(true); + assertThat(foundUser.get().getName()).isEqualTo(USER_NAME_ADAM); } @Test @Transactional - public void shouldReturnStreamOfUsersWithNameWhenExistWithSameGivenName() { + public void givenUsersWithSameNameInDBWhenFindAllByNameThenReturnStreamOfUsers() { User user1 = new User(); user1.setName(USER_NAME_ADAM); userRepository.save(user1); @@ -70,12 +77,12 @@ public class UserRepositoryIntegrationTest { userRepository.save(user4); try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { - assertThat(foundUsersStream.count(), equalTo(3l)); + assertThat(foundUsersStream.count()).isEqualTo(3l); } } @Test - public void shouldReturnUserWithGivenStatusAsync() throws ExecutionException, InterruptedException { + public void givenUserInDBWhenFindOneByStatusAsyncThenReturnCompletableFutureUser() throws ExecutionException, InterruptedException { User user = new User(); user.setName(USER_NAME_ADAM); user.setStatus(ACTIVE_STATUS); @@ -83,8 +90,271 @@ public class UserRepositoryIntegrationTest { CompletableFuture userByStatus = userRepository.findOneByStatus(ACTIVE_STATUS); - assertThat(userByStatus.get().getName(), equalTo(USER_NAME_ADAM)); + assertThat(userByStatus.get().getName()).isEqualTo(USER_NAME_ADAM); + } + @Test + public void givenUsersInDBWhenFindAllWithQueryAnnotationThenReturnCollectionWithActiveUsers() { + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setStatus(ACTIVE_STATUS); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_ADAM); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User user3 = new User(); + user3.setName(USER_NAME_ADAM); + user3.setStatus(INACTIVE_STATUS); + userRepository.save(user3); + + Collection allActiveUsers = userRepository.findAllActiveUsers(); + + assertThat(allActiveUsers.size()).isEqualTo(2); + } + + @Test + public void givenUsersInDBWhenFindAllWithQueryAnnotationNativeThenReturnCollectionWithActiveUsers() { + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setStatus(ACTIVE_STATUS); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_ADAM); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User user3 = new User(); + user3.setName(USER_NAME_ADAM); + user3.setStatus(INACTIVE_STATUS); + userRepository.save(user3); + + Collection allActiveUsers = userRepository.findAllActiveUsersNative(); + + assertThat(allActiveUsers.size()).isEqualTo(2); + } + + @Test + public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationThenReturnActiveUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationNativeThenReturnActiveUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationIndexedParamsThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParamsThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNamesThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationIndexedParamsThenReturnUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByNameLike("Ad"); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNamedParamsThenReturnUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad"); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNativeThenReturnUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByNameLikeNative("Ad"); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindAllWithSortByNameThenReturnUsersSorted() { + userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); + + List usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + + assertThat(usersSortByName.get(0).getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test(expected = PropertyReferenceException.class) + public void givenUsersInDBWhenFindAllSortWithFunctionThenThrowException() { + userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); + + userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + + List usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)")); + + assertThat(usersSortByNameLength.get(0).getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindAllSortWithFunctionQueryAnnotationJPQLThenReturnUsersSorted() { + userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); + + userRepository.findAllUsers(new Sort("name")); + + List usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); + + assertThat(usersSortByNameLength.get(0).getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationJPQLThenReturnPageOfUsers() { + userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE2", INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", INACTIVE_STATUS)); + + Page usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3)); + + assertThat(usersPage.getContent().get(0).getName()).isEqualTo("SAMPLE1"); + } + + @Test + public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationNativeThenReturnPageOfUsers() { + userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE2", INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", INACTIVE_STATUS)); + + Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3)); + + assertThat(usersSortByNameLength.getContent().get(0).getName()).isEqualTo("SAMPLE1"); + } + + @Test + @Transactional + public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationJPQLThenModifyMatchingUsers() { + userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", ACTIVE_STATUS)); + + int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE"); + + assertThat(updatedUsersSize).isEqualTo(2); + } + + @Test + @Transactional + public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() { + userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", ACTIVE_STATUS)); + userRepository.flush(); + + int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE"); + + assertThat(updatedUsersSize).isEqualTo(2); } @After From a529a53c5f86ffa59c8fe6dc4282646f65553907 Mon Sep 17 00:00:00 2001 From: KevinGilmore Date: Tue, 24 Apr 2018 21:50:57 -0500 Subject: [PATCH 27/46] Update README files (#4065) * BAEL-1612: Update README * BAEL-1562: Update README * BAEL-1562: Update README --- core-java/README.md | 2 +- spring-thymeleaf/README.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java/README.md b/core-java/README.md index b9d87be785..c38d6b6160 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -151,4 +151,4 @@ - [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced) - [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings) - [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition) - +- [The "final" Keyword in Java](http://www.baeldung.com/java-final) diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index 4d152aee8a..9210186a98 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -11,6 +11,7 @@ - [How to Work with Dates in Thymeleaef](http://www.baeldung.com/dates-in-thymeleaf) - [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven) - [Working with Booleans in Thymeleaf](http://www.baeldung.com/working-with-booleans-in-thymeleaf) +- [Working with Fragments in Thymeleaf](http://www.baeldung.com/spring-thymeleaf-fragments) ### Build the Project From 3922598eda37c725afdb6e9c5c07d7d49c4be049 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Wed, 25 Apr 2018 09:28:33 +0300 Subject: [PATCH 28/46] remove comments --- .../baeldung/ignite/spring/config/SpringDataConfig.java | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/libraries-data/src/main/java/com/baeldung/ignite/spring/config/SpringDataConfig.java b/libraries-data/src/main/java/com/baeldung/ignite/spring/config/SpringDataConfig.java index 20a00a0285..7627c91bc6 100644 --- a/libraries-data/src/main/java/com/baeldung/ignite/spring/config/SpringDataConfig.java +++ b/libraries-data/src/main/java/com/baeldung/ignite/spring/config/SpringDataConfig.java @@ -19,14 +19,9 @@ public class SpringDataConfig { @Bean public Ignite igniteInstance() { IgniteConfiguration config = new IgniteConfiguration(); - // Setting some custom name for the node. - //config.setIgniteInstanceName("springDataNode"); - // Enabling peer-class loading feature. - //config.setPeerClassLoadingEnabled(true); - // Defining and creating a new cache to be used by Ignite Spring Data - // repository. + CacheConfiguration cache = new CacheConfiguration("baeldungCache"); - // Setting SQL schema for the cache. + cache.setIndexedTypes(Integer.class, EmployeeDTO.class); config.setCacheConfiguration(cache); return Ignition.start(config); From c465c9a837bd71a59ee021283947107052f9a0b4 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 13:37:29 +0530 Subject: [PATCH 29/46] Back-link corrected (#4071) --- apache-poi/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-poi/README.md b/apache-poi/README.md index c052bc9bf6..862981991d 100644 --- a/apache-poi/README.md +++ b/apache-poi/README.md @@ -1,4 +1,4 @@ ### Relevant Articles: - [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi) - [Working with Microsoft Excel in Java](http://www.baeldung.com/java-microsoft-excel) -- [Creating a MS PowerPoint Presentation in Java](https://github.com/eugenp/tutorials/tree/master/apache-poi) +- [Creating a MS PowerPoint Presentation in Java](http://www.baeldung.com/apache-poi-slideshow) From b55e44a923b68d7b5c92bb07ec1029d987e77ad6 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 13:44:05 +0530 Subject: [PATCH 30/46] Back-link corrected (#4073) --- spring-5/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-5/README.md b/spring-5/README.md index 566b905c74..d37927cfc7 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -12,7 +12,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring 5 Functional Bean Registration](http://www.baeldung.com/spring-5-functional-beans) - [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config) - [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) -- [Spring 5 Testing with @EnabledIf Annotation](http://www.baeldung.com/sring-5-enabledif) +- [Spring 5 Testing with @EnabledIf Annotation](http://www.baeldung.com/spring-5-enabledIf) - [Introduction to Spring REST Docs](http://www.baeldung.com/spring-rest-docs) - [Spring Security 5 – OAuth2 Login](http://www.baeldung.com/spring-security-5-oauth2-login) - [Spring ResponseStatusException](http://www.baeldung.com/spring-response-status-exception) From 47c841d274b8815bdf495aad874c5f7d9789f9d6 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 13:45:34 +0530 Subject: [PATCH 31/46] Back-link added (#4074) --- couchbase/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/couchbase/README.md b/couchbase/README.md index f124a0192c..9b76609593 100644 --- a/couchbase/README.md +++ b/couchbase/README.md @@ -5,6 +5,7 @@ - [Using Couchbase in a Spring Application](http://www.baeldung.com/couchbase-sdk-spring) - [Asynchronous Batch Opereations in Couchbase](http://www.baeldung.com/async-batch-operations-in-couchbase) - [Querying Couchbase with MapReduce Views](http://www.baeldung.com/couchbase-query-mapreduce-view) +- [Querying Couchbase with N1QL](http://www.baeldung.com/n1ql-couchbase) ### Overview This Maven project contains the Java code for the Couchbase entities and Spring services From 29e7690bb7041bc38f523a214decfb17c4561a71 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 13:46:47 +0530 Subject: [PATCH 32/46] Back-link added (#4075) --- core-kotlin/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-kotlin/README.md b/core-kotlin/README.md index d6bd41a111..630d4c7436 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -24,3 +24,4 @@ - [Regular Expressions in Kotlin](http://www.baeldung.com/kotlin-regular-expressions) - [Objects in Kotlin](http://www.baeldung.com/kotlin-objects) - [Reading from a File in Kotlin](http://www.baeldung.com/kotlin-read-file) +- [Guide to Kotlin @JvmField](http://www.baeldung.com/kotlin-jvm-field-annotation) From dddca4ebcf8469a668be7781c3c0a1023bf9617b Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 13:49:07 +0530 Subject: [PATCH 33/46] Back-link added (#4076) --- spring-mvc-kotlin/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-mvc-kotlin/README.md b/spring-mvc-kotlin/README.md index b7cbcb1a7a..4e92117c52 100644 --- a/spring-mvc-kotlin/README.md +++ b/spring-mvc-kotlin/README.md @@ -1,3 +1,4 @@ ### Relevant articles - [Spring MVC Setup with Kotlin](http://www.baeldung.com/spring-mvc-kotlin) - [Working with Kotlin and JPA](https://github.com/eugenp/tutorials/tree/master/spring-mvc-kotlin) +- [Kotlin-allopen and Spring](http://www.baeldung.com/kotlin-allopen-spring) From 7f5fe746aa6cecbe19f96ad40afc595d6d029a68 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 13:49:26 +0530 Subject: [PATCH 34/46] Back-link added (#4077) --- static-analysis/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/static-analysis/README.md b/static-analysis/README.md index 74cc64b90d..e4d4bc7bfc 100644 --- a/static-analysis/README.md +++ b/static-analysis/README.md @@ -1,3 +1,4 @@ ## Relevant articles: - [Introduction to PMD](http://www.baeldung.com/pmd) +- [Java Static Analysis Tools in Eclipse and IntelliJ IDEA](http://www.baeldung.com/java-static-analysis-tools) From cf38a2c3af74d0764eec151d4184b00ce93a50ad Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 13:50:29 +0530 Subject: [PATCH 35/46] Back-link added (#4078) --- libraries/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries/README.md b/libraries/README.md index 7c06aa88ca..bac06ae2d7 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -72,6 +72,7 @@ - [Introduction to OpenCSV](http://www.baeldung.com/opencsv) - [A Guide to Unirest](http://www.baeldung.com/unirest) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) +- [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy) 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. From 4f9b20ea12f94dc9f606b227e9e733625e003c8a Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 13:52:13 +0530 Subject: [PATCH 36/46] Back-link added (#4080) --- testing-modules/junit-5/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index 85e628668a..0a9dccf666 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -11,4 +11,4 @@ - [JUnit 5 @Test Annotation](http://www.baeldung.com/junit-5-test-annotation) - [JUnit Assert an Exception is Thrown](http://www.baeldung.com/junit-assert-exception) - [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) - +- [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) From 64c8f6ebb3b303ec4da83b620fac89ac83f40999 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 13:52:56 +0530 Subject: [PATCH 37/46] Back-link added (#4081) --- core-java-9/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-9/README.md b/core-java-9/README.md index 152b9f8841..d0758d585b 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -22,3 +22,4 @@ - [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles) - [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client) - [Method Handles in Java](http://www.baeldung.com/java-method-handles) +- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue) From 3fcac48c7d8438575d22b5af65011a9b84ae5cbb Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 13:53:49 +0530 Subject: [PATCH 38/46] Back-link added (#4083) --- guava/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/guava/README.md b/guava/README.md index 08814fd8b5..bb4e225649 100644 --- a/guava/README.md +++ b/guava/README.md @@ -32,3 +32,4 @@ - [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) From 872d24faa58c8665803f22491f923f95e6b173fb Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 13:55:19 +0530 Subject: [PATCH 39/46] Back-link corrected (#4086) --- spring-bom/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-bom/README.md b/spring-bom/README.md index 10e3502d11..d056216a2e 100644 --- a/spring-bom/README.md +++ b/spring-bom/README.md @@ -1,3 +1,3 @@ ### Relevant Articles: -- [Spring with Maven BOM] +- [Spring with Maven BOM](http://www.baeldung.com/spring-maven-bom) From ec594224480d3c980bb90e9014f90f8c68dfb022 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 13:55:39 +0530 Subject: [PATCH 40/46] Back-link added (#4087) --- spring-core/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-core/README.md b/spring-core/README.md index 0d984e87d4..b6804a4ce0 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -10,5 +10,6 @@ - [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults) - [Groovy Bean Definitions](http://www.baeldung.com/spring-groovy-beans) - [XML-Based Injection in Spring](http://www.baeldung.com/spring-xml-injection) -- [A Quick Guide to the Spring @Lazy Annotation] (http://www.baeldung.com/spring-lazy-annotation) +- [A Quick Guide to the Spring @Lazy Annotation](http://www.baeldung.com/spring-lazy-annotation) - [Injecting Prototype Beans into a Singleton Instance in Spring](http://www.baeldung.com/spring-inject-prototype-bean-into-singleton) +- [How to Inject a Property Value Into a Class Not Managed by Spring?](http://www.baeldung.com/inject-properties-value-non-spring-class) From 4f7355873fc75c86e23a31bc6db519aa05894911 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 14:01:03 +0530 Subject: [PATCH 41/46] Back-link added (#4091) --- core-java-io/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java-io/README.md b/core-java-io/README.md index 52485acfd5..f2ac99584f 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -22,4 +22,5 @@ - [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor) - [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute) - [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api) -- [Zipping and Unzipping in Java](http://www.baeldung.com/java-compress-and-uncompress) \ No newline at end of file +- [Zipping and Unzipping in Java](http://www.baeldung.com/java-compress-and-uncompress) +- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice) From 13c7bae874b8d33abb65643c05a7ff7f52b797fa Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 14:07:29 +0530 Subject: [PATCH 42/46] Back-link added (#4089) --- algorithms/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/algorithms/README.md b/algorithms/README.md index 23209a5966..df445146d9 100644 --- a/algorithms/README.md +++ b/algorithms/README.md @@ -20,3 +20,4 @@ - [A Maze Solver in Java](http://www.baeldung.com/java-solve-maze) - [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku) - [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words) +- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations) From 4ff02d42133bde02fa9a652fb2f8fca27ce7680f Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Wed, 25 Apr 2018 15:52:05 +0100 Subject: [PATCH 43/46] added example code for Java mail (#4101) --- core-java/pom.xml | 5 ++ .../java/com/baeldung/mail/EmailService.java | 80 +++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/mail/EmailService.java diff --git a/core-java/pom.xml b/core-java/pom.xml index f7bf9ed12a..05275e149d 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -235,6 +235,11 @@ h2 1.4.197 + + javax.mail + mail + 1.5.0-b01 + diff --git a/core-java/src/main/java/com/baeldung/mail/EmailService.java b/core-java/src/main/java/com/baeldung/mail/EmailService.java new file mode 100644 index 0000000000..e775b9f708 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/mail/EmailService.java @@ -0,0 +1,80 @@ +package com.baeldung.mail; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.Properties; +import javax.mail.*; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeMultipart; + +public class EmailService { + + private String host = ""; + private int port = 0; + private String username = ""; + private String password = ""; + + + public EmailService(String host, int port, String username, String password) { + + this.host = host; + this.port = port; + this.username = username; + this.password = password; + + sendMail(); + } + + private void sendMail() { + + Properties prop = new Properties(); + prop.put("mail.smtp.auth", true); + prop.put("mail.smtp.starttls.enable", "true"); + prop.put("mail.smtp.host", host); + prop.put("mail.smtp.port", port); + prop.put("mail.smtp.ssl.trust", host); + + Session session = Session.getInstance(prop, new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + + try { + + Message message = new MimeMessage(session); + message.setFrom(new InternetAddress("from@gmail.com")); + message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com")); + message.setSubject("Mail Subject"); + + String msg = "This is my first email using JavaMailer"; + + MimeBodyPart mimeBodyPart = new MimeBodyPart(); + mimeBodyPart.setContent(msg, "text/html"); + + MimeBodyPart attachmentBodyPart = new MimeBodyPart(); + attachmentBodyPart.attachFile(new File("pom.xml")); + + Multipart multipart = new MimeMultipart(); + multipart.addBodyPart(mimeBodyPart); + multipart.addBodyPart(attachmentBodyPart); + + message.setContent(multipart); + + Transport.send(message); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void main(String ... args) { + new EmailService("smtp.mailtrap.io", 25, "87ba3d9555fae8", "91cb4379af43ed"); + } + +} From 6f649662b9551f6a26afb280a8cdd14f3f3fe888 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 21:24:35 +0530 Subject: [PATCH 44/46] Back-link added (#4099) --- core-java-io/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-io/README.md b/core-java-io/README.md index f2ac99584f..84720e7b77 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -23,4 +23,5 @@ - [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute) - [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api) - [Zipping and Unzipping in Java](http://www.baeldung.com/java-compress-and-uncompress) +- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path) - [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice) From 18daff358604009e82f60b51ea4cdb0f6027e802 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 21:25:11 +0530 Subject: [PATCH 45/46] Back-link added (#4088) --- core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/README.md b/core-java/README.md index c38d6b6160..4eb98b1b33 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -151,4 +151,5 @@ - [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced) - [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings) - [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition) +- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max) - [The "final" Keyword in Java](http://www.baeldung.com/java-final) From e5aff9cf81d8a00b78972f8b809929f9b09655c0 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Wed, 25 Apr 2018 21:25:36 +0530 Subject: [PATCH 46/46] Back-link added (#4082) --- libraries/README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/libraries/README.md b/libraries/README.md index bac06ae2d7..1bb3799075 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -59,12 +59,12 @@ - [Intro to JDO Queries 2/2](http://www.baeldung.com/jdo-queries) - [Guide to google-http-client](http://www.baeldung.com/google-http-client) - [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client) -- [Programatically Create, Configure, and Run a Tomcat Server] (http://www.baeldung.com/tomcat-programmatic-setup) +- [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup) - [A Docker Guide for Java](http://www.baeldung.com/docker-java-api) - [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling) - [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic) - [Introduction To OpenCSV](http://www.baeldung.com/opencsv) -- [Introduction to Akka Actors in Java] (http://www.baeldung.com/akka-actors-java) +- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) - [Asynchronous HTTP with async-http-client in Java](https://github.com/eugenp/tutorials/tree/master/libraries) - [Introduction to Smooks](http://www.baeldung.com/smooks) - [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets) @@ -72,6 +72,7 @@ - [Introduction to OpenCSV](http://www.baeldung.com/opencsv) - [A Guide to Unirest](http://www.baeldung.com/unirest) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) +- [A Guide to Apache Commons Collections CollectionUtils](http://www.baeldung.com/apache-commons-collection-utils) - [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy) 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.