From ae47827879d0e9396ad5de5f979f495629a35838 Mon Sep 17 00:00:00 2001 From: alv21 Date: Thu, 8 Feb 2018 19:15:56 +0100 Subject: [PATCH 001/152] Different Types of Bean Injection in Spring --- .../beansinjectiontypes/Cabriolet.java | 8 +++ .../com/baeldung/beansinjectiontypes/Car.java | 6 ++ .../DealershipTraditionalStyle.java | 9 +++ .../DealershipWithDependenciesInjection.java | 13 +++++ .../baeldung/beansinjectiontypes/Sedan.java | 10 ++++ .../constructor/Config.java | 20 +++++++ .../constructor/Dealership.java | 20 +++++++ .../constructor/HornCheckerFile.java | 15 +++++ .../constructor/HornCheckerXML.java | 15 +++++ .../beansinjectiontypes/setter/Config.java | 22 ++++++++ .../setter/Dealership.java | 19 +++++++ .../setter/HornCheckerFile.java | 15 +++++ .../setter/HornCheckerXML.java | 15 +++++ .../resources/beansinjectiontypes-ctx.xml | 10 ++++ .../BeansInjectionTypesIntegrationTest.java | 56 +++++++++++++++++++ 15 files changed, 253 insertions(+) create mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/Cabriolet.java create mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/Car.java create mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/DealershipTraditionalStyle.java create mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/DealershipWithDependenciesInjection.java create mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/Sedan.java create mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/Config.java create mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/Dealership.java create mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/HornCheckerFile.java create mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/HornCheckerXML.java create mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/Config.java create mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/Dealership.java create mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/HornCheckerFile.java create mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/HornCheckerXML.java create mode 100644 spring-core/src/main/resources/beansinjectiontypes-ctx.xml create mode 100644 spring-core/src/test/java/com/baeldung/beansinjectiontypes/BeansInjectionTypesIntegrationTest.java diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Cabriolet.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Cabriolet.java new file mode 100644 index 0000000000..2bf9b8b954 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Cabriolet.java @@ -0,0 +1,8 @@ +package com.baeldung.beansinjectiontypes; + +public class Cabriolet implements Car{ + + public void honk(){ + System.out.println("I'm a cabriolet!"); + } +} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Car.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Car.java new file mode 100644 index 0000000000..e88e218f95 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Car.java @@ -0,0 +1,6 @@ +package com.baeldung.beansinjectiontypes; + +public interface Car { + + public void honk(); +} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/DealershipTraditionalStyle.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/DealershipTraditionalStyle.java new file mode 100644 index 0000000000..b917049e41 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/DealershipTraditionalStyle.java @@ -0,0 +1,9 @@ +package com.baeldung.beansinjectiontypes; + +public class DealershipTraditionalStyle { + private Car car = new Sedan(); + + public Car getCar() { + return car; + } +} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/DealershipWithDependenciesInjection.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/DealershipWithDependenciesInjection.java new file mode 100644 index 0000000000..9b25e21dc7 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/DealershipWithDependenciesInjection.java @@ -0,0 +1,13 @@ +package com.baeldung.beansinjectiontypes; + +public class DealershipWithDependenciesInjection { + private Car car; + + public DealershipWithDependenciesInjection(Car car) { + this.car = car; + } + + public Car getCar() { + return car; + } +} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Sedan.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Sedan.java new file mode 100644 index 0000000000..0ae4cf5a40 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Sedan.java @@ -0,0 +1,10 @@ +package com.baeldung.beansinjectiontypes; + +import org.springframework.stereotype.Component; + +@Component +public class Sedan implements Car { + public void honk(){ + System.out.println("I'm a sedan!"); + } +} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/Config.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/Config.java new file mode 100644 index 0000000000..3e2534f892 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/Config.java @@ -0,0 +1,20 @@ +package com.baeldung.beansinjectiontypes.constructor; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.beansinjectiontypes.Car; +import com.baeldung.beansinjectiontypes.Sedan; + +@Configuration(value="constructorConfig") +public class Config { + @Bean + public Car car() { + return new Sedan(); + } + + @Bean + public Dealership dealership() { + return new Dealership(car()); + } +} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/Dealership.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/Dealership.java new file mode 100644 index 0000000000..6151ec8e70 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/Dealership.java @@ -0,0 +1,20 @@ +package com.baeldung.beansinjectiontypes.constructor; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.baeldung.beansinjectiontypes.Car; + +@Component(value="constructorDealership") +public class Dealership { + private Car car; + + @Autowired + public Dealership(Car car) { + this.car = car; + } + + public Car getCar() { + return car; + } +} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/HornCheckerFile.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/HornCheckerFile.java new file mode 100644 index 0000000000..924372e3df --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/HornCheckerFile.java @@ -0,0 +1,15 @@ +package com.baeldung.beansinjectiontypes.constructor; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class HornCheckerFile { + + public static void main(String[] args) { + try (AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(Config.class)) { + Dealership dealership = (Dealership) context.getBean("dealership"); + + dealership.getCar().honk(); + } + } +} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/HornCheckerXML.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/HornCheckerXML.java new file mode 100644 index 0000000000..3c035986e6 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/HornCheckerXML.java @@ -0,0 +1,15 @@ +package com.baeldung.beansinjectiontypes.constructor; + +import org.springframework.context.support.FileSystemXmlApplicationContext; + +public class HornCheckerXML { + + public static void main(String[] args) { + try (FileSystemXmlApplicationContext context = + new FileSystemXmlApplicationContext("src/main/resources/beansinjectiontypes-ctx.xml")) { + Dealership dealership = (Dealership) context.getBean("constructorDealership"); + + dealership.getCar().honk(); + } + } +} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/Config.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/Config.java new file mode 100644 index 0000000000..212d303ce7 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/Config.java @@ -0,0 +1,22 @@ +package com.baeldung.beansinjectiontypes.setter; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.beansinjectiontypes.Car; +import com.baeldung.beansinjectiontypes.Sedan; + +@Configuration(value="setterConfig") +public class Config { + @Bean + public Car car() { + return new Sedan(); + } + + @Bean + public Dealership dealership() { + Dealership dealership = new Dealership(); + dealership.setCar(car()); + return dealership; + } +} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/Dealership.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/Dealership.java new file mode 100644 index 0000000000..db9c7cbceb --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/Dealership.java @@ -0,0 +1,19 @@ +package com.baeldung.beansinjectiontypes.setter; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.baeldung.beansinjectiontypes.Car; + +@Component(value="setterDealership") +public class Dealership { + private Car car; + + @Autowired + public void setCar(Car car) { + this.car = car; + } + public Car getCar() { + return car; + } +} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/HornCheckerFile.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/HornCheckerFile.java new file mode 100644 index 0000000000..3372635bd3 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/HornCheckerFile.java @@ -0,0 +1,15 @@ +package com.baeldung.beansinjectiontypes.setter; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class HornCheckerFile { + + public static void main(String[] args) { + try (AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(Config.class)) { + Dealership dealership = (Dealership) context.getBean("dealership"); + + dealership.getCar().honk(); + } + } +} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/HornCheckerXML.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/HornCheckerXML.java new file mode 100644 index 0000000000..0863d16d86 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/HornCheckerXML.java @@ -0,0 +1,15 @@ +package com.baeldung.beansinjectiontypes.setter; + +import org.springframework.context.support.FileSystemXmlApplicationContext; + +public class HornCheckerXML { + + public static void main(String[] args) { + try (FileSystemXmlApplicationContext context = + new FileSystemXmlApplicationContext("src/main/resources/beansinjectiontypes-ctx.xml")) { + Dealership dealership = (Dealership) context.getBean("setterDealership"); + + dealership.getCar().honk(); + } + } +} diff --git a/spring-core/src/main/resources/beansinjectiontypes-ctx.xml b/spring-core/src/main/resources/beansinjectiontypes-ctx.xml new file mode 100644 index 0000000000..86131a83b1 --- /dev/null +++ b/spring-core/src/main/resources/beansinjectiontypes-ctx.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/beansinjectiontypes/BeansInjectionTypesIntegrationTest.java b/spring-core/src/test/java/com/baeldung/beansinjectiontypes/BeansInjectionTypesIntegrationTest.java new file mode 100644 index 0000000000..9ffa44ced7 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/beansinjectiontypes/BeansInjectionTypesIntegrationTest.java @@ -0,0 +1,56 @@ +package com.baeldung.beansinjectiontypes; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.support.FileSystemXmlApplicationContext; + +import com.baeldung.beansinjectiontypes.constructor.Config; +import com.baeldung.beansinjectiontypes.constructor.Dealership; + +public class BeansInjectionTypesIntegrationTest { + + @Test + public void configBean_WhenSetOnConstructor_ThenDependencyValid() { + try (AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(Config.class)) { + Dealership dealership = (Dealership) context.getBean("dealership"); + + assertTrue(dealership.getCar() instanceof Sedan); + } + } + + @Test + public void configBean_WhenSetOnSetter_ThenDependencyValid() { + try (AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(com.baeldung.beansinjectiontypes.setter.Config.class)) { + com.baeldung.beansinjectiontypes.setter.Dealership dealership = + (com.baeldung.beansinjectiontypes.setter.Dealership) context.getBean("dealership"); + + assertTrue(dealership.getCar() instanceof Sedan); + } + } + + @Test + public void annotationAndXML_WhenSetOnSetter_ThenDependencyValid() { + try (FileSystemXmlApplicationContext context = + new FileSystemXmlApplicationContext("src/main/resources/beansinjectiontypes-ctx.xml")) { + Dealership dealership = (Dealership) context.getBean("constructorDealership"); + + assertTrue(dealership.getCar() instanceof Sedan); + } + } + + @Test + public void annotationAndXML_WhenSetOnConstructor_ThenDependencyValid() { + try (FileSystemXmlApplicationContext context = + new FileSystemXmlApplicationContext("src/main/resources/beansinjectiontypes-ctx.xml")) { + com.baeldung.beansinjectiontypes.setter.Dealership dealership = + (com.baeldung.beansinjectiontypes.setter.Dealership) context.getBean("setterDealership"); + + assertTrue(dealership.getCar() instanceof Sedan); + } + } + +} From e792f17f82f863850d07884f4638c53beca7f52f Mon Sep 17 00:00:00 2001 From: alv21 Date: Fri, 2 Mar 2018 18:08:04 +0100 Subject: [PATCH 002/152] BAEL-1585 --- .../com/baeldung/java_8_features/Car.java | 31 +++++++++++++++++++ .../baeldung/java8/Java8MaxMinUnitTest.java | 26 ++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 core-java-8/src/main/java/com/baeldung/java_8_features/Car.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Car.java b/core-java-8/src/main/java/com/baeldung/java_8_features/Car.java new file mode 100644 index 0000000000..139475bc25 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/java_8_features/Car.java @@ -0,0 +1,31 @@ +package com.baeldung.java_8_features; + +public class Car { + + private String model; + private int topSpeed; + + public Car(String model, int topSpeed) { + super(); + this.model = model; + this.topSpeed = topSpeed; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + + public int getTopSpeed() { + return topSpeed; + } + + public void setTopSpeed(int topSpeed) { + this.topSpeed = topSpeed; + } + + +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java index 4979338452..55caeeba5e 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.java8; import com.baeldung.java_8_features.Person; +import com.baeldung.java_8_features.Car; import org.junit.Test; import java.util.Arrays; @@ -44,4 +45,29 @@ public class Java8MaxMinUnitTest { assertEquals("Should be Alex", alex, minByAge); } + @Test + public void whenArrayIsOfIntegerThenMinCanBeDoneUsingIntegerComparator() { + int[] integers = new int[] { 20, 98, 12, 7, 35 }; + + int min = Arrays.stream(integers) + .min() + .getAsInt(); + + assertEquals(7, min); + } + + @Test + public void whenArrayIsOfPersonObjectThenMaxCanBeDoneUsingCustomComparatorThroughLambda() { + final Car porsche = new Car("Porsche 959", 319); + final Car ferrari = new Car("Ferrari 288 GTO", 303); + final Car bugatti = new Car("Bugatti Veyron 16.4 Super Sport", 415); + final Car mcLaren = new Car("McLaren F1", 355); + final Car[] fastCars = { porsche, ferrari, bugatti, mcLaren }; + + final Car maxBySpeed = Arrays.stream(fastCars) + .max(Comparator.comparing(Car::getTopSpeed)) + .orElseThrow(NoSuchElementException::new); + + assertEquals(bugatti, maxBySpeed); + } } From af542fce4092246ca65e9799260be3bd726f286f Mon Sep 17 00:00:00 2001 From: alv21 Date: Fri, 2 Mar 2018 22:32:37 +0100 Subject: [PATCH 003/152] Revert "Different Types of Bean Injection in Spring" This reverts commit ae47827879d0e9396ad5de5f979f495629a35838. --- .../beansinjectiontypes/Cabriolet.java | 8 --- .../com/baeldung/beansinjectiontypes/Car.java | 6 -- .../DealershipTraditionalStyle.java | 9 --- .../DealershipWithDependenciesInjection.java | 13 ----- .../baeldung/beansinjectiontypes/Sedan.java | 10 ---- .../constructor/Config.java | 20 ------- .../constructor/Dealership.java | 20 ------- .../constructor/HornCheckerFile.java | 15 ----- .../constructor/HornCheckerXML.java | 15 ----- .../beansinjectiontypes/setter/Config.java | 22 -------- .../setter/Dealership.java | 19 ------- .../setter/HornCheckerFile.java | 15 ----- .../setter/HornCheckerXML.java | 15 ----- .../resources/beansinjectiontypes-ctx.xml | 10 ---- .../BeansInjectionTypesIntegrationTest.java | 56 ------------------- 15 files changed, 253 deletions(-) delete mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/Cabriolet.java delete mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/Car.java delete mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/DealershipTraditionalStyle.java delete mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/DealershipWithDependenciesInjection.java delete mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/Sedan.java delete mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/Config.java delete mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/Dealership.java delete mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/HornCheckerFile.java delete mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/HornCheckerXML.java delete mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/Config.java delete mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/Dealership.java delete mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/HornCheckerFile.java delete mode 100644 spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/HornCheckerXML.java delete mode 100644 spring-core/src/main/resources/beansinjectiontypes-ctx.xml delete mode 100644 spring-core/src/test/java/com/baeldung/beansinjectiontypes/BeansInjectionTypesIntegrationTest.java diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Cabriolet.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Cabriolet.java deleted file mode 100644 index 2bf9b8b954..0000000000 --- a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Cabriolet.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.beansinjectiontypes; - -public class Cabriolet implements Car{ - - public void honk(){ - System.out.println("I'm a cabriolet!"); - } -} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Car.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Car.java deleted file mode 100644 index e88e218f95..0000000000 --- a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Car.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.beansinjectiontypes; - -public interface Car { - - public void honk(); -} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/DealershipTraditionalStyle.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/DealershipTraditionalStyle.java deleted file mode 100644 index b917049e41..0000000000 --- a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/DealershipTraditionalStyle.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.beansinjectiontypes; - -public class DealershipTraditionalStyle { - private Car car = new Sedan(); - - public Car getCar() { - return car; - } -} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/DealershipWithDependenciesInjection.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/DealershipWithDependenciesInjection.java deleted file mode 100644 index 9b25e21dc7..0000000000 --- a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/DealershipWithDependenciesInjection.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.beansinjectiontypes; - -public class DealershipWithDependenciesInjection { - private Car car; - - public DealershipWithDependenciesInjection(Car car) { - this.car = car; - } - - public Car getCar() { - return car; - } -} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Sedan.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Sedan.java deleted file mode 100644 index 0ae4cf5a40..0000000000 --- a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/Sedan.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.beansinjectiontypes; - -import org.springframework.stereotype.Component; - -@Component -public class Sedan implements Car { - public void honk(){ - System.out.println("I'm a sedan!"); - } -} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/Config.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/Config.java deleted file mode 100644 index 3e2534f892..0000000000 --- a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/Config.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.beansinjectiontypes.constructor; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.baeldung.beansinjectiontypes.Car; -import com.baeldung.beansinjectiontypes.Sedan; - -@Configuration(value="constructorConfig") -public class Config { - @Bean - public Car car() { - return new Sedan(); - } - - @Bean - public Dealership dealership() { - return new Dealership(car()); - } -} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/Dealership.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/Dealership.java deleted file mode 100644 index 6151ec8e70..0000000000 --- a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/Dealership.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.beansinjectiontypes.constructor; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.baeldung.beansinjectiontypes.Car; - -@Component(value="constructorDealership") -public class Dealership { - private Car car; - - @Autowired - public Dealership(Car car) { - this.car = car; - } - - public Car getCar() { - return car; - } -} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/HornCheckerFile.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/HornCheckerFile.java deleted file mode 100644 index 924372e3df..0000000000 --- a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/HornCheckerFile.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.beansinjectiontypes.constructor; - -import org.springframework.context.annotation.AnnotationConfigApplicationContext; - -public class HornCheckerFile { - - public static void main(String[] args) { - try (AnnotationConfigApplicationContext context = - new AnnotationConfigApplicationContext(Config.class)) { - Dealership dealership = (Dealership) context.getBean("dealership"); - - dealership.getCar().honk(); - } - } -} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/HornCheckerXML.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/HornCheckerXML.java deleted file mode 100644 index 3c035986e6..0000000000 --- a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/constructor/HornCheckerXML.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.beansinjectiontypes.constructor; - -import org.springframework.context.support.FileSystemXmlApplicationContext; - -public class HornCheckerXML { - - public static void main(String[] args) { - try (FileSystemXmlApplicationContext context = - new FileSystemXmlApplicationContext("src/main/resources/beansinjectiontypes-ctx.xml")) { - Dealership dealership = (Dealership) context.getBean("constructorDealership"); - - dealership.getCar().honk(); - } - } -} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/Config.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/Config.java deleted file mode 100644 index 212d303ce7..0000000000 --- a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/Config.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.beansinjectiontypes.setter; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.baeldung.beansinjectiontypes.Car; -import com.baeldung.beansinjectiontypes.Sedan; - -@Configuration(value="setterConfig") -public class Config { - @Bean - public Car car() { - return new Sedan(); - } - - @Bean - public Dealership dealership() { - Dealership dealership = new Dealership(); - dealership.setCar(car()); - return dealership; - } -} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/Dealership.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/Dealership.java deleted file mode 100644 index db9c7cbceb..0000000000 --- a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/Dealership.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.beansinjectiontypes.setter; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.baeldung.beansinjectiontypes.Car; - -@Component(value="setterDealership") -public class Dealership { - private Car car; - - @Autowired - public void setCar(Car car) { - this.car = car; - } - public Car getCar() { - return car; - } -} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/HornCheckerFile.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/HornCheckerFile.java deleted file mode 100644 index 3372635bd3..0000000000 --- a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/HornCheckerFile.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.beansinjectiontypes.setter; - -import org.springframework.context.annotation.AnnotationConfigApplicationContext; - -public class HornCheckerFile { - - public static void main(String[] args) { - try (AnnotationConfigApplicationContext context = - new AnnotationConfigApplicationContext(Config.class)) { - Dealership dealership = (Dealership) context.getBean("dealership"); - - dealership.getCar().honk(); - } - } -} diff --git a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/HornCheckerXML.java b/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/HornCheckerXML.java deleted file mode 100644 index 0863d16d86..0000000000 --- a/spring-core/src/main/java/com/baeldung/beansinjectiontypes/setter/HornCheckerXML.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.beansinjectiontypes.setter; - -import org.springframework.context.support.FileSystemXmlApplicationContext; - -public class HornCheckerXML { - - public static void main(String[] args) { - try (FileSystemXmlApplicationContext context = - new FileSystemXmlApplicationContext("src/main/resources/beansinjectiontypes-ctx.xml")) { - Dealership dealership = (Dealership) context.getBean("setterDealership"); - - dealership.getCar().honk(); - } - } -} diff --git a/spring-core/src/main/resources/beansinjectiontypes-ctx.xml b/spring-core/src/main/resources/beansinjectiontypes-ctx.xml deleted file mode 100644 index 86131a83b1..0000000000 --- a/spring-core/src/main/resources/beansinjectiontypes-ctx.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/spring-core/src/test/java/com/baeldung/beansinjectiontypes/BeansInjectionTypesIntegrationTest.java b/spring-core/src/test/java/com/baeldung/beansinjectiontypes/BeansInjectionTypesIntegrationTest.java deleted file mode 100644 index 9ffa44ced7..0000000000 --- a/spring-core/src/test/java/com/baeldung/beansinjectiontypes/BeansInjectionTypesIntegrationTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.beansinjectiontypes; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.support.FileSystemXmlApplicationContext; - -import com.baeldung.beansinjectiontypes.constructor.Config; -import com.baeldung.beansinjectiontypes.constructor.Dealership; - -public class BeansInjectionTypesIntegrationTest { - - @Test - public void configBean_WhenSetOnConstructor_ThenDependencyValid() { - try (AnnotationConfigApplicationContext context = - new AnnotationConfigApplicationContext(Config.class)) { - Dealership dealership = (Dealership) context.getBean("dealership"); - - assertTrue(dealership.getCar() instanceof Sedan); - } - } - - @Test - public void configBean_WhenSetOnSetter_ThenDependencyValid() { - try (AnnotationConfigApplicationContext context = - new AnnotationConfigApplicationContext(com.baeldung.beansinjectiontypes.setter.Config.class)) { - com.baeldung.beansinjectiontypes.setter.Dealership dealership = - (com.baeldung.beansinjectiontypes.setter.Dealership) context.getBean("dealership"); - - assertTrue(dealership.getCar() instanceof Sedan); - } - } - - @Test - public void annotationAndXML_WhenSetOnSetter_ThenDependencyValid() { - try (FileSystemXmlApplicationContext context = - new FileSystemXmlApplicationContext("src/main/resources/beansinjectiontypes-ctx.xml")) { - Dealership dealership = (Dealership) context.getBean("constructorDealership"); - - assertTrue(dealership.getCar() instanceof Sedan); - } - } - - @Test - public void annotationAndXML_WhenSetOnConstructor_ThenDependencyValid() { - try (FileSystemXmlApplicationContext context = - new FileSystemXmlApplicationContext("src/main/resources/beansinjectiontypes-ctx.xml")) { - com.baeldung.beansinjectiontypes.setter.Dealership dealership = - (com.baeldung.beansinjectiontypes.setter.Dealership) context.getBean("setterDealership"); - - assertTrue(dealership.getCar() instanceof Sedan); - } - } - -} From c7fbcd217ce6abe93d5dabafad98cc5007adf5ed Mon Sep 17 00:00:00 2001 From: alv21 Date: Fri, 2 Mar 2018 22:38:52 +0100 Subject: [PATCH 004/152] Revert "BAEL-1585" This reverts commit e792f17f82f863850d07884f4638c53beca7f52f. --- .../com/baeldung/java_8_features/Car.java | 31 ------------------- .../baeldung/java8/Java8MaxMinUnitTest.java | 26 ---------------- 2 files changed, 57 deletions(-) delete mode 100644 core-java-8/src/main/java/com/baeldung/java_8_features/Car.java diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Car.java b/core-java-8/src/main/java/com/baeldung/java_8_features/Car.java deleted file mode 100644 index 139475bc25..0000000000 --- a/core-java-8/src/main/java/com/baeldung/java_8_features/Car.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.java_8_features; - -public class Car { - - private String model; - private int topSpeed; - - public Car(String model, int topSpeed) { - super(); - this.model = model; - this.topSpeed = topSpeed; - } - - public String getModel() { - return model; - } - - public void setModel(String model) { - this.model = model; - } - - public int getTopSpeed() { - return topSpeed; - } - - public void setTopSpeed(int topSpeed) { - this.topSpeed = topSpeed; - } - - -} diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java index 55caeeba5e..4979338452 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java @@ -1,7 +1,6 @@ package com.baeldung.java8; import com.baeldung.java_8_features.Person; -import com.baeldung.java_8_features.Car; import org.junit.Test; import java.util.Arrays; @@ -45,29 +44,4 @@ public class Java8MaxMinUnitTest { assertEquals("Should be Alex", alex, minByAge); } - @Test - public void whenArrayIsOfIntegerThenMinCanBeDoneUsingIntegerComparator() { - int[] integers = new int[] { 20, 98, 12, 7, 35 }; - - int min = Arrays.stream(integers) - .min() - .getAsInt(); - - assertEquals(7, min); - } - - @Test - public void whenArrayIsOfPersonObjectThenMaxCanBeDoneUsingCustomComparatorThroughLambda() { - final Car porsche = new Car("Porsche 959", 319); - final Car ferrari = new Car("Ferrari 288 GTO", 303); - final Car bugatti = new Car("Bugatti Veyron 16.4 Super Sport", 415); - final Car mcLaren = new Car("McLaren F1", 355); - final Car[] fastCars = { porsche, ferrari, bugatti, mcLaren }; - - final Car maxBySpeed = Arrays.stream(fastCars) - .max(Comparator.comparing(Car::getTopSpeed)) - .orElseThrow(NoSuchElementException::new); - - assertEquals(bugatti, maxBySpeed); - } } From 8e2c1ba4000cf4e25afbfb9fb826612989b88a88 Mon Sep 17 00:00:00 2001 From: Chirag Dewan Date: Sat, 15 Dec 2018 16:05:16 +0530 Subject: [PATCH 005/152] BAEL-2100 Custom Lombok Annotation --- lombok-custom/pom.xml | 58 ++++++++ .../com/baeldung/singleton/Singleton.java | 10 ++ .../handlers/SingletonEclipseHandler.java | 124 ++++++++++++++++++ .../handlers/SingletonJavacHandler.java | 108 +++++++++++++++ pom.xml | 5 +- 5 files changed, 304 insertions(+), 1 deletion(-) create mode 100644 lombok-custom/pom.xml create mode 100644 lombok-custom/src/main/java/com/baeldung/singleton/Singleton.java create mode 100644 lombok-custom/src/main/java/com/baeldung/singleton/handlers/SingletonEclipseHandler.java create mode 100644 lombok-custom/src/main/java/com/baeldung/singleton/handlers/SingletonJavacHandler.java diff --git a/lombok-custom/pom.xml b/lombok-custom/pom.xml new file mode 100644 index 0000000000..41bd042a5e --- /dev/null +++ b/lombok-custom/pom.xml @@ -0,0 +1,58 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + 4.0.0 + lombok-custom + 0.1-SNAPSHOT + + + + org.projectlombok + lombok + 1.14.8 + provided + + + + org.kohsuke.metainf-services + metainf-services + 1.8 + + + + org.eclipse.jdt + core + 3.3.0-v_771 + + + + + + default-tools.jar + + + java.vendor + Oracle Corporation + + + + + com.sun + tools + ${java.version} + system + ${java.home}/../lib/tools.jar + + + + + + + \ No newline at end of file diff --git a/lombok-custom/src/main/java/com/baeldung/singleton/Singleton.java b/lombok-custom/src/main/java/com/baeldung/singleton/Singleton.java new file mode 100644 index 0000000000..2d2fd0ffb9 --- /dev/null +++ b/lombok-custom/src/main/java/com/baeldung/singleton/Singleton.java @@ -0,0 +1,10 @@ +package com.baeldung.singleton; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +public @interface Singleton { + + +} diff --git a/lombok-custom/src/main/java/com/baeldung/singleton/handlers/SingletonEclipseHandler.java b/lombok-custom/src/main/java/com/baeldung/singleton/handlers/SingletonEclipseHandler.java new file mode 100644 index 0000000000..03cdd707a4 --- /dev/null +++ b/lombok-custom/src/main/java/com/baeldung/singleton/handlers/SingletonEclipseHandler.java @@ -0,0 +1,124 @@ +package com.baeldung.singleton.handlers; + +import com.baeldung.singleton.Singleton; +import lombok.core.AnnotationValues; +import lombok.eclipse.EclipseAnnotationHandler; +import lombok.eclipse.EclipseNode; +import lombok.eclipse.handlers.EclipseHandlerUtil; +import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; +import org.eclipse.jdt.internal.compiler.ast.Annotation; +import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; +import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; +import org.eclipse.jdt.internal.compiler.ast.FieldReference; +import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; +import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; +import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; +import org.eclipse.jdt.internal.compiler.ast.Statement; +import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; +import org.eclipse.jdt.internal.compiler.ast.TypeReference; +import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; +import org.kohsuke.MetaInfServices; + +import static lombok.eclipse.Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG; +import static org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants.AccFinal; +import static org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants.AccPrivate; +import static org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants.AccStatic; + +@MetaInfServices(EclipseAnnotationHandler.class) +public class SingletonEclipseHandler extends EclipseAnnotationHandler { + + + @Override + public void handle(AnnotationValues annotation, Annotation ast, EclipseNode annotationNode) { + + //remove annotation + EclipseHandlerUtil.unboxAndRemoveAnnotationParameter(ast, "onType", "@Singleton(onType=", annotationNode); + + //add private constructor + EclipseNode singletonClass = annotationNode.up(); + + TypeDeclaration singletonClassType = (TypeDeclaration) singletonClass.get(); + ConstructorDeclaration constructor = addConstructor(singletonClass, singletonClassType); + + TypeReference singletonTypeRef = EclipseHandlerUtil.cloneSelfType(singletonClass, singletonClassType); + + //add inner class + + //add instance field + StringBuilder sb = new StringBuilder(); + sb.append(singletonClass.getName()); + sb.append("Holder"); + String innerClassName = sb.toString(); + TypeDeclaration innerClass = new TypeDeclaration(singletonClassType.compilationResult); + innerClass.modifiers = AccPrivate | AccStatic; + innerClass.name = innerClassName.toCharArray(); + + FieldDeclaration instanceVar = addInstanceVar(constructor, singletonTypeRef, innerClass); + + FieldDeclaration[] declarations = new FieldDeclaration[]{instanceVar}; + innerClass.fields = declarations; + + EclipseHandlerUtil.injectType(singletonClass, innerClass); + + addFactoryMethod(singletonClass, singletonClassType, singletonTypeRef, innerClass, instanceVar); + + + } + + private void addFactoryMethod(EclipseNode singletonClass, TypeDeclaration astNode, TypeReference typeReference, TypeDeclaration innerClass, FieldDeclaration field) { + MethodDeclaration factoryMethod = new MethodDeclaration(astNode.compilationResult); + factoryMethod.modifiers = AccStatic | ClassFileConstants.AccPublic; + factoryMethod.returnType = typeReference; + factoryMethod.sourceStart = astNode.sourceStart; + factoryMethod.sourceEnd = astNode.sourceEnd; + factoryMethod.selector = "getInstance".toCharArray(); + factoryMethod.bits = ECLIPSE_DO_NOT_TOUCH_FLAG; + + long pS = factoryMethod.sourceStart; + long pE = factoryMethod.sourceEnd; + long p = (long) pS << 32 | pE; + + FieldReference ref = new FieldReference(field.name, p); + ref.receiver = new SingleNameReference(innerClass.name, p); + + ReturnStatement statement = new ReturnStatement(ref, astNode.sourceStart, astNode.sourceEnd); + + factoryMethod.statements = new Statement[]{statement}; + + EclipseHandlerUtil.injectMethod(singletonClass, factoryMethod); + } + + private FieldDeclaration addInstanceVar(ConstructorDeclaration constructor, TypeReference typeReference, TypeDeclaration innerClass) { + FieldDeclaration field = new FieldDeclaration(); + field.modifiers = AccPrivate | AccStatic | AccFinal; + field.name = "INSTANCE".toCharArray(); + + field.type = typeReference; + + AllocationExpression exp = new AllocationExpression(); + exp.type = typeReference; + exp.binding = constructor.binding; + exp.sourceStart = innerClass.sourceStart; + exp.sourceEnd = innerClass.sourceEnd; + + field.initialization = exp; + return field; + } + + private ConstructorDeclaration addConstructor(EclipseNode singletonClass, TypeDeclaration astNode) { + ConstructorDeclaration constructor = new ConstructorDeclaration(astNode.compilationResult); + constructor.modifiers = AccPrivate; + constructor.selector = astNode.name; + constructor.sourceStart = astNode.sourceStart; + constructor.sourceEnd = astNode.sourceEnd; + constructor.thrownExceptions = null; + constructor.typeParameters = null; + constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG; + constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = astNode.sourceStart; + constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = astNode.sourceEnd; + constructor.arguments = null; + + EclipseHandlerUtil.injectMethod(singletonClass, constructor); + return constructor; + } +} diff --git a/lombok-custom/src/main/java/com/baeldung/singleton/handlers/SingletonJavacHandler.java b/lombok-custom/src/main/java/com/baeldung/singleton/handlers/SingletonJavacHandler.java new file mode 100644 index 0000000000..1f4cf0ea58 --- /dev/null +++ b/lombok-custom/src/main/java/com/baeldung/singleton/handlers/SingletonJavacHandler.java @@ -0,0 +1,108 @@ +package com.baeldung.singleton.handlers; + +import com.baeldung.singleton.Singleton; +import com.sun.tools.javac.code.Flags; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.util.Context; +import com.sun.tools.javac.util.List; +import com.sun.tools.javac.util.ListBuffer; +import lombok.core.AnnotationValues; +import lombok.javac.Javac8BasedLombokOptions; +import lombok.javac.JavacAnnotationHandler; +import lombok.javac.JavacNode; +import lombok.javac.JavacTreeMaker; +import lombok.javac.handlers.JavacHandlerUtil; +import org.kohsuke.MetaInfServices; + +import static lombok.javac.handlers.JavacHandlerUtil.deleteAnnotationIfNeccessary; +import static lombok.javac.handlers.JavacHandlerUtil.deleteImportFromCompilationUnit; + +@MetaInfServices(JavacAnnotationHandler.class) +public class SingletonJavacHandler extends JavacAnnotationHandler { + + @Override + public void handle(AnnotationValues annotation, JCTree.JCAnnotation ast, JavacNode annotationNode) { + + Context context = annotationNode.getContext(); + + Javac8BasedLombokOptions options = Javac8BasedLombokOptions.replaceWithDelombokOptions(context); + options.deleteLombokAnnotations(); + + //remove annotation + deleteAnnotationIfNeccessary(annotationNode, Singleton.class); + //remove import + deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel"); + + //private constructor + JavacNode singletonClass = annotationNode.up(); + JavacTreeMaker singletonClassTreeMaker = singletonClass.getTreeMaker(); + + addPrivateConstructor(singletonClass, singletonClassTreeMaker); + + //singleton holder + JavacNode holderInnerClass = addInnerClass(singletonClass, singletonClassTreeMaker); + + //inject static field to this + addInstanceVar(singletonClass, singletonClassTreeMaker, holderInnerClass); + + //add factory method + addFactoryMethod(singletonClass, singletonClassTreeMaker, holderInnerClass); + } + + private void addFactoryMethod(JavacNode singletonClass, JavacTreeMaker singletonClassTreeMaker, JavacNode holderInnerClass) { + JCTree.JCModifiers modifiers = singletonClassTreeMaker.Modifiers(Flags.PUBLIC | Flags.STATIC); + + JCTree.JCClassDecl singletonClassDecl = (JCTree.JCClassDecl) singletonClass.get(); + JCTree.JCIdent singletonClassType = singletonClassTreeMaker.Ident(singletonClassDecl.name); + + JCTree.JCBlock block = addReturnBlock(singletonClassTreeMaker, holderInnerClass); + + JCTree.JCMethodDecl factoryMethod = singletonClassTreeMaker.MethodDef(modifiers, singletonClass.toName("getInstance"), singletonClassType, List.nil(), List.nil(), List.nil(), block, null); + JavacHandlerUtil.injectMethod(singletonClass, factoryMethod); + } + + private JCTree.JCBlock addReturnBlock(JavacTreeMaker singletonClassTreeMaker, JavacNode holderInnerClass) { + + JCTree.JCClassDecl holderInnerClassDecl = (JCTree.JCClassDecl) holderInnerClass.get(); + JavacTreeMaker holderInnerClassTreeMaker = holderInnerClass.getTreeMaker(); + JCTree.JCIdent holderInnerClassType = holderInnerClassTreeMaker.Ident(holderInnerClassDecl.name); + + JCTree.JCFieldAccess instanceVarAccess = holderInnerClassTreeMaker.Select(holderInnerClassType, holderInnerClass.toName("INSTANCE")); + JCTree.JCReturn returnValue = singletonClassTreeMaker.Return(instanceVarAccess); + + ListBuffer statements = new ListBuffer<>(); + statements.append(returnValue); + + return singletonClassTreeMaker.Block(0L, statements.toList()); + } + + + private void addInstanceVar(JavacNode singletonClass, JavacTreeMaker singletonClassTM, JavacNode holderClass) { + JCTree.JCModifiers fieldMod = singletonClassTM.Modifiers(Flags.PRIVATE | Flags.STATIC | Flags.FINAL); + + JCTree.JCClassDecl singletonClassDecl = (JCTree.JCClassDecl) singletonClass.get(); + JCTree.JCIdent singletonClassType = singletonClassTM.Ident(singletonClassDecl.name); + + JCTree.JCNewClass newKeyword = singletonClassTM.NewClass(null, List.nil(), singletonClassType, List.nil(), null); + + JCTree.JCVariableDecl instanceVar = singletonClassTM.VarDef(fieldMod, singletonClass.toName("INSTANCE"), singletonClassType, newKeyword); + JavacHandlerUtil.injectField(holderClass, instanceVar); + } + + private JavacNode addInnerClass(JavacNode singletonClass, JavacTreeMaker singletonTM) { + JCTree.JCModifiers modifiers = singletonTM.Modifiers(Flags.PRIVATE | Flags.STATIC); + String innerClassName = singletonClass.getName() + "Holder"; + JCTree.JCClassDecl innerClassDecl = singletonTM.ClassDef(modifiers, singletonClass.toName(innerClassName), List.nil(), null, List.nil(), List.nil()); + return JavacHandlerUtil.injectType(singletonClass, innerClassDecl); + } + + private void addPrivateConstructor(JavacNode singletonClass, JavacTreeMaker singletonTM) { + JCTree.JCModifiers modifiers = singletonTM.Modifiers(Flags.PRIVATE); + JCTree.JCBlock block = singletonTM.Block(0L, List.nil()); + JCTree.JCMethodDecl constructor = singletonTM.MethodDef(modifiers, singletonClass.toName(""), null, List.nil(), List.nil(), List.nil(), block, null); + + JavacHandlerUtil.injectMethod(singletonClass, constructor); + } + + +} diff --git a/pom.xml b/pom.xml index 99dae9decb..03a66080c2 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,10 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT - parent-modules + + lombok-custom + + parent-modules pom From 8880d96d3a0c6c5dcdc0f188756d89543fec7481 Mon Sep 17 00:00:00 2001 From: codehunter34 Date: Sun, 23 Dec 2018 16:41:11 -0500 Subject: [PATCH 006/152] BAEL-2399: Guice vs Spring - Dependency Injection --- .../com/baeldung/examples/common/Account.java | 27 +++++++ .../examples/common/AccountService.java | 8 +++ .../examples/common/AccountServiceImpl.java | 15 ++++ .../com/baeldung/examples/common/Address.java | 35 +++++++++ .../baeldung/examples/common/BookService.java | 9 +++ .../examples/common/BookServiceImpl.java | 12 ++++ .../com/baeldung/examples/guice/Employee.java | 32 +++++++++ .../java/com/baeldung/examples/guice/Foo.java | 5 ++ .../baeldung/examples/guice/FooGenerator.java | 11 +++ .../baeldung/examples/guice/GuiceUser.java | 32 +++++++++ .../examples/guice/GuiceUserService.java | 19 +++++ .../com/baeldung/examples/guice/Person.java | 39 ++++++++++ .../examples/guice/modules/GuiceModule.java | 47 ++++++++++++ .../baeldung/examples/spring/AppConfig.java | 19 +++++ .../baeldung/examples/spring/SpringUser.java | 35 +++++++++ .../com/baeldung/examples/spring/Student.java | 34 +++++++++ .../baeldung/examples/spring/UserService.java | 22 ++++++ .../com/baeldung/examples/GuiceTests.java | 72 +++++++++++++++++++ .../com/baeldung/examples/SpringTests.java | 58 +++++++++++++++ 19 files changed, 531 insertions(+) create mode 100644 guice/src/main/java/com/baeldung/examples/common/Account.java create mode 100644 guice/src/main/java/com/baeldung/examples/common/AccountService.java create mode 100644 guice/src/main/java/com/baeldung/examples/common/AccountServiceImpl.java create mode 100644 guice/src/main/java/com/baeldung/examples/common/Address.java create mode 100644 guice/src/main/java/com/baeldung/examples/common/BookService.java create mode 100644 guice/src/main/java/com/baeldung/examples/common/BookServiceImpl.java create mode 100644 guice/src/main/java/com/baeldung/examples/guice/Employee.java create mode 100644 guice/src/main/java/com/baeldung/examples/guice/Foo.java create mode 100644 guice/src/main/java/com/baeldung/examples/guice/FooGenerator.java create mode 100644 guice/src/main/java/com/baeldung/examples/guice/GuiceUser.java create mode 100644 guice/src/main/java/com/baeldung/examples/guice/GuiceUserService.java create mode 100644 guice/src/main/java/com/baeldung/examples/guice/Person.java create mode 100644 guice/src/main/java/com/baeldung/examples/guice/modules/GuiceModule.java create mode 100644 guice/src/main/java/com/baeldung/examples/spring/AppConfig.java create mode 100644 guice/src/main/java/com/baeldung/examples/spring/SpringUser.java create mode 100644 guice/src/main/java/com/baeldung/examples/spring/Student.java create mode 100644 guice/src/main/java/com/baeldung/examples/spring/UserService.java create mode 100644 guice/src/test/java/com/baeldung/examples/GuiceTests.java create mode 100644 guice/src/test/java/com/baeldung/examples/SpringTests.java diff --git a/guice/src/main/java/com/baeldung/examples/common/Account.java b/guice/src/main/java/com/baeldung/examples/common/Account.java new file mode 100644 index 0000000000..09a9d80b6a --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/Account.java @@ -0,0 +1,27 @@ +package com.baeldung.examples.common; + +import org.springframework.stereotype.Component; + +@Component +public class Account { + + private String accountNumber; + private String type; + + public String getAccountNumber() { + return accountNumber; + } + + public void setAccountNumber(String accountNumber) { + this.accountNumber = accountNumber; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/guice/src/main/java/com/baeldung/examples/common/AccountService.java b/guice/src/main/java/com/baeldung/examples/common/AccountService.java new file mode 100644 index 0000000000..d6a7fe1d11 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/AccountService.java @@ -0,0 +1,8 @@ +package com.baeldung.examples.common; + +import java.util.List; + +public interface AccountService { + public List listAccountTypes(); + +} diff --git a/guice/src/main/java/com/baeldung/examples/common/AccountServiceImpl.java b/guice/src/main/java/com/baeldung/examples/common/AccountServiceImpl.java new file mode 100644 index 0000000000..9cecf021fe --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/AccountServiceImpl.java @@ -0,0 +1,15 @@ +package com.baeldung.examples.common; + +import java.util.Arrays; +import java.util.List; + +import org.springframework.stereotype.Component; + +@Component +public class AccountServiceImpl implements AccountService { + + public List listAccountTypes() { + return Arrays.asList("Checking", "Saving"); + } + +} diff --git a/guice/src/main/java/com/baeldung/examples/common/Address.java b/guice/src/main/java/com/baeldung/examples/common/Address.java new file mode 100644 index 0000000000..3b07c47011 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/Address.java @@ -0,0 +1,35 @@ +package com.baeldung.examples.common; + +import org.springframework.stereotype.Component; + +@Component +public class Address { + private String city; + private String state; + private String county; + + 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 getCounty() { + return county; + } + + public void setCounty(String county) { + this.county = county; + } + +} diff --git a/guice/src/main/java/com/baeldung/examples/common/BookService.java b/guice/src/main/java/com/baeldung/examples/common/BookService.java new file mode 100644 index 0000000000..3aca9d90d7 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/BookService.java @@ -0,0 +1,9 @@ +package com.baeldung.examples.common; + +import java.util.List; + +public interface BookService { + + public List findBestSellerBooks(); + +} diff --git a/guice/src/main/java/com/baeldung/examples/common/BookServiceImpl.java b/guice/src/main/java/com/baeldung/examples/common/BookServiceImpl.java new file mode 100644 index 0000000000..b5499c678d --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/BookServiceImpl.java @@ -0,0 +1,12 @@ +package com.baeldung.examples.common; + +import java.util.Arrays; +import java.util.List; + +public class BookServiceImpl implements BookService { + + public List findBestSellerBooks() { + return Arrays.asList("Harry Potter", "Lord of The Rings"); + } + +} diff --git a/guice/src/main/java/com/baeldung/examples/guice/Employee.java b/guice/src/main/java/com/baeldung/examples/guice/Employee.java new file mode 100644 index 0000000000..b85d251a05 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/guice/Employee.java @@ -0,0 +1,32 @@ +package com.baeldung.examples.guice; + +import com.google.inject.Inject; + +public class Employee { + + private String firstName; + private String lastName; + + @Inject + public Employee(String firstName) { + this.firstName = firstName; + this.lastName = "Default"; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + +} diff --git a/guice/src/main/java/com/baeldung/examples/guice/Foo.java b/guice/src/main/java/com/baeldung/examples/guice/Foo.java new file mode 100644 index 0000000000..a4f22a6f69 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/guice/Foo.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.guice; + + +public class Foo { +} diff --git a/guice/src/main/java/com/baeldung/examples/guice/FooGenerator.java b/guice/src/main/java/com/baeldung/examples/guice/FooGenerator.java new file mode 100644 index 0000000000..b2d3309d0e --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/guice/FooGenerator.java @@ -0,0 +1,11 @@ +package com.baeldung.examples.guice; + +import org.springframework.lang.Nullable; + +import com.google.inject.Inject; + +public class FooGenerator { + @Inject + public FooGenerator(@Nullable Foo foo) { + } +} \ No newline at end of file diff --git a/guice/src/main/java/com/baeldung/examples/guice/GuiceUser.java b/guice/src/main/java/com/baeldung/examples/guice/GuiceUser.java new file mode 100644 index 0000000000..df438add5b --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/guice/GuiceUser.java @@ -0,0 +1,32 @@ +package com.baeldung.examples.guice; + +import com.baeldung.examples.common.Account; +import com.baeldung.examples.common.Address; +import com.google.inject.Inject; + +public class GuiceUser { + + @Inject + private Account account; + + private Address address; + + public Account getAccount() { + return account; + } + + public void setAccount(Account account) { + this.account = account; + } + + public Address getAddress() { + return address; + } + + @Inject + public void setAddress(Address address) { + this.address = address; + address.setCity("Default"); + } + +} diff --git a/guice/src/main/java/com/baeldung/examples/guice/GuiceUserService.java b/guice/src/main/java/com/baeldung/examples/guice/GuiceUserService.java new file mode 100644 index 0000000000..18cb076661 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/guice/GuiceUserService.java @@ -0,0 +1,19 @@ +package com.baeldung.examples.guice; + +import com.baeldung.examples.common.AccountService; +import com.google.inject.Inject; + +public class GuiceUserService { + + @Inject + private AccountService accountService; + + public AccountService getAccountService() { + return accountService; + } + + public void setAccountService(AccountService accountService) { + this.accountService = accountService; + } + +} diff --git a/guice/src/main/java/com/baeldung/examples/guice/Person.java b/guice/src/main/java/com/baeldung/examples/guice/Person.java new file mode 100644 index 0000000000..45ee5f4b89 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/guice/Person.java @@ -0,0 +1,39 @@ +package com.baeldung.examples.guice; + +import com.baeldung.examples.common.Address; +import com.google.inject.Inject; + +public class Person { + private String firstName; + + private String lastName; + + private Address address; + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Address getAddress() { + return address; + } + + @Inject + public void setAddress(Address address) { + this.address = address; + address.setCity("Default"); + } + +} diff --git a/guice/src/main/java/com/baeldung/examples/guice/modules/GuiceModule.java b/guice/src/main/java/com/baeldung/examples/guice/modules/GuiceModule.java new file mode 100644 index 0000000000..44b566240e --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/guice/modules/GuiceModule.java @@ -0,0 +1,47 @@ +package com.baeldung.examples.guice.modules; + +import com.baeldung.examples.common.AccountService; +import com.baeldung.examples.common.AccountServiceImpl; +import com.baeldung.examples.common.BookService; +import com.baeldung.examples.common.BookServiceImpl; +import com.baeldung.examples.guice.Foo; +import com.baeldung.examples.guice.Person; +import com.google.inject.AbstractModule; +import com.google.inject.Provider; +import com.google.inject.Provides; + +public class GuiceModule extends AbstractModule { + + @Override + protected void configure() { + try { + bind(AccountService.class).to(AccountServiceImpl.class); + bind(Foo.class).toProvider(new Provider() { + public Foo get() { + return null; + } + }); + + bind(Person.class).toConstructor(Person.class.getConstructor()); + // bind(Person.class).toProvider(new Provider() { + // public Person get() { + // Person p = new Person(); + // return p; + // } + // }); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + @Provides + public BookService bookServiceGenerator() { + return new BookServiceImpl(); + } + +} diff --git a/guice/src/main/java/com/baeldung/examples/spring/AppConfig.java b/guice/src/main/java/com/baeldung/examples/spring/AppConfig.java new file mode 100644 index 0000000000..e5b6648e0d --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/spring/AppConfig.java @@ -0,0 +1,19 @@ +package com.baeldung.examples.spring; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.examples.common.BookService; +import com.baeldung.examples.common.BookServiceImpl; + +@Configuration +@ComponentScan("com.baeldung.examples") +public class AppConfig { + + @Bean + public BookService bookServiceGenerator() { + return new BookServiceImpl(); + } + +} diff --git a/guice/src/main/java/com/baeldung/examples/spring/SpringUser.java b/guice/src/main/java/com/baeldung/examples/spring/SpringUser.java new file mode 100644 index 0000000000..ba6aaab09b --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/spring/SpringUser.java @@ -0,0 +1,35 @@ +package com.baeldung.examples.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.baeldung.examples.common.Account; +import com.baeldung.examples.common.Address; + +@Component +public class SpringUser { + + @Autowired + private Account account; + + private Address address; + + public Account getAccount() { + return account; + } + + public void setAccount(Account account) { + this.account = account; + } + + public Address getAddress() { + return address; + } + + @Autowired + public void setAddress(Address address) { + this.address = address; + address.setCity("Default"); + } + +} diff --git a/guice/src/main/java/com/baeldung/examples/spring/Student.java b/guice/src/main/java/com/baeldung/examples/spring/Student.java new file mode 100644 index 0000000000..d8b61a91ef --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/spring/Student.java @@ -0,0 +1,34 @@ +package com.baeldung.examples.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class Student { + private String firstName; + private String lastName; + + @Autowired + public Student(@Value("Default") String firstName, @Value("Default") String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + +} diff --git a/guice/src/main/java/com/baeldung/examples/spring/UserService.java b/guice/src/main/java/com/baeldung/examples/spring/UserService.java new file mode 100644 index 0000000000..91b95c100d --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/spring/UserService.java @@ -0,0 +1,22 @@ +package com.baeldung.examples.spring; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.baeldung.examples.common.AccountService; + +@Component +public class UserService { + + @Autowired + private AccountService accountService; + + public AccountService getAccountService() { + return accountService; + } + + public void setAccountService(AccountService accountService) { + this.accountService = accountService; + } + +} diff --git a/guice/src/test/java/com/baeldung/examples/GuiceTests.java b/guice/src/test/java/com/baeldung/examples/GuiceTests.java new file mode 100644 index 0000000000..b87289a1a4 --- /dev/null +++ b/guice/src/test/java/com/baeldung/examples/GuiceTests.java @@ -0,0 +1,72 @@ +package com.baeldung.examples; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +import com.baeldung.examples.common.BookService; +import com.baeldung.examples.guice.Employee; +import com.baeldung.examples.guice.FooGenerator; +import com.baeldung.examples.guice.GuiceUser; +import com.baeldung.examples.guice.GuiceUserService; +import com.baeldung.examples.guice.Person; +import com.baeldung.examples.guice.modules.GuiceModule; +import com.google.inject.Guice; +import com.google.inject.Injector; + +public class GuiceTests { + + @Test + public void givenAccountFieldInjectedInGuiceUser_WhenGetAccountInvoked_ThenReturnValueIsNotNull() { + Injector injector = Guice.createInjector(new GuiceModule()); + GuiceUser guiceUser = injector.getInstance(GuiceUser.class); + assertNotNull(guiceUser.getAccount()); + } + + @Test + public void givenAccountServiceInjectedInGuiceUserService_WhenGetAccountServiceInvoked_ThenReturnValueIsNotNull() { + Injector injector = Guice.createInjector(new GuiceModule()); + GuiceUserService guiceUserService = injector.getInstance(GuiceUserService.class); + assertNotNull(guiceUserService.getAccountService()); + } + + @Test + public void givenBookServiceIsRegisteredInModule_WhenBookServiceIsInjected_ThenReturnValueIsNotNull() { + Injector injector = Guice.createInjector(new GuiceModule()); + BookService bookService = injector.getInstance(BookService.class); + assertNotNull(bookService); + } + + @Test + public void givenFooGeneratorConstructorParameterIsNotNullable_WhenFooGeneratorIsInjected_ThenTestFailsByProvisionException() { + Injector injector = Guice.createInjector(new GuiceModule()); + FooGenerator fooGenerator = injector.getInstance(FooGenerator.class); + assertNotNull(fooGenerator); + } + + @Test + public void givenMultipleBindingsForPerson_WhenPersonIsInjected_ThenTestFailsByProvisionException() { + Injector injector = Guice.createInjector(new GuiceModule()); + Person person = injector.getInstance(Person.class); + assertNotNull(person); + } + + @Test + public void givenEmployeeConstructorAnnotatedByInject_WhenEmployeeIsInjected_ThenInstanceWillBeCreatedFromTheConstructor() { + Injector injector = Guice.createInjector(new GuiceModule()); + Employee employee = injector.getInstance(Employee.class); + assertNotNull(employee); + assertEquals("Default", employee.getLastName()); + } + + @Test + public void givenAddressAutowiredToGuiceUserBySetterInjection_WhenGuiceUserIsInjected_ThenAddressInitializedByTheSetter() { + Injector injector = Guice.createInjector(new GuiceModule()); + GuiceUser guiceUser = injector.getInstance(GuiceUser.class); + assertNotNull(guiceUser); + assertNotNull(guiceUser.getAddress()); + assertEquals("Default", guiceUser.getAddress().getCity()); + } + +} diff --git a/guice/src/test/java/com/baeldung/examples/SpringTests.java b/guice/src/test/java/com/baeldung/examples/SpringTests.java new file mode 100644 index 0000000000..327e409cc1 --- /dev/null +++ b/guice/src/test/java/com/baeldung/examples/SpringTests.java @@ -0,0 +1,58 @@ +package com.baeldung.examples; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.examples.common.BookService; +import com.baeldung.examples.spring.AppConfig; +import com.baeldung.examples.spring.SpringUser; +import com.baeldung.examples.spring.Student; +import com.baeldung.examples.spring.UserService; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = { AppConfig.class }) +public class SpringTests { + @Autowired + ApplicationContext context; + + @Test + public void givenAccountFieldAutowiredToSpringUser_WhenGetAccountInvoked_ThenReturnValueIsNotNull() { + SpringUser springUser = context.getBean(SpringUser.class); + assertNotNull(springUser.getAccount()); + } + + @Test + public void givenAccountServiceFieldAutowiredToUserService_WhenGetAccountServiceInvoked_ThenReturnValueIsNotNull() { + UserService userService = context.getBean(UserService.class); + assertNotNull(userService.getAccountService()); + } + + @Test + public void givenBookServiceIsRegisteredAsBeanInContext_WhenBookServiceIsRetrievedFromContext_ThenReturnValueIsNotNull() { + BookService bookService = context.getBean(BookService.class); + assertNotNull(bookService); + } + + @Test + public void givenStudentConstructorAnnotatedByAutowired_WhenStudentIsRetrievedFromContext_ThenInstanceWillBeCreatedFromTheConstructor() { + Student student = context.getBean(Student.class); + assertNotNull(student); + assertEquals("Default", student.getFirstName()); + assertEquals("Default", student.getLastName()); + } + + @Test + public void givenAddressAutowiredToSpringUserBySetterInjection_WhenSpringUserRetrievedFromContext_ThenAddressInitializedByTheSetter() { + SpringUser springUser = context.getBean(SpringUser.class); + assertNotNull(springUser.getAddress()); + assertEquals("Default", springUser.getAddress().getCity()); + } + +} From acf8034d9352feded9a4e442e654ae517c182e10 Mon Sep 17 00:00:00 2001 From: codehunter34 Date: Wed, 26 Dec 2018 23:58:04 -0500 Subject: [PATCH 007/152] BAEL-2399: Guice vs Spring - Dependency Injection --- guice/pom.xml | 62 ++++++++++++------- .../{GuiceTests.java => GuiceUnitTest.java} | 2 +- .../{SpringTests.java => SpringUnitTest.java} | 2 +- 3 files changed, 41 insertions(+), 25 deletions(-) rename guice/src/test/java/com/baeldung/examples/{GuiceTests.java => GuiceUnitTest.java} (96%) rename guice/src/test/java/com/baeldung/examples/{SpringTests.java => SpringUnitTest.java} (96%) diff --git a/guice/pom.xml b/guice/pom.xml index f3e7873245..54532bc992 100644 --- a/guice/pom.xml +++ b/guice/pom.xml @@ -1,29 +1,45 @@ - - 4.0.0 - com.baeldung.examples.guice - guice - 1.0-SNAPSHOT - jar - guice + + 4.0.0 + com.baeldung.examples.guice + guice + 1.0-SNAPSHOT + jar + guice - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - com.google.inject - guice - ${guice.version} - - + + + com.google.inject + guice + ${guice.version} + - - 4.1.0 - + + org.springframework + spring-context + ${spring.version} + + + + org.springframework + spring-test + ${springtest.version} + test + + + + + 4.1.0 + 5.1.3.RELEASE + 5.1.3.RELEASE + diff --git a/guice/src/test/java/com/baeldung/examples/GuiceTests.java b/guice/src/test/java/com/baeldung/examples/GuiceUnitTest.java similarity index 96% rename from guice/src/test/java/com/baeldung/examples/GuiceTests.java rename to guice/src/test/java/com/baeldung/examples/GuiceUnitTest.java index b87289a1a4..ebc35de405 100644 --- a/guice/src/test/java/com/baeldung/examples/GuiceTests.java +++ b/guice/src/test/java/com/baeldung/examples/GuiceUnitTest.java @@ -15,7 +15,7 @@ import com.baeldung.examples.guice.modules.GuiceModule; import com.google.inject.Guice; import com.google.inject.Injector; -public class GuiceTests { +public class GuiceUnitTest { @Test public void givenAccountFieldInjectedInGuiceUser_WhenGetAccountInvoked_ThenReturnValueIsNotNull() { diff --git a/guice/src/test/java/com/baeldung/examples/SpringTests.java b/guice/src/test/java/com/baeldung/examples/SpringUnitTest.java similarity index 96% rename from guice/src/test/java/com/baeldung/examples/SpringTests.java rename to guice/src/test/java/com/baeldung/examples/SpringUnitTest.java index 327e409cc1..0bd6770909 100644 --- a/guice/src/test/java/com/baeldung/examples/SpringTests.java +++ b/guice/src/test/java/com/baeldung/examples/SpringUnitTest.java @@ -18,7 +18,7 @@ import com.baeldung.examples.spring.UserService; @RunWith(SpringRunner.class) @ContextConfiguration(classes = { AppConfig.class }) -public class SpringTests { +public class SpringUnitTest { @Autowired ApplicationContext context; From aeba601c1f5bd14ad061a18c69babe92db97735d Mon Sep 17 00:00:00 2001 From: codehunter34 Date: Wed, 26 Dec 2018 23:58:04 -0500 Subject: [PATCH 008/152] BAEL-2399: Guice vs Spring - Dependency Injection --- guice/pom.xml | 62 ++++++++++++------- .../{GuiceTests.java => GuiceUnitTest.java} | 2 +- .../{SpringTests.java => SpringUnitTest.java} | 2 +- 3 files changed, 41 insertions(+), 25 deletions(-) rename guice/src/test/java/com/baeldung/examples/{GuiceTests.java => GuiceUnitTest.java} (96%) rename guice/src/test/java/com/baeldung/examples/{SpringTests.java => SpringUnitTest.java} (96%) diff --git a/guice/pom.xml b/guice/pom.xml index f3e7873245..54532bc992 100644 --- a/guice/pom.xml +++ b/guice/pom.xml @@ -1,29 +1,45 @@ - - 4.0.0 - com.baeldung.examples.guice - guice - 1.0-SNAPSHOT - jar - guice + + 4.0.0 + com.baeldung.examples.guice + guice + 1.0-SNAPSHOT + jar + guice - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - com.google.inject - guice - ${guice.version} - - + + + com.google.inject + guice + ${guice.version} + - - 4.1.0 - + + org.springframework + spring-context + ${spring.version} + + + + org.springframework + spring-test + ${springtest.version} + test + + + + + 4.1.0 + 5.1.3.RELEASE + 5.1.3.RELEASE + diff --git a/guice/src/test/java/com/baeldung/examples/GuiceTests.java b/guice/src/test/java/com/baeldung/examples/GuiceUnitTest.java similarity index 96% rename from guice/src/test/java/com/baeldung/examples/GuiceTests.java rename to guice/src/test/java/com/baeldung/examples/GuiceUnitTest.java index b87289a1a4..ebc35de405 100644 --- a/guice/src/test/java/com/baeldung/examples/GuiceTests.java +++ b/guice/src/test/java/com/baeldung/examples/GuiceUnitTest.java @@ -15,7 +15,7 @@ import com.baeldung.examples.guice.modules.GuiceModule; import com.google.inject.Guice; import com.google.inject.Injector; -public class GuiceTests { +public class GuiceUnitTest { @Test public void givenAccountFieldInjectedInGuiceUser_WhenGetAccountInvoked_ThenReturnValueIsNotNull() { diff --git a/guice/src/test/java/com/baeldung/examples/SpringTests.java b/guice/src/test/java/com/baeldung/examples/SpringUnitTest.java similarity index 96% rename from guice/src/test/java/com/baeldung/examples/SpringTests.java rename to guice/src/test/java/com/baeldung/examples/SpringUnitTest.java index 327e409cc1..0bd6770909 100644 --- a/guice/src/test/java/com/baeldung/examples/SpringTests.java +++ b/guice/src/test/java/com/baeldung/examples/SpringUnitTest.java @@ -18,7 +18,7 @@ import com.baeldung.examples.spring.UserService; @RunWith(SpringRunner.class) @ContextConfiguration(classes = { AppConfig.class }) -public class SpringTests { +public class SpringUnitTest { @Autowired ApplicationContext context; From bd63df8caf05acee9307f84f94c83a304cbc401b Mon Sep 17 00:00:00 2001 From: codehunter34 Date: Tue, 1 Jan 2019 02:46:06 -0500 Subject: [PATCH 009/152] BAEL-2399: Guice vs Spring - Dependency Injection --- .../main/java/com/baeldung/examples/common/PersonDao.java | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 guice/src/main/java/com/baeldung/examples/common/PersonDao.java diff --git a/guice/src/main/java/com/baeldung/examples/common/PersonDao.java b/guice/src/main/java/com/baeldung/examples/common/PersonDao.java new file mode 100644 index 0000000000..980fee0252 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/PersonDao.java @@ -0,0 +1,5 @@ +package com.baeldung.examples.common; + +public interface PersonDao { + +} From d740cb2da09e0dfeef3ae166473785aa92f3a443 Mon Sep 17 00:00:00 2001 From: codehunter34 Date: Tue, 1 Jan 2019 02:46:06 -0500 Subject: [PATCH 010/152] BAEL-2399: Guice vs Spring - Dependency Injection --- .../java/com/baeldung/examples/common/PersonDaoImpl.java | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 guice/src/main/java/com/baeldung/examples/common/PersonDaoImpl.java diff --git a/guice/src/main/java/com/baeldung/examples/common/PersonDaoImpl.java b/guice/src/main/java/com/baeldung/examples/common/PersonDaoImpl.java new file mode 100644 index 0000000000..971db5aa87 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/PersonDaoImpl.java @@ -0,0 +1,8 @@ +package com.baeldung.examples.common; + +import org.springframework.stereotype.Component; + +@Component +public class PersonDaoImpl implements PersonDao { + +} \ No newline at end of file From 3ac96662fc8d9f83936f21fc688a13ffd648af40 Mon Sep 17 00:00:00 2001 From: codehunter34 Date: Tue, 1 Jan 2019 02:46:06 -0500 Subject: [PATCH 011/152] BAEL-2399: Guice vs Spring - Dependency Injection --- .../examples/common/PersonDaoImpl.java | 8 ++++++++ .../examples/guice/GuicePersonService.java | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 guice/src/main/java/com/baeldung/examples/common/PersonDaoImpl.java create mode 100644 guice/src/main/java/com/baeldung/examples/guice/GuicePersonService.java diff --git a/guice/src/main/java/com/baeldung/examples/common/PersonDaoImpl.java b/guice/src/main/java/com/baeldung/examples/common/PersonDaoImpl.java new file mode 100644 index 0000000000..971db5aa87 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/common/PersonDaoImpl.java @@ -0,0 +1,8 @@ +package com.baeldung.examples.common; + +import org.springframework.stereotype.Component; + +@Component +public class PersonDaoImpl implements PersonDao { + +} \ No newline at end of file diff --git a/guice/src/main/java/com/baeldung/examples/guice/GuicePersonService.java b/guice/src/main/java/com/baeldung/examples/guice/GuicePersonService.java new file mode 100644 index 0000000000..ce12e3e528 --- /dev/null +++ b/guice/src/main/java/com/baeldung/examples/guice/GuicePersonService.java @@ -0,0 +1,19 @@ +package com.baeldung.examples.guice; + +import com.baeldung.examples.common.PersonDao; +import com.google.inject.Inject; + +public class GuicePersonService { + + @Inject + private PersonDao personDao; + + public PersonDao getPersonDao() { + return personDao; + } + + public void setPersonDao(PersonDao personDao) { + this.personDao = personDao; + } + +} From 91f8c421c9941997165d0e7ac1e8c3e81836432d Mon Sep 17 00:00:00 2001 From: amdegregorio Date: Tue, 8 Jan 2019 10:31:20 -0500 Subject: [PATCH 012/152] example code for Article How to Write to a CSV File in Java --- .../com/baeldung/csv/WriteCsvFileExample.java | 29 ++++++ .../csv/WriteCsvFileExampleUnitTest.java | 90 +++++++++++++++++++ .../src/test/resources/exampleOutput.csv | 2 + 3 files changed, 121 insertions(+) create mode 100644 core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java create mode 100644 core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java create mode 100644 core-java-io/src/test/resources/exampleOutput.csv diff --git a/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java b/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java new file mode 100644 index 0000000000..fd3678d2c5 --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java @@ -0,0 +1,29 @@ +package com.baeldung.csv; + +import java.io.BufferedWriter; +import java.io.IOException; + +public class WriteCsvFileExample { + + public void writeLine(BufferedWriter writer, String[] data) throws IOException { + StringBuilder csvLine = new StringBuilder(); + + for (int i = 0; i < data.length; i++) { + if (i > 0) { + csvLine.append(","); + } + csvLine.append(escapeSpecialCharacters(data[i])); + } + + writer.write(csvLine.toString()); + } + + public String escapeSpecialCharacters(String data) { + String escapedData = data.replaceAll("\\R", " "); + if (data.contains(",") || data.contains("\"") || data.contains("'")) { + data = data.replace("\"", "\"\""); + escapedData = "\"" + data + "\""; + } + return escapedData; + } +} diff --git a/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java b/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java new file mode 100644 index 0000000000..4ac84f939d --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java @@ -0,0 +1,90 @@ +package com.baeldung.csv; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class WriteCsvFileExampleUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(WriteCsvFileExampleUnitTest.class); + + private static final String CSV_FILE_NAME = "src/test/resources/exampleOutput.csv"; + private WriteCsvFileExample csvExample; + + @Before + public void setupClass() { + csvExample = new WriteCsvFileExample(); + } + + @Test + public void givenCommaContainingData_whenEscapeSpecialCharacters_stringReturnedInQuotes() { + String data = "three,two,one"; + String escapedData = csvExample.escapeSpecialCharacters(data); + + String expectedData = "\"three,two,one\""; + assertEquals(expectedData, escapedData); + } + + @Test + public void givenQuoteContainingData_whenEscapeSpecialCharacters_stringReturnedFormatted() { + String data = "She said \"Hello\""; + String escapedData = csvExample.escapeSpecialCharacters(data); + + String expectedData = "\"She said \"\"Hello\"\"\""; + assertEquals(expectedData, escapedData); + } + + @Test + public void givenNewlineContainingData_whenEscapeSpecialCharacters_stringReturnedInQuotes() { + String dataNewline = "This contains\na newline"; + String dataCarriageReturn = "This contains\r\na newline and carriage return"; + String escapedDataNl = csvExample.escapeSpecialCharacters(dataNewline); + String escapedDataCr = csvExample.escapeSpecialCharacters(dataCarriageReturn); + + String expectedData = "This contains a newline"; + assertEquals(expectedData, escapedDataNl); + String expectedDataCr = "This contains a newline and carriage return"; + assertEquals(expectedDataCr, escapedDataCr); + } + + @Test + public void givenNonSpecialData_whenEscapeSpecialCharacters_stringReturnedUnchanged() { + String data = "This is nothing special"; + String returnedData = csvExample.escapeSpecialCharacters(data); + + assertEquals(data, returnedData); + } + + @Test + public void givenBufferedWriter_whenWriteLine_thenOutputCreated() { + List dataLines = new ArrayList(); + dataLines.add(new String[] { "John", "Doe", "38", "Comment Data\nAnother line of comment data" }); + dataLines.add(new String[] { "Jane", "Doe, Jr.", "19", "She said \"I'm being quoted\"" }); + + File csvOutputFile = new File(CSV_FILE_NAME); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(csvOutputFile))) { + for (Iterator dataIterator = dataLines.iterator(); dataIterator.hasNext();) { + csvExample.writeLine(writer, dataIterator.next()); + if (dataIterator.hasNext()) { + writer.newLine(); + } + } + writer.flush(); + } catch (IOException e) { + LOG.error("IOException " + e.getMessage()); + } + + assertTrue(csvOutputFile.exists()); + } +} diff --git a/core-java-io/src/test/resources/exampleOutput.csv b/core-java-io/src/test/resources/exampleOutput.csv new file mode 100644 index 0000000000..45c37f3a3b --- /dev/null +++ b/core-java-io/src/test/resources/exampleOutput.csv @@ -0,0 +1,2 @@ +John,Doe,38,Comment Data Another line of comment data +Jane,"Doe, Jr.",19,"She said ""I'm being quoted""" \ No newline at end of file From 81e2750ee0011d4badb355b87c112177a0e0d333 Mon Sep 17 00:00:00 2001 From: amdegregorio Date: Thu, 10 Jan 2019 10:50:03 -0500 Subject: [PATCH 013/152] Updated to use a Stream --- .../com/baeldung/csv/WriteCsvFileExample.java | 7 ++----- .../csv/WriteCsvFileExampleUnitTest.java | 20 +++++++------------ 2 files changed, 9 insertions(+), 18 deletions(-) diff --git a/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java b/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java index fd3678d2c5..e1237481b1 100644 --- a/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java +++ b/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java @@ -1,11 +1,8 @@ package com.baeldung.csv; -import java.io.BufferedWriter; -import java.io.IOException; - public class WriteCsvFileExample { - public void writeLine(BufferedWriter writer, String[] data) throws IOException { + public String convertToCSV(String[] data) { StringBuilder csvLine = new StringBuilder(); for (int i = 0; i < data.length; i++) { @@ -15,7 +12,7 @@ public class WriteCsvFileExample { csvLine.append(escapeSpecialCharacters(data[i])); } - writer.write(csvLine.toString()); + return csvLine.toString(); } public String escapeSpecialCharacters(String data) { diff --git a/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java b/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java index 4ac84f939d..e30ec0818c 100644 --- a/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java +++ b/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java @@ -3,12 +3,10 @@ package com.baeldung.csv; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import java.io.BufferedWriter; import java.io.File; -import java.io.FileWriter; -import java.io.IOException; +import java.io.FileNotFoundException; +import java.io.PrintWriter; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import org.junit.Before; @@ -73,15 +71,11 @@ public class WriteCsvFileExampleUnitTest { dataLines.add(new String[] { "Jane", "Doe, Jr.", "19", "She said \"I'm being quoted\"" }); File csvOutputFile = new File(CSV_FILE_NAME); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(csvOutputFile))) { - for (Iterator dataIterator = dataLines.iterator(); dataIterator.hasNext();) { - csvExample.writeLine(writer, dataIterator.next()); - if (dataIterator.hasNext()) { - writer.newLine(); - } - } - writer.flush(); - } catch (IOException e) { + try (PrintWriter pw = new PrintWriter(csvOutputFile)) { + dataLines.stream() + .map(csvExample::convertToCSV) + .forEach(pw::println); + } catch (FileNotFoundException e) { LOG.error("IOException " + e.getMessage()); } From 2db589c5b47ee20cbc7b3e82d857bd261938dd0d Mon Sep 17 00:00:00 2001 From: amdegregorio Date: Mon, 14 Jan 2019 13:35:07 -0500 Subject: [PATCH 014/152] Updated to use Streams in convertToCSV for BAEL-2499 --- .../com/baeldung/csv/WriteCsvFileExample.java | 16 ++++++---------- .../csv/WriteCsvFileExampleUnitTest.java | 2 +- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java b/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java index e1237481b1..f409d05b06 100644 --- a/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java +++ b/core-java-io/src/main/java/com/baeldung/csv/WriteCsvFileExample.java @@ -1,18 +1,14 @@ package com.baeldung.csv; +import java.util.stream.Collectors; +import java.util.stream.Stream; + public class WriteCsvFileExample { public String convertToCSV(String[] data) { - StringBuilder csvLine = new StringBuilder(); - - for (int i = 0; i < data.length; i++) { - if (i > 0) { - csvLine.append(","); - } - csvLine.append(escapeSpecialCharacters(data[i])); - } - - return csvLine.toString(); + return Stream.of(data) + .map(this::escapeSpecialCharacters) + .collect(Collectors.joining(",")); } public String escapeSpecialCharacters(String data) { diff --git a/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java b/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java index e30ec0818c..0658ec6101 100644 --- a/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java +++ b/core-java-io/src/test/java/com/baeldung/csv/WriteCsvFileExampleUnitTest.java @@ -65,7 +65,7 @@ public class WriteCsvFileExampleUnitTest { } @Test - public void givenBufferedWriter_whenWriteLine_thenOutputCreated() { + public void givenDataArray_whenConvertToCSV_thenOutputCreated() { List dataLines = new ArrayList(); dataLines.add(new String[] { "John", "Doe", "38", "Comment Data\nAnother line of comment data" }); dataLines.add(new String[] { "Jane", "Doe, Jr.", "19", "She said \"I'm being quoted\"" }); From 2e2f3bc4a95f83b91188b5ea7ee75e7913d3fe03 Mon Sep 17 00:00:00 2001 From: Chirag Dewan Date: Tue, 15 Jan 2019 17:14:03 +0530 Subject: [PATCH 015/152] BAEL-2408 Java Project Loom --- .../java/com/baeldung/loom/AsyncThreads.java | 22 +++++++++++++ .../com/baeldung/loom/BlockingThreads.java | 33 +++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 libraries/src/main/java/com/baeldung/loom/AsyncThreads.java create mode 100644 libraries/src/main/java/com/baeldung/loom/BlockingThreads.java diff --git a/libraries/src/main/java/com/baeldung/loom/AsyncThreads.java b/libraries/src/main/java/com/baeldung/loom/AsyncThreads.java new file mode 100644 index 0000000000..1ec448be69 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/loom/AsyncThreads.java @@ -0,0 +1,22 @@ +package com.baeldung.loom; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +public class AsyncThreads { + + public static void main(String[] args) throws ExecutionException, InterruptedException { + + CompletableFuture cf = CompletableFuture.runAsync(() -> { + + System.out.println("Hello " + Thread.currentThread().getName()); + }); + + cf.thenRun(() -> { + + System.out.println("World " + Thread.currentThread().getName()); + }); + + cf.get(); + } +} diff --git a/libraries/src/main/java/com/baeldung/loom/BlockingThreads.java b/libraries/src/main/java/com/baeldung/loom/BlockingThreads.java new file mode 100644 index 0000000000..de11529753 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/loom/BlockingThreads.java @@ -0,0 +1,33 @@ +package com.baeldung.loom; + +public class BlockingThreads { + + private static final Object LOCK = new Object(); + + public static void main(String[] args) throws InterruptedException { + + Thread thread1 = new Thread(() -> { + synchronized (LOCK) { + System.out.println("Hello " + Thread.currentThread().getName()); + LOCK.notify(); + } + }); + + + Thread thread2 = new Thread(() -> { + synchronized (LOCK) { + try { + System.out.println("Will wait for thread1 now..."); + LOCK.wait(); + System.out.println("World " + Thread.currentThread().getName()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + }); + + thread2.start(); + thread1.start(); + + } +} From d83101854c35218ea54bbaa5f6ce6747d16d44bf Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Fri, 18 Jan 2019 11:05:26 +0400 Subject: [PATCH 016/152] primitive collections libraries added --- core-java-arrays/pom.xml | 16 ++++ .../baeldung/array/PrimitiveCollections.java | 34 ++++++++ .../array/PrimitivesListPerformance.java | 77 +++++++++++++++++++ 3 files changed, 127 insertions(+) create mode 100644 core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java create mode 100644 core-java-arrays/src/main/java/com/baeldung/array/PrimitivesListPerformance.java diff --git a/core-java-arrays/pom.xml b/core-java-arrays/pom.xml index d2d0453e87..6d4109804e 100644 --- a/core-java-arrays/pom.xml +++ b/core-java-arrays/pom.xml @@ -52,6 +52,22 @@ spring-web ${springframework.spring-web.version} + + + net.sf.trove4j + trove4j + 3.0.2 + + + it.unimi.dsi + fastutil + 8.1.0 + + + colt + colt + 1.2.0 + diff --git a/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java b/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java new file mode 100644 index 0000000000..115c5fe5c3 --- /dev/null +++ b/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java @@ -0,0 +1,34 @@ +package com.baeldung.array; + +import com.google.common.primitives.ImmutableIntArray; +import com.google.common.primitives.Ints; +import gnu.trove.list.array.TIntArrayList; + +import java.util.Arrays; +import java.util.List; + +public class PrimitiveCollections { + + public static void main(String[] args) { + + int[] primitives = new int[] {5, 10, 0, 2}; + + guavaPrimitives(primitives); + + trovePrimitives(primitives); + } + + private static void trovePrimitives(int[] primitives) { + TIntArrayList list = new TIntArrayList(primitives); + } + + private static void guavaPrimitives(int[] primitives) { + + ImmutableIntArray list = ImmutableIntArray.builder().addAll(primitives).build(); + + List integers = Ints.asList(primitives); + + int[] primitive = Ints.toArray(Arrays.asList(1, 2, 3, 4, 5)); + System.out.println(Arrays.toString(primitive)); + } +} diff --git a/core-java-arrays/src/main/java/com/baeldung/array/PrimitivesListPerformance.java b/core-java-arrays/src/main/java/com/baeldung/array/PrimitivesListPerformance.java new file mode 100644 index 0000000000..9db3a75574 --- /dev/null +++ b/core-java-arrays/src/main/java/com/baeldung/array/PrimitivesListPerformance.java @@ -0,0 +1,77 @@ +package com.baeldung.array; + +import it.unimi.dsi.fastutil.ints.IntArrayList; +import gnu.trove.list.array.TIntArrayList; +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 10) +public class PrimitivesListPerformance { + + @State(Scope.Thread) + public static class Initialize { + + List arrayList = new ArrayList<>(); + TIntArrayList tList = new TIntArrayList(); + cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(); + IntArrayList fastUtilList = new IntArrayList(); + + int getValue = 10; + + final int iterations = 100000; + + @Setup(Level.Trial) + public void setUp() { + + for (int i = 0; i < iterations; i++) { + arrayList.add(i); + tList.add(i); + coltList.add(i); + fastUtilList.add(i); + } + + arrayList.add(getValue); + tList.add(getValue); + coltList.add(getValue); + fastUtilList.add(getValue); + } + } + + @Benchmark + public boolean containsArrayList(PrimitivesListPerformance.Initialize state) { + return state.arrayList.contains(state.getValue); + } + + @Benchmark + public boolean containsTIntList(PrimitivesListPerformance.Initialize state) { + return state.tList.contains(state.getValue); + } + + @Benchmark + public boolean containsColtIntList(PrimitivesListPerformance.Initialize state) { + return state.coltList.contains(state.getValue); + } + + @Benchmark + public boolean containsFastUtilIntList(PrimitivesListPerformance.Initialize state) { + return state.fastUtilList.contains(state.getValue); + } + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(PrimitivesListPerformance.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} From 2acd1e27929ec4c4e06f0d79f2bc52a4a502dc0c Mon Sep 17 00:00:00 2001 From: dupirefr Date: Sat, 19 Jan 2019 10:06:35 +0100 Subject: [PATCH 017/152] [BAEL-2424] Updated tests to illustrate modifiers filtering and to disable order checking --- .../baeldung/reflection/MonthEmployee.java | 2 +- .../java/com/baeldung/reflection/Person.java | 2 +- .../PersonAndEmployeeReflectionUnitTest.java | 138 ++++++++++-------- 3 files changed, 82 insertions(+), 60 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/reflection/MonthEmployee.java b/core-java/src/main/java/com/baeldung/reflection/MonthEmployee.java index 697ecc1500..df2a19bbff 100644 --- a/core-java/src/main/java/com/baeldung/reflection/MonthEmployee.java +++ b/core-java/src/main/java/com/baeldung/reflection/MonthEmployee.java @@ -2,6 +2,6 @@ package com.baeldung.reflection; public class MonthEmployee extends Employee { - private double reward; + protected double reward; } diff --git a/core-java/src/main/java/com/baeldung/reflection/Person.java b/core-java/src/main/java/com/baeldung/reflection/Person.java index 23b312cdd9..e036ab5223 100644 --- a/core-java/src/main/java/com/baeldung/reflection/Person.java +++ b/core-java/src/main/java/com/baeldung/reflection/Person.java @@ -2,7 +2,7 @@ package com.baeldung.reflection; public class Person { - public String lastName; + protected String lastName; private String firstName; } diff --git a/core-java/src/test/java/com/baeldung/reflection/PersonAndEmployeeReflectionUnitTest.java b/core-java/src/test/java/com/baeldung/reflection/PersonAndEmployeeReflectionUnitTest.java index c051f165f1..b1a6a1fe57 100644 --- a/core-java/src/test/java/com/baeldung/reflection/PersonAndEmployeeReflectionUnitTest.java +++ b/core-java/src/test/java/com/baeldung/reflection/PersonAndEmployeeReflectionUnitTest.java @@ -3,10 +3,13 @@ package com.baeldung.reflection; import org.junit.Test; import java.lang.reflect.Field; +import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; import static org.junit.Assert.*; @@ -26,30 +29,14 @@ public class PersonAndEmployeeReflectionUnitTest { // Then assertEquals(2, allFields.length); - Field lastNameField = allFields[0]; - assertEquals(LAST_NAME_FIELD, lastNameField.getName()); - assertEquals(String.class, lastNameField.getType()); - - Field firstNameField = allFields[1]; - assertEquals(FIRST_NAME_FIELD, firstNameField.getName()); - assertEquals(String.class, firstNameField.getType()); - } - - @Test - public void givenEmployeeClass_whenSuperClassGetDeclaredFields_thenOneField() { - // When - Field[] allFields = Employee.class.getSuperclass().getDeclaredFields(); - - // Then - assertEquals(2, allFields.length); - - Field lastNameField = allFields[0]; - assertEquals(LAST_NAME_FIELD, lastNameField.getName()); - assertEquals(String.class, lastNameField.getType()); - - Field firstNameField = allFields[1]; - assertEquals(FIRST_NAME_FIELD, firstNameField.getName()); - assertEquals(String.class, firstNameField.getType()); + assertTrue(Arrays.stream(allFields).anyMatch(field -> + field.getName().equals(LAST_NAME_FIELD) + && field.getType().equals(String.class)) + ); + assertTrue(Arrays.stream(allFields).anyMatch(field -> + field.getName().equals(FIRST_NAME_FIELD) + && field.getType().equals(String.class)) + ); } @Test @@ -60,9 +47,28 @@ public class PersonAndEmployeeReflectionUnitTest { // Then assertEquals(1, allFields.length); - Field employeeIdField = allFields[0]; - assertEquals(EMPLOYEE_ID_FIELD, employeeIdField.getName()); - assertEquals(int.class, employeeIdField.getType()); + assertTrue(Arrays.stream(allFields).anyMatch(field -> + field.getName().equals(EMPLOYEE_ID_FIELD) + && field.getType().equals(int.class)) + ); + } + + @Test + public void givenEmployeeClass_whenSuperClassGetDeclaredFields_thenOneField() { + // When + Field[] allFields = Employee.class.getSuperclass().getDeclaredFields(); + + // Then + assertEquals(2, allFields.length); + + assertTrue(Arrays.stream(allFields).anyMatch(field -> + field.getName().equals(LAST_NAME_FIELD) + && field.getType().equals(String.class)) + ); + assertTrue(Arrays.stream(allFields).anyMatch(field -> + field.getName().equals(FIRST_NAME_FIELD) + && field.getType().equals(String.class)) + ); } @Test @@ -76,42 +82,56 @@ public class PersonAndEmployeeReflectionUnitTest { // Then assertEquals(3, allFields.length); - Field lastNameField = allFields[0]; - assertEquals(LAST_NAME_FIELD, lastNameField.getName()); - assertEquals(String.class, lastNameField.getType()); - - Field firstNameField = allFields[1]; - assertEquals(FIRST_NAME_FIELD, firstNameField.getName()); - assertEquals(String.class, firstNameField.getType()); - - Field employeeIdField = allFields[2]; - assertEquals(EMPLOYEE_ID_FIELD, employeeIdField.getName()); - assertEquals(int.class, employeeIdField.getType()); + assertTrue(Arrays.stream(allFields).anyMatch(field -> + field.getName().equals(LAST_NAME_FIELD) + && field.getType().equals(String.class)) + ); + assertTrue(Arrays.stream(allFields).anyMatch(field -> + field.getName().equals(FIRST_NAME_FIELD) + && field.getType().equals(String.class)) + ); + assertTrue(Arrays.stream(allFields).anyMatch(field -> + field.getName().equals(EMPLOYEE_ID_FIELD) + && field.getType().equals(int.class)) + ); } @Test - public void givenMonthEmployeeClass_whenGetAllFields_thenFourFields() { + public void givenEmployeeClass_whenGetDeclaredFieldsOnEmployeeSuperclassWithModifiersFilter_thenOneFields() { + // When + List personFields = Arrays.stream(Employee.class.getSuperclass().getDeclaredFields()) + .filter(f -> Modifier.isPublic(f.getModifiers()) || Modifier.isProtected(f.getModifiers())) + .collect(Collectors.toList()); + + // Then + assertEquals(1, personFields.size()); + + assertTrue(personFields.stream().anyMatch(field -> + field.getName().equals(LAST_NAME_FIELD) + && field.getType().equals(String.class)) + ); + } + + @Test + public void givenMonthEmployeeClass_whenGetAllFields_thenThreeFields() { // When List allFields = getAllFields(MonthEmployee.class); // Then - assertEquals(4, allFields.size()); + assertEquals(3, allFields.size()); - Field lastNameField = allFields.get(0); - assertEquals(LAST_NAME_FIELD, lastNameField.getName()); - assertEquals(String.class, lastNameField.getType()); - - Field firstNameField = allFields.get(1); - assertEquals(FIRST_NAME_FIELD, firstNameField.getName()); - assertEquals(String.class, firstNameField.getType()); - - Field employeeIdField = allFields.get(2); - assertEquals(EMPLOYEE_ID_FIELD, employeeIdField.getName()); - assertEquals(int.class, employeeIdField.getType()); - - Field monthEmployeeRewardField = allFields.get(3); - assertEquals(MONTH_EMPLOYEE_REWARD_FIELD, monthEmployeeRewardField.getName()); - assertEquals(double.class, monthEmployeeRewardField.getType()); + assertTrue(allFields.stream().anyMatch(field -> + field.getName().equals(LAST_NAME_FIELD) + && field.getType().equals(String.class)) + ); + assertTrue(allFields.stream().anyMatch(field -> + field.getName().equals(EMPLOYEE_ID_FIELD) + && field.getType().equals(int.class)) + ); + assertTrue(allFields.stream().anyMatch(field -> + field.getName().equals(MONTH_EMPLOYEE_REWARD_FIELD) + && field.getType().equals(double.class)) + ); } public List getAllFields(Class clazz) { @@ -119,9 +139,11 @@ public class PersonAndEmployeeReflectionUnitTest { return Collections.emptyList(); } - List result = new ArrayList<>(); - result.addAll(getAllFields(clazz.getSuperclass())); - result.addAll(Arrays.asList(clazz.getDeclaredFields())); + List result = new ArrayList<>(getAllFields(clazz.getSuperclass())); + List filteredFields = Arrays.stream(clazz.getDeclaredFields()) + .filter(f -> Modifier.isPublic(f.getModifiers()) || Modifier.isProtected(f.getModifiers())) + .collect(Collectors.toList()); + result.addAll(filteredFields); return result; } From c713ddee6da9f3b3efc13a0b1935582c2581fee0 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Mon, 21 Jan 2019 09:26:47 +0400 Subject: [PATCH 018/152] trove list --- .../java/com/baeldung/array/PrimitiveCollections.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java b/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java index 115c5fe5c3..b991dcb598 100644 --- a/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java +++ b/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java @@ -2,6 +2,7 @@ package com.baeldung.array; import com.google.common.primitives.ImmutableIntArray; import com.google.common.primitives.Ints; +import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import java.util.Arrays; @@ -13,13 +14,16 @@ public class PrimitiveCollections { int[] primitives = new int[] {5, 10, 0, 2}; - guavaPrimitives(primitives); + //guavaPrimitives(primitives); trovePrimitives(primitives); } private static void trovePrimitives(int[] primitives) { - TIntArrayList list = new TIntArrayList(primitives); + TIntList tList = new TIntArrayList(primitives); + tList.reverse(); + System.out.println(tList); + System.out.println(tList.size()); } private static void guavaPrimitives(int[] primitives) { From 81f23992cb19ef7860cc4faa57df167a5d6d8ecd Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Mon, 21 Jan 2019 13:08:09 +0400 Subject: [PATCH 019/152] primitive collections --- .../baeldung/array/PrimitiveCollections.java | 24 +++++++------------ 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java b/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java index b991dcb598..85f4dd2498 100644 --- a/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java +++ b/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java @@ -2,8 +2,6 @@ package com.baeldung.array; import com.google.common.primitives.ImmutableIntArray; import com.google.common.primitives.Ints; -import gnu.trove.list.TIntList; -import gnu.trove.list.array.TIntArrayList; import java.util.Arrays; import java.util.List; @@ -14,25 +12,21 @@ public class PrimitiveCollections { int[] primitives = new int[] {5, 10, 0, 2}; - //guavaPrimitives(primitives); - - trovePrimitives(primitives); + guavaPrimitives(primitives); } - private static void trovePrimitives(int[] primitives) { - TIntList tList = new TIntArrayList(primitives); - tList.reverse(); - System.out.println(tList); - System.out.println(tList.size()); - } private static void guavaPrimitives(int[] primitives) { - ImmutableIntArray list = ImmutableIntArray.builder().addAll(primitives).build(); + ImmutableIntArray immutableIntArray = ImmutableIntArray.builder().addAll(primitives).build(); + System.out.println(immutableIntArray); - List integers = Ints.asList(primitives); + List list = Ints.asList(primitives); - int[] primitive = Ints.toArray(Arrays.asList(1, 2, 3, 4, 5)); - System.out.println(Arrays.toString(primitive)); + int[] primitiveArray = Ints.toArray(list); + + int[] concatenated = Ints.concat(primitiveArray, primitives); + + System.out.println(Arrays.toString(concatenated)); } } From ae344b37ec7d7c0ed2cb0141e96c9811ad4eea71 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Fri, 25 Jan 2019 09:51:15 +0400 Subject: [PATCH 020/152] move the code into core-java-collections-lists module --- core-java-arrays/pom.xml | 16 ---------- core-java-collections-list/pom.xml | 29 +++++++++++++++++++ .../list/primitive}/PrimitiveCollections.java | 2 +- .../primitive}/PrimitivesListPerformance.java | 3 +- 4 files changed, 31 insertions(+), 19 deletions(-) rename {core-java-arrays/src/main/java/com/baeldung/array => core-java-collections-list/src/main/java/com/baeldung/list/primitive}/PrimitiveCollections.java (95%) rename {core-java-arrays/src/main/java/com/baeldung/array => core-java-collections-list/src/main/java/com/baeldung/list/primitive}/PrimitivesListPerformance.java (97%) diff --git a/core-java-arrays/pom.xml b/core-java-arrays/pom.xml index 6d4109804e..d2d0453e87 100644 --- a/core-java-arrays/pom.xml +++ b/core-java-arrays/pom.xml @@ -52,22 +52,6 @@ spring-web ${springframework.spring-web.version} - - - net.sf.trove4j - trove4j - 3.0.2 - - - it.unimi.dsi - fastutil - 8.1.0 - - - colt - colt - 1.2.0 - diff --git a/core-java-collections-list/pom.xml b/core-java-collections-list/pom.xml index ee99e470d0..bc71882683 100644 --- a/core-java-collections-list/pom.xml +++ b/core-java-collections-list/pom.xml @@ -36,6 +36,33 @@ ${lombok.version} provided + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator-annprocess.version} + + + + net.sf.trove4j + trove4j + 3.0.2 + + + it.unimi.dsi + fastutil + 8.1.0 + + + colt + colt + 1.2.0 + @@ -44,5 +71,7 @@ 1.7.0 3.11.1 1.16.12 + 1.19 + 1.19 diff --git a/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java similarity index 95% rename from core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java rename to core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java index 85f4dd2498..d6da32d899 100644 --- a/core-java-arrays/src/main/java/com/baeldung/array/PrimitiveCollections.java +++ b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java @@ -1,4 +1,4 @@ -package com.baeldung.array; +package com.baeldung.list.primitive; import com.google.common.primitives.ImmutableIntArray; import com.google.common.primitives.Ints; diff --git a/core-java-arrays/src/main/java/com/baeldung/array/PrimitivesListPerformance.java b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java similarity index 97% rename from core-java-arrays/src/main/java/com/baeldung/array/PrimitivesListPerformance.java rename to core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java index 9db3a75574..f57c8d65a6 100644 --- a/core-java-arrays/src/main/java/com/baeldung/array/PrimitivesListPerformance.java +++ b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java @@ -1,4 +1,4 @@ -package com.baeldung.array; +package com.baeldung.list.primitive; import it.unimi.dsi.fastutil.ints.IntArrayList; import gnu.trove.list.array.TIntArrayList; @@ -9,7 +9,6 @@ import org.openjdk.jmh.runner.options.OptionsBuilder; import java.util.ArrayList; import java.util.List; -import java.util.Random; import java.util.concurrent.TimeUnit; @BenchmarkMode(Mode.AverageTime) From 2f5ef3480b97cea30ec57dafb9370a114f9f8b18 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Fri, 25 Jan 2019 10:54:59 +0400 Subject: [PATCH 021/152] remove Ints examples --- .../com/baeldung/list/primitive/PrimitiveCollections.java | 8 -------- 1 file changed, 8 deletions(-) diff --git a/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java index d6da32d899..5a8ddc0acd 100644 --- a/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java +++ b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java @@ -20,13 +20,5 @@ public class PrimitiveCollections { ImmutableIntArray immutableIntArray = ImmutableIntArray.builder().addAll(primitives).build(); System.out.println(immutableIntArray); - - List list = Ints.asList(primitives); - - int[] primitiveArray = Ints.toArray(list); - - int[] concatenated = Ints.concat(primitiveArray, primitives); - - System.out.println(Arrays.toString(concatenated)); } } From 931dc2ae18577e9189ba83e44f2344b087c1563f Mon Sep 17 00:00:00 2001 From: alv21 Date: Fri, 25 Jan 2019 21:15:59 -0800 Subject: [PATCH 022/152] BAEL-2466 spring soap --- spring-soap/.gitignore | 1 + spring-soap/pom.xml | 68 +++++++++ .../com/baeldung/springsoap/Application.java | 12 ++ .../baeldung/springsoap/CountryEndpoint.java | 30 ++++ .../springsoap/CountryRepository.java | 47 ++++++ .../baeldung/springsoap/WebServiceConfig.java | 41 +++++ .../com/baeldung/springsoap/gen/Country.java | 144 ++++++++++++++++++ .../com/baeldung/springsoap/gen/Currency.java | 47 ++++++ .../springsoap/gen/GetCountryRequest.java | 71 +++++++++ .../springsoap/gen/GetCountryResponse.java | 71 +++++++++ .../springsoap/gen/ObjectFactory.java | 63 ++++++++ .../baeldung/springsoap/gen/package-info.java | 9 ++ spring-soap/src/main/resources/countries.xsd | 37 +++++ spring-soap/src/main/resources/request.xml | 23 +++ .../ApplicationIntegrationTest.java | 39 +++++ 15 files changed, 703 insertions(+) create mode 100644 spring-soap/.gitignore create mode 100644 spring-soap/pom.xml create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/Application.java create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/CountryEndpoint.java create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/CountryRepository.java create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/WebServiceConfig.java create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/gen/Country.java create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/gen/Currency.java create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/gen/GetCountryRequest.java create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/gen/GetCountryResponse.java create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/gen/ObjectFactory.java create mode 100644 spring-soap/src/main/java/com/baeldung/springsoap/gen/package-info.java create mode 100644 spring-soap/src/main/resources/countries.xsd create mode 100644 spring-soap/src/main/resources/request.xml create mode 100644 spring-soap/src/test/java/com/baeldung/springsoap/ApplicationIntegrationTest.java diff --git a/spring-soap/.gitignore b/spring-soap/.gitignore new file mode 100644 index 0000000000..b83d22266a --- /dev/null +++ b/spring-soap/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml new file mode 100644 index 0000000000..54a1d86038 --- /dev/null +++ b/spring-soap/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + org.springframework + spring-soap + 1.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.0.5.RELEASE + + + + 1.8 + + + + + + org.springframework.boot + spring-boot-starter-web-services + + + wsdl4j + wsdl4j + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + org.codehaus.mojo + jaxb2-maven-plugin + 1.6 + + + xjc + + xjc + + + + + ${project.basedir}/src/main/resources/ + ${project.basedir}/src/main/java + false + + + + + + + diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/Application.java b/spring-soap/src/main/java/com/baeldung/springsoap/Application.java new file mode 100644 index 0000000000..ad9258447c --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.springsoap; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/CountryEndpoint.java b/spring-soap/src/main/java/com/baeldung/springsoap/CountryEndpoint.java new file mode 100644 index 0000000000..745131767a --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/CountryEndpoint.java @@ -0,0 +1,30 @@ +package com.baeldung.springsoap; + +import com.baeldung.springsoap.gen.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ws.server.endpoint.annotation.Endpoint; +import org.springframework.ws.server.endpoint.annotation.PayloadRoot; +import org.springframework.ws.server.endpoint.annotation.RequestPayload; +import org.springframework.ws.server.endpoint.annotation.ResponsePayload; + +@Endpoint +public class CountryEndpoint { + + private static final String NAMESPACE_URI = "http://www.baeldung.com/springsoap/gen"; + + private CountryRepository countryRepository; + + @Autowired + public CountryEndpoint(CountryRepository countryRepository) { + this.countryRepository = countryRepository; + } + + @PayloadRoot(namespace = NAMESPACE_URI, localPart = "getCountryRequest") + @ResponsePayload + public GetCountryResponse getCountry(@RequestPayload GetCountryRequest request) { + GetCountryResponse response = new GetCountryResponse(); + response.setCountry(countryRepository.findCountry(request.getName())); + + return response; + } +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/CountryRepository.java b/spring-soap/src/main/java/com/baeldung/springsoap/CountryRepository.java new file mode 100644 index 0000000000..8a0f58a64e --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/CountryRepository.java @@ -0,0 +1,47 @@ +package com.baeldung.springsoap; + +import com.baeldung.springsoap.gen.*; +import org.springframework.stereotype.Component; +import org.springframework.util.Assert; + +import javax.annotation.PostConstruct; +import java.util.HashMap; +import java.util.Map; + +@Component +public class CountryRepository { + + private static final Map countries = new HashMap<>(); + + @PostConstruct + public void initData() { + Country spain = new Country(); + spain.setName("Spain"); + spain.setCapital("Madrid"); + spain.setCurrency(Currency.EUR); + spain.setPopulation(46704314); + + countries.put(spain.getName(), spain); + + Country poland = new Country(); + poland.setName("Poland"); + poland.setCapital("Warsaw"); + poland.setCurrency(Currency.PLN); + poland.setPopulation(38186860); + + countries.put(poland.getName(), poland); + + Country uk = new Country(); + uk.setName("United Kingdom"); + uk.setCapital("London"); + uk.setCurrency(Currency.GBP); + uk.setPopulation(63705000); + + countries.put(uk.getName(), uk); + } + + public Country findCountry(String name) { + Assert.notNull(name, "The country's name must not be null"); + return countries.get(name); + } +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/WebServiceConfig.java b/spring-soap/src/main/java/com/baeldung/springsoap/WebServiceConfig.java new file mode 100644 index 0000000000..930a961208 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/WebServiceConfig.java @@ -0,0 +1,41 @@ +package com.baeldung.springsoap; + +import org.springframework.boot.web.servlet.ServletRegistrationBean; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.ws.config.annotation.EnableWs; +import org.springframework.ws.config.annotation.WsConfigurerAdapter; +import org.springframework.ws.transport.http.MessageDispatcherServlet; +import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition; +import org.springframework.xml.xsd.SimpleXsdSchema; +import org.springframework.xml.xsd.XsdSchema; + +@EnableWs +@Configuration +public class WebServiceConfig extends WsConfigurerAdapter { + + @Bean + public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) { + MessageDispatcherServlet servlet = new MessageDispatcherServlet(); + servlet.setApplicationContext(applicationContext); + servlet.setTransformWsdlLocations(true); + return new ServletRegistrationBean(servlet, "/ws/*"); + } + + @Bean(name = "countries") + public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) { + DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition(); + wsdl11Definition.setPortTypeName("CountriesPort"); + wsdl11Definition.setLocationUri("/ws"); + wsdl11Definition.setTargetNamespace("http://www.baeldung.com/springsoap/gen"); + wsdl11Definition.setSchema(countriesSchema); + return wsdl11Definition; + } + + @Bean + public XsdSchema countriesSchema() { + return new SimpleXsdSchema(new ClassPathResource("countries.xsd")); + } +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/gen/Country.java b/spring-soap/src/main/java/com/baeldung/springsoap/gen/Country.java new file mode 100644 index 0000000000..e3eb686d6b --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/gen/Country.java @@ -0,0 +1,144 @@ +// +// Questo file è stato generato dall'architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.2.7 +// Vedere http://java.sun.com/xml/jaxb +// Qualsiasi modifica a questo file andrà persa durante la ricompilazione dello schema di origine. +// Generato il: 2019.01.25 alle 06:06:58 PM PST +// + + +package com.baeldung.springsoap.gen; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Classe Java per country complex type. + * + *

Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe. + * + *

+ * <complexType name="country">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="population" type="{http://www.w3.org/2001/XMLSchema}int"/>
+ *         <element name="capital" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="currency" type="{http://www.baeldung.com/springsoap/gen}currency"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "country", propOrder = { + "name", + "population", + "capital", + "currency" +}) +public class Country { + + @XmlElement(required = true) + protected String name; + protected int population; + @XmlElement(required = true) + protected String capital; + @XmlElement(required = true) + protected Currency currency; + + /** + * Recupera il valore della proprietà name. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Imposta il valore della proprietà name. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + + /** + * Recupera il valore della proprietà population. + * + */ + public int getPopulation() { + return population; + } + + /** + * Imposta il valore della proprietà population. + * + */ + public void setPopulation(int value) { + this.population = value; + } + + /** + * Recupera il valore della proprietà capital. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCapital() { + return capital; + } + + /** + * Imposta il valore della proprietà capital. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCapital(String value) { + this.capital = value; + } + + /** + * Recupera il valore della proprietà currency. + * + * @return + * possible object is + * {@link Currency } + * + */ + public Currency getCurrency() { + return currency; + } + + /** + * Imposta il valore della proprietà currency. + * + * @param value + * allowed object is + * {@link Currency } + * + */ + public void setCurrency(Currency value) { + this.currency = value; + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/gen/Currency.java b/spring-soap/src/main/java/com/baeldung/springsoap/gen/Currency.java new file mode 100644 index 0000000000..9b0660466f --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/gen/Currency.java @@ -0,0 +1,47 @@ +// +// Questo file è stato generato dall'architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.2.7 +// Vedere http://java.sun.com/xml/jaxb +// Qualsiasi modifica a questo file andrà persa durante la ricompilazione dello schema di origine. +// Generato il: 2019.01.25 alle 06:06:58 PM PST +// + + +package com.baeldung.springsoap.gen; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Classe Java per currency. + * + *

Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe. + *

+ *

+ * <simpleType name="currency">
+ *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *     <enumeration value="GBP"/>
+ *     <enumeration value="EUR"/>
+ *     <enumeration value="PLN"/>
+ *   </restriction>
+ * </simpleType>
+ * 
+ * + */ +@XmlType(name = "currency") +@XmlEnum +public enum Currency { + + GBP, + EUR, + PLN; + + public String value() { + return name(); + } + + public static Currency fromValue(String v) { + return valueOf(v); + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/gen/GetCountryRequest.java b/spring-soap/src/main/java/com/baeldung/springsoap/gen/GetCountryRequest.java new file mode 100644 index 0000000000..7e1f151929 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/gen/GetCountryRequest.java @@ -0,0 +1,71 @@ +// +// Questo file è stato generato dall'architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.2.7 +// Vedere http://java.sun.com/xml/jaxb +// Qualsiasi modifica a questo file andrà persa durante la ricompilazione dello schema di origine. +// Generato il: 2019.01.25 alle 06:06:58 PM PST +// + + +package com.baeldung.springsoap.gen; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Classe Java per anonymous complex type. + * + *

Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe. + * + *

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "name" +}) +@XmlRootElement(name = "getCountryRequest") +public class GetCountryRequest { + + @XmlElement(required = true) + protected String name; + + /** + * Recupera il valore della proprietà name. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Imposta il valore della proprietà name. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/gen/GetCountryResponse.java b/spring-soap/src/main/java/com/baeldung/springsoap/gen/GetCountryResponse.java new file mode 100644 index 0000000000..38c49193b4 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/gen/GetCountryResponse.java @@ -0,0 +1,71 @@ +// +// Questo file è stato generato dall'architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.2.7 +// Vedere http://java.sun.com/xml/jaxb +// Qualsiasi modifica a questo file andrà persa durante la ricompilazione dello schema di origine. +// Generato il: 2019.01.25 alle 06:06:58 PM PST +// + + +package com.baeldung.springsoap.gen; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Classe Java per anonymous complex type. + * + *

Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe. + * + *

+ * <complexType>
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="country" type="{http://www.baeldung.com/springsoap/gen}country"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "country" +}) +@XmlRootElement(name = "getCountryResponse") +public class GetCountryResponse { + + @XmlElement(required = true) + protected Country country; + + /** + * Recupera il valore della proprietà country. + * + * @return + * possible object is + * {@link Country } + * + */ + public Country getCountry() { + return country; + } + + /** + * Imposta il valore della proprietà country. + * + * @param value + * allowed object is + * {@link Country } + * + */ + public void setCountry(Country value) { + this.country = value; + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/gen/ObjectFactory.java b/spring-soap/src/main/java/com/baeldung/springsoap/gen/ObjectFactory.java new file mode 100644 index 0000000000..6b9691efc0 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/gen/ObjectFactory.java @@ -0,0 +1,63 @@ +// +// Questo file è stato generato dall'architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.2.7 +// Vedere http://java.sun.com/xml/jaxb +// Qualsiasi modifica a questo file andrà persa durante la ricompilazione dello schema di origine. +// Generato il: 2019.01.25 alle 06:06:58 PM PST +// + + +package com.baeldung.springsoap.gen; + +import javax.xml.bind.annotation.XmlRegistry; + + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the com.baeldung.springsoap.gen package. + *

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. + * + */ +@XmlRegistry +public class ObjectFactory { + + + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.springsoap.gen + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link GetCountryRequest } + * + */ + public GetCountryRequest createGetCountryRequest() { + return new GetCountryRequest(); + } + + /** + * Create an instance of {@link GetCountryResponse } + * + */ + public GetCountryResponse createGetCountryResponse() { + return new GetCountryResponse(); + } + + /** + * Create an instance of {@link Country } + * + */ + public Country createCountry() { + return new Country(); + } + +} diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/gen/package-info.java b/spring-soap/src/main/java/com/baeldung/springsoap/gen/package-info.java new file mode 100644 index 0000000000..9638be3d94 --- /dev/null +++ b/spring-soap/src/main/java/com/baeldung/springsoap/gen/package-info.java @@ -0,0 +1,9 @@ +// +// Questo file è stato generato dall'architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.2.7 +// Vedere http://java.sun.com/xml/jaxb +// Qualsiasi modifica a questo file andrà persa durante la ricompilazione dello schema di origine. +// Generato il: 2019.01.25 alle 06:06:58 PM PST +// + +@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/springsoap/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +package com.baeldung.springsoap.gen; diff --git a/spring-soap/src/main/resources/countries.xsd b/spring-soap/src/main/resources/countries.xsd new file mode 100644 index 0000000000..524e5ac2d5 --- /dev/null +++ b/spring-soap/src/main/resources/countries.xsd @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-soap/src/main/resources/request.xml b/spring-soap/src/main/resources/request.xml new file mode 100644 index 0000000000..7a94aeeee6 --- /dev/null +++ b/spring-soap/src/main/resources/request.xml @@ -0,0 +1,23 @@ + + + + + Spain + + + + + + + + + + Spain + 46704314 + Madrid + EUR + + + + \ No newline at end of file diff --git a/spring-soap/src/test/java/com/baeldung/springsoap/ApplicationIntegrationTest.java b/spring-soap/src/test/java/com/baeldung/springsoap/ApplicationIntegrationTest.java new file mode 100644 index 0000000000..18c8a96576 --- /dev/null +++ b/spring-soap/src/test/java/com/baeldung/springsoap/ApplicationIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.springsoap; + +import com.baeldung.springsoap.gen.GetCountryRequest; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.oxm.jaxb.Jaxb2Marshaller; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.util.ClassUtils; +import org.springframework.ws.client.core.WebServiceTemplate; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class ApplicationIntegrationTest { + + private Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); + + @LocalServerPort private int port = 0; + + @Before + public void init() throws Exception { + marshaller.setPackagesToScan(ClassUtils.getPackageName(GetCountryRequest.class)); + marshaller.afterPropertiesSet(); + } + + @Test + public void whenSendRequest_thenResponseIsNotNull() { + WebServiceTemplate ws = new WebServiceTemplate(marshaller); + GetCountryRequest request = new GetCountryRequest(); + request.setName("Spain"); + + assertThat(ws.marshalSendAndReceive("http://localhost:" + port + "/ws", request)).isNotNull(); + } +} \ No newline at end of file From 720c32ab78b18e3fc092700e674c4e84724ef33b Mon Sep 17 00:00:00 2001 From: amdegregorio Date: Sat, 26 Jan 2019 09:00:26 -0500 Subject: [PATCH 023/152] BAEL-2542 Creating a Jar - example code --- .../java/com/baeldung/jar/Dimensioner.java | 27 ++++++++++++ .../java/com/baeldung/jar/JarExample.java | 31 +++++++++++++ .../main/java/com/baeldung/jar/Rectangle.java | 44 +++++++++++++++++++ .../resources/META-INF/example_manifest.txt | 1 + .../src/main/resources/files/dimensions.txt | 3 ++ 5 files changed, 106 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/jar/Dimensioner.java create mode 100644 core-java/src/main/java/com/baeldung/jar/JarExample.java create mode 100644 core-java/src/main/java/com/baeldung/jar/Rectangle.java create mode 100644 core-java/src/main/resources/META-INF/example_manifest.txt create mode 100644 core-java/src/main/resources/files/dimensions.txt diff --git a/core-java/src/main/java/com/baeldung/jar/Dimensioner.java b/core-java/src/main/java/com/baeldung/jar/Dimensioner.java new file mode 100644 index 0000000000..bc5cea4010 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/jar/Dimensioner.java @@ -0,0 +1,27 @@ +package com.baeldung.jar; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; + +public class Dimensioner { + + public List loadFromFile(String dimensionFile) throws FileNotFoundException, IOException { + List rectangles = new ArrayList(); + try (BufferedReader br = new BufferedReader(new InputStreamReader(Dimensioner.class.getResourceAsStream(dimensionFile)))) { + String line; + while ((line = br.readLine()) != null) { + String[] dimensions = line.split(","); + if (dimensions.length == 2) { + Rectangle rectangle = new Rectangle(Integer.valueOf(dimensions[0]), Integer.valueOf(dimensions[1])); + rectangles.add(rectangle); + } + } + } + return rectangles; + } + +} diff --git a/core-java/src/main/java/com/baeldung/jar/JarExample.java b/core-java/src/main/java/com/baeldung/jar/JarExample.java new file mode 100644 index 0000000000..262df3a5ec --- /dev/null +++ b/core-java/src/main/java/com/baeldung/jar/JarExample.java @@ -0,0 +1,31 @@ +package com.baeldung.jar; + +import java.io.IOException; +import java.util.List; + +public class JarExample { + private static final String DIMENSION_FILE = "/dimensions.txt"; + + public static void main(String[] args) { + String environment = System.getProperty("environment"); + if (environment != null && environment.equalsIgnoreCase("prod")) { + Dimensioner dimensioner = new Dimensioner(); + try { + List rectangles = dimensioner.loadFromFile(DIMENSION_FILE); + rectangles.forEach(rectangle -> { + rectangle.printArea(); + rectangle.printPerimeter(); + }); + } catch (IOException e) { + System.err.println("Exception loading dimensions"); + } + } else if (args.length > 0) { + int length = Integer.valueOf(args[0]); + int width = (args.length > 1) ? Integer.valueOf(args[1]) : Integer.valueOf(args[0]); + Rectangle rectangle = new Rectangle(length, width); + rectangle.printArea(); + rectangle.printPerimeter(); + } + } + +} diff --git a/core-java/src/main/java/com/baeldung/jar/Rectangle.java b/core-java/src/main/java/com/baeldung/jar/Rectangle.java new file mode 100644 index 0000000000..f2a174c819 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/jar/Rectangle.java @@ -0,0 +1,44 @@ +package com.baeldung.jar; + +public class Rectangle { + private int length; + private int width; + + public Rectangle(int length, int width) { + this.length = length; + this.width = width; + } + + public int area() { + return length * width; + } + + public int perimeter() { + return (length * 2) + (width * 2); + } + + public void printArea() { + System.out.println("Area: " + area()); + } + + public void printPerimeter() { + System.out.println("Perimeter: " + perimeter()); + } + + public int getLength() { + return length; + } + + public void setLength(int length) { + this.length = length; + } + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + this.width = width; + } + +} diff --git a/core-java/src/main/resources/META-INF/example_manifest.txt b/core-java/src/main/resources/META-INF/example_manifest.txt new file mode 100644 index 0000000000..90e83e9b42 --- /dev/null +++ b/core-java/src/main/resources/META-INF/example_manifest.txt @@ -0,0 +1 @@ +Main-Class: com.baeldung.jar.JarExample diff --git a/core-java/src/main/resources/files/dimensions.txt b/core-java/src/main/resources/files/dimensions.txt new file mode 100644 index 0000000000..0397c2a610 --- /dev/null +++ b/core-java/src/main/resources/files/dimensions.txt @@ -0,0 +1,3 @@ +12,16 +24,6 +7,19 \ No newline at end of file From 4c1c93e1f698c06137de54737fb11fc828b27857 Mon Sep 17 00:00:00 2001 From: alv21 Date: Sat, 26 Jan 2019 09:14:27 -0800 Subject: [PATCH 024/152] BAEL-2466 spring-soap module added --- pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pom.xml b/pom.xml index d084d0f7af..fe55a9bf44 100644 --- a/pom.xml +++ b/pom.xml @@ -749,6 +749,7 @@ spring-security-x509 spring-session spring-sleuth + spring-soap spring-social-login spring-spel spring-state-machine @@ -1458,6 +1459,7 @@ spring-security-x509 spring-session spring-sleuth + spring-soap spring-social-login spring-spel spring-state-machine From aed3e8f829d418a90afea6d659123afed0dd9e4c Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 27 Jan 2019 15:09:00 +0200 Subject: [PATCH 025/152] Update README.md --- core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java/README.md b/core-java/README.md index 5aee69d9a9..d6cb619ed3 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -46,3 +46,4 @@ - [Graphs in Java](https://www.baeldung.com/java-graphs) - [Console I/O in Java](http://www.baeldung.com/java-console-input-output) - [Formatting with printf() in Java](https://www.baeldung.com/java-printstream-printf) +- [Retrieve Fields from a Java Class Using Reflection](https://www.baeldung.com/java-reflection-class-fields) From 79f1babc26b4d96686e1815d4437d0c5f3f0c65f Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 27 Jan 2019 15:09:46 +0200 Subject: [PATCH 026/152] Update README.md --- persistence-modules/java-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/java-jpa/README.md b/persistence-modules/java-jpa/README.md index 2eea5e60b4..5fe119cca4 100644 --- a/persistence-modules/java-jpa/README.md +++ b/persistence-modules/java-jpa/README.md @@ -4,3 +4,4 @@ - [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures) - [Fixing the JPA error “java.lang.String cannot be cast to Ljava.lang.String;”](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast) - [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph) +- [JPA 2.2 Support for Java 8 Date/Time Types](https://www.baeldung.com/jpa-java-time) From 639e0046d7ef36502edffff27be8a88b7d2d1ad4 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 27 Jan 2019 15:10:33 +0200 Subject: [PATCH 027/152] Update README.md --- 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 2ad980ca6a..fcb3302a48 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -36,4 +36,5 @@ - [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array) - [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader) - [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension) -- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type) \ No newline at end of file +- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type) +- [Create a Directory in Java](https://www.baeldung.com/java-create-directory) From 242dc1dbcee7394319af5eafb91b209fe39421fc Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 27 Jan 2019 15:11:21 +0200 Subject: [PATCH 028/152] Update README.md --- persistence-modules/hibernate5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/hibernate5/README.md b/persistence-modules/hibernate5/README.md index 03bdd9b759..a4e95a9062 100644 --- a/persistence-modules/hibernate5/README.md +++ b/persistence-modules/hibernate5/README.md @@ -29,3 +29,4 @@ - [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query) - [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0) - [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object) +- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions) From 8a3d3f934402b3409b3392edfccff8b4f1ad8a5e Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 27 Jan 2019 15:12:01 +0200 Subject: [PATCH 029/152] Update README.md --- java-streams/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/java-streams/README.md b/java-streams/README.md index 33ca2619a8..f2afd570f6 100644 --- a/java-streams/README.md +++ b/java-streams/README.md @@ -15,3 +15,4 @@ - [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering) - [Introduction to Protonpack](https://www.baeldung.com/java-protonpack) - [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda) +- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count) From ac53498b767eaa5052933373a823a58365263583 Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Sun, 27 Jan 2019 15:40:36 +0200 Subject: [PATCH 030/152] BAEL-2659 - Reading a file in Groovy --- .../groovy/com/baeldung/file/ReadFile.groovy | 61 +++++++++++++++++++ .../src/main/resources/fileContent.txt | 3 + .../com/baeldung/file/ReadFileUnitTest.groovy | 58 ++++++++++++++++++ 3 files changed, 122 insertions(+) create mode 100644 core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy create mode 100644 core-groovy/src/main/resources/fileContent.txt create mode 100644 core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy diff --git a/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy b/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy new file mode 100644 index 0000000000..fca5bde06f --- /dev/null +++ b/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy @@ -0,0 +1,61 @@ +package com.baeldung.file + +class ReadFile { + + /** + * reads file content in string using File.text + * @param filePath + * @return + */ + String readFileString(String filePath) { + File file = new File(filePath) + String fileContent = file.text + return fileContent + } + + /** + * reads file content in string with encoding using File.getText + * @param filePath + * @return + */ + String readFileStringWithCharset(String filePath) { + File file = new File(filePath) + String utf8Content = file.getText("UTF-8") + return utf8Content + } + + /** + * reads file content line by line using withReader and reader.readLine + * @param filePath + * @return + */ + int readFileLineByLine(String filePath) { + File file = new File(filePath) + def line, noOfLines = 0; + file.withReader { reader -> + while ((line = reader.readLine())!=null) + { + println "${line}" + noOfLines++ + } + } + return noOfLines + } + + /** + * reads file content in list of lines + * @param filePath + * @return + */ + List readFileInList(String filePath) { + File file = new File(filePath) + def lines = file.readLines() + return lines + } + + public static void main(String[] args) { + def file = new File("../../src") + println file.directorySize + } + +} \ No newline at end of file diff --git a/core-groovy/src/main/resources/fileContent.txt b/core-groovy/src/main/resources/fileContent.txt new file mode 100644 index 0000000000..643e4af3de --- /dev/null +++ b/core-groovy/src/main/resources/fileContent.txt @@ -0,0 +1,3 @@ +Line 1 : Hello World!!! +Line 2 : This is a file content. +Line 3 : String content diff --git a/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy new file mode 100644 index 0000000000..c90cc8b960 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy @@ -0,0 +1,58 @@ +package com.baeldung.file + +import spock.lang.Specification + +class ReadFileUnitTest extends Specification { + + ReadFile readFile + + void setup () { + readFile = new ReadFile() + } + + def 'Should return file content in string using ReadFile.readFileString given filePath' () { + given: + def filePath = "src/main/resources/fileContent.txt" + when: + def fileContent = readFile.readFileString(filePath) + then: + fileContent + fileContent instanceof String + fileContent.contains("""Line 1 : Hello World!!! +Line 2 : This is a file content. +Line 3 : String content""") + + } + + def 'Should return UTF-8 encoded file content in string using ReadFile.readFileStringWithCharset given filePath' () { + given: + def filePath = "src/main/resources/fileContent.txt" + when: + def noOfLines = readFile.readFileStringWithCharset(filePath) + then: + noOfLines + noOfLines instanceof String + } + + def 'Should return number of lines in File using ReadFile.readFileLineByLine given filePath' () { + given: + def filePath = "src/main/resources/fileContent.txt" + when: + def noOfLines = readFile.readFileLineByLine(filePath) + then: + noOfLines + noOfLines instanceof Integer + assert noOfLines, 3 + } + + def 'Should return File Content in list of lines using ReadFile.readFileInList given filePath' () { + given: + def filePath = "src/main/resources/fileContent.txt" + when: + def lines = readFile.readFileInList(filePath) + then: + lines + lines instanceof List + assert lines.size(), 3 + } +} \ No newline at end of file From fd70f654b54e3ac59a9477809aed14c833ec15fa Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Sun, 27 Jan 2019 17:45:34 +0400 Subject: [PATCH 031/152] primitive list collections --- .../list/primitive/PrimitiveCollections.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java index 5a8ddc0acd..50f372e9c9 100644 --- a/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java +++ b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java @@ -2,6 +2,8 @@ package com.baeldung.list.primitive; import com.google.common.primitives.ImmutableIntArray; import com.google.common.primitives.Ints; +import gnu.trove.list.array.TIntArrayList; +import it.unimi.dsi.fastutil.ints.IntArrayList; import java.util.Arrays; import java.util.List; @@ -13,6 +15,18 @@ public class PrimitiveCollections { int[] primitives = new int[] {5, 10, 0, 2}; guavaPrimitives(primitives); + + TIntArrayList tList = new TIntArrayList(primitives); + + cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(primitives); + + IntArrayList fastUtilList = new IntArrayList(primitives); + + System.out.println(tList); + + System.out.println(coltList); + + System.out.println(fastUtilList); } From f22d1073d19416ba5d327149b316babebb8b4b47 Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Sun, 27 Jan 2019 22:47:27 +0200 Subject: [PATCH 032/152] BAEL-2659 - Reading a file in Groovy - changed order of functions --- .../groovy/com/baeldung/file/ReadFile.groovy | 48 +++++++++---------- .../com/baeldung/file/ReadFileUnitTest.groovy | 44 ++++++++--------- 2 files changed, 44 insertions(+), 48 deletions(-) diff --git a/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy b/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy index fca5bde06f..73208a52c8 100644 --- a/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy +++ b/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy @@ -2,28 +2,6 @@ package com.baeldung.file class ReadFile { - /** - * reads file content in string using File.text - * @param filePath - * @return - */ - String readFileString(String filePath) { - File file = new File(filePath) - String fileContent = file.text - return fileContent - } - - /** - * reads file content in string with encoding using File.getText - * @param filePath - * @return - */ - String readFileStringWithCharset(String filePath) { - File file = new File(filePath) - String utf8Content = file.getText("UTF-8") - return utf8Content - } - /** * reads file content line by line using withReader and reader.readLine * @param filePath @@ -52,10 +30,28 @@ class ReadFile { def lines = file.readLines() return lines } - - public static void main(String[] args) { - def file = new File("../../src") - println file.directorySize + + /** + * reads file content in string using File.text + * @param filePath + * @return + */ + String readFileString(String filePath) { + File file = new File(filePath) + String fileContent = file.text + return fileContent } + /** + * reads file content in string with encoding using File.getText + * @param filePath + * @return + */ + String readFileStringWithCharset(String filePath) { + File file = new File(filePath) + String utf8Content = file.getText("UTF-8") + return utf8Content + } + + } \ No newline at end of file diff --git a/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy index c90cc8b960..105a8e157f 100644 --- a/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy @@ -10,6 +10,28 @@ class ReadFileUnitTest extends Specification { readFile = new ReadFile() } + def 'Should return number of lines in File using ReadFile.readFileLineByLine given filePath' () { + given: + def filePath = "src/main/resources/fileContent.txt" + when: + def noOfLines = readFile.readFileLineByLine(filePath) + then: + noOfLines + noOfLines instanceof Integer + assert noOfLines, 3 + } + + def 'Should return File Content in list of lines using ReadFile.readFileInList given filePath' () { + given: + def filePath = "src/main/resources/fileContent.txt" + when: + def lines = readFile.readFileInList(filePath) + then: + lines + lines instanceof List + assert lines.size(), 3 + } + def 'Should return file content in string using ReadFile.readFileString given filePath' () { given: def filePath = "src/main/resources/fileContent.txt" @@ -33,26 +55,4 @@ Line 3 : String content""") noOfLines noOfLines instanceof String } - - def 'Should return number of lines in File using ReadFile.readFileLineByLine given filePath' () { - given: - def filePath = "src/main/resources/fileContent.txt" - when: - def noOfLines = readFile.readFileLineByLine(filePath) - then: - noOfLines - noOfLines instanceof Integer - assert noOfLines, 3 - } - - def 'Should return File Content in list of lines using ReadFile.readFileInList given filePath' () { - given: - def filePath = "src/main/resources/fileContent.txt" - when: - def lines = readFile.readFileInList(filePath) - then: - lines - lines instanceof List - assert lines.size(), 3 - } } \ No newline at end of file From 44d5be301ce9e69b69f4ef632250f6b8f07cd8c0 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Mon, 28 Jan 2019 15:15:05 +0400 Subject: [PATCH 033/152] remove performance test --- .../primitive/PrimitivesListPerformance.java | 76 ------------------- 1 file changed, 76 deletions(-) delete mode 100644 core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java diff --git a/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java deleted file mode 100644 index f57c8d65a6..0000000000 --- a/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.baeldung.list.primitive; - -import it.unimi.dsi.fastutil.ints.IntArrayList; -import gnu.trove.list.array.TIntArrayList; -import org.openjdk.jmh.annotations.*; -import org.openjdk.jmh.runner.Runner; -import org.openjdk.jmh.runner.options.Options; -import org.openjdk.jmh.runner.options.OptionsBuilder; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -@BenchmarkMode(Mode.AverageTime) -@OutputTimeUnit(TimeUnit.NANOSECONDS) -@Warmup(iterations = 10) -public class PrimitivesListPerformance { - - @State(Scope.Thread) - public static class Initialize { - - List arrayList = new ArrayList<>(); - TIntArrayList tList = new TIntArrayList(); - cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(); - IntArrayList fastUtilList = new IntArrayList(); - - int getValue = 10; - - final int iterations = 100000; - - @Setup(Level.Trial) - public void setUp() { - - for (int i = 0; i < iterations; i++) { - arrayList.add(i); - tList.add(i); - coltList.add(i); - fastUtilList.add(i); - } - - arrayList.add(getValue); - tList.add(getValue); - coltList.add(getValue); - fastUtilList.add(getValue); - } - } - - @Benchmark - public boolean containsArrayList(PrimitivesListPerformance.Initialize state) { - return state.arrayList.contains(state.getValue); - } - - @Benchmark - public boolean containsTIntList(PrimitivesListPerformance.Initialize state) { - return state.tList.contains(state.getValue); - } - - @Benchmark - public boolean containsColtIntList(PrimitivesListPerformance.Initialize state) { - return state.coltList.contains(state.getValue); - } - - @Benchmark - public boolean containsFastUtilIntList(PrimitivesListPerformance.Initialize state) { - return state.fastUtilList.contains(state.getValue); - } - - public static void main(String[] args) throws Exception { - Options options = new OptionsBuilder() - .include(PrimitivesListPerformance.class.getSimpleName()).threads(1) - .forks(1).shouldFailOnError(true) - .shouldDoGC(true) - .jvmArgs("-server").build(); - new Runner(options).run(); - } -} From d944b67c29a56d83ea31603238aa599de7cb212e Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Mon, 28 Jan 2019 15:23:01 +0400 Subject: [PATCH 034/152] remove JMH dependency --- core-java-collections-list/pom.xml | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/core-java-collections-list/pom.xml b/core-java-collections-list/pom.xml index bc71882683..a7e711088a 100644 --- a/core-java-collections-list/pom.xml +++ b/core-java-collections-list/pom.xml @@ -37,17 +37,6 @@ provided - - org.openjdk.jmh - jmh-core - ${jmh-core.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh-generator-annprocess.version} - - net.sf.trove4j trove4j @@ -71,7 +60,5 @@ 1.7.0 3.11.1 1.16.12 - 1.19 - 1.19 From 66c92495fb27780f76c0409408fc38cdcf3f83f4 Mon Sep 17 00:00:00 2001 From: amdegregorio Date: Mon, 28 Jan 2019 06:53:52 -0500 Subject: [PATCH 035/152] BAEL-2542 Update system property name --- core-java/src/main/java/com/baeldung/jar/JarExample.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java/src/main/java/com/baeldung/jar/JarExample.java b/core-java/src/main/java/com/baeldung/jar/JarExample.java index 262df3a5ec..daa44025d5 100644 --- a/core-java/src/main/java/com/baeldung/jar/JarExample.java +++ b/core-java/src/main/java/com/baeldung/jar/JarExample.java @@ -7,8 +7,8 @@ public class JarExample { private static final String DIMENSION_FILE = "/dimensions.txt"; public static void main(String[] args) { - String environment = System.getProperty("environment"); - if (environment != null && environment.equalsIgnoreCase("prod")) { + String inputType = System.getProperty("input"); + if (inputType != null && inputType.equalsIgnoreCase("file")) { Dimensioner dimensioner = new Dimensioner(); try { List rectangles = dimensioner.loadFromFile(DIMENSION_FILE); From 1f4d1839f44232312c289e30b6869420dd558520 Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Tue, 29 Jan 2019 17:27:52 +0200 Subject: [PATCH 036/152] BAEL-2659 - Reading a file in Groovy - added more examples and unit tests --- .../groovy/com/baeldung/file/ReadFile.groovy | 36 ++++++++++++++++++ core-groovy/src/main/resources/sample.png | Bin 0 -> 329 bytes .../src/main/resources/utf8Content.html | 5 +++ .../com/baeldung/file/ReadFileUnitTest.groovy | 12 +++++- 4 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 core-groovy/src/main/resources/sample.png create mode 100644 core-groovy/src/main/resources/utf8Content.html diff --git a/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy b/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy index 73208a52c8..38bf189e63 100644 --- a/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy +++ b/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy @@ -53,5 +53,41 @@ class ReadFile { return utf8Content } + /** + * reads content of binary file and returns byte array + * @param filePath + * @return + */ + byte[] readBinaryFile(String filePath) { + File file = new File(filePath) + byte[] binaryContent = file.bytes + return binaryContent + } + + /** + * More Examples of reading a file + * @return + */ + def moreExamples() { + def list = new File("src/main/resources/fileContent.txt").collect {it} + + def array = new File("src/main/resources/fileContent.txt") as String[] + + new File("src/main/resources/fileContent.txt").eachLine { line -> + println line + } + + def is = new File("src/main/resources/fileContent.txt").newInputStream() + is.eachLine { + println it + } + is.close() + + new File("src/main/resources/fileContent.txt").withInputStream { stream -> + stream.eachLine { line -> + println line + } + } + } } \ No newline at end of file diff --git a/core-groovy/src/main/resources/sample.png b/core-groovy/src/main/resources/sample.png new file mode 100644 index 0000000000000000000000000000000000000000..7d473430b7bec514f7de12f5769fe7c5859e8c5d GIT binary patch literal 329 zcmeAS@N?(olHy`uVBq!ia0vp^JRr;gBp8b2n5}^nQC}X^4DKU-G|w_t}fLBA)Suv#nrW z!^h2QnY_`l!BOq-UXEX{m2up>JTQkX)2m zTvF+fTUlI^nXH#utd~++ke^qgmzgTe~DWM4ffP81J literal 0 HcmV?d00001 diff --git a/core-groovy/src/main/resources/utf8Content.html b/core-groovy/src/main/resources/utf8Content.html new file mode 100644 index 0000000000..9d941200b1 --- /dev/null +++ b/core-groovy/src/main/resources/utf8Content.html @@ -0,0 +1,5 @@ +ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ +ᛋᚳᛖᚪᛚ᛫ᚦᛖᚪᚻ᛫ᛗᚪᚾᚾᚪ᛫ᚷᛖᚻᚹᛦᛚᚳ᛫ᛗᛁᚳᛚᚢᚾ᛫ᚻᛦᛏ᛫ᛞᚫᛚᚪᚾ +ᚷᛁᚠ᛫ᚻᛖ᛫ᚹᛁᛚᛖ᛫ᚠᚩᚱ᛫ᛞᚱᛁᚻᛏᚾᛖ᛫ᛞᚩᛗᛖᛋ᛫ᚻᛚᛇᛏᚪᚾ + +¥ · £ · € · $ · ¢ · ₡ · ₢ · ₣ · ₤ · ₥ · ₦ · ₧ · ₨ · ₩ · ₪ · ₫ · ₭ · ₮ · ₯ · ₹ \ No newline at end of file diff --git a/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy index 105a8e157f..5fc1409276 100644 --- a/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy @@ -48,11 +48,21 @@ Line 3 : String content""") def 'Should return UTF-8 encoded file content in string using ReadFile.readFileStringWithCharset given filePath' () { given: - def filePath = "src/main/resources/fileContent.txt" + def filePath = "src/main/resources/utf8Content.html" when: def noOfLines = readFile.readFileStringWithCharset(filePath) then: noOfLines noOfLines instanceof String } + + def 'Should return binary file content in byte arry using ReadFile.readBinaryFile given filePath' () { + given: + def filePath = "src/main/resources/sample.png" + when: + def noOfLines = readFile.readBinaryFile(filePath) + then: + noOfLines + noOfLines instanceof byte[] + } } \ No newline at end of file From 0b988db96d1fa03768402b81360722d0606114b8 Mon Sep 17 00:00:00 2001 From: Ger Roza Date: Tue, 29 Jan 2019 17:04:33 -0200 Subject: [PATCH 037/152] Moved Building REST API article related code from spring-rest-full to spring-boot-rest module --- spring-boot-rest/pom.xml | 2 - .../com/baeldung/persistence/IOperations.java | 13 +++++ .../service/common/AbstractService.java | 34 ++++++++++++- .../persistence/service/impl/FooService.java | 11 +++++ .../web/controller/FooController.java | 48 +++++++++++++++---- .../event/SingleResourceRetrievedEvent.java | 22 +++++++++ ...ourceRetrievedDiscoverabilityListener.java | 34 +++++++++++++ spring-rest-full/.attach_pid28499 | 0 .../org/baeldung/persistence/IOperations.java | 6 +-- .../service/common/AbstractService.java | 10 ---- .../persistence/service/impl/FooService.java | 12 ----- .../web/controller/FooController.java | 14 ------ 12 files changed, 153 insertions(+), 53 deletions(-) create mode 100644 spring-boot-rest/src/main/java/com/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java create mode 100644 spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java delete mode 100644 spring-rest-full/.attach_pid28499 diff --git a/spring-boot-rest/pom.xml b/spring-boot-rest/pom.xml index cf4ac0371b..3c8c4d7486 100644 --- a/spring-boot-rest/pom.xml +++ b/spring-boot-rest/pom.xml @@ -51,7 +51,6 @@ net.sourceforge.htmlunit htmlunit - ${htmlunit.version} test @@ -67,7 +66,6 @@ com.baeldung.SpringBootRestApplication - 2.32 27.0.1-jre diff --git a/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java b/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java index d8996ca50d..1cc732ab08 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java +++ b/spring-boot-rest/src/main/java/com/baeldung/persistence/IOperations.java @@ -1,16 +1,29 @@ package com.baeldung.persistence; import java.io.Serializable; +import java.util.List; import org.springframework.data.domain.Page; public interface IOperations { + // read - one + + T findOne(final long id); + // read - all + List findAll(); + Page findPaginated(int page, int size); // write T create(final T entity); + + T update(final T entity); + + void delete(final T entity); + + void deleteById(final long entityId); } diff --git a/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java b/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java index 871f768895..5900c443b8 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java +++ b/spring-boot-rest/src/main/java/com/baeldung/persistence/service/common/AbstractService.java @@ -1,6 +1,7 @@ package com.baeldung.persistence.service.common; import java.io.Serializable; +import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -8,23 +9,54 @@ import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.transaction.annotation.Transactional; import com.baeldung.persistence.IOperations; +import com.google.common.collect.Lists; @Transactional public abstract class AbstractService implements IOperations { + // read - one + + @Override + @Transactional(readOnly = true) + public T findOne(final long id) { + return getDao().findById(id) + .get(); + } + // read - all + @Override + @Transactional(readOnly = true) + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + @Override public Page findPaginated(final int page, final int size) { return getDao().findAll(PageRequest.of(page, size)); } // write - + @Override public T create(final T entity) { return getDao().save(entity); } + + @Override + public T update(final T entity) { + return getDao().save(entity); + } + + @Override + public void delete(final T entity) { + getDao().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + getDao().deleteById(entityId); + } protected abstract PagingAndSortingRepository getDao(); diff --git a/spring-boot-rest/src/main/java/com/baeldung/persistence/service/impl/FooService.java b/spring-boot-rest/src/main/java/com/baeldung/persistence/service/impl/FooService.java index 9d705f51d3..299e5ec214 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/persistence/service/impl/FooService.java +++ b/spring-boot-rest/src/main/java/com/baeldung/persistence/service/impl/FooService.java @@ -1,5 +1,7 @@ package com.baeldung.persistence.service.impl; +import java.util.List; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -11,6 +13,7 @@ import com.baeldung.persistence.dao.IFooDao; import com.baeldung.persistence.model.Foo; import com.baeldung.persistence.service.IFooService; import com.baeldung.persistence.service.common.AbstractService; +import com.google.common.collect.Lists; @Service @Transactional @@ -36,5 +39,13 @@ public class FooService extends AbstractService implements IFooService { public Page findPaginated(Pageable pageable) { return dao.findAll(pageable); } + + // overridden to be secured + + @Override + @Transactional(readOnly = true) + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } } diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java b/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java index b35295cf99..59e33263db 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java +++ b/spring-boot-rest/src/main/java/com/baeldung/web/controller/FooController.java @@ -9,14 +9,16 @@ import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponentsBuilder; import com.baeldung.persistence.model.Foo; @@ -24,9 +26,11 @@ import com.baeldung.persistence.service.IFooService; import com.baeldung.web.exception.MyResourceNotFoundException; import com.baeldung.web.hateoas.event.PaginatedResultsRetrievedEvent; import com.baeldung.web.hateoas.event.ResourceCreatedEvent; +import com.baeldung.web.hateoas.event.SingleResourceRetrievedEvent; +import com.baeldung.web.util.RestPreconditions; import com.google.common.base.Preconditions; -@Controller +@RestController @RequestMapping(value = "/auth/foos") public class FooController { @@ -42,10 +46,24 @@ public class FooController { // API + // read - one + + @GetMapping(value = "/{id}") + public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { + final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); + + eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response)); + return resourceById; + } + // read - all - @RequestMapping(params = { "page", "size" }, method = RequestMethod.GET) - @ResponseBody + @GetMapping + public List findAll() { + return service.findAll(); + } + + @GetMapping(params = { "page", "size" }) public List findPaginated(@RequestParam("page") final int page, @RequestParam("size") final int size, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { final Page resultPage = service.findPaginated(page, size); @@ -59,7 +77,6 @@ public class FooController { } @GetMapping("/pageable") - @ResponseBody public List findPaginatedWithPageable(Pageable pageable, final UriComponentsBuilder uriBuilder, final HttpServletResponse response) { final Page resultPage = service.findPaginated(pageable); @@ -74,9 +91,8 @@ public class FooController { // write - @RequestMapping(method = RequestMethod.POST) + @PostMapping @ResponseStatus(HttpStatus.CREATED) - @ResponseBody public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { Preconditions.checkNotNull(resource); final Foo foo = service.create(resource); @@ -86,4 +102,18 @@ public class FooController { return foo; } + + @PutMapping(value = "/{id}") + @ResponseStatus(HttpStatus.OK) + public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { + Preconditions.checkNotNull(resource); + RestPreconditions.checkFound(service.findOne(resource.getId())); + service.update(resource); + } + + @DeleteMapping(value = "/{id}") + @ResponseStatus(HttpStatus.OK) + public void delete(@PathVariable("id") final Long id) { + service.deleteById(id); + } } diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java b/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java new file mode 100644 index 0000000000..70face083c --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/event/SingleResourceRetrievedEvent.java @@ -0,0 +1,22 @@ +package com.baeldung.web.hateoas.event; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.context.ApplicationEvent; + +public class SingleResourceRetrievedEvent extends ApplicationEvent { + private final HttpServletResponse response; + + public SingleResourceRetrievedEvent(final Object source, final HttpServletResponse response) { + super(source); + + this.response = response; + } + + // API + + public HttpServletResponse getResponse() { + return response; + } + +} \ No newline at end of file diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java b/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java new file mode 100644 index 0000000000..d527c308b9 --- /dev/null +++ b/spring-boot-rest/src/main/java/com/baeldung/web/hateoas/listener/SingleResourceRetrievedDiscoverabilityListener.java @@ -0,0 +1,34 @@ +package com.baeldung.web.hateoas.listener; + +import javax.servlet.http.HttpServletResponse; + +import com.baeldung.web.hateoas.event.SingleResourceRetrievedEvent; +import com.baeldung.web.util.LinkUtil; +import org.springframework.context.ApplicationListener; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import com.google.common.base.Preconditions; +import com.google.common.net.HttpHeaders; + +@Component +class SingleResourceRetrievedDiscoverabilityListener implements ApplicationListener { + + @Override + public void onApplicationEvent(final SingleResourceRetrievedEvent resourceRetrievedEvent) { + Preconditions.checkNotNull(resourceRetrievedEvent); + + final HttpServletResponse response = resourceRetrievedEvent.getResponse(); + addLinkHeaderOnSingleResourceRetrieval(response); + } + + void addLinkHeaderOnSingleResourceRetrieval(final HttpServletResponse response) { + final String requestURL = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri().toASCIIString(); + final int positionOfLastSlash = requestURL.lastIndexOf("/"); + final String uriForResourceCreation = requestURL.substring(0, positionOfLastSlash); + + final String linkHeaderValue = LinkUtil.createLinkHeader(uriForResourceCreation, "collection"); + response.addHeader(HttpHeaders.LINK, linkHeaderValue); + } + +} \ No newline at end of file diff --git a/spring-rest-full/.attach_pid28499 b/spring-rest-full/.attach_pid28499 deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-rest-full/src/main/java/org/baeldung/persistence/IOperations.java b/spring-rest-full/src/main/java/org/baeldung/persistence/IOperations.java index 8c5593c3e8..0b617bf7ab 100644 --- a/spring-rest-full/src/main/java/org/baeldung/persistence/IOperations.java +++ b/spring-rest-full/src/main/java/org/baeldung/persistence/IOperations.java @@ -16,11 +16,7 @@ public interface IOperations { // write T create(final T entity); - + T update(final T entity); - void delete(final T entity); - - void deleteById(final long entityId); - } diff --git a/spring-rest-full/src/main/java/org/baeldung/persistence/service/common/AbstractService.java b/spring-rest-full/src/main/java/org/baeldung/persistence/service/common/AbstractService.java index 59ccea8b12..059516eeba 100644 --- a/spring-rest-full/src/main/java/org/baeldung/persistence/service/common/AbstractService.java +++ b/spring-rest-full/src/main/java/org/baeldung/persistence/service/common/AbstractService.java @@ -40,16 +40,6 @@ public abstract class AbstractService implements IOperat return getDao().save(entity); } - @Override - public void delete(final T entity) { - getDao().delete(entity); - } - - @Override - public void deleteById(final long entityId) { - getDao().delete(entityId); - } - protected abstract PagingAndSortingRepository getDao(); } diff --git a/spring-rest-full/src/main/java/org/baeldung/persistence/service/impl/FooService.java b/spring-rest-full/src/main/java/org/baeldung/persistence/service/impl/FooService.java index d46f1bfe90..32fe1bd7e0 100644 --- a/spring-rest-full/src/main/java/org/baeldung/persistence/service/impl/FooService.java +++ b/spring-rest-full/src/main/java/org/baeldung/persistence/service/impl/FooService.java @@ -1,7 +1,5 @@ package org.baeldung.persistence.service.impl; -import java.util.List; - import org.baeldung.persistence.dao.IFooDao; import org.baeldung.persistence.model.Foo; import org.baeldung.persistence.service.IFooService; @@ -11,8 +9,6 @@ import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import com.google.common.collect.Lists; - @Service @Transactional public class FooService extends AbstractService implements IFooService { @@ -38,12 +34,4 @@ public class FooService extends AbstractService implements IFooService { return dao.retrieveByName(name); } - // overridden to be secured - - @Override - @Transactional(readOnly = true) - public List findAll() { - return Lists.newArrayList(getDao().findAll()); - } - } diff --git a/spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java index 443d0908ee..2e4dbcacc9 100644 --- a/spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java +++ b/spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java @@ -80,20 +80,6 @@ public class FooController { return foo; } - @RequestMapping(value = "/{id}", method = RequestMethod.PUT) - @ResponseStatus(HttpStatus.OK) - public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { - Preconditions.checkNotNull(resource); - RestPreconditions.checkFound(service.findOne(resource.getId())); - service.update(resource); - } - - @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) - @ResponseStatus(HttpStatus.OK) - public void delete(@PathVariable("id") final Long id) { - service.deleteById(id); - } - @RequestMapping(method = RequestMethod.HEAD) @ResponseStatus(HttpStatus.OK) public void head(final HttpServletResponse resp) { From e51d996ec1fab6f0239cd436e0739fd8f5d22bba Mon Sep 17 00:00:00 2001 From: Ger Roza Date: Tue, 29 Jan 2019 17:05:09 -0200 Subject: [PATCH 038/152] Added spring boot related tests for building Rest API article --- .../web/FooControllerAppIntegrationTest.java | 36 +++++++++++ .../FooControllerWebLayerIntegrationTest.java | 60 +++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java create mode 100644 spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java new file mode 100644 index 0000000000..bd5b5eb58e --- /dev/null +++ b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerAppIntegrationTest.java @@ -0,0 +1,36 @@ +package com.baeldung.web; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; + +/** + * + * We'll start the whole context, but not the server. We'll mock the REST calls instead. + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class FooControllerAppIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenFindPaginatedRequest_thenEmptyResponse() throws Exception { + this.mockMvc.perform(get("/auth/foos").param("page", "0") + .param("size", "2")) + .andExpect(status().isOk()) + .andExpect(content().json("[]")); + } + +} diff --git a/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java new file mode 100644 index 0000000000..7e41cf6393 --- /dev/null +++ b/spring-boot-rest/src/test/java/com/baeldung/web/FooControllerWebLayerIntegrationTest.java @@ -0,0 +1,60 @@ +package com.baeldung.web; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.Collections; + +import org.hamcrest.Matchers; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.persistence.model.Foo; +import com.baeldung.persistence.service.IFooService; +import com.baeldung.web.controller.FooController; +import com.baeldung.web.hateoas.event.PaginatedResultsRetrievedEvent; + +/** + * + * We'll start only the web layer. + * + */ +@RunWith(SpringRunner.class) +@WebMvcTest(FooController.class) +public class FooControllerWebLayerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private IFooService service; + + @MockBean + private ApplicationEventPublisher publisher; + + @Test() + public void givenPresentFoo_whenFindPaginatedRequest_thenPageWithFooRetrieved() throws Exception { + Page page = new PageImpl<>(Collections.singletonList(new Foo("fooName"))); + when(service.findPaginated(0, 2)).thenReturn(page); + doNothing().when(publisher) + .publishEvent(any(PaginatedResultsRetrievedEvent.class)); + + this.mockMvc.perform(get("/auth/foos").param("page", "0") + .param("size", "2")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$",Matchers.hasSize(1))); + } + +} From 822b09baab5b1a4080bf8311c2e562f46397b2a0 Mon Sep 17 00:00:00 2001 From: ciro Date: Tue, 29 Jan 2019 11:31:15 -0800 Subject: [PATCH 039/152] BAEL-2466 moving request.xml --- spring-soap/src/{main => test}/resources/request.xml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename spring-soap/src/{main => test}/resources/request.xml (100%) diff --git a/spring-soap/src/main/resources/request.xml b/spring-soap/src/test/resources/request.xml similarity index 100% rename from spring-soap/src/main/resources/request.xml rename to spring-soap/src/test/resources/request.xml From 281432707993500042df7f02f1fa3b2310d9d401 Mon Sep 17 00:00:00 2001 From: Ger Roza Date: Tue, 29 Jan 2019 19:17:01 -0200 Subject: [PATCH 040/152] Moved article from Readme files --- spring-boot-rest/README.md | 3 ++- spring-rest-full/README.md | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-boot-rest/README.md b/spring-boot-rest/README.md index 2c89a64a00..ffc48126d3 100644 --- a/spring-boot-rest/README.md +++ b/spring-boot-rest/README.md @@ -2,4 +2,5 @@ Module for the articles that are part of the Spring REST E-book: 1. [Bootstrap a Web Application with Spring 5](https://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) 2. [Error Handling for REST with Spring](http://www.baeldung.com/exception-handling-for-rest-with-spring) -3. [REST Pagination in Spring](http://www.baeldung.com/rest-api-pagination-in-spring) \ No newline at end of file +3. [REST Pagination in Spring](http://www.baeldung.com/rest-api-pagination-in-spring) +4. [Build a REST API with Spring and Java Config](http://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration) \ No newline at end of file diff --git a/spring-rest-full/README.md b/spring-rest-full/README.md index 2ef3a09e37..5140c4b270 100644 --- a/spring-rest-full/README.md +++ b/spring-rest-full/README.md @@ -16,7 +16,6 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Project Configuration with Spring](http://www.baeldung.com/project-configuration-with-spring) - [Metrics for your Spring REST API](http://www.baeldung.com/spring-rest-api-metrics) - [Bootstrap a Web Application with Spring 4](http://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) -- [Build a REST API with Spring and Java Config](http://www.baeldung.com/building-a-restful-web-service-with-spring-and-java-based-configuration) - [Spring Security Expressions - hasRole Example](https://www.baeldung.com/spring-security-expressions-basic) From 50a8870d4f95175e409b51972fc31ae014bb1a2f Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Wed, 30 Jan 2019 13:46:56 +0200 Subject: [PATCH 041/152] BAEL-2659 - Reading a file in Groovy - added more example --- .../src/main/groovy/com/baeldung/file/ReadFile.groovy | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy b/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy index 38bf189e63..828f702e82 100644 --- a/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy +++ b/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy @@ -69,6 +69,14 @@ class ReadFile { * @return */ def moreExamples() { + + new File("src/main/resources/utf8Content.html").withReader('UTF-8') { reader -> + def line + while ((line = reader.readLine())!=null) { + println "${line}" + } + } + def list = new File("src/main/resources/fileContent.txt").collect {it} def array = new File("src/main/resources/fileContent.txt") as String[] From f1ea814185be1e0bf555bb49c737da27eed86b3f Mon Sep 17 00:00:00 2001 From: rodolforfq <31481067+rodolforfq@users.noreply.github.com> Date: Wed, 30 Jan 2019 11:40:24 -0400 Subject: [PATCH 042/152] New examples (#6242) Adding new examples. Improvement in existing method. --- .../baeldung/java8/lambda/methodreference/Bicycle.java | 5 +++++ .../methodreference/MethodReferenceExamples.java | 10 +++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/Bicycle.java b/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/Bicycle.java index 760a24d7c2..26f9f8bc46 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/Bicycle.java +++ b/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/Bicycle.java @@ -5,6 +5,11 @@ public class Bicycle { private String brand; private Integer frameSize; + public Bicycle(String brand) { + this.brand = brand; + this.frameSize = 0; + } + public Bicycle(String brand, Integer frameSize) { this.brand = brand; this.frameSize = frameSize; diff --git a/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceExamples.java b/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceExamples.java index 3b9a5ec6ff..ede0ef9f70 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceExamples.java +++ b/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceExamples.java @@ -52,10 +52,18 @@ public class MethodReferenceExamples { bikes.add(bikeCreatorMethodReference.apply("GT", 40)); } + @Test + public void referenceToConstructorSimpleExample() { + List bikeBrands = Arrays.asList("Giant", "Scott", "Trek", "GT"); + bikeBrands.stream() + .map(Bicycle::new) + .toArray(Bicycle[]::new); + } + @Test public void limitationsAndAdditionalExamples() { createBicyclesList().forEach(b -> System.out.printf("Bike brand is '%s' and frame size is '%d'%n", b.getBrand(), b.getFrameSize())); - createBicyclesList().forEach((o) -> this.doNothingAtAll(o)); + createBicyclesList().forEach((o) -> MethodReferenceExamples.doNothingAtAll(o)); } private List createBicyclesList() { From 499aec3490118b3e9d92264edcc4f8816c5f3abb Mon Sep 17 00:00:00 2001 From: amdegregorio Date: Wed, 30 Jan 2019 13:55:37 -0500 Subject: [PATCH 043/152] updates to simplify example --- .../java/com/baeldung/jar/Dimensioner.java | 27 ------------ .../java/com/baeldung/jar/JarExample.java | 24 +--------- .../main/java/com/baeldung/jar/Rectangle.java | 44 ------------------- 3 files changed, 1 insertion(+), 94 deletions(-) delete mode 100644 core-java/src/main/java/com/baeldung/jar/Dimensioner.java delete mode 100644 core-java/src/main/java/com/baeldung/jar/Rectangle.java diff --git a/core-java/src/main/java/com/baeldung/jar/Dimensioner.java b/core-java/src/main/java/com/baeldung/jar/Dimensioner.java deleted file mode 100644 index bc5cea4010..0000000000 --- a/core-java/src/main/java/com/baeldung/jar/Dimensioner.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.jar; - -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.List; - -public class Dimensioner { - - public List loadFromFile(String dimensionFile) throws FileNotFoundException, IOException { - List rectangles = new ArrayList(); - try (BufferedReader br = new BufferedReader(new InputStreamReader(Dimensioner.class.getResourceAsStream(dimensionFile)))) { - String line; - while ((line = br.readLine()) != null) { - String[] dimensions = line.split(","); - if (dimensions.length == 2) { - Rectangle rectangle = new Rectangle(Integer.valueOf(dimensions[0]), Integer.valueOf(dimensions[1])); - rectangles.add(rectangle); - } - } - } - return rectangles; - } - -} diff --git a/core-java/src/main/java/com/baeldung/jar/JarExample.java b/core-java/src/main/java/com/baeldung/jar/JarExample.java index daa44025d5..5f33188adf 100644 --- a/core-java/src/main/java/com/baeldung/jar/JarExample.java +++ b/core-java/src/main/java/com/baeldung/jar/JarExample.java @@ -1,31 +1,9 @@ package com.baeldung.jar; -import java.io.IOException; -import java.util.List; - public class JarExample { - private static final String DIMENSION_FILE = "/dimensions.txt"; public static void main(String[] args) { - String inputType = System.getProperty("input"); - if (inputType != null && inputType.equalsIgnoreCase("file")) { - Dimensioner dimensioner = new Dimensioner(); - try { - List rectangles = dimensioner.loadFromFile(DIMENSION_FILE); - rectangles.forEach(rectangle -> { - rectangle.printArea(); - rectangle.printPerimeter(); - }); - } catch (IOException e) { - System.err.println("Exception loading dimensions"); - } - } else if (args.length > 0) { - int length = Integer.valueOf(args[0]); - int width = (args.length > 1) ? Integer.valueOf(args[1]) : Integer.valueOf(args[0]); - Rectangle rectangle = new Rectangle(length, width); - rectangle.printArea(); - rectangle.printPerimeter(); - } + System.out.println("Hello Baeldung Reader!"); } } diff --git a/core-java/src/main/java/com/baeldung/jar/Rectangle.java b/core-java/src/main/java/com/baeldung/jar/Rectangle.java deleted file mode 100644 index f2a174c819..0000000000 --- a/core-java/src/main/java/com/baeldung/jar/Rectangle.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.jar; - -public class Rectangle { - private int length; - private int width; - - public Rectangle(int length, int width) { - this.length = length; - this.width = width; - } - - public int area() { - return length * width; - } - - public int perimeter() { - return (length * 2) + (width * 2); - } - - public void printArea() { - System.out.println("Area: " + area()); - } - - public void printPerimeter() { - System.out.println("Perimeter: " + perimeter()); - } - - public int getLength() { - return length; - } - - public void setLength(int length) { - this.length = length; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - -} From 4d1c8634facc2e9fb305c794c27e379bf7bb4aeb Mon Sep 17 00:00:00 2001 From: psevestre Date: Thu, 31 Jan 2019 00:16:26 -0200 Subject: [PATCH 044/152] Code for BAEL-1381 (#6214) * BAEL-1381 * [BAEL-1381] * [BAEL-1381] New module name * [BAEL-1381] software-security module --- pom.xml | 3 +- .../sql-injection-samples/.gitignore | 25 +++ .../sql-injection-samples/pom.xml | 61 +++++++ .../examples/security/sql/AccountDAO.java | 169 ++++++++++++++++++ .../examples/security/sql/AccountDTO.java | 16 ++ .../sql/SqlInjectionSamplesApplication.java | 14 ++ .../src/main/resources/application.properties | 0 .../resources/db/changelog/create-tables.xml | 19 ++ .../main/resources/db/master-changelog.xml | 8 + ...qlInjectionSamplesApplicationUnitTest.java | 60 +++++++ .../src/test/resources/application-test.yml | 6 + .../src/test/resources/data.sql | 4 + .../src/test/resources/schema.sql | 6 + 13 files changed, 390 insertions(+), 1 deletion(-) create mode 100644 software-security/sql-injection-samples/.gitignore create mode 100644 software-security/sql-injection-samples/pom.xml create mode 100644 software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java create mode 100644 software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java create mode 100644 software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java create mode 100644 software-security/sql-injection-samples/src/main/resources/application.properties create mode 100644 software-security/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml create mode 100644 software-security/sql-injection-samples/src/main/resources/db/master-changelog.xml create mode 100644 software-security/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java create mode 100644 software-security/sql-injection-samples/src/test/resources/application-test.yml create mode 100644 software-security/sql-injection-samples/src/test/resources/data.sql create mode 100644 software-security/sql-injection-samples/src/test/resources/schema.sql diff --git a/pom.xml b/pom.xml index 01cb86d103..787a03c2fb 100644 --- a/pom.xml +++ b/pom.xml @@ -567,7 +567,8 @@ rule-engines/rulebook rsocket rxjava - rxjava-2 + rxjava-2 + software-security/sql-injection-samples diff --git a/software-security/sql-injection-samples/.gitignore b/software-security/sql-injection-samples/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/software-security/sql-injection-samples/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/software-security/sql-injection-samples/pom.xml b/software-security/sql-injection-samples/pom.xml new file mode 100644 index 0000000000..d5e64db6b3 --- /dev/null +++ b/software-security/sql-injection-samples/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + com.baeldung + sql-injection-samples + 0.0.1-SNAPSHOT + sql-injection-samples + Sample SQL Injection tests + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-jdbc + + + + org.apache.derby + derby + runtime + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.projectlombok + lombok + provided + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java new file mode 100644 index 0000000000..447dcc456d --- /dev/null +++ b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java @@ -0,0 +1,169 @@ +/** + * + */ +package com.baeldung.examples.security.sql; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import javax.sql.DataSource; + +import org.springframework.stereotype.Component; + +/** + * @author Philippe + * + */ +@Component +public class AccountDAO { + + private final DataSource dataSource; + + public AccountDAO(DataSource dataSource) { + this.dataSource = dataSource; + } + + /** + * Return all accounts owned by a given customer,given his/her external id + * + * @param customerId + * @return + */ + public List unsafeFindAccountsByCustomerId(String customerId) { + + String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = '" + customerId + "'"; + + try (Connection c = dataSource.getConnection(); + ResultSet rs = c.createStatement() + .executeQuery(sql)) { + List accounts = new ArrayList<>(); + while (rs.next()) { + AccountDTO acc = AccountDTO.builder() + .customerId(rs.getString("customer_id")) + .branchId(rs.getString("branch_id")) + .accNumber(rs.getString("acc_number")) + .balance(rs.getBigDecimal("balance")) + .build(); + + accounts.add(acc); + } + + return accounts; + } catch (SQLException ex) { + throw new RuntimeException(ex); + } + } + + /** + * Return all accounts owned by a given customer,given his/her external id + * + * @param customerId + * @return + */ + public List safeFindAccountsByCustomerId(String customerId) { + + String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = ?"; + + try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement(sql)) { + p.setString(1, customerId); + ResultSet rs = p.executeQuery(); + List accounts = new ArrayList<>(); + while (rs.next()) { + AccountDTO acc = AccountDTO.builder() + .customerId(rs.getString("customerId")) + .branchId(rs.getString("branch_id")) + .accNumber(rs.getString("acc_number")) + .balance(rs.getBigDecimal("balance")) + .build(); + + accounts.add(acc); + } + return accounts; + } catch (SQLException ex) { + throw new RuntimeException(ex); + } + } + + private static final Set VALID_COLUMNS_FOR_ORDER_BY = Stream.of("acc_number", "branch_id", "balance") + .collect(Collectors.toCollection(HashSet::new)); + + /** + * Return all accounts owned by a given customer,given his/her external id + * + * @param customerId + * @return + */ + public List safeFindAccountsByCustomerId(String customerId, String orderBy) { + + String sql = "select " + "customer_id,acc_number,branch_id,balance from Accounts where customer_id = ? "; + + if (VALID_COLUMNS_FOR_ORDER_BY.contains(orderBy)) { + sql = sql + " order by " + orderBy; + } + else { + throw new IllegalArgumentException("Nice try!"); + } + + try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement(sql)) { + + p.setString(1, customerId); + ResultSet rs = p.executeQuery(); + List accounts = new ArrayList<>(); + while (rs.next()) { + AccountDTO acc = AccountDTO.builder() + .customerId(rs.getString("customerId")) + .branchId(rs.getString("branch_id")) + .accNumber(rs.getString("acc_number")) + .balance(rs.getBigDecimal("balance")) + .build(); + + accounts.add(acc); + } + + return accounts; + } catch (SQLException ex) { + throw new RuntimeException(ex); + } + } + + /** + * Invalid placeholder usage example + * + * @param tableName + * @return + */ + public List wrongCountRecordsByTableName(String tableName) { + + try (Connection c = dataSource.getConnection(); + PreparedStatement p = c.prepareStatement("select count(*) from ?")) { + + p.setString(1, tableName); + ResultSet rs = p.executeQuery(); + List accounts = new ArrayList<>(); + while (rs.next()) { + AccountDTO acc = AccountDTO.builder() + .customerId(rs.getString("customerId")) + .branchId(rs.getString("branch_id")) + .accNumber(rs.getString("acc_number")) + .balance(rs.getBigDecimal("balance")) + .build(); + + accounts.add(acc); + } + + return accounts; + } catch (SQLException ex) { + throw new RuntimeException(ex); + } + } + +} diff --git a/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java new file mode 100644 index 0000000000..2e6fa04af4 --- /dev/null +++ b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDTO.java @@ -0,0 +1,16 @@ +package com.baeldung.examples.security.sql; + +import java.math.BigDecimal; + +import lombok.Builder; +import lombok.Data; + +@Data +@Builder +public class AccountDTO { + + private String customerId; + private String accNumber; + private String branchId; + private BigDecimal balance; +} diff --git a/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java new file mode 100644 index 0000000000..c1083ae3de --- /dev/null +++ b/software-security/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.examples.security.sql; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SqlInjectionSamplesApplication { + + public static void main(String[] args) { + SpringApplication.run(SqlInjectionSamplesApplication.class, args); + } + +} + diff --git a/software-security/sql-injection-samples/src/main/resources/application.properties b/software-security/sql-injection-samples/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/software-security/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml b/software-security/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml new file mode 100644 index 0000000000..a405c02049 --- /dev/null +++ b/software-security/sql-injection-samples/src/main/resources/db/changelog/create-tables.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/software-security/sql-injection-samples/src/main/resources/db/master-changelog.xml b/software-security/sql-injection-samples/src/main/resources/db/master-changelog.xml new file mode 100644 index 0000000000..047ca2b314 --- /dev/null +++ b/software-security/sql-injection-samples/src/main/resources/db/master-changelog.xml @@ -0,0 +1,8 @@ + + + + \ No newline at end of file diff --git a/software-security/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java b/software-security/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java new file mode 100644 index 0000000000..1f37ba04b6 --- /dev/null +++ b/software-security/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.examples.security.sql; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.examples.security.sql.AccountDAO; +import com.baeldung.examples.security.sql.AccountDTO; + +@RunWith(SpringRunner.class) +@SpringBootTest +@ActiveProfiles({ "test" }) +public class SqlInjectionSamplesApplicationUnitTest { + + @Autowired + private AccountDAO target; + + @Test + public void givenAVulnerableMethod_whenValidCustomerId_thenReturnSingleAccount() { + + List accounts = target.unsafeFindAccountsByCustomerId("C1"); + assertThat(accounts).isNotNull(); + assertThat(accounts).isNotEmpty(); + assertThat(accounts).hasSize(1); + } + + @Test + public void givenAVulnerableMethod_whenHackedCustomerId_thenReturnAllAccounts() { + + List accounts = target.unsafeFindAccountsByCustomerId("C1' or '1'='1"); + assertThat(accounts).isNotNull(); + assertThat(accounts).isNotEmpty(); + assertThat(accounts).hasSize(3); + } + + @Test + public void givenASafeMethod_whenHackedCustomerId_thenReturnNoAccounts() { + + List accounts = target.safeFindAccountsByCustomerId("C1' or '1'='1"); + assertThat(accounts).isNotNull(); + assertThat(accounts).isEmpty(); + } + + @Test(expected = IllegalArgumentException.class) + public void givenASafeMethod_whenInvalidOrderBy_thenThroweException() { + target.safeFindAccountsByCustomerId("C1", "INVALID"); + } + + @Test(expected = RuntimeException.class) + public void givenWrongPlaceholderUsageMethod_whenNormalCall_thenThrowsException() { + target.wrongCountRecordsByTableName("Accounts"); + } +} diff --git a/software-security/sql-injection-samples/src/test/resources/application-test.yml b/software-security/sql-injection-samples/src/test/resources/application-test.yml new file mode 100644 index 0000000000..d07ee10aee --- /dev/null +++ b/software-security/sql-injection-samples/src/test/resources/application-test.yml @@ -0,0 +1,6 @@ +# +# Test profile configuration +# +spring: + datasource: + initialization-mode: always diff --git a/software-security/sql-injection-samples/src/test/resources/data.sql b/software-security/sql-injection-samples/src/test/resources/data.sql new file mode 100644 index 0000000000..586618a07f --- /dev/null +++ b/software-security/sql-injection-samples/src/test/resources/data.sql @@ -0,0 +1,4 @@ +insert into Accounts(customer_id,acc_number,branch_id,balance) values ('C1','0001',1,1000.00); +insert into Accounts(customer_id,acc_number,branch_id,balance) values ('C2','0002',1,500.00); +insert into Accounts(customer_id,acc_number,branch_id,balance) values ('C3','0003',1,501.00); + diff --git a/software-security/sql-injection-samples/src/test/resources/schema.sql b/software-security/sql-injection-samples/src/test/resources/schema.sql new file mode 100644 index 0000000000..bfb0ae8059 --- /dev/null +++ b/software-security/sql-injection-samples/src/test/resources/schema.sql @@ -0,0 +1,6 @@ +create table Accounts ( + customer_id varchar(16) not null, + acc_number varchar(16) not null, + branch_id decimal(8,0), + balance decimal(16,4) +); From b48f77cf6e61afb2990f52a9fe515813aa0f8f3a Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Thu, 31 Jan 2019 12:46:25 +0200 Subject: [PATCH 045/152] BAEL-2659 - Reading a file in Groovy - corrected variable names --- .../main/groovy/com/baeldung/file/ReadFile.groovy | 8 +++++++- core-groovy/src/main/resources/utf8Content.html | 4 +--- .../com/baeldung/file/ReadFileUnitTest.groovy | 14 ++++++++------ 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy b/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy index 828f702e82..4239fa534c 100644 --- a/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy +++ b/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy @@ -70,6 +70,7 @@ class ReadFile { */ def moreExamples() { + //with reader with utf-8 new File("src/main/resources/utf8Content.html").withReader('UTF-8') { reader -> def line while ((line = reader.readLine())!=null) { @@ -77,20 +78,25 @@ class ReadFile { } } + //collect api def list = new File("src/main/resources/fileContent.txt").collect {it} + //as operator def array = new File("src/main/resources/fileContent.txt") as String[] - + + //eachline new File("src/main/resources/fileContent.txt").eachLine { line -> println line } + //newInputStream with eachLine def is = new File("src/main/resources/fileContent.txt").newInputStream() is.eachLine { println it } is.close() + //withInputStream new File("src/main/resources/fileContent.txt").withInputStream { stream -> stream.eachLine { line -> println line diff --git a/core-groovy/src/main/resources/utf8Content.html b/core-groovy/src/main/resources/utf8Content.html index 9d941200b1..873a75b8d0 100644 --- a/core-groovy/src/main/resources/utf8Content.html +++ b/core-groovy/src/main/resources/utf8Content.html @@ -1,5 +1,3 @@ ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ ᛋᚳᛖᚪᛚ᛫ᚦᛖᚪᚻ᛫ᛗᚪᚾᚾᚪ᛫ᚷᛖᚻᚹᛦᛚᚳ᛫ᛗᛁᚳᛚᚢᚾ᛫ᚻᛦᛏ᛫ᛞᚫᛚᚪᚾ -ᚷᛁᚠ᛫ᚻᛖ᛫ᚹᛁᛚᛖ᛫ᚠᚩᚱ᛫ᛞᚱᛁᚻᛏᚾᛖ᛫ᛞᚩᛗᛖᛋ᛫ᚻᛚᛇᛏᚪᚾ - -¥ · £ · € · $ · ¢ · ₡ · ₢ · ₣ · ₤ · ₥ · ₦ · ₧ · ₨ · ₩ · ₪ · ₫ · ₭ · ₮ · ₯ · ₹ \ No newline at end of file +ᚷᛁᚠ᛫ᚻᛖ᛫ᚹᛁᛚᛖ᛫ᚠᚩᚱ᛫ᛞᚱᛁᚻᛏᚾᛖ᛫ᛞᚩᛗᛖᛋ᛫ᚻᛚᛇᛏᚪᚾ \ No newline at end of file diff --git a/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy index 5fc1409276..0d0e2aed1a 100644 --- a/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy @@ -50,19 +50,21 @@ Line 3 : String content""") given: def filePath = "src/main/resources/utf8Content.html" when: - def noOfLines = readFile.readFileStringWithCharset(filePath) + def encodedContent = readFile.readFileStringWithCharset(filePath) then: - noOfLines - noOfLines instanceof String + encodedContent + encodedContent instanceof String } def 'Should return binary file content in byte arry using ReadFile.readBinaryFile given filePath' () { given: def filePath = "src/main/resources/sample.png" when: - def noOfLines = readFile.readBinaryFile(filePath) + def binaryContent = readFile.readBinaryFile(filePath) then: - noOfLines - noOfLines instanceof byte[] + binaryContent + binaryContent instanceof byte[] + binaryContent.length == 329 } + } \ No newline at end of file From ca98fbb7062c13129ee3193b679a64ad9da63f84 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Thu, 31 Jan 2019 16:18:59 +0400 Subject: [PATCH 046/152] Added Stream Api --- .../list/primitive/PrimitiveCollections.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java index 50f372e9c9..01372763e9 100644 --- a/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java +++ b/core-java-collections-list/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java @@ -7,15 +7,20 @@ import it.unimi.dsi.fastutil.ints.IntArrayList; import java.util.Arrays; import java.util.List; +import java.util.OptionalDouble; +import java.util.function.IntPredicate; +import java.util.stream.IntStream; public class PrimitiveCollections { public static void main(String[] args) { - int[] primitives = new int[] {5, 10, 0, 2}; + int[] primitives = new int[] {5, 10, 0, 2, -8}; guavaPrimitives(primitives); + intStream(primitives); + TIntArrayList tList = new TIntArrayList(primitives); cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(primitives); @@ -29,6 +34,15 @@ public class PrimitiveCollections { System.out.println(fastUtilList); } + private static void intStream(int[] primitives) { + + IntStream stream = IntStream.of(5, 10, 0, 2, -8); + + IntStream newStream = IntStream.of(primitives); + + OptionalDouble average = stream.filter(i -> i > 0).average(); + } + private static void guavaPrimitives(int[] primitives) { From 56a832273e35c82da8d6de1b041ed518f11b53ce Mon Sep 17 00:00:00 2001 From: Dave Crane Date: Thu, 31 Jan 2019 12:48:35 +0000 Subject: [PATCH 047/152] Lombok SuperBuilder Issue: BAEL-2561 --- .../buildermethodname}/Child.java | 2 +- .../buildermethodname}/Parent.java | 2 +- .../buildermethodname/Student.java | 16 ++++ .../inheritance/superbuilder/Child.java | 11 +++ .../inheritance/superbuilder/Parent.java | 11 +++ .../inheritance/superbuilder/Student.java | 10 ++ .../lombok/builder/BuilderUnitTest.java | 16 ---- ...derInheritanceUsingMethodNameUnitTest.java | 40 ++++++++ ...rInheritanceUsingSuperBuilderUnitTest.java | 96 +++++++++++++++++++ 9 files changed, 186 insertions(+), 18 deletions(-) rename lombok/src/main/java/com/baeldung/lombok/builder/{ => inheritance/buildermethodname}/Child.java (86%) rename lombok/src/main/java/com/baeldung/lombok/builder/{ => inheritance/buildermethodname}/Parent.java (70%) create mode 100644 lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Student.java create mode 100644 lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Child.java create mode 100644 lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Parent.java create mode 100644 lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Student.java create mode 100644 lombok/src/test/java/com/baeldung/lombok/builder/inheritance/buildermethodname/BuilderInheritanceUsingMethodNameUnitTest.java create mode 100644 lombok/src/test/java/com/baeldung/lombok/builder/inheritance/superbuilder/BuilderInheritanceUsingSuperBuilderUnitTest.java diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/Child.java b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Child.java similarity index 86% rename from lombok/src/main/java/com/baeldung/lombok/builder/Child.java rename to lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Child.java index 70f6d9c46e..4cfcc22fb2 100644 --- a/lombok/src/main/java/com/baeldung/lombok/builder/Child.java +++ b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Child.java @@ -1,4 +1,4 @@ -package com.baeldung.lombok.builder; +package com.baeldung.lombok.builder.inheritance.buildermethodname; import lombok.Builder; import lombok.Getter; diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/Parent.java b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Parent.java similarity index 70% rename from lombok/src/main/java/com/baeldung/lombok/builder/Parent.java rename to lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Parent.java index 0cf76d4b00..93e48ee44e 100644 --- a/lombok/src/main/java/com/baeldung/lombok/builder/Parent.java +++ b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Parent.java @@ -1,4 +1,4 @@ -package com.baeldung.lombok.builder; +package com.baeldung.lombok.builder.inheritance.buildermethodname; import lombok.Builder; import lombok.Getter; diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Student.java b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Student.java new file mode 100644 index 0000000000..c8eea84b97 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/buildermethodname/Student.java @@ -0,0 +1,16 @@ +package com.baeldung.lombok.builder.inheritance.buildermethodname; + +import lombok.Builder; +import lombok.Getter; + +@Getter +public class Student extends Child { + + private final String schoolName; + + @Builder(builderMethodName = "studentBuilder") + public Student(String parentName, int parentAge, String childName, int childAge, String schoolName) { + super(parentName, parentAge, childName, childAge); + this.schoolName = schoolName; + } +} diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Child.java b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Child.java new file mode 100644 index 0000000000..92285ebdc3 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Child.java @@ -0,0 +1,11 @@ +package com.baeldung.lombok.builder.inheritance.superbuilder; + +import lombok.Getter; +import lombok.experimental.SuperBuilder; + +@Getter +@SuperBuilder(toBuilder = true) +public class Child extends Parent { + private final String childName; + private final int childAge; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Parent.java b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Parent.java new file mode 100644 index 0000000000..b8e0934520 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Parent.java @@ -0,0 +1,11 @@ +package com.baeldung.lombok.builder.inheritance.superbuilder; + +import lombok.Getter; +import lombok.experimental.SuperBuilder; + +@Getter +@SuperBuilder(toBuilder = true) +public class Parent { + private final String parentName; + private final int parentAge; +} diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Student.java b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Student.java new file mode 100644 index 0000000000..db43bacafa --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/inheritance/superbuilder/Student.java @@ -0,0 +1,10 @@ +package com.baeldung.lombok.builder.inheritance.superbuilder; + +import lombok.Getter; +import lombok.experimental.SuperBuilder; + +@Getter +@SuperBuilder(toBuilder = true) +public class Student extends Child { + private final String schoolName; +} diff --git a/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java index 56a380569d..546c38f140 100644 --- a/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java +++ b/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java @@ -40,20 +40,4 @@ public class BuilderUnitTest { assertThat(testImmutableClient.getName()).isEqualTo("foo"); assertThat(testImmutableClient.getId()).isEqualTo(1); } - - @Test - public void givenBuilderAtMethodLevel_ChildInheritingParentIsBuilt() { - Child child = Child.childBuilder() - .parentName("Andrea") - .parentAge(38) - .childName("Emma") - .childAge(6) - .build(); - - assertThat(child.getChildName()).isEqualTo("Emma"); - assertThat(child.getChildAge()).isEqualTo(6); - assertThat(child.getParentName()).isEqualTo("Andrea"); - assertThat(child.getParentAge()).isEqualTo(38); - } - } diff --git a/lombok/src/test/java/com/baeldung/lombok/builder/inheritance/buildermethodname/BuilderInheritanceUsingMethodNameUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/builder/inheritance/buildermethodname/BuilderInheritanceUsingMethodNameUnitTest.java new file mode 100644 index 0000000000..cf50b2577b --- /dev/null +++ b/lombok/src/test/java/com/baeldung/lombok/builder/inheritance/buildermethodname/BuilderInheritanceUsingMethodNameUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.lombok.builder.inheritance.buildermethodname; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +public class BuilderInheritanceUsingMethodNameUnitTest { + + @Test + public void givenBuilderAtMethodLevel_ChildInheritingParentIsBuilt() { + Child child = Child.childBuilder() + .parentName("Andrea") + .parentAge(38) + .childName("Emma") + .childAge(6) + .build(); + + assertThat(child.getChildName()).isEqualTo("Emma"); + assertThat(child.getChildAge()).isEqualTo(6); + assertThat(child.getParentName()).isEqualTo("Andrea"); + assertThat(child.getParentAge()).isEqualTo(38); + } + + @Test + public void givenSuperBuilderOnAllThreeLevels_StudentInheritingChildAndParentIsBuilt() { + Student student = Student.studentBuilder() + .parentName("Andrea") + .parentAge(38) + .childName("Emma") + .childAge(6) + .schoolName("Baeldung High School") + .build(); + + assertThat(student.getChildName()).isEqualTo("Emma"); + assertThat(student.getChildAge()).isEqualTo(6); + assertThat(student.getParentName()).isEqualTo("Andrea"); + assertThat(student.getParentAge()).isEqualTo(38); + assertThat(student.getSchoolName()).isEqualTo("Baeldung High School"); + } +} diff --git a/lombok/src/test/java/com/baeldung/lombok/builder/inheritance/superbuilder/BuilderInheritanceUsingSuperBuilderUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/builder/inheritance/superbuilder/BuilderInheritanceUsingSuperBuilderUnitTest.java new file mode 100644 index 0000000000..72bfa6567b --- /dev/null +++ b/lombok/src/test/java/com/baeldung/lombok/builder/inheritance/superbuilder/BuilderInheritanceUsingSuperBuilderUnitTest.java @@ -0,0 +1,96 @@ +package com.baeldung.lombok.builder.inheritance.superbuilder; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +public class BuilderInheritanceUsingSuperBuilderUnitTest { + + @Test + public void givenSuperBuilderOnParentAndOnChild_ChildInheritingParentIsBuilt() { + Child child = Child.builder() + .parentName("Andrea") + .parentAge(38) + .childName("Emma") + .childAge(6) + .build(); + + assertThat(child.getChildName()).isEqualTo("Emma"); + assertThat(child.getChildAge()).isEqualTo(6); + assertThat(child.getParentName()).isEqualTo("Andrea"); + assertThat(child.getParentAge()).isEqualTo(38); + } + + @Test + public void givenSuperBuilderOnParent_StandardBuilderIsBuilt() { + Parent parent = Parent.builder() + .parentName("Andrea") + .parentAge(38) + .build(); + + assertThat(parent.getParentName()).isEqualTo("Andrea"); + assertThat(parent.getParentAge()).isEqualTo(38); + } + + @Test + public void givenToBuilderIsSetToTrueOnParentAndChild_DeepCopyViaBuilderIsPossible() { + Child child1 = Child.builder() + .parentName("Andrea") + .parentAge(38) + .childName("Emma") + .childAge(6) + .build(); + + Child child2 = child1.toBuilder() + .childName("Anna") + .build(); + + assertThat(child2.getChildName()).isEqualTo("Anna"); + assertThat(child2.getChildAge()).isEqualTo(6); + assertThat(child2.getParentName()).isEqualTo("Andrea"); + assertThat(child2.getParentAge()).isEqualTo(38); + + } + + @Test + public void givenSuperBuilderOnAllThreeLevels_StudentInheritingChildAndParentIsBuilt() { + Student student = Student.builder() + .parentName("Andrea") + .parentAge(38) + .childName("Emma") + .childAge(6) + .schoolName("Baeldung High School") + .build(); + + assertThat(student.getChildName()).isEqualTo("Emma"); + assertThat(student.getChildAge()).isEqualTo(6); + assertThat(student.getParentName()).isEqualTo("Andrea"); + assertThat(student.getParentAge()).isEqualTo(38); + assertThat(student.getSchoolName()).isEqualTo("Baeldung High School"); + } + + @Test + public void givenToBuilderIsSetToTrueOnParentChildAndStudent_DeepCopyViaBuilderIsPossible() { + Student student1 = Student.builder() + .parentName("Andrea") + .parentAge(38) + .childName("Emma") + .childAge(6) + .schoolName("School 1") + .build(); + + Student student2 = student1.toBuilder() + .childName("Anna") + .schoolName("School 2") + .build(); + + assertThat(student2.getChildName()).isEqualTo("Anna"); + assertThat(student2.getChildAge()).isEqualTo(6); + assertThat(student2.getParentName()).isEqualTo("Andrea"); + assertThat(student2.getParentAge()).isEqualTo(38); + assertThat(student2.getSchoolName()).isEqualTo("School 2"); + + } + + +} From bd166ed82f02a49b7c1eadec210b0c1459745c33 Mon Sep 17 00:00:00 2001 From: Andrey Shcherbakov Date: Thu, 31 Jan 2019 22:18:07 +0100 Subject: [PATCH 048/152] Fix the integration test in module spring-4 --- .../org/baeldung/SpringContextIntegrationTest.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/spring-4/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-4/src/test/java/org/baeldung/SpringContextIntegrationTest.java index 9dfac2bd9e..d646e22511 100644 --- a/spring-4/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-4/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -2,13 +2,16 @@ package org.baeldung; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; import com.baeldung.flips.ApplicationConfig; -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ApplicationConfig.class) + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = ApplicationConfig.class) +@WebAppConfiguration public class SpringContextIntegrationTest { @Test From 1c556fe4fc9192eef90e0c60e084b202fd004a9e Mon Sep 17 00:00:00 2001 From: Andrey Shcherbakov Date: Thu, 31 Jan 2019 22:28:46 +0100 Subject: [PATCH 049/152] Fix the integration test in module springboot-autoconfiguration This test requires that MySQL engine is up. --- .../SpringContextIntegrationTest.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 spring-boot-autoconfiguration/src/test/java/com/baeldung/SpringContextIntegrationTest.java diff --git a/spring-boot-autoconfiguration/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-boot-autoconfiguration/src/test/java/com/baeldung/SpringContextIntegrationTest.java new file mode 100644 index 0000000000..a0138bec8d --- /dev/null +++ b/spring-boot-autoconfiguration/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +import com.baeldung.autoconfiguration.MySQLAutoconfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MySQLAutoconfiguration.class) +@WebAppConfiguration +public class SpringContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} \ No newline at end of file From 191039ffc60afc3b39ef09be79a54887a8e9d164 Mon Sep 17 00:00:00 2001 From: Andrey Shcherbakov Date: Fri, 1 Feb 2019 07:19:07 +0100 Subject: [PATCH 050/152] Add code for issue BAEL-2574 (#6249) * Add code for issue BAEL-2574 This is a code for article "Access Spring MVC Model object in JS" Set up the project Add a test * Rename the test class --- spring-boot-mvc/pom.xml | 10 ++++++ .../java/com/baeldung/accessparamsjs/App.java | 13 ++++++++ .../baeldung/accessparamsjs/Controller.java | 32 +++++++++++++++++++ .../src/main/resources/application.properties | 4 ++- .../src/main/webapp/WEB-INF/jsp/index.jsp | 27 ++++++++++++++++ spring-boot-mvc/src/main/webapp/js/jquery.js | 2 ++ .../src/main/webapp/js/script-async-jquery.js | 6 ++++ .../src/main/webapp/js/script-async.js | 6 ++++ spring-boot-mvc/src/main/webapp/js/script.js | 4 +++ .../accessparamsjs/ControllerUnitTest.java | 28 ++++++++++++++++ 10 files changed, 131 insertions(+), 1 deletion(-) create mode 100644 spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/App.java create mode 100644 spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/Controller.java create mode 100644 spring-boot-mvc/src/main/webapp/WEB-INF/jsp/index.jsp create mode 100644 spring-boot-mvc/src/main/webapp/js/jquery.js create mode 100644 spring-boot-mvc/src/main/webapp/js/script-async-jquery.js create mode 100644 spring-boot-mvc/src/main/webapp/js/script-async.js create mode 100644 spring-boot-mvc/src/main/webapp/js/script.js create mode 100644 spring-boot-mvc/src/test/java/com/baeldung/accessparamsjs/ControllerUnitTest.java diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml index b219e53431..bb3e6312ab 100644 --- a/spring-boot-mvc/pom.xml +++ b/spring-boot-mvc/pom.xml @@ -72,6 +72,16 @@ ${spring.fox.version} + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + javax.servlet + jstl + + diff --git a/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/App.java b/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/App.java new file mode 100644 index 0000000000..2ffbb354c3 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/App.java @@ -0,0 +1,13 @@ +package com.baeldung.accessparamsjs; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class App { + + public static void main(String[] args) { + SpringApplication.run(App.class, args); + } + +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/Controller.java b/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/Controller.java new file mode 100644 index 0000000000..cc838eb6a5 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/accessparamsjs/Controller.java @@ -0,0 +1,32 @@ +package com.baeldung.accessparamsjs; + +import java.util.Map; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.ModelAndView; + +/** + * Sample rest controller for the tutorial article + * "Access Spring MVC Model object in JavaScript". + * + * @author Andrew Shcherbakov + * + */ +@RestController +public class Controller { + + /** + * Define two model objects (one integer and one string) and pass them to the view. + * + * @param model + * @return + */ + @RequestMapping("/index") + public ModelAndView index(Map model) { + model.put("number", 1234); + model.put("message", "Hello from Spring MVC"); + return new ModelAndView("/index"); + } + +} diff --git a/spring-boot-mvc/src/main/resources/application.properties b/spring-boot-mvc/src/main/resources/application.properties index 709574239b..00362e2588 100644 --- a/spring-boot-mvc/src/main/resources/application.properties +++ b/spring-boot-mvc/src/main/resources/application.properties @@ -1 +1,3 @@ -spring.main.allow-bean-definition-overriding=true \ No newline at end of file +spring.main.allow-bean-definition-overriding=true +spring.mvc.view.prefix=/WEB-INF/jsp/ +spring.mvc.view.suffix=.jsp \ No newline at end of file diff --git a/spring-boot-mvc/src/main/webapp/WEB-INF/jsp/index.jsp b/spring-boot-mvc/src/main/webapp/WEB-INF/jsp/index.jsp new file mode 100644 index 0000000000..d9f3966e82 --- /dev/null +++ b/spring-boot-mvc/src/main/webapp/WEB-INF/jsp/index.jsp @@ -0,0 +1,27 @@ + +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> + + +Access Spring MVC params + + + + + + +

Data from the external JS file (due to loading order)

+
+
+

Asynchronous loading from external JS file (plain JS)

+
+
+

Asynchronous loading from external JS file (jQuery)

+
+
+ + + + \ No newline at end of file diff --git a/spring-boot-mvc/src/main/webapp/js/jquery.js b/spring-boot-mvc/src/main/webapp/js/jquery.js new file mode 100644 index 0000000000..4d9b3a2587 --- /dev/null +++ b/spring-boot-mvc/src/main/webapp/js/jquery.js @@ -0,0 +1,2 @@ +/*! jQuery v3.3.1 | (c) JS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){"use strict";var n=[],r=e.document,i=Object.getPrototypeOf,o=n.slice,a=n.concat,s=n.push,u=n.indexOf,l={},c=l.toString,f=l.hasOwnProperty,p=f.toString,d=p.call(Object),h={},g=function e(t){return"function"==typeof t&&"number"!=typeof t.nodeType},y=function e(t){return null!=t&&t===t.window},v={type:!0,src:!0,noModule:!0};function m(e,t,n){var i,o=(t=t||r).createElement("script");if(o.text=e,n)for(i in v)n[i]&&(o[i]=n[i]);t.head.appendChild(o).parentNode.removeChild(o)}function x(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[c.call(e)]||"object":typeof e}var b="3.3.1",w=function(e,t){return new w.fn.init(e,t)},T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;w.fn=w.prototype={jquery:"3.3.1",constructor:w,length:0,toArray:function(){return o.call(this)},get:function(e){return null==e?o.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=w.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return w.each(this,e)},map:function(e){return this.pushStack(w.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(o.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(n>=0&&n0&&t-1 in e)}var E=function(e){var t,n,r,i,o,a,s,u,l,c,f,p,d,h,g,y,v,m,x,b="sizzle"+1*new Date,w=e.document,T=0,C=0,E=ae(),k=ae(),S=ae(),D=function(e,t){return e===t&&(f=!0),0},N={}.hasOwnProperty,A=[],j=A.pop,q=A.push,L=A.push,H=A.slice,O=function(e,t){for(var n=0,r=e.length;n+~]|"+M+")"+M+"*"),z=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),X=new RegExp(W),U=new RegExp("^"+R+"$"),V={ID:new RegExp("^#("+R+")"),CLASS:new RegExp("^\\.("+R+")"),TAG:new RegExp("^("+R+"|[*])"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+W),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+P+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},G=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Q=/^[^{]+\{\s*\[native \w/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,K=/[+~]/,Z=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ee=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},te=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ne=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},re=function(){p()},ie=me(function(e){return!0===e.disabled&&("form"in e||"label"in e)},{dir:"parentNode",next:"legend"});try{L.apply(A=H.call(w.childNodes),w.childNodes),A[w.childNodes.length].nodeType}catch(e){L={apply:A.length?function(e,t){q.apply(e,H.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function oe(e,t,r,i){var o,s,l,c,f,h,v,m=t&&t.ownerDocument,T=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==T&&9!==T&&11!==T)return r;if(!i&&((t?t.ownerDocument||t:w)!==d&&p(t),t=t||d,g)){if(11!==T&&(f=J.exec(e)))if(o=f[1]){if(9===T){if(!(l=t.getElementById(o)))return r;if(l.id===o)return r.push(l),r}else if(m&&(l=m.getElementById(o))&&x(t,l)&&l.id===o)return r.push(l),r}else{if(f[2])return L.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return L.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!S[e+" "]&&(!y||!y.test(e))){if(1!==T)m=t,v=e;else if("object"!==t.nodeName.toLowerCase()){(c=t.getAttribute("id"))?c=c.replace(te,ne):t.setAttribute("id",c=b),s=(h=a(e)).length;while(s--)h[s]="#"+c+" "+ve(h[s]);v=h.join(","),m=K.test(e)&&ge(t.parentNode)||t}if(v)try{return L.apply(r,m.querySelectorAll(v)),r}catch(e){}finally{c===b&&t.removeAttribute("id")}}}return u(e.replace(B,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function se(e){return e[b]=!0,e}function ue(e){var t=d.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function le(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function ce(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function fe(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}function pe(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function de(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ie(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return se(function(t){return t=+t,se(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}n=oe.support={},o=oe.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},p=oe.setDocument=function(e){var t,i,a=e?e.ownerDocument||e:w;return a!==d&&9===a.nodeType&&a.documentElement?(d=a,h=d.documentElement,g=!o(d),w!==d&&(i=d.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",re,!1):i.attachEvent&&i.attachEvent("onunload",re)),n.attributes=ue(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=ue(function(e){return e.appendChild(d.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Q.test(d.getElementsByClassName),n.getById=ue(function(e){return h.appendChild(e).id=b,!d.getElementsByName||!d.getElementsByName(b).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){var n="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&g)return t.getElementsByClassName(e)},v=[],y=[],(n.qsa=Q.test(d.querySelectorAll))&&(ue(function(e){h.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&y.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||y.push("\\["+M+"*(?:value|"+P+")"),e.querySelectorAll("[id~="+b+"-]").length||y.push("~="),e.querySelectorAll(":checked").length||y.push(":checked"),e.querySelectorAll("a#"+b+"+*").length||y.push(".#.+[+~]")}),ue(function(e){e.innerHTML="";var t=d.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&y.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&y.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&y.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),y.push(",.*:")})),(n.matchesSelector=Q.test(m=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&ue(function(e){n.disconnectedMatch=m.call(e,"*"),m.call(e,"[s!='']:x"),v.push("!=",W)}),y=y.length&&new RegExp(y.join("|")),v=v.length&&new RegExp(v.join("|")),t=Q.test(h.compareDocumentPosition),x=t||Q.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===d||e.ownerDocument===w&&x(w,e)?-1:t===d||t.ownerDocument===w&&x(w,t)?1:c?O(c,e)-O(c,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===d?-1:t===d?1:i?-1:o?1:c?O(c,e)-O(c,t):0;if(i===o)return ce(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?ce(a[r],s[r]):a[r]===w?-1:s[r]===w?1:0},d):d},oe.matches=function(e,t){return oe(e,null,null,t)},oe.matchesSelector=function(e,t){if((e.ownerDocument||e)!==d&&p(e),t=t.replace(z,"='$1']"),n.matchesSelector&&g&&!S[t+" "]&&(!v||!v.test(t))&&(!y||!y.test(t)))try{var r=m.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){}return oe(t,d,null,[e]).length>0},oe.contains=function(e,t){return(e.ownerDocument||e)!==d&&p(e),x(e,t)},oe.attr=function(e,t){(e.ownerDocument||e)!==d&&p(e);var i=r.attrHandle[t.toLowerCase()],o=i&&N.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},oe.escape=function(e){return(e+"").replace(te,ne)},oe.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},oe.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,c=!n.sortStable&&e.slice(0),e.sort(D),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return c=null,e},i=oe.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=oe.selectors={cacheLength:50,createPseudo:se,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(Z,ee),e[3]=(e[3]||e[4]||e[5]||"").replace(Z,ee),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||oe.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&oe.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return V.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=a(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(Z,ee).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=oe.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace($," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,f,p,d,h,g=o!==a?"nextSibling":"previousSibling",y=t.parentNode,v=s&&t.nodeName.toLowerCase(),m=!u&&!s,x=!1;if(y){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===v:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?y.firstChild:y.lastChild],a&&m){x=(d=(l=(c=(f=(p=y)[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]||[])[0]===T&&l[1])&&l[2],p=d&&y.childNodes[d];while(p=++d&&p&&p[g]||(x=d=0)||h.pop())if(1===p.nodeType&&++x&&p===t){c[e]=[T,d,x];break}}else if(m&&(x=d=(l=(c=(f=(p=t)[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]||[])[0]===T&&l[1]),!1===x)while(p=++d&&p&&p[g]||(x=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===v:1===p.nodeType)&&++x&&(m&&((c=(f=p[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]=[T,x]),p===t))break;return(x-=i)===r||x%r==0&&x/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||oe.error("unsupported pseudo: "+e);return i[b]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?se(function(e,n){var r,o=i(e,t),a=o.length;while(a--)e[r=O(e,o[a])]=!(n[r]=o[a])}):function(e){return i(e,0,n)}):i}},pseudos:{not:se(function(e){var t=[],n=[],r=s(e.replace(B,"$1"));return r[b]?se(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:se(function(e){return function(t){return oe(e,t).length>0}}),contains:se(function(e){return e=e.replace(Z,ee),function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:se(function(e){return U.test(e||"")||oe.error("unsupported lang: "+e),e=e.replace(Z,ee).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===d.activeElement&&(!d.hasFocus||d.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:de(!1),disabled:de(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function be(e,t,n){for(var r=0,i=t.length;r-1&&(o[l]=!(a[l]=f))}}else v=we(v===a?v.splice(h,v.length):v),i?i(null,a,v,u):L.apply(a,v)})}function Ce(e){for(var t,n,i,o=e.length,a=r.relative[e[0].type],s=a||r.relative[" "],u=a?1:0,c=me(function(e){return e===t},s,!0),f=me(function(e){return O(t,e)>-1},s,!0),p=[function(e,n,r){var i=!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):f(e,n,r));return t=null,i}];u1&&xe(p),u>1&&ve(e.slice(0,u-1).concat({value:" "===e[u-2].type?"*":""})).replace(B,"$1"),n,u0,i=e.length>0,o=function(o,a,s,u,c){var f,h,y,v=0,m="0",x=o&&[],b=[],w=l,C=o||i&&r.find.TAG("*",c),E=T+=null==w?1:Math.random()||.1,k=C.length;for(c&&(l=a===d||a||c);m!==k&&null!=(f=C[m]);m++){if(i&&f){h=0,a||f.ownerDocument===d||(p(f),s=!g);while(y=e[h++])if(y(f,a||d,s)){u.push(f);break}c&&(T=E)}n&&((f=!y&&f)&&v--,o&&x.push(f))}if(v+=m,n&&m!==v){h=0;while(y=t[h++])y(x,b,a,s);if(o){if(v>0)while(m--)x[m]||b[m]||(b[m]=j.call(u));b=we(b)}L.apply(u,b),c&&!o&&b.length>0&&v+t.length>1&&oe.uniqueSort(u)}return c&&(T=E,l=w),x};return n?se(o):o}return s=oe.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=a(e)),n=t.length;while(n--)(o=Ce(t[n]))[b]?r.push(o):i.push(o);(o=S(e,Ee(i,r))).selector=e}return o},u=oe.select=function(e,t,n,i){var o,u,l,c,f,p="function"==typeof e&&e,d=!i&&a(e=p.selector||e);if(n=n||[],1===d.length){if((u=d[0]=d[0].slice(0)).length>2&&"ID"===(l=u[0]).type&&9===t.nodeType&&g&&r.relative[u[1].type]){if(!(t=(r.find.ID(l.matches[0].replace(Z,ee),t)||[])[0]))return n;p&&(t=t.parentNode),e=e.slice(u.shift().value.length)}o=V.needsContext.test(e)?0:u.length;while(o--){if(l=u[o],r.relative[c=l.type])break;if((f=r.find[c])&&(i=f(l.matches[0].replace(Z,ee),K.test(u[0].type)&&ge(t.parentNode)||t))){if(u.splice(o,1),!(e=i.length&&ve(u)))return L.apply(n,i),n;break}}}return(p||s(e,d))(i,t,!g,n,!t||K.test(e)&&ge(t.parentNode)||t),n},n.sortStable=b.split("").sort(D).join("")===b,n.detectDuplicates=!!f,p(),n.sortDetached=ue(function(e){return 1&e.compareDocumentPosition(d.createElement("fieldset"))}),ue(function(e){return e.innerHTML="","#"===e.firstChild.getAttribute("href")})||le("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&ue(function(e){return e.innerHTML="",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||le("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),ue(function(e){return null==e.getAttribute("disabled")})||le(P,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),oe}(e);w.find=E,w.expr=E.selectors,w.expr[":"]=w.expr.pseudos,w.uniqueSort=w.unique=E.uniqueSort,w.text=E.getText,w.isXMLDoc=E.isXML,w.contains=E.contains,w.escapeSelector=E.escape;var k=function(e,t,n){var r=[],i=void 0!==n;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&w(e).is(n))break;r.push(e)}return r},S=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},D=w.expr.match.needsContext;function N(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var A=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,t,n){return g(t)?w.grep(e,function(e,r){return!!t.call(e,r,e)!==n}):t.nodeType?w.grep(e,function(e){return e===t!==n}):"string"!=typeof t?w.grep(e,function(e){return u.call(t,e)>-1!==n}):w.filter(t,e,n)}w.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?w.find.matchesSelector(r,e)?[r]:[]:w.find.matches(e,w.grep(t,function(e){return 1===e.nodeType}))},w.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(w(e).filter(function(){for(t=0;t1?w.uniqueSort(n):n},filter:function(e){return this.pushStack(j(this,e||[],!1))},not:function(e){return this.pushStack(j(this,e||[],!0))},is:function(e){return!!j(this,"string"==typeof e&&D.test(e)?w(e):e||[],!1).length}});var q,L=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(w.fn.init=function(e,t,n){var i,o;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(i="<"===e[0]&&">"===e[e.length-1]&&e.length>=3?[null,e,null]:L.exec(e))||!i[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(i[1]){if(t=t instanceof w?t[0]:t,w.merge(this,w.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:r,!0)),A.test(i[1])&&w.isPlainObject(t))for(i in t)g(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}return(o=r.getElementById(i[2]))&&(this[0]=o,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):g(e)?void 0!==n.ready?n.ready(e):e(w):w.makeArray(e,this)}).prototype=w.fn,q=w(r);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};w.fn.extend({has:function(e){var t=w(e,this),n=t.length;return this.filter(function(){for(var e=0;e-1:1===n.nodeType&&w.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?w.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?u.call(w(e),this[0]):u.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(w.uniqueSort(w.merge(this.get(),w(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}w.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return k(e,"parentNode")},parentsUntil:function(e,t,n){return k(e,"parentNode",n)},next:function(e){return P(e,"nextSibling")},prev:function(e){return P(e,"previousSibling")},nextAll:function(e){return k(e,"nextSibling")},prevAll:function(e){return k(e,"previousSibling")},nextUntil:function(e,t,n){return k(e,"nextSibling",n)},prevUntil:function(e,t,n){return k(e,"previousSibling",n)},siblings:function(e){return S((e.parentNode||{}).firstChild,e)},children:function(e){return S(e.firstChild)},contents:function(e){return N(e,"iframe")?e.contentDocument:(N(e,"template")&&(e=e.content||e),w.merge([],e.childNodes))}},function(e,t){w.fn[e]=function(n,r){var i=w.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=w.filter(r,i)),this.length>1&&(O[e]||w.uniqueSort(i),H.test(e)&&i.reverse()),this.pushStack(i)}});var M=/[^\x20\t\r\n\f]+/g;function R(e){var t={};return w.each(e.match(M)||[],function(e,n){t[n]=!0}),t}w.Callbacks=function(e){e="string"==typeof e?R(e):w.extend({},e);var t,n,r,i,o=[],a=[],s=-1,u=function(){for(i=i||e.once,r=t=!0;a.length;s=-1){n=a.shift();while(++s-1)o.splice(n,1),n<=s&&s--}),this},has:function(e){return e?w.inArray(e,o)>-1:o.length>0},empty:function(){return o&&(o=[]),this},disable:function(){return i=a=[],o=n="",this},disabled:function(){return!o},lock:function(){return i=a=[],n||t||(o=n=""),this},locked:function(){return!!i},fireWith:function(e,n){return i||(n=[e,(n=n||[]).slice?n.slice():n],a.push(n),t||u()),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!r}};return l};function I(e){return e}function W(e){throw e}function $(e,t,n,r){var i;try{e&&g(i=e.promise)?i.call(e).done(t).fail(n):e&&g(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}w.extend({Deferred:function(t){var n=[["notify","progress",w.Callbacks("memory"),w.Callbacks("memory"),2],["resolve","done",w.Callbacks("once memory"),w.Callbacks("once memory"),0,"resolved"],["reject","fail",w.Callbacks("once memory"),w.Callbacks("once memory"),1,"rejected"]],r="pending",i={state:function(){return r},always:function(){return o.done(arguments).fail(arguments),this},"catch":function(e){return i.then(null,e)},pipe:function(){var e=arguments;return w.Deferred(function(t){w.each(n,function(n,r){var i=g(e[r[4]])&&e[r[4]];o[r[1]](function(){var e=i&&i.apply(this,arguments);e&&g(e.promise)?e.promise().progress(t.notify).done(t.resolve).fail(t.reject):t[r[0]+"With"](this,i?[e]:arguments)})}),e=null}).promise()},then:function(t,r,i){var o=0;function a(t,n,r,i){return function(){var s=this,u=arguments,l=function(){var e,l;if(!(t=o&&(r!==W&&(s=void 0,u=[e]),n.rejectWith(s,u))}};t?c():(w.Deferred.getStackHook&&(c.stackTrace=w.Deferred.getStackHook()),e.setTimeout(c))}}return w.Deferred(function(e){n[0][3].add(a(0,e,g(i)?i:I,e.notifyWith)),n[1][3].add(a(0,e,g(t)?t:I)),n[2][3].add(a(0,e,g(r)?r:W))}).promise()},promise:function(e){return null!=e?w.extend(e,i):i}},o={};return w.each(n,function(e,t){var a=t[2],s=t[5];i[t[1]]=a.add,s&&a.add(function(){r=s},n[3-e][2].disable,n[3-e][3].disable,n[0][2].lock,n[0][3].lock),a.add(t[3].fire),o[t[0]]=function(){return o[t[0]+"With"](this===o?void 0:this,arguments),this},o[t[0]+"With"]=a.fireWith}),i.promise(o),t&&t.call(o,o),o},when:function(e){var t=arguments.length,n=t,r=Array(n),i=o.call(arguments),a=w.Deferred(),s=function(e){return function(n){r[e]=this,i[e]=arguments.length>1?o.call(arguments):n,--t||a.resolveWith(r,i)}};if(t<=1&&($(e,a.done(s(n)).resolve,a.reject,!t),"pending"===a.state()||g(i[n]&&i[n].then)))return a.then();while(n--)$(i[n],s(n),a.reject);return a.promise()}});var B=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;w.Deferred.exceptionHook=function(t,n){e.console&&e.console.warn&&t&&B.test(t.name)&&e.console.warn("jQuery.Deferred exception: "+t.message,t.stack,n)},w.readyException=function(t){e.setTimeout(function(){throw t})};var F=w.Deferred();w.fn.ready=function(e){return F.then(e)["catch"](function(e){w.readyException(e)}),this},w.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--w.readyWait:w.isReady)||(w.isReady=!0,!0!==e&&--w.readyWait>0||F.resolveWith(r,[w]))}}),w.ready.then=F.then;function _(){r.removeEventListener("DOMContentLoaded",_),e.removeEventListener("load",_),w.ready()}"complete"===r.readyState||"loading"!==r.readyState&&!r.documentElement.doScroll?e.setTimeout(w.ready):(r.addEventListener("DOMContentLoaded",_),e.addEventListener("load",_));var z=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===x(n)){i=!0;for(s in n)z(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,g(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(w(e),n)})),t))for(;s1,null,!0)},removeData:function(e){return this.each(function(){K.remove(this,e)})}}),w.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=J.get(e,t),n&&(!r||Array.isArray(n)?r=J.access(e,t,w.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=w.queue(e,t),r=n.length,i=n.shift(),o=w._queueHooks(e,t),a=function(){w.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return J.get(e,n)||J.access(e,n,{empty:w.Callbacks("once memory").add(function(){J.remove(e,[t+"queue",n])})})}}),w.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length\x20\t\r\n\f]+)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ge.optgroup=ge.option,ge.tbody=ge.tfoot=ge.colgroup=ge.caption=ge.thead,ge.th=ge.td;function ye(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&N(e,t)?w.merge([e],n):n}function ve(e,t){for(var n=0,r=e.length;n-1)i&&i.push(o);else if(l=w.contains(o.ownerDocument,o),a=ye(f.appendChild(o),"script"),l&&ve(a),n){c=0;while(o=a[c++])he.test(o.type||"")&&n.push(o)}return f}!function(){var e=r.createDocumentFragment().appendChild(r.createElement("div")),t=r.createElement("input");t.setAttribute("type","radio"),t.setAttribute("checked","checked"),t.setAttribute("name","t"),e.appendChild(t),h.checkClone=e.cloneNode(!0).cloneNode(!0).lastChild.checked,e.innerHTML="",h.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue}();var be=r.documentElement,we=/^key/,Te=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ce=/^([^.]*)(?:\.(.+)|)/;function Ee(){return!0}function ke(){return!1}function Se(){try{return r.activeElement}catch(e){}}function De(e,t,n,r,i,o){var a,s;if("object"==typeof t){"string"!=typeof n&&(r=r||n,n=void 0);for(s in t)De(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=ke;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return w().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=w.guid++)),e.each(function(){w.event.add(this,t,i,r,n)})}w.event={global:{},add:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=J.get(e);if(y){n.handler&&(n=(o=n).handler,i=o.selector),i&&w.find.matchesSelector(be,i),n.guid||(n.guid=w.guid++),(u=y.events)||(u=y.events={}),(a=y.handle)||(a=y.handle=function(t){return"undefined"!=typeof w&&w.event.triggered!==t.type?w.event.dispatch.apply(e,arguments):void 0}),l=(t=(t||"").match(M)||[""]).length;while(l--)d=g=(s=Ce.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=w.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=w.event.special[d]||{},c=w.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&w.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(e,r,h,a)||e.addEventListener&&e.addEventListener(d,a)),f.add&&(f.add.call(e,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),w.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=J.hasData(e)&&J.get(e);if(y&&(u=y.events)){l=(t=(t||"").match(M)||[""]).length;while(l--)if(s=Ce.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){f=w.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,y.handle)||w.removeEvent(e,d,y.handle),delete u[d])}else for(d in u)w.event.remove(e,d+t[l],n,r,!0);w.isEmptyObject(u)&&J.remove(e,"handle events")}},dispatch:function(e){var t=w.event.fix(e),n,r,i,o,a,s,u=new Array(arguments.length),l=(J.get(this,"events")||{})[t.type]||[],c=w.event.special[t.type]||{};for(u[0]=t,n=1;n=1))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n-1:w.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&s.push({elem:l,handlers:o})}return l=this,u\x20\t\r\n\f]*)[^>]*)\/>/gi,Ae=/\s*$/g;function Le(e,t){return N(e,"table")&&N(11!==t.nodeType?t:t.firstChild,"tr")?w(e).children("tbody")[0]||e:e}function He(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Oe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Pe(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(J.hasData(e)&&(o=J.access(e),a=J.set(t,o),l=o.events)){delete a.handle,a.events={};for(i in l)for(n=0,r=l[i].length;n1&&"string"==typeof y&&!h.checkClone&&je.test(y))return e.each(function(i){var o=e.eq(i);v&&(t[0]=y.call(this,i,o.html())),Re(o,t,n,r)});if(p&&(i=xe(t,e[0].ownerDocument,!1,e,r),o=i.firstChild,1===i.childNodes.length&&(i=o),o||r)){for(u=(s=w.map(ye(i,"script"),He)).length;f")},clone:function(e,t,n){var r,i,o,a,s=e.cloneNode(!0),u=w.contains(e.ownerDocument,e);if(!(h.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||w.isXMLDoc(e)))for(a=ye(s),r=0,i=(o=ye(e)).length;r0&&ve(a,!u&&ye(e,"script")),s},cleanData:function(e){for(var t,n,r,i=w.event.special,o=0;void 0!==(n=e[o]);o++)if(Y(n)){if(t=n[J.expando]){if(t.events)for(r in t.events)i[r]?w.event.remove(n,r):w.removeEvent(n,r,t.handle);n[J.expando]=void 0}n[K.expando]&&(n[K.expando]=void 0)}}}),w.fn.extend({detach:function(e){return Ie(this,e,!0)},remove:function(e){return Ie(this,e)},text:function(e){return z(this,function(e){return void 0===e?w.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return Re(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||Le(this,e).appendChild(e)})},prepend:function(){return Re(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Le(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(w.cleanData(ye(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return w.clone(this,e,t)})},html:function(e){return z(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Ae.test(e)&&!ge[(de.exec(e)||["",""])[1].toLowerCase()]){e=w.htmlPrefilter(e);try{for(;n=0&&(u+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-u-s-.5))),u}function et(e,t,n){var r=$e(e),i=Fe(e,t,r),o="border-box"===w.css(e,"boxSizing",!1,r),a=o;if(We.test(i)){if(!n)return i;i="auto"}return a=a&&(h.boxSizingReliable()||i===e.style[t]),("auto"===i||!parseFloat(i)&&"inline"===w.css(e,"display",!1,r))&&(i=e["offset"+t[0].toUpperCase()+t.slice(1)],a=!0),(i=parseFloat(i)||0)+Ze(e,t,n||(o?"border":"content"),a,r,i)+"px"}w.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Fe(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=G(t),u=Xe.test(t),l=e.style;if(u||(t=Je(s)),a=w.cssHooks[t]||w.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"==(o=typeof n)&&(i=ie.exec(n))&&i[1]&&(n=ue(e,t,i),o="number"),null!=n&&n===n&&("number"===o&&(n+=i&&i[3]||(w.cssNumber[s]?"":"px")),h.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(u?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,s=G(t);return Xe.test(t)||(t=Je(s)),(a=w.cssHooks[t]||w.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=Fe(e,t,r)),"normal"===i&&t in Ve&&(i=Ve[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),w.each(["height","width"],function(e,t){w.cssHooks[t]={get:function(e,n,r){if(n)return!ze.test(w.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?et(e,t,r):se(e,Ue,function(){return et(e,t,r)})},set:function(e,n,r){var i,o=$e(e),a="border-box"===w.css(e,"boxSizing",!1,o),s=r&&Ze(e,t,r,a,o);return a&&h.scrollboxSize()===o.position&&(s-=Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-parseFloat(o[t])-Ze(e,t,"border",!1,o)-.5)),s&&(i=ie.exec(n))&&"px"!==(i[3]||"px")&&(e.style[t]=n,n=w.css(e,t)),Ke(e,n,s)}}}),w.cssHooks.marginLeft=_e(h.reliableMarginLeft,function(e,t){if(t)return(parseFloat(Fe(e,"marginLeft"))||e.getBoundingClientRect().left-se(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),w.each({margin:"",padding:"",border:"Width"},function(e,t){w.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];r<4;r++)i[e+oe[r]+t]=o[r]||o[r-2]||o[0];return i}},"margin"!==e&&(w.cssHooks[e+t].set=Ke)}),w.fn.extend({css:function(e,t){return z(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=$e(e),i=t.length;a1)}});function tt(e,t,n,r,i){return new tt.prototype.init(e,t,n,r,i)}w.Tween=tt,tt.prototype={constructor:tt,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||w.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(w.cssNumber[n]?"":"px")},cur:function(){var e=tt.propHooks[this.prop];return e&&e.get?e.get(this):tt.propHooks._default.get(this)},run:function(e){var t,n=tt.propHooks[this.prop];return this.options.duration?this.pos=t=w.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):tt.propHooks._default.set(this),this}},tt.prototype.init.prototype=tt.prototype,tt.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=w.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){w.fx.step[e.prop]?w.fx.step[e.prop](e):1!==e.elem.nodeType||null==e.elem.style[w.cssProps[e.prop]]&&!w.cssHooks[e.prop]?e.elem[e.prop]=e.now:w.style(e.elem,e.prop,e.now+e.unit)}}},tt.propHooks.scrollTop=tt.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},w.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},w.fx=tt.prototype.init,w.fx.step={};var nt,rt,it=/^(?:toggle|show|hide)$/,ot=/queueHooks$/;function at(){rt&&(!1===r.hidden&&e.requestAnimationFrame?e.requestAnimationFrame(at):e.setTimeout(at,w.fx.interval),w.fx.tick())}function st(){return e.setTimeout(function(){nt=void 0}),nt=Date.now()}function ut(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=oe[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function lt(e,t,n){for(var r,i=(pt.tweeners[t]||[]).concat(pt.tweeners["*"]),o=0,a=i.length;o1)},removeAttr:function(e){return this.each(function(){w.removeAttr(this,e)})}}),w.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?w.prop(e,t,n):(1===o&&w.isXMLDoc(e)||(i=w.attrHooks[t.toLowerCase()]||(w.expr.match.bool.test(t)?dt:void 0)),void 0!==n?null===n?void w.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=w.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!h.radioValue&&"radio"===t&&N(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(M);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),dt={set:function(e,t,n){return!1===t?w.removeAttr(e,n):e.setAttribute(n,n),n}},w.each(w.expr.match.bool.source.match(/\w+/g),function(e,t){var n=ht[t]||w.find.attr;ht[t]=function(e,t,r){var i,o,a=t.toLowerCase();return r||(o=ht[a],ht[a]=i,i=null!=n(e,t,r)?a:null,ht[a]=o),i}});var gt=/^(?:input|select|textarea|button)$/i,yt=/^(?:a|area)$/i;w.fn.extend({prop:function(e,t){return z(this,w.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[w.propFix[e]||e]})}}),w.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&w.isXMLDoc(e)||(t=w.propFix[t]||t,i=w.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=w.find.attr(e,"tabindex");return t?parseInt(t,10):gt.test(e.nodeName)||yt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),h.optSelected||(w.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),w.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){w.propFix[this.toLowerCase()]=this});function vt(e){return(e.match(M)||[]).join(" ")}function mt(e){return e.getAttribute&&e.getAttribute("class")||""}function xt(e){return Array.isArray(e)?e:"string"==typeof e?e.match(M)||[]:[]}w.fn.extend({addClass:function(e){var t,n,r,i,o,a,s,u=0;if(g(e))return this.each(function(t){w(this).addClass(e.call(this,t,mt(this)))});if((t=xt(e)).length)while(n=this[u++])if(i=mt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=t[a++])r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},removeClass:function(e){var t,n,r,i,o,a,s,u=0;if(g(e))return this.each(function(t){w(this).removeClass(e.call(this,t,mt(this)))});if(!arguments.length)return this.attr("class","");if((t=xt(e)).length)while(n=this[u++])if(i=mt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=t[a++])while(r.indexOf(" "+o+" ")>-1)r=r.replace(" "+o+" "," ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},toggleClass:function(e,t){var n=typeof e,r="string"===n||Array.isArray(e);return"boolean"==typeof t&&r?t?this.addClass(e):this.removeClass(e):g(e)?this.each(function(n){w(this).toggleClass(e.call(this,n,mt(this),t),t)}):this.each(function(){var t,i,o,a;if(r){i=0,o=w(this),a=xt(e);while(t=a[i++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else void 0!==e&&"boolean"!==n||((t=mt(this))&&J.set(this,"__className__",t),this.setAttribute&&this.setAttribute("class",t||!1===e?"":J.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&(" "+vt(mt(n))+" ").indexOf(t)>-1)return!0;return!1}});var bt=/\r/g;w.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=g(e),this.each(function(n){var i;1===this.nodeType&&(null==(i=r?e.call(this,n,w(this).val()):e)?i="":"number"==typeof i?i+="":Array.isArray(i)&&(i=w.map(i,function(e){return null==e?"":e+""})),(t=w.valHooks[this.type]||w.valHooks[this.nodeName.toLowerCase()])&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return(t=w.valHooks[i.type]||w.valHooks[i.nodeName.toLowerCase()])&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:"string"==typeof(n=i.value)?n.replace(bt,""):null==n?"":n}}}),w.extend({valHooks:{option:{get:function(e){var t=w.find.attr(e,"value");return null!=t?t:vt(w.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,s=a?null:[],u=a?o+1:i.length;for(r=o<0?u:a?o:0;r-1)&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),w.each(["radio","checkbox"],function(){w.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=w.inArray(w(e).val(),t)>-1}},h.checkOn||(w.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),h.focusin="onfocusin"in e;var wt=/^(?:focusinfocus|focusoutblur)$/,Tt=function(e){e.stopPropagation()};w.extend(w.event,{trigger:function(t,n,i,o){var a,s,u,l,c,p,d,h,v=[i||r],m=f.call(t,"type")?t.type:t,x=f.call(t,"namespace")?t.namespace.split("."):[];if(s=h=u=i=i||r,3!==i.nodeType&&8!==i.nodeType&&!wt.test(m+w.event.triggered)&&(m.indexOf(".")>-1&&(m=(x=m.split(".")).shift(),x.sort()),c=m.indexOf(":")<0&&"on"+m,t=t[w.expando]?t:new w.Event(m,"object"==typeof t&&t),t.isTrigger=o?2:3,t.namespace=x.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+x.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=i),n=null==n?[t]:w.makeArray(n,[t]),d=w.event.special[m]||{},o||!d.trigger||!1!==d.trigger.apply(i,n))){if(!o&&!d.noBubble&&!y(i)){for(l=d.delegateType||m,wt.test(l+m)||(s=s.parentNode);s;s=s.parentNode)v.push(s),u=s;u===(i.ownerDocument||r)&&v.push(u.defaultView||u.parentWindow||e)}a=0;while((s=v[a++])&&!t.isPropagationStopped())h=s,t.type=a>1?l:d.bindType||m,(p=(J.get(s,"events")||{})[t.type]&&J.get(s,"handle"))&&p.apply(s,n),(p=c&&s[c])&&p.apply&&Y(s)&&(t.result=p.apply(s,n),!1===t.result&&t.preventDefault());return t.type=m,o||t.isDefaultPrevented()||d._default&&!1!==d._default.apply(v.pop(),n)||!Y(i)||c&&g(i[m])&&!y(i)&&((u=i[c])&&(i[c]=null),w.event.triggered=m,t.isPropagationStopped()&&h.addEventListener(m,Tt),i[m](),t.isPropagationStopped()&&h.removeEventListener(m,Tt),w.event.triggered=void 0,u&&(i[c]=u)),t.result}},simulate:function(e,t,n){var r=w.extend(new w.Event,n,{type:e,isSimulated:!0});w.event.trigger(r,null,t)}}),w.fn.extend({trigger:function(e,t){return this.each(function(){w.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return w.event.trigger(e,t,n,!0)}}),h.focusin||w.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){w.event.simulate(t,e.target,w.event.fix(e))};w.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=J.access(r,t);i||r.addEventListener(e,n,!0),J.access(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=J.access(r,t)-1;i?J.access(r,t,i):(r.removeEventListener(e,n,!0),J.remove(r,t))}}});var Ct=e.location,Et=Date.now(),kt=/\?/;w.parseXML=function(t){var n;if(!t||"string"!=typeof t)return null;try{n=(new e.DOMParser).parseFromString(t,"text/xml")}catch(e){n=void 0}return n&&!n.getElementsByTagName("parsererror").length||w.error("Invalid XML: "+t),n};var St=/\[\]$/,Dt=/\r?\n/g,Nt=/^(?:submit|button|image|reset|file)$/i,At=/^(?:input|select|textarea|keygen)/i;function jt(e,t,n,r){var i;if(Array.isArray(t))w.each(t,function(t,i){n||St.test(e)?r(e,i):jt(e+"["+("object"==typeof i&&null!=i?t:"")+"]",i,n,r)});else if(n||"object"!==x(t))r(e,t);else for(i in t)jt(e+"["+i+"]",t[i],n,r)}w.param=function(e,t){var n,r=[],i=function(e,t){var n=g(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(Array.isArray(e)||e.jquery&&!w.isPlainObject(e))w.each(e,function(){i(this.name,this.value)});else for(n in e)jt(n,e[n],t,i);return r.join("&")},w.fn.extend({serialize:function(){return w.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=w.prop(this,"elements");return e?w.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!w(this).is(":disabled")&&At.test(this.nodeName)&&!Nt.test(e)&&(this.checked||!pe.test(e))}).map(function(e,t){var n=w(this).val();return null==n?null:Array.isArray(n)?w.map(n,function(e){return{name:t.name,value:e.replace(Dt,"\r\n")}}):{name:t.name,value:n.replace(Dt,"\r\n")}}).get()}});var qt=/%20/g,Lt=/#.*$/,Ht=/([?&])_=[^&]*/,Ot=/^(.*?):[ \t]*([^\r\n]*)$/gm,Pt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Mt=/^(?:GET|HEAD)$/,Rt=/^\/\//,It={},Wt={},$t="*/".concat("*"),Bt=r.createElement("a");Bt.href=Ct.href;function Ft(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(M)||[];if(g(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function _t(e,t,n,r){var i={},o=e===Wt;function a(s){var u;return i[s]=!0,w.each(e[s]||[],function(e,s){var l=s(t,n,r);return"string"!=typeof l||o||i[l]?o?!(u=l):void 0:(t.dataTypes.unshift(l),a(l),!1)}),u}return a(t.dataTypes[0])||!i["*"]&&a("*")}function zt(e,t){var n,r,i=w.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&w.extend(!0,e,r),e}function Xt(e,t,n){var r,i,o,a,s=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in s)if(s[i]&&s[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}a||(a=i)}o=o||a}if(o)return o!==u[0]&&u.unshift(o),n[o]}function Ut(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(!(a=l[u+" "+o]||l["* "+o]))for(i in l)if((s=i.split(" "))[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){!0===a?a=l[i]:!0!==l[i]&&(o=s[0],c.unshift(s[1]));break}if(!0!==a)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}w.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ct.href,type:"GET",isLocal:Pt.test(Ct.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":$t,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":w.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?zt(zt(e,w.ajaxSettings),t):zt(w.ajaxSettings,e)},ajaxPrefilter:Ft(It),ajaxTransport:Ft(Wt),ajax:function(t,n){"object"==typeof t&&(n=t,t=void 0),n=n||{};var i,o,a,s,u,l,c,f,p,d,h=w.ajaxSetup({},n),g=h.context||h,y=h.context&&(g.nodeType||g.jquery)?w(g):w.event,v=w.Deferred(),m=w.Callbacks("once memory"),x=h.statusCode||{},b={},T={},C="canceled",E={readyState:0,getResponseHeader:function(e){var t;if(c){if(!s){s={};while(t=Ot.exec(a))s[t[1].toLowerCase()]=t[2]}t=s[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return c?a:null},setRequestHeader:function(e,t){return null==c&&(e=T[e.toLowerCase()]=T[e.toLowerCase()]||e,b[e]=t),this},overrideMimeType:function(e){return null==c&&(h.mimeType=e),this},statusCode:function(e){var t;if(e)if(c)E.always(e[E.status]);else for(t in e)x[t]=[x[t],e[t]];return this},abort:function(e){var t=e||C;return i&&i.abort(t),k(0,t),this}};if(v.promise(E),h.url=((t||h.url||Ct.href)+"").replace(Rt,Ct.protocol+"//"),h.type=n.method||n.type||h.method||h.type,h.dataTypes=(h.dataType||"*").toLowerCase().match(M)||[""],null==h.crossDomain){l=r.createElement("a");try{l.href=h.url,l.href=l.href,h.crossDomain=Bt.protocol+"//"+Bt.host!=l.protocol+"//"+l.host}catch(e){h.crossDomain=!0}}if(h.data&&h.processData&&"string"!=typeof h.data&&(h.data=w.param(h.data,h.traditional)),_t(It,h,n,E),c)return E;(f=w.event&&h.global)&&0==w.active++&&w.event.trigger("ajaxStart"),h.type=h.type.toUpperCase(),h.hasContent=!Mt.test(h.type),o=h.url.replace(Lt,""),h.hasContent?h.data&&h.processData&&0===(h.contentType||"").indexOf("application/x-www-form-urlencoded")&&(h.data=h.data.replace(qt,"+")):(d=h.url.slice(o.length),h.data&&(h.processData||"string"==typeof h.data)&&(o+=(kt.test(o)?"&":"?")+h.data,delete h.data),!1===h.cache&&(o=o.replace(Ht,"$1"),d=(kt.test(o)?"&":"?")+"_="+Et+++d),h.url=o+d),h.ifModified&&(w.lastModified[o]&&E.setRequestHeader("If-Modified-Since",w.lastModified[o]),w.etag[o]&&E.setRequestHeader("If-None-Match",w.etag[o])),(h.data&&h.hasContent&&!1!==h.contentType||n.contentType)&&E.setRequestHeader("Content-Type",h.contentType),E.setRequestHeader("Accept",h.dataTypes[0]&&h.accepts[h.dataTypes[0]]?h.accepts[h.dataTypes[0]]+("*"!==h.dataTypes[0]?", "+$t+"; q=0.01":""):h.accepts["*"]);for(p in h.headers)E.setRequestHeader(p,h.headers[p]);if(h.beforeSend&&(!1===h.beforeSend.call(g,E,h)||c))return E.abort();if(C="abort",m.add(h.complete),E.done(h.success),E.fail(h.error),i=_t(Wt,h,n,E)){if(E.readyState=1,f&&y.trigger("ajaxSend",[E,h]),c)return E;h.async&&h.timeout>0&&(u=e.setTimeout(function(){E.abort("timeout")},h.timeout));try{c=!1,i.send(b,k)}catch(e){if(c)throw e;k(-1,e)}}else k(-1,"No Transport");function k(t,n,r,s){var l,p,d,b,T,C=n;c||(c=!0,u&&e.clearTimeout(u),i=void 0,a=s||"",E.readyState=t>0?4:0,l=t>=200&&t<300||304===t,r&&(b=Xt(h,E,r)),b=Ut(h,b,E,l),l?(h.ifModified&&((T=E.getResponseHeader("Last-Modified"))&&(w.lastModified[o]=T),(T=E.getResponseHeader("etag"))&&(w.etag[o]=T)),204===t||"HEAD"===h.type?C="nocontent":304===t?C="notmodified":(C=b.state,p=b.data,l=!(d=b.error))):(d=C,!t&&C||(C="error",t<0&&(t=0))),E.status=t,E.statusText=(n||C)+"",l?v.resolveWith(g,[p,C,E]):v.rejectWith(g,[E,C,d]),E.statusCode(x),x=void 0,f&&y.trigger(l?"ajaxSuccess":"ajaxError",[E,h,l?p:d]),m.fireWith(g,[E,C]),f&&(y.trigger("ajaxComplete",[E,h]),--w.active||w.event.trigger("ajaxStop")))}return E},getJSON:function(e,t,n){return w.get(e,t,n,"json")},getScript:function(e,t){return w.get(e,void 0,t,"script")}}),w.each(["get","post"],function(e,t){w[t]=function(e,n,r,i){return g(n)&&(i=i||r,r=n,n=void 0),w.ajax(w.extend({url:e,type:t,dataType:i,data:n,success:r},w.isPlainObject(e)&&e))}}),w._evalUrl=function(e){return w.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},w.fn.extend({wrapAll:function(e){var t;return this[0]&&(g(e)&&(e=e.call(this[0])),t=w(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(e){return g(e)?this.each(function(t){w(this).wrapInner(e.call(this,t))}):this.each(function(){var t=w(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=g(e);return this.each(function(n){w(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(e){return this.parent(e).not("body").each(function(){w(this).replaceWith(this.childNodes)}),this}}),w.expr.pseudos.hidden=function(e){return!w.expr.pseudos.visible(e)},w.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},w.ajaxSettings.xhr=function(){try{return new e.XMLHttpRequest}catch(e){}};var Vt={0:200,1223:204},Gt=w.ajaxSettings.xhr();h.cors=!!Gt&&"withCredentials"in Gt,h.ajax=Gt=!!Gt,w.ajaxTransport(function(t){var n,r;if(h.cors||Gt&&!t.crossDomain)return{send:function(i,o){var a,s=t.xhr();if(s.open(t.type,t.url,t.async,t.username,t.password),t.xhrFields)for(a in t.xhrFields)s[a]=t.xhrFields[a];t.mimeType&&s.overrideMimeType&&s.overrideMimeType(t.mimeType),t.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(a in i)s.setRequestHeader(a,i[a]);n=function(e){return function(){n&&(n=r=s.onload=s.onerror=s.onabort=s.ontimeout=s.onreadystatechange=null,"abort"===e?s.abort():"error"===e?"number"!=typeof s.status?o(0,"error"):o(s.status,s.statusText):o(Vt[s.status]||s.status,s.statusText,"text"!==(s.responseType||"text")||"string"!=typeof s.responseText?{binary:s.response}:{text:s.responseText},s.getAllResponseHeaders()))}},s.onload=n(),r=s.onerror=s.ontimeout=n("error"),void 0!==s.onabort?s.onabort=r:s.onreadystatechange=function(){4===s.readyState&&e.setTimeout(function(){n&&r()})},n=n("abort");try{s.send(t.hasContent&&t.data||null)}catch(e){if(n)throw e}},abort:function(){n&&n()}}}),w.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),w.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return w.globalEval(e),e}}}),w.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),w.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(i,o){t=w("