diff --git a/.gitignore b/.gitignore
index 210807d09e..e841cc4bf5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,8 +7,11 @@
# Eclipse
.settings/
+*.project
+*.classpath
.prefs
*.prefs
+.metadata/
# Intellij
.idea/
@@ -23,3 +26,4 @@ log/
target/
spring-openid/src/main/resources/application.properties
+.recommenders/
diff --git a/README.md b/README.md
index da46989455..f0d3d29da7 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,7 @@
The "REST with Spring" Classes
==============================
-After 5 months of work, here's the Master Class:
+After 5 months of work, here's the Master Class of REST With Spring:
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
@@ -19,3 +19,8 @@ Any IDE can be used to work with the projects, but if you're using Eclipse, cons
- import the included **formatter** in Eclipse:
`https://github.com/eugenp/tutorials/tree/master/eclipse`
+
+
+CI - Jenkins
+================================
+This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials/)**
diff --git a/assertj/pom.xml b/assertj/pom.xml
new file mode 100644
index 0000000000..ce97278a97
--- /dev/null
+++ b/assertj/pom.xml
@@ -0,0 +1,38 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ assertj
+ 1.0.0-SNAPSHOT
+
+
+
+ junit
+ junit
+ 4.12
+
+
+ org.assertj
+ assertj-core
+ 3.4.1
+ test
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.3
+
+ 1.8
+ 1.8
+
+
+
+
+
\ No newline at end of file
diff --git a/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Dog.java b/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Dog.java
new file mode 100644
index 0000000000..623f71214c
--- /dev/null
+++ b/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Dog.java
@@ -0,0 +1,19 @@
+package com.baeldung.assertj.introduction.domain;
+
+public class Dog {
+ private String name;
+ private Float weight;
+
+ public Dog(String name, Float weight) {
+ this.name = name;
+ this.weight = weight;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Float getWeight() {
+ return weight;
+ }
+}
diff --git a/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Person.java b/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Person.java
new file mode 100644
index 0000000000..90ef787ebe
--- /dev/null
+++ b/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Person.java
@@ -0,0 +1,19 @@
+package com.baeldung.assertj.introduction.domain;
+
+public class Person {
+ private String name;
+ private Integer age;
+
+ public Person(String name, Integer age) {
+ this.name = name;
+ this.age = age;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Integer getAge() {
+ return age;
+ }
+}
diff --git a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java
new file mode 100644
index 0000000000..21bc40ae9f
--- /dev/null
+++ b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java
@@ -0,0 +1,143 @@
+package com.baeldung.assertj.introduction;
+
+import com.baeldung.assertj.introduction.domain.Dog;
+import com.baeldung.assertj.introduction.domain.Person;
+import org.assertj.core.util.Maps;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.entry;
+import static org.assertj.core.api.Assertions.withPrecision;
+
+public class AssertJCoreTest {
+
+ @Test
+ public void whenComparingReferences_thenNotEqual() throws Exception {
+ Dog fido = new Dog("Fido", 5.15f);
+ Dog fidosClone = new Dog("Fido", 5.15f);
+
+ assertThat(fido).isNotEqualTo(fidosClone);
+ }
+
+ @Test
+ public void whenComparingFields_thenEqual() throws Exception {
+ Dog fido = new Dog("Fido", 5.15f);
+ Dog fidosClone = new Dog("Fido", 5.15f);
+
+ assertThat(fido).isEqualToComparingFieldByFieldRecursively(fidosClone);
+ }
+
+ @Test
+ public void whenCheckingForElement_thenContains() throws Exception {
+ List list = Arrays.asList("1", "2", "3");
+
+ assertThat(list)
+ .contains("1");
+ }
+
+ @Test
+ public void whenCheckingForElement_thenMultipleAssertions() throws Exception {
+ List list = Arrays.asList("1", "2", "3");
+
+ assertThat(list).isNotEmpty();
+ assertThat(list).startsWith("1");
+ assertThat(list).doesNotContainNull();
+
+ assertThat(list)
+ .isNotEmpty()
+ .contains("1")
+ .startsWith("1")
+ .doesNotContainNull()
+ .containsSequence("2", "3");
+ }
+
+ @Test
+ public void whenCheckingRunnable_thenIsInterface() throws Exception {
+ assertThat(Runnable.class).isInterface();
+ }
+
+ @Test
+ public void whenCheckingCharacter_thenIsUnicode() throws Exception {
+ char someCharacter = 'c';
+
+ assertThat(someCharacter)
+ .isNotEqualTo('a')
+ .inUnicode()
+ .isGreaterThanOrEqualTo('b')
+ .isLowerCase();
+ }
+
+ @Test
+ public void whenAssigningNSEExToException_thenIsAssignable() throws Exception {
+ assertThat(Exception.class).isAssignableFrom(NoSuchElementException.class);
+ }
+
+ @Test
+ public void whenComparingWithOffset_thenEquals() throws Exception {
+ assertThat(5.1).isEqualTo(5, withPrecision(1d));
+ }
+
+ @Test
+ public void whenCheckingString_then() throws Exception {
+ assertThat("".isEmpty()).isTrue();
+ }
+
+ @Test
+ public void whenCheckingFile_then() throws Exception {
+ final File someFile = File.createTempFile("aaa", "bbb");
+ someFile.deleteOnExit();
+
+ assertThat(someFile)
+ .exists()
+ .isFile()
+ .canRead()
+ .canWrite();
+ }
+
+ @Test
+ public void whenCheckingIS_then() throws Exception {
+ InputStream given = new ByteArrayInputStream("foo".getBytes());
+ InputStream expected = new ByteArrayInputStream("foo".getBytes());
+
+ assertThat(given).hasSameContentAs(expected);
+ }
+
+ @Test
+ public void whenGivenMap_then() throws Exception {
+ Map map = Maps.newHashMap(2, "a");
+
+ assertThat(map)
+ .isNotEmpty()
+ .containsKey(2)
+ .doesNotContainKeys(10)
+ .contains(entry(2, "a"));
+ }
+
+ @Test
+ public void whenGivenException_then() throws Exception {
+ Exception ex = new Exception("abc");
+
+ assertThat(ex)
+ .hasNoCause()
+ .hasMessageEndingWith("c");
+ }
+
+ @Ignore // IN ORDER TO TEST, REMOVE THIS LINE
+ @Test
+ public void whenRunningAssertion_thenDescribed() throws Exception {
+ Person person = new Person("Alex", 34);
+
+ assertThat(person.getAge())
+ .as("%s's age should be equal to 100")
+ .isEqualTo(100);
+ }
+}
diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml
index 0e589ebf47..8c9bb36f7d 100644
--- a/core-java-8/pom.xml
+++ b/core-java-8/pom.xml
@@ -41,6 +41,12 @@
3.3.2
+
+ org.slf4j
+ slf4j-api
+ ${org.slf4j.version}
+
+
@@ -57,6 +63,12 @@
test
+
+ org.assertj
+ assertj-core
+ 3.4.1
+
+
org.mockito
mockito-core
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java b/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java
new file mode 100644
index 0000000000..125b6fbe38
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java
@@ -0,0 +1,16 @@
+package com.baeldung.datetime;
+
+import java.time.Duration;
+import java.time.LocalTime;
+import java.time.Period;
+
+public class UseDuration {
+
+ public LocalTime modifyDates(LocalTime localTime,Duration duration){
+ return localTime.plus(duration);
+ }
+
+ public Duration getDifferenceBetweenDates(LocalTime localTime1,LocalTime localTime2){
+ return Duration.between(localTime1, localTime2);
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java
new file mode 100644
index 0000000000..47b1b3f67d
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java
@@ -0,0 +1,46 @@
+package com.baeldung.datetime;
+
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.temporal.ChronoUnit;
+import java.time.temporal.TemporalAdjusters;
+
+public class UseLocalDate {
+
+ public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth){
+ return LocalDate.of(year, month, dayOfMonth);
+ }
+
+ public LocalDate getLocalDateUsingParseMethod(String representation){
+ return LocalDate.parse(representation);
+ }
+
+ public LocalDate getLocalDateFromClock(){
+ LocalDate localDate = LocalDate.now();
+ return localDate;
+ }
+
+ public LocalDate getNextDay(LocalDate localDate){
+ return localDate.plusDays(1);
+ }
+
+ public LocalDate getPreviousDay(LocalDate localDate){
+ return localDate.minus(1, ChronoUnit.DAYS);
+ }
+
+ public DayOfWeek getDayOfWeek(LocalDate localDate){
+ DayOfWeek day = localDate.getDayOfWeek();
+ return day;
+ }
+
+ public LocalDate getFirstDayOfMonth(){
+ LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
+ return firstDayOfMonth;
+ }
+
+ public LocalDateTime getStartOfDay(LocalDate localDate){
+ LocalDateTime startofDay = localDate.atStartOfDay();
+ return startofDay;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java
new file mode 100644
index 0000000000..7aa1eaa276
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java
@@ -0,0 +1,11 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDateTime;
+
+public class UseLocalDateTime {
+
+ public LocalDateTime getLocalDateTimeUsingParseMethod(String representation){
+ return LocalDateTime.parse(representation);
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java
new file mode 100644
index 0000000000..e13fd10d6f
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java
@@ -0,0 +1,35 @@
+package com.baeldung.datetime;
+
+import java.time.LocalTime;
+import java.time.temporal.ChronoUnit;
+
+public class UseLocalTime {
+
+ public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds){
+ LocalTime localTime = LocalTime.of(hour, min, seconds);
+ return localTime;
+ }
+
+ public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation){
+ LocalTime localTime = LocalTime.parse(timeRepresentation);
+ return localTime;
+ }
+
+ public LocalTime getLocalTimeFromClock(){
+ LocalTime localTime = LocalTime.now();
+ return localTime;
+ }
+
+ public LocalTime addAnHour(LocalTime localTime){
+ LocalTime newTime = localTime.plus(1,ChronoUnit.HOURS);
+ return newTime;
+ }
+
+ public int getHourFromLocalTime(LocalTime localTime){
+ return localTime.getHour();
+ }
+
+ public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute){
+ return localTime.withMinute(minute);
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java b/core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java
new file mode 100644
index 0000000000..326cfad650
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java
@@ -0,0 +1,15 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDate;
+import java.time.Period;
+
+public class UsePeriod {
+
+ public LocalDate modifyDates(LocalDate localDate,Period period){
+ return localDate.plus(period);
+ }
+
+ public Period getDifferenceBetweenDates(LocalDate localDate1,LocalDate localDate2){
+ return Period.between(localDate1, localDate2);
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java b/core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java
new file mode 100644
index 0000000000..1ddb096cf6
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java
@@ -0,0 +1,19 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.util.Calendar;
+import java.util.Date;
+
+public class UseToInstant {
+
+ public LocalDateTime convertDateToLocalDate(Date date){
+ LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
+ return localDateTime;
+ }
+
+ public LocalDateTime convertDateToLocalDate(Calendar calendar){
+ LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
+ return localDateTime;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java
new file mode 100644
index 0000000000..0369de9835
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java
@@ -0,0 +1,13 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+
+public class UseZonedDateTime {
+
+ public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime,ZoneId zoneId){
+ ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
+ return zonedDateTime;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/streamApi/Product.java b/core-java-8/src/main/java/com/baeldung/streamApi/Product.java
new file mode 100644
index 0000000000..18f3a61904
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/streamApi/Product.java
@@ -0,0 +1,51 @@
+package com.baeldung.streamApi;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+/**
+ * Created by Alex Vengr
+ */
+public class Product {
+
+ private int price;
+
+ private String name;
+
+ private boolean utilize;
+
+ public Product(int price, String name) {
+ this(price);
+ this.name = name;
+ }
+
+ public Product(int price) {
+ this.price = price;
+ }
+
+ public Product() {
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public void setPrice(int price) {
+ this.price = price;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+
+ public static Stream streamOf(List list) {
+ return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java b/core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java
new file mode 100644
index 0000000000..a543c80eaf
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java
@@ -0,0 +1,19 @@
+package com.baeldung.dateapi;
+
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.TimeZone;
+
+public class ConversionExample {
+ public static void main(String[] args) {
+ Instant instantFromCalendar = GregorianCalendar.getInstance().toInstant();
+ ZonedDateTime zonedDateTimeFromCalendar = new GregorianCalendar().toZonedDateTime();
+ Date dateFromInstant = Date.from(Instant.now());
+ GregorianCalendar calendarFromZonedDateTime = GregorianCalendar.from(ZonedDateTime.now());
+ Instant instantFromDate = new Date().toInstant();
+ ZoneId zoneIdFromTimeZone = TimeZone.getTimeZone("PST").toZoneId();
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java b/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java
new file mode 100644
index 0000000000..4bce40c2d9
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java
@@ -0,0 +1,89 @@
+package com.baeldung.dateapi;
+
+import org.junit.Test;
+
+import java.text.ParseException;
+import java.time.Duration;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.Month;
+import java.time.YearMonth;
+import java.time.format.DateTimeFormatter;
+import java.time.temporal.ChronoUnit;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class JavaUtilTimeTest {
+
+ @Test
+ public void currentTime() {
+ final LocalDate now = LocalDate.now();
+
+ System.out.println(now);
+ // there is not much to test here
+ }
+
+ @Test
+ public void specificTime() {
+ LocalDate birthDay = LocalDate.of(1990, Month.DECEMBER, 15);
+
+ System.out.println(birthDay);
+ // there is not much to test here
+ }
+
+ @Test
+ public void extractMonth() {
+ Month month = LocalDate.of(1990, Month.DECEMBER, 15).getMonth();
+
+ assertThat(month).isEqualTo(Month.DECEMBER);
+ }
+
+ @Test
+ public void subtractTime() {
+ LocalDateTime fiveHoursBefore = LocalDateTime.of(1990, Month.DECEMBER, 15, 15, 0).minusHours(5);
+
+ assertThat(fiveHoursBefore.getHour()).isEqualTo(10);
+ }
+
+ @Test
+ public void alterField() {
+ LocalDateTime inJune = LocalDateTime.of(1990, Month.DECEMBER, 15, 15, 0).with(Month.JUNE);
+
+ assertThat(inJune.getMonth()).isEqualTo(Month.JUNE);
+ }
+
+ @Test
+ public void truncate() {
+ LocalTime truncated = LocalTime.of(15, 12, 34).truncatedTo(ChronoUnit.HOURS);
+
+ assertThat(truncated).isEqualTo(LocalTime.of(15, 0, 0));
+ }
+
+ @Test
+ public void getTimeSpan() {
+ LocalDateTime now = LocalDateTime.now();
+ LocalDateTime hourLater = now.plusHours(1);
+ Duration span = Duration.between(now, hourLater);
+
+ assertThat(span).isEqualTo(Duration.ofHours(1));
+ }
+
+ @Test
+ public void formatAndParse() throws ParseException {
+ LocalDate someDate = LocalDate.of(2016, 12, 7);
+ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
+ String formattedDate = someDate.format(formatter);
+ LocalDate parsedDate = LocalDate.parse(formattedDate, formatter);
+
+ assertThat(formattedDate).isEqualTo("2016-12-07");
+ assertThat(parsedDate).isEqualTo(someDate);
+ }
+
+ @Test
+ public void daysInMonth() {
+ int daysInMonth = YearMonth.of(1990, 2).lengthOfMonth();
+
+ assertThat(daysInMonth).isEqualTo(28);
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTest.java
new file mode 100644
index 0000000000..8af33393be
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTest.java
@@ -0,0 +1,55 @@
+package com.baeldung.datetime;
+
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.Month;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UseLocalDateTest {
+
+ UseLocalDate useLocalDate = new UseLocalDate();
+
+ @Test
+ public void givenValues_whenUsingFactoryOf_thenLocalDate(){
+ Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingFactoryOfMethod(2016,5,10).toString());
+ }
+
+ @Test
+ public void givenString_whenUsingParse_thenLocalDate(){
+ Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
+ }
+
+ @Test
+ public void whenUsingClock_thenLocalDate(){
+ Assert.assertEquals(LocalDate.now(),useLocalDate.getLocalDateFromClock());
+ }
+
+ @Test
+ public void givenDate_whenUsingPlus_thenNextDay(){
+ Assert.assertEquals(LocalDate.now().plusDays(1),useLocalDate.getNextDay(LocalDate.now()));
+ }
+
+ @Test
+ public void givenDate_whenUsingMinus_thenPreviousDay(){
+ Assert.assertEquals(LocalDate.now().minusDays(1),useLocalDate.getPreviousDay(LocalDate.now()));
+ }
+
+ @Test
+ public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek(){
+ Assert.assertEquals(DayOfWeek.SUNDAY,useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
+ }
+
+ @Test
+ public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth(){
+ Assert.assertEquals(1,useLocalDate.getFirstDayOfMonth().getDayOfMonth());
+ }
+
+ @Test
+ public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight(){
+ Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"),useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeTest.java
new file mode 100644
index 0000000000..69a289fd02
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDate;
+import java.time.LocalTime;
+import java.time.Month;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UseLocalDateTimeTest {
+
+ UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
+
+ @Test
+ public void givenString_whenUsingParse_thenLocalDateTime(){
+ Assert.assertEquals(LocalDate.of(2016, Month.MAY, 10),useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
+ Assert.assertEquals(LocalTime.of(6,30),useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeTest.java
new file mode 100644
index 0000000000..7776fad363
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeTest.java
@@ -0,0 +1,36 @@
+package com.baeldung.datetime;
+
+import java.time.LocalTime;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UseLocalTimeTest {
+
+ UseLocalTime useLocalTime = new UseLocalTime();
+
+ @Test
+ public void givenValues_whenUsingFactoryOf_thenLocalTime(){
+ Assert.assertEquals("07:07:07",useLocalTime.getLocalTimeUsingFactoryOfMethod(7,7,7).toString());
+ }
+
+ @Test
+ public void givenString_whenUsingParse_thenLocalTime(){
+ Assert.assertEquals("06:30",useLocalTime.getLocalTimeUsingParseMethod("06:30").toString());
+ }
+
+ @Test
+ public void givenTime_whenAddHour_thenLocalTime(){
+ Assert.assertEquals("07:30",useLocalTime.addAnHour(LocalTime.of(6,30)).toString());
+ }
+
+ @Test
+ public void getHourFromLocalTime(){
+ Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1,1)));
+ }
+
+ @Test
+ public void getLocalTimeWithMinuteSetToValue(){
+ Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10,10), 20));
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java
new file mode 100644
index 0000000000..8a3228aaa5
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java
@@ -0,0 +1,29 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.Period;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UsePeriodTest {
+ UsePeriod usingPeriod=new UsePeriod();
+
+ @Test
+ public void givenPeriodAndLocalDate_thenCalculateModifiedDate(){
+ Period period = Period.ofDays(1);
+ LocalDate localDate = LocalDate.parse("2007-05-10");
+ Assert.assertEquals(localDate.plusDays(1),usingPeriod.modifyDates(localDate, period));
+ }
+
+ @Test
+ public void givenDates_thenGetPeriod(){
+ LocalDate localDate1 = LocalDate.parse("2007-05-10");
+ LocalDate localDate2 = LocalDate.parse("2007-05-15");
+
+ Assert.assertEquals(Period.ofDays(5), usingPeriod.getDifferenceBetweenDates(localDate1, localDate2));
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java
new file mode 100644
index 0000000000..5af01ad678
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java
@@ -0,0 +1,20 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UseZonedDateTimeTest {
+
+ UseZonedDateTime zonedDateTime=new UseZonedDateTime();
+
+ @Test
+ public void givenZoneId_thenZonedDateTime(){
+ ZoneId zoneId=ZoneId.of("Europe/Paris");
+ ZonedDateTime zonedDatetime=zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId);
+ Assert.assertEquals(zoneId,ZoneId.from(zonedDatetime));
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java
new file mode 100644
index 0000000000..37326c6d26
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java
@@ -0,0 +1,263 @@
+package com.baeldung.java8;
+
+import com.baeldung.streamApi.Product;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.*;
+import java.util.regex.Pattern;
+import java.util.stream.*;
+
+import static org.junit.Assert.*;
+
+public class Java8StreamApiTest {
+
+ private long counter;
+
+ private static Logger log = LoggerFactory.getLogger(Java8StreamApiTest.class);
+
+ private List productList;
+
+ @Before
+ public void init() {
+ productList = Arrays.asList(
+ new Product(23, "potatoes"), new Product(14, "orange"),
+ new Product(13, "lemon"), new Product(23, "bread"),
+ new Product(13, "sugar"));
+ }
+
+ @Test
+ public void checkPipeline_whenStreamOneElementShorter_thenCorrect() {
+
+ List list = Arrays.asList("abc1", "abc2", "abc3");
+ long size = list.stream().skip(1)
+ .map(element -> element.substring(0, 3)).count();
+ assertEquals(list.size() - 1, size);
+ }
+
+ @Test
+ public void checkOrder_whenChangeQuantityOfMethodCalls_thenCorrect() {
+
+ List list = Arrays.asList("abc1", "abc2", "abc3");
+
+ counter = 0;
+ long sizeFirst = list.stream()
+ .skip(2).map(element -> {
+ wasCalled();
+ return element.substring(0, 3);
+ }).count();
+ assertEquals(1, counter);
+
+ counter = 0;
+ long sizeSecond = list.stream().map(element -> {
+ wasCalled();
+ return element.substring(0, 3);
+ }).skip(2).count();
+ assertEquals(3, counter);
+ }
+
+ @Test
+ public void createEmptyStream_whenEmpty_thenCorrect() {
+
+ Stream streamEmpty = Stream.empty();
+ assertEquals(0, streamEmpty.count());
+
+ List names = Collections.emptyList();
+ Stream streamOf = Product.streamOf(names);
+ assertTrue(streamOf.count() == 0);
+ }
+
+ @Test
+ public void createStream_whenCreated_thenCorrect() {
+
+ Collection collection = Arrays.asList("a", "b", "c");
+ Stream streamOfCollection = collection.stream();
+ assertEquals(3, streamOfCollection.count());
+
+ Stream streamOfArray = Stream.of("a", "b", "c");
+ assertEquals(3, streamOfArray.count());
+
+ String[] arr = new String[]{"a", "b", "c"};
+ Stream streamOfArrayPart = Arrays.stream(arr, 1, 3);
+ assertEquals(2, streamOfArrayPart.count());
+
+ IntStream intStream = IntStream.range(1, 3);
+ LongStream longStream = LongStream.rangeClosed(1, 3);
+ Random random = new Random();
+ DoubleStream doubleStream = random.doubles(3);
+ assertEquals(2, intStream.count());
+ assertEquals(3, longStream.count());
+ assertEquals(3, doubleStream.count());
+
+ IntStream streamOfChars = "abc".chars();
+ IntStream str = "".chars();
+ assertEquals(3, streamOfChars.count());
+
+ Stream streamOfString = Pattern.compile(", ").splitAsStream("a, b, c");
+ assertEquals("a", streamOfString.findFirst().get());
+
+ Path path = getPath();
+ Stream streamOfStrings = null;
+ try {
+ streamOfStrings = Files.lines(path, Charset.forName("UTF-8"));
+ } catch (IOException e) {
+ log.error("Error creating streams from paths {}", path, e.getMessage(), e);
+ }
+ assertEquals("a", streamOfStrings.findFirst().get());
+
+ Stream streamBuilder = Stream.builder().add("a").add("b").add("c").build();
+ assertEquals(3, streamBuilder.count());
+
+ Stream streamGenerated = Stream.generate(() -> "element").limit(10);
+ assertEquals(10, streamGenerated.count());
+
+ Stream streamIterated = Stream.iterate(40, n -> n + 2).limit(20);
+ assertTrue(40 <= streamIterated.findAny().get());
+ }
+
+ @Test
+ public void runStreamPipeline_whenOrderIsRight_thenCorrect() {
+
+ List list = Arrays.asList("abc1", "abc2", "abc3");
+ Optional stream = list.stream()
+ .filter(element -> {
+ log.info("filter() was called");
+ return element.contains("2");
+ }).map(element -> {
+ log.info("map() was called");
+ return element.toUpperCase();
+ }).findFirst();
+ }
+
+ @Test
+ public void reduce_whenExpected_thenCorrect() {
+
+ OptionalInt reduced = IntStream.range(1, 4).reduce((a, b) -> a + b);
+ assertEquals(6, reduced.getAsInt());
+
+ int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b);
+ assertEquals(16, reducedTwoParams);
+
+ int reducedThreeParams = Stream.of(1, 2, 3)
+ .reduce(10, (a, b) -> a + b, (a, b) -> {
+ log.info("combiner was called");
+ return a + b;
+ });
+ assertEquals(16, reducedThreeParams);
+
+ int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream()
+ .reduce(10, (a, b) -> a + b, (a, b) -> {
+ log.info("combiner was called");
+ return a + b;
+ });
+ assertEquals(36, reducedThreeParamsParallel);
+ }
+
+ @Test
+ public void collecting_whenAsExpected_thenCorrect() {
+
+ List collectorCollection = productList.stream()
+ .map(Product::getName).collect(Collectors.toList());
+
+ assertTrue(collectorCollection instanceof List);
+ assertEquals(5, collectorCollection.size());
+
+ String listToString = productList.stream().map(Product::getName)
+ .collect(Collectors.joining(", ", "[", "]"));
+
+ assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]"));
+
+ double averagePrice = productList.stream().collect(Collectors.averagingInt(Product::getPrice));
+ assertTrue(17.2 == averagePrice);
+
+ int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice));
+ assertEquals(86, summingPrice);
+
+ IntSummaryStatistics statistics = productList.stream()
+ .collect(Collectors.summarizingInt(Product::getPrice));
+ assertEquals(23, statistics.getMax());
+
+ Map> collectorMapOfLists = productList.stream()
+ .collect(Collectors.groupingBy(Product::getPrice));
+ assertEquals(3, collectorMapOfLists.keySet().size());
+
+ Map> mapPartioned = productList.stream()
+ .collect(Collectors.partitioningBy(element -> element.getPrice() > 15));
+ assertEquals(2, mapPartioned.keySet().size());
+
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void collect_whenThrows_thenCorrect() {
+ Set unmodifiableSet = productList.stream()
+ .collect(Collectors.collectingAndThen(Collectors.toSet(),
+ Collections::unmodifiableSet));
+ unmodifiableSet.add(new Product(4, "tea"));
+ }
+
+ @Test
+ public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() {
+ Collector> toLinkedList =
+ Collector.of(LinkedList::new, LinkedList::add,
+ (first, second) -> {
+ first.addAll(second);
+ return first;
+ });
+
+ LinkedList linkedListOfPersons = productList.stream().collect(toLinkedList);
+ assertTrue(linkedListOfPersons.containsAll(productList));
+ }
+
+ @Test
+ public void parallelStream_whenWorks_thenCorrect() {
+ Stream streamOfCollection = productList.parallelStream();
+ boolean isParallel = streamOfCollection.isParallel();
+ boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12)
+ .anyMatch(price -> price > 200);
+ assertTrue(isParallel && haveBigPrice);
+ }
+
+ @Test
+ public void parallel_whenIsParallel_thenCorrect() {
+ IntStream intStreamParallel =
+ IntStream.range(1, 150).parallel().map(element -> element * 34);
+ boolean isParallel = intStreamParallel.isParallel();
+ assertTrue(isParallel);
+ }
+
+ @Test
+ public void parallel_whenIsSequential_thenCorrect() {
+ IntStream intStreamParallel =
+ IntStream.range(1, 150).parallel().map(element -> element * 34);
+ IntStream intStreamSequential = intStreamParallel.sequential();
+ boolean isParallel = intStreamParallel.isParallel();
+ assertFalse(isParallel);
+ }
+
+ private Path getPath() {
+ Path path = null;
+ try {
+ path = Files.createTempFile(null, ".txt");
+ } catch (IOException e) {
+ log.error(e.getMessage());
+ }
+
+ try (BufferedWriter writer = Files.newBufferedWriter(path)) {
+ writer.write("a\nb\nc");
+ } catch (IOException e) {
+ log.error(e.getMessage());
+ }
+ return path;
+ }
+
+ private void wasCalled() {
+ counter++;
+ }
+}
diff --git a/core-java/.classpath b/core-java/.classpath
index f9b079e8c9..ca829f1262 100644
--- a/core-java/.classpath
+++ b/core-java/.classpath
@@ -27,7 +27,7 @@
-
+
diff --git a/core-java/.settings/org.eclipse.jdt.core.prefs b/core-java/.settings/org.eclipse.jdt.core.prefs
index 046168cf24..1882edb712 100644
--- a/core-java/.settings/org.eclipse.jdt.core.prefs
+++ b/core-java/.settings/org.eclipse.jdt.core.prefs
@@ -6,8 +6,13 @@ org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annota
org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
-org.eclipse.jdt.core.compiler.compliance=1.7
+org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.8
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
@@ -92,4 +97,4 @@ org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore
org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.7
+org.eclipse.jdt.core.compiler.source=1.8
diff --git a/core-java/.settings/org.eclipse.wst.common.project.facet.core.xml b/core-java/.settings/org.eclipse.wst.common.project.facet.core.xml
index bc0009a455..f4ef8aa0a5 100644
--- a/core-java/.settings/org.eclipse.wst.common.project.facet.core.xml
+++ b/core-java/.settings/org.eclipse.wst.common.project.facet.core.xml
@@ -1,4 +1,4 @@
-
+
diff --git a/core-java/pom.xml b/core-java/pom.xml
index 39cb79a86a..cb194a6d9f 100644
--- a/core-java/pom.xml
+++ b/core-java/pom.xml
@@ -126,8 +126,8 @@
maven-compiler-plugin
${maven-compiler-plugin.version}
- 1.7
- 1.7
+ 1.8
+ 1.8
diff --git a/core-java/src/main/java/com/baeldung/enums/Pizza.java b/core-java/src/main/java/com/baeldung/enums/Pizza.java
index b1c90b42cf..7742781081 100644
--- a/core-java/src/main/java/com/baeldung/enums/Pizza.java
+++ b/core-java/src/main/java/com/baeldung/enums/Pizza.java
@@ -3,37 +3,36 @@ package com.baeldung.enums;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
-import org.apache.commons.collections15.CollectionUtils;
import org.apache.commons.collections15.Predicate;
import java.io.IOException;
-import java.util.ArrayList;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.List;
+import java.util.stream.Collectors;
public class Pizza {
- private static EnumSet undeliveredPizzaStatuses =
- EnumSet.of(PizzaStatusEnum.ORDERED, PizzaStatusEnum.READY);
+ private static EnumSet undeliveredPizzaStatuses =
+ EnumSet.of(PizzaStatus.ORDERED, PizzaStatus.READY);
- private PizzaStatusEnum status;
+ private PizzaStatus status;
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
- public enum PizzaStatusEnum {
- ORDERED (5){
+ public enum PizzaStatus {
+ ORDERED(5) {
@Override
public boolean isOrdered() {
return true;
}
},
- READY (2){
+ READY(2) {
@Override
public boolean isReady() {
return true;
}
},
- DELIVERED (0){
+ DELIVERED(0) {
@Override
public boolean isDelivered() {
return true;
@@ -42,26 +41,33 @@ public class Pizza {
private int timeToDelivery;
- public boolean isOrdered() {return false;}
+ public boolean isOrdered() {
+ return false;
+ }
- public boolean isReady() {return false;}
+ public boolean isReady() {
+ return false;
+ }
+
+ public boolean isDelivered() {
+ return false;
+ }
- public boolean isDelivered(){return false;}
@JsonProperty("timeToDelivery")
public int getTimeToDelivery() {
return timeToDelivery;
}
- private PizzaStatusEnum (int timeToDelivery) {
+ PizzaStatus(int timeToDelivery) {
this.timeToDelivery = timeToDelivery;
}
}
- public PizzaStatusEnum getStatus() {
+ public PizzaStatus getStatus() {
return status;
}
- public void setStatus(PizzaStatusEnum status) {
+ public void setStatus(PizzaStatus status) {
this.status = status;
}
@@ -73,32 +79,23 @@ public class Pizza {
System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");
}
- public static List getAllUndeliveredPizza(List input) {
- List undelivered = input;
- CollectionUtils.filter(undelivered, thatAreNotDelivered());
- return undelivered;
+ public static List getAllUndeliveredPizzas(List input) {
+ return input.stream().filter(
+ (s) -> undeliveredPizzaStatuses.contains(s.getStatus()))
+ .collect(Collectors.toList());
}
- public static EnumMap> groupPizzaByStatus(List pizzaList) {
- EnumMap> pzByStatus = new EnumMap>(PizzaStatusEnum.class);
- for (Pizza pz : pizzaList) {
- PizzaStatusEnum status = pz.getStatus();
-
- if (pzByStatus.containsKey(status)) {
- pzByStatus.get(status).add(pz);
- } else {
- List newPzList = new ArrayList();
- newPzList.add(pz);
- pzByStatus.put(status, newPzList);
- }
- }
- return pzByStatus;
+ public static EnumMap>
+ groupPizzaByStatus(List pzList) {
+ return pzList.stream().collect(
+ Collectors.groupingBy(Pizza::getStatus,
+ () -> new EnumMap<>(PizzaStatus.class), Collectors.toList()));
}
public void deliver() {
if (isDeliverable()) {
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
- this.setStatus(PizzaStatusEnum.DELIVERED);
+ this.setStatus(PizzaStatus.DELIVERED);
}
}
@@ -108,10 +105,6 @@ public class Pizza {
}
private static Predicate thatAreNotDelivered() {
- return new Predicate() {
- public boolean evaluate(Pizza entry) {
- return undeliveredPizzaStatuses.contains(entry.getStatus());
- }
- };
+ return entry -> undeliveredPizzaStatuses.contains(entry.getStatus());
}
}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java b/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java
index 9210945783..a276b3c000 100644
--- a/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java
+++ b/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java
@@ -1,9 +1,10 @@
package com.baeldung.enums;
public enum PizzaDeliverySystemConfiguration {
- INSTANCE ;
- private PizzaDeliverySystemConfiguration() {
- //Do the configuration initialization which
+ INSTANCE;
+
+ PizzaDeliverySystemConfiguration() {
+ // Do the configuration initialization which
// involves overriding defaults like delivery strategy
}
diff --git a/core-java/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java b/core-java/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java
index 95b79810cd..a5f684a141 100644
--- a/core-java/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java
+++ b/core-java/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java
@@ -31,7 +31,7 @@ public class JavaCollectionConversionUnitTest {
@Test
public final void givenUsingCoreJava_whenListConvertedToArray_thenCorrect() {
- final List sourceList = Lists. newArrayList(0, 1, 2, 3, 4, 5);
+ final List sourceList = Arrays.asList(0, 1, 2, 3, 4, 5);
final Integer[] targetArray = sourceList.toArray(new Integer[sourceList.size()]);
}
diff --git a/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java b/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java
index 9f6a8feae5..a6814ee600 100644
--- a/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java
+++ b/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java
@@ -15,66 +15,66 @@ public class PizzaTest {
@Test
public void givenPizaOrder_whenReady_thenDeliverable() {
Pizza testPz = new Pizza();
- testPz.setStatus(Pizza.PizzaStatusEnum.READY);
+ testPz.setStatus(Pizza.PizzaStatus.READY);
assertTrue(testPz.isDeliverable());
}
@Test
public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
- List pzList = new ArrayList();
+ List pzList = new ArrayList<>();
Pizza pz1 = new Pizza();
- pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
+ pz1.setStatus(Pizza.PizzaStatus.DELIVERED);
Pizza pz2 = new Pizza();
- pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
+ pz2.setStatus(Pizza.PizzaStatus.ORDERED);
Pizza pz3 = new Pizza();
- pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
+ pz3.setStatus(Pizza.PizzaStatus.ORDERED);
Pizza pz4 = new Pizza();
- pz4.setStatus(Pizza.PizzaStatusEnum.READY);
+ pz4.setStatus(Pizza.PizzaStatus.READY);
pzList.add(pz1);
pzList.add(pz2);
pzList.add(pz3);
pzList.add(pz4);
- List undeliveredPzs = Pizza.getAllUndeliveredPizza(pzList);
+ List undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
assertTrue(undeliveredPzs.size() == 3);
}
@Test
public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
- List pzList = new ArrayList();
+ List pzList = new ArrayList<>();
Pizza pz1 = new Pizza();
- pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
+ pz1.setStatus(Pizza.PizzaStatus.DELIVERED);
Pizza pz2 = new Pizza();
- pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
+ pz2.setStatus(Pizza.PizzaStatus.ORDERED);
Pizza pz3 = new Pizza();
- pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
+ pz3.setStatus(Pizza.PizzaStatus.ORDERED);
Pizza pz4 = new Pizza();
- pz4.setStatus(Pizza.PizzaStatusEnum.READY);
+ pz4.setStatus(Pizza.PizzaStatus.READY);
pzList.add(pz1);
pzList.add(pz2);
pzList.add(pz3);
pzList.add(pz4);
- EnumMap> map = Pizza.groupPizzaByStatus(pzList);
- assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1);
- assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2);
- assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1);
+ EnumMap> map = Pizza.groupPizzaByStatus(pzList);
+ assertTrue(map.get(Pizza.PizzaStatus.DELIVERED).size() == 1);
+ assertTrue(map.get(Pizza.PizzaStatus.ORDERED).size() == 2);
+ assertTrue(map.get(Pizza.PizzaStatus.READY).size() == 1);
}
@Test
public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
Pizza pz = new Pizza();
- pz.setStatus(Pizza.PizzaStatusEnum.READY);
+ pz.setStatus(Pizza.PizzaStatus.READY);
pz.deliver();
- assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
+ assertTrue(pz.getStatus() == Pizza.PizzaStatus.DELIVERED);
}
}
diff --git a/dependency-injection/.gitignore b/dependency-injection/.gitignore
new file mode 100644
index 0000000000..6531dfc93f
--- /dev/null
+++ b/dependency-injection/.gitignore
@@ -0,0 +1,12 @@
+RemoteSystemsTempFiles/
+.classpath
+.project
+.settings/
+bin/
+.metadata/
+docs/*.autosave
+docs/*.autosave
+.recommenders/
+build/
+.gradle/
+.DS_Store
diff --git a/dependency-injection/pom.xml b/dependency-injection/pom.xml
new file mode 100644
index 0000000000..667ea87402
--- /dev/null
+++ b/dependency-injection/pom.xml
@@ -0,0 +1,83 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ dependency-injection
+ 0.0.1-SNAPSHOT
+ war
+
+ Resource vs Inject vs Autowired
+ Accompanying the demonstration of the use of the annotations related to injection mechanisms, namely
+ Resource, Inject, and Autowired
+
+
+
+
+ junit
+ junit
+ 4.11
+ test
+
+
+ org.mockito
+ mockito-all
+ 1.10.19
+
+
+ org.springframework
+ spring-test
+ 4.2.6.RELEASE
+
+
+ org.springframework
+ spring-core
+ 4.2.6.RELEASE
+
+
+ org.springframework
+ spring-beans
+ 4.2.6.RELEASE
+
+
+ org.springframework
+ spring-context
+ 4.2.6.RELEASE
+
+
+ javax.inject
+ javax.inject
+ 1
+
+
+
+
+
+
+ maven-compiler-plugin
+
+ 1.8
+ 1.8
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ **/*Test.java
+
+
+
+
+
+
+
+
+ java.net
+ https://maven.java.net/content/repositories/releases/
+
+
+
diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java b/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java
new file mode 100644
index 0000000000..48c4495465
--- /dev/null
+++ b/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredName.java
@@ -0,0 +1,9 @@
+package com.baeldung.configuration;
+
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ComponentScan(basePackages = {"com.baeldung.dependency"})
+public class ApplicationContextTestAutowiredName {
+}
diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java b/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java
new file mode 100644
index 0000000000..ef6690ab4b
--- /dev/null
+++ b/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredQualifier.java
@@ -0,0 +1,24 @@
+package com.baeldung.configuration;
+
+import com.baeldung.dependency.AnotherArbitraryDependency;
+import com.baeldung.dependency.ArbitraryDependency;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class ApplicationContextTestAutowiredQualifier {
+
+ @Bean
+ public ArbitraryDependency autowiredFieldDependency() {
+ ArbitraryDependency autowiredFieldDependency = new ArbitraryDependency();
+
+ return autowiredFieldDependency;
+ }
+
+ @Bean
+ public ArbitraryDependency anotherAutowiredFieldDependency() {
+ ArbitraryDependency anotherAutowiredFieldDependency = new AnotherArbitraryDependency();
+
+ return anotherAutowiredFieldDependency;
+ }
+}
diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java b/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java
new file mode 100644
index 0000000000..240bc466b7
--- /dev/null
+++ b/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestAutowiredType.java
@@ -0,0 +1,15 @@
+package com.baeldung.configuration;
+
+import com.baeldung.dependency.ArbitraryDependency;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class ApplicationContextTestAutowiredType {
+
+ @Bean
+ public ArbitraryDependency autowiredFieldDependency() {
+ ArbitraryDependency autowiredFieldDependency = new ArbitraryDependency();
+ return autowiredFieldDependency;
+ }
+}
diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectName.java b/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectName.java
new file mode 100644
index 0000000000..851aa0b8ee
--- /dev/null
+++ b/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectName.java
@@ -0,0 +1,16 @@
+package com.baeldung.configuration;
+
+import com.baeldung.dependency.ArbitraryDependency;
+import com.baeldung.dependency.YetAnotherArbitraryDependency;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class ApplicationContextTestInjectName {
+
+ @Bean
+ public ArbitraryDependency yetAnotherFieldInjectDependency() {
+ ArbitraryDependency yetAnotherFieldInjectDependency = new YetAnotherArbitraryDependency();
+ return yetAnotherFieldInjectDependency;
+ }
+}
diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java b/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java
new file mode 100644
index 0000000000..59af5a91bb
--- /dev/null
+++ b/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectQualifier.java
@@ -0,0 +1,22 @@
+package com.baeldung.configuration;
+
+import com.baeldung.dependency.AnotherArbitraryDependency;
+import com.baeldung.dependency.ArbitraryDependency;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class ApplicationContextTestInjectQualifier {
+
+ @Bean
+ public ArbitraryDependency defaultFile() {
+ ArbitraryDependency defaultFile = new ArbitraryDependency();
+ return defaultFile;
+ }
+
+ @Bean
+ public ArbitraryDependency namedFile() {
+ ArbitraryDependency namedFile = new AnotherArbitraryDependency();
+ return namedFile;
+ }
+}
diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectType.java b/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectType.java
new file mode 100644
index 0000000000..1e1f01f269
--- /dev/null
+++ b/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestInjectType.java
@@ -0,0 +1,15 @@
+package com.baeldung.configuration;
+
+import com.baeldung.dependency.ArbitraryDependency;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class ApplicationContextTestInjectType {
+
+ @Bean
+ public ArbitraryDependency injectDependency() {
+ ArbitraryDependency injectDependency = new ArbitraryDependency();
+ return injectDependency;
+ }
+}
diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java b/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java
new file mode 100644
index 0000000000..cb1b5981e8
--- /dev/null
+++ b/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceNameType.java
@@ -0,0 +1,16 @@
+package com.baeldung.configuration;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import java.io.File;
+
+@Configuration
+public class ApplicationContextTestResourceNameType {
+
+ @Bean(name = "namedFile")
+ public File namedFile() {
+ File namedFile = new File("namedFile.txt");
+ return namedFile;
+ }
+}
diff --git a/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java b/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java
new file mode 100644
index 0000000000..c9aa2f4a7d
--- /dev/null
+++ b/dependency-injection/src/main/java/com/baeldung/configuration/ApplicationContextTestResourceQualifier.java
@@ -0,0 +1,22 @@
+package com.baeldung.configuration;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import java.io.File;
+
+@Configuration
+public class ApplicationContextTestResourceQualifier {
+
+ @Bean(name = "defaultFile")
+ public File defaultFile() {
+ File defaultFile = new File("defaultFile.txt");
+ return defaultFile;
+ }
+
+ @Bean(name = "namedFile")
+ public File namedFile() {
+ File namedFile = new File("namedFile.txt");
+ return namedFile;
+ }
+}
diff --git a/dependency-injection/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java b/dependency-injection/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java
new file mode 100644
index 0000000000..0e19523b7e
--- /dev/null
+++ b/dependency-injection/src/main/java/com/baeldung/dependency/AnotherArbitraryDependency.java
@@ -0,0 +1,13 @@
+package com.baeldung.dependency;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class AnotherArbitraryDependency extends ArbitraryDependency {
+
+ private final String label = "Another Arbitrary Dependency";
+
+ public String toString() {
+ return label;
+ }
+}
diff --git a/dependency-injection/src/main/java/com/baeldung/dependency/ArbitraryDependency.java b/dependency-injection/src/main/java/com/baeldung/dependency/ArbitraryDependency.java
new file mode 100644
index 0000000000..3c90492d2c
--- /dev/null
+++ b/dependency-injection/src/main/java/com/baeldung/dependency/ArbitraryDependency.java
@@ -0,0 +1,13 @@
+package com.baeldung.dependency;
+
+import org.springframework.stereotype.Component;
+
+@Component(value = "autowiredFieldDependency")
+public class ArbitraryDependency {
+
+ private final String label = "Arbitrary Dependency";
+
+ public String toString() {
+ return label;
+ }
+}
diff --git a/dependency-injection/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java b/dependency-injection/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java
new file mode 100644
index 0000000000..a88abd0924
--- /dev/null
+++ b/dependency-injection/src/main/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java
@@ -0,0 +1,13 @@
+package com.baeldung.dependency;
+
+import org.springframework.stereotype.Component;
+
+@Component
+public class YetAnotherArbitraryDependency extends ArbitraryDependency {
+
+ private final String label = "Yet Another Arbitrary Dependency";
+
+ public String toString() {
+ return label;
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameTest.java b/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameTest.java
new file mode 100644
index 0000000000..cbdac68543
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameTest.java
@@ -0,0 +1,29 @@
+package com.baeldung.autowired;
+
+import com.baeldung.configuration.ApplicationContextTestAutowiredName;
+import com.baeldung.dependency.ArbitraryDependency;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.AnnotationConfigContextLoader;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(
+ loader = AnnotationConfigContextLoader.class,
+ classes = ApplicationContextTestAutowiredName.class)
+public class FieldAutowiredNameTest {
+
+ @Autowired
+ private ArbitraryDependency autowiredFieldDependency;
+
+ @Test
+ public void givenAutowiredAnnotation_WhenOnField_ThenDependencyValid() {
+ assertNotNull(autowiredFieldDependency);
+ assertEquals("Arbitrary Dependency", autowiredFieldDependency.toString());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredTest.java b/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredTest.java
new file mode 100644
index 0000000000..b736871f85
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredTest.java
@@ -0,0 +1,29 @@
+package com.baeldung.autowired;
+
+import com.baeldung.configuration.ApplicationContextTestAutowiredType;
+import com.baeldung.dependency.ArbitraryDependency;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.AnnotationConfigContextLoader;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(
+ loader = AnnotationConfigContextLoader.class,
+ classes = ApplicationContextTestAutowiredType.class)
+public class FieldAutowiredTest {
+
+ @Autowired
+ private ArbitraryDependency fieldDependency;
+
+ @Test
+ public void givenAutowired_WhenSetOnField_ThenDependencyResolved() {
+ assertNotNull(fieldDependency);
+ assertEquals("Arbitrary Dependency", fieldDependency.toString());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredTest.java b/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredTest.java
new file mode 100644
index 0000000000..cbc3d56f67
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredTest.java
@@ -0,0 +1,41 @@
+package com.baeldung.autowired;
+
+import com.baeldung.configuration.ApplicationContextTestAutowiredQualifier;
+import com.baeldung.dependency.ArbitraryDependency;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.AnnotationConfigContextLoader;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(
+ loader = AnnotationConfigContextLoader.class,
+ classes = ApplicationContextTestAutowiredQualifier.class)
+public class FieldQualifierAutowiredTest {
+
+ @Autowired
+ @Qualifier("autowiredFieldDependency")
+ private ArbitraryDependency fieldDependency1;
+
+ @Autowired
+ @Qualifier("anotherAutowiredFieldDependency")
+ private ArbitraryDependency fieldDependency2;
+
+ @Test
+ public void givenAutowiredQualifier_WhenOnField_ThenDep1Valid() {
+ assertNotNull(fieldDependency1);
+ assertEquals("Arbitrary Dependency", fieldDependency1.toString());
+ }
+
+ @Test
+ public void givenAutowiredQualifier_WhenOnField_ThenDep2Valid() {
+ assertNotNull(fieldDependency2);
+ assertEquals("Another Arbitrary Dependency", fieldDependency2.toString());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectTest.java b/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectTest.java
new file mode 100644
index 0000000000..665c9f1ddc
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectTest.java
@@ -0,0 +1,32 @@
+package com.baeldung.inject;
+
+import com.baeldung.configuration.ApplicationContextTestInjectName;
+import com.baeldung.dependency.ArbitraryDependency;
+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.support.AnnotationConfigContextLoader;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(
+ loader = AnnotationConfigContextLoader.class,
+ classes = ApplicationContextTestInjectName.class)
+public class FieldByNameInjectTest {
+
+ @Inject
+ @Named("yetAnotherFieldInjectDependency")
+ private ArbitraryDependency yetAnotherFieldInjectDependency;
+
+ @Test
+ public void givenInjectQualifier_WhenSetOnField_ThenDependencyValid() {
+ assertNotNull(yetAnotherFieldInjectDependency);
+ assertEquals("Yet Another Arbitrary Dependency", yetAnotherFieldInjectDependency.toString());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectTest.java b/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectTest.java
new file mode 100644
index 0000000000..7561c39e76
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectTest.java
@@ -0,0 +1,30 @@
+package com.baeldung.inject;
+
+import com.baeldung.configuration.ApplicationContextTestInjectType;
+import com.baeldung.dependency.ArbitraryDependency;
+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.support.AnnotationConfigContextLoader;
+
+import javax.inject.Inject;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(
+ loader = AnnotationConfigContextLoader.class,
+ classes = ApplicationContextTestInjectType.class)
+public class FieldInjectTest {
+
+ @Inject
+ private ArbitraryDependency fieldInjectDependency;
+
+ @Test
+ public void givenInjectAnnotation_WhenOnField_ThenValidDependency() {
+ assertNotNull(fieldInjectDependency);
+ assertEquals("Arbitrary Dependency", fieldInjectDependency.toString());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectTest.java b/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectTest.java
new file mode 100644
index 0000000000..7e5f7e7453
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectTest.java
@@ -0,0 +1,41 @@
+package com.baeldung.inject;
+
+import com.baeldung.configuration.ApplicationContextTestInjectQualifier;
+import com.baeldung.dependency.ArbitraryDependency;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.AnnotationConfigContextLoader;
+
+import javax.inject.Inject;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
+ classes = ApplicationContextTestInjectQualifier.class)
+public class FieldQualifierInjectTest {
+
+ @Inject
+ @Qualifier("defaultFile")
+ private ArbitraryDependency defaultDependency;
+
+ @Inject
+ @Qualifier("namedFile")
+ private ArbitraryDependency namedDependency;
+
+ @Test
+ public void givenInjectQualifier_WhenOnField_ThenDefaultFileValid() {
+ assertNotNull(defaultDependency);
+ assertEquals("Arbitrary Dependency", defaultDependency.toString());
+ }
+
+ @Test
+ public void givenInjectQualifier_WhenOnField_ThenNamedFileValid() {
+ assertNotNull(defaultDependency);
+ assertEquals("Another Arbitrary Dependency", namedDependency.toString());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionTest.java b/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionTest.java
new file mode 100644
index 0000000000..ef7e7b0aeb
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionTest.java
@@ -0,0 +1,30 @@
+package com.baeldung.resource;
+
+import com.baeldung.configuration.ApplicationContextTestResourceNameType;
+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.support.AnnotationConfigContextLoader;
+
+import javax.annotation.Resource;
+import java.io.File;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(
+ loader = AnnotationConfigContextLoader.class,
+ classes = ApplicationContextTestResourceNameType.class)
+public class FieldResourceInjectionTest {
+
+ @Resource(name = "namedFile")
+ private File defaultFile;
+
+ @Test
+ public void givenResourceAnnotation_WhenOnField_ThenDependencyValid() {
+ assertNotNull(defaultFile);
+ assertEquals("namedFile.txt", defaultFile.getName());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceTest.java b/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceTest.java
new file mode 100644
index 0000000000..95e9fc0bd5
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceTest.java
@@ -0,0 +1,45 @@
+package com.baeldung.resource;
+
+import com.baeldung.configuration.ApplicationContextTestResourceQualifier;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.AnnotationConfigContextLoader;
+
+import javax.annotation.Resource;
+import java.io.File;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(
+ loader = AnnotationConfigContextLoader.class,
+ classes = ApplicationContextTestResourceQualifier.class)
+public class MethodByQualifierResourceTest {
+
+ private File arbDependency;
+ private File anotherArbDependency;
+
+ @Test
+ public void givenResourceQualifier_WhenSetter_ThenValidDependencies() {
+ assertNotNull(arbDependency);
+ assertEquals("namedFile.txt", arbDependency.getName());
+ assertNotNull(anotherArbDependency);
+ assertEquals("defaultFile.txt", anotherArbDependency.getName());
+ }
+
+ @Resource
+ @Qualifier("namedFile")
+ public void setArbDependency(File arbDependency) {
+ this.arbDependency = arbDependency;
+ }
+
+ @Resource
+ @Qualifier("defaultFile")
+ public void setAnotherArbDependency(File anotherArbDependency) {
+ this.anotherArbDependency = anotherArbDependency;
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceTest.java b/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceTest.java
new file mode 100644
index 0000000000..ad9a9a4fb6
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceTest.java
@@ -0,0 +1,34 @@
+package com.baeldung.resource;
+
+import com.baeldung.configuration.ApplicationContextTestResourceNameType;
+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.support.AnnotationConfigContextLoader;
+
+import javax.annotation.Resource;
+import java.io.File;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(
+ loader = AnnotationConfigContextLoader.class,
+ classes = ApplicationContextTestResourceNameType.class)
+public class MethodByTypeResourceTest {
+
+ private File defaultFile;
+
+ @Resource
+ protected void setDefaultFile(File defaultFile) {
+ this.defaultFile = defaultFile;
+ }
+
+ @Test
+ public void givenResourceAnnotation_WhenSetter_ThenValidDependency() {
+ assertNotNull(defaultFile);
+ assertEquals("namedFile.txt", defaultFile.getName());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionTest.java b/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionTest.java
new file mode 100644
index 0000000000..1622d8896c
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionTest.java
@@ -0,0 +1,34 @@
+package com.baeldung.resource;
+
+import com.baeldung.configuration.ApplicationContextTestResourceNameType;
+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.support.AnnotationConfigContextLoader;
+
+import javax.annotation.Resource;
+import java.io.File;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(
+ loader = AnnotationConfigContextLoader.class,
+ classes = ApplicationContextTestResourceNameType.class)
+public class MethodResourceInjectionTest {
+
+ private File defaultFile;
+
+ @Resource(name = "namedFile")
+ protected void setDefaultFile(File defaultFile) {
+ this.defaultFile = defaultFile;
+ }
+
+ @Test
+ public void givenResourceAnnotation_WhenSetter_ThenDependencyValid() {
+ assertNotNull(defaultFile);
+ assertEquals("namedFile.txt", defaultFile.getName());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java b/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java
new file mode 100644
index 0000000000..da104ecaae
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java
@@ -0,0 +1,29 @@
+package com.baeldung.resource;
+
+import com.baeldung.configuration.ApplicationContextTestResourceNameType;
+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.support.AnnotationConfigContextLoader;
+
+import javax.annotation.Resource;
+import java.io.File;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
+ classes = ApplicationContextTestResourceNameType.class)
+public class NamedResourceTest {
+
+ @Resource(name = "namedFile")
+ private File testFile;
+
+ @Test
+ public void givenResourceAnnotation_WhenOnField_THEN_DEPENDENCY_Found() {
+ assertNotNull(testFile);
+ assertEquals("namedFile.txt", testFile.getName());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionTest.java b/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionTest.java
new file mode 100644
index 0000000000..024c8e2bbe
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionTest.java
@@ -0,0 +1,42 @@
+package com.baeldung.resource;
+
+import com.baeldung.configuration.ApplicationContextTestResourceQualifier;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.AnnotationConfigContextLoader;
+
+import javax.annotation.Resource;
+import java.io.File;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(
+ loader = AnnotationConfigContextLoader.class,
+ classes = ApplicationContextTestResourceQualifier.class)
+public class QualifierResourceInjectionTest {
+
+ @Resource
+ @Qualifier("defaultFile")
+ private File dependency1;
+
+ @Resource
+ @Qualifier("namedFile")
+ private File dependency2;
+
+ @Test
+ public void givenResourceAnnotation_WhenField_ThenDependency1Valid() {
+ assertNotNull(dependency1);
+ assertEquals("defaultFile.txt", dependency1.getName());
+ }
+
+ @Test
+ public void givenResourceQualifier_WhenField_ThenDependency2Valid() {
+ assertNotNull(dependency2);
+ assertEquals("namedFile.txt", dependency2.getName());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionTest.java b/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionTest.java
new file mode 100644
index 0000000000..aa7cfda975
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionTest.java
@@ -0,0 +1,33 @@
+package com.baeldung.resource;
+
+import com.baeldung.configuration.ApplicationContextTestResourceNameType;
+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.support.AnnotationConfigContextLoader;
+
+import javax.annotation.Resource;
+import java.io.File;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
+ classes = ApplicationContextTestResourceNameType.class)
+public class SetterResourceInjectionTest {
+
+ private File defaultFile;
+
+ @Resource
+ protected void setDefaultFile(File defaultFile) {
+ this.defaultFile = defaultFile;
+ }
+
+ @Test
+ public void givenResourceAnnotation_WhenOnSetter_THEN_MUST_INJECT_Dependency() {
+ assertNotNull(defaultFile);
+ assertEquals("namedFile.txt", defaultFile.getName());
+ }
+}
diff --git a/gatling/pom.xml b/gatling/pom.xml
new file mode 100644
index 0000000000..273797d76c
--- /dev/null
+++ b/gatling/pom.xml
@@ -0,0 +1,110 @@
+
+
+ 4.0.0
+ org.baeldung
+ gatling
+ 1.0-SNAPSHOT
+
+
+ 1.8
+ 1.8
+ 2.11.7
+ UTF-8
+ 2.2.0
+ 3.2.2
+
+
+
+
+
+ io.gatling
+ gatling-app
+ ${gatling.version}
+
+
+ io.gatling
+ gatling-recorder
+ ${gatling.version}
+
+
+ io.gatling.highcharts
+ gatling-charts-highcharts
+ ${gatling.version}
+
+
+ org.scala-lang
+ scala-library
+ ${scala.version}
+
+
+
+
+
+
+ io.gatling.highcharts
+ gatling-charts-highcharts
+
+
+ io.gatling
+ gatling-app
+
+
+ io.gatling
+ gatling-recorder
+
+
+ org.scala-lang
+ scala-library
+
+
+
+
+ src/test/scala
+
+
+
+ net.alchim31.maven
+ scala-maven-plugin
+ ${scala-maven-plugin.version}
+
+
+
+
+
+ net.alchim31.maven
+ scala-maven-plugin
+
+
+
+ testCompile
+
+
+
+ -Ybackend:GenBCode
+ -Ydelambdafy:method
+ -target:jvm-1.8
+ -deprecation
+ -feature
+ -unchecked
+ -language:implicitConversions
+ -language:postfixOps
+
+
+
+
+
+
+ io.gatling
+ gatling-maven-plugin
+ ${gatling.version}
+
+
+ test
+ execute
+
+
+
+
+
+
diff --git a/gatling/src/test/resources/gatling.conf b/gatling/src/test/resources/gatling.conf
new file mode 100644
index 0000000000..8bfa0ed366
--- /dev/null
+++ b/gatling/src/test/resources/gatling.conf
@@ -0,0 +1,127 @@
+#########################
+# Gatling Configuration #
+#########################
+
+# This file contains all the settings configurable for Gatling with their default values
+
+gatling {
+ core {
+ #outputDirectoryBaseName = "" # The prefix for each simulation result folder (then suffixed by the report generation timestamp)
+ #runDescription = "" # The description for this simulation run, displayed in each report
+ #encoding = "utf-8" # Encoding to use throughout Gatling for file and string manipulation
+ #simulationClass = "" # The FQCN of the simulation to run (when used in conjunction with noReports, the simulation for which assertions will be validated)
+ #mute = false # When set to true, don't ask for simulation name nor run description (currently only used by Gatling SBT plugin)
+ #elFileBodiesCacheMaxCapacity = 200 # Cache size for request body EL templates, set to 0 to disable
+ #rawFileBodiesCacheMaxCapacity = 200 # Cache size for request body Raw templates, set to 0 to disable
+ #rawFileBodiesInMemoryMaxSize = 1000 # Below this limit, raw file bodies will be cached in memory
+
+ extract {
+ regex {
+ #cacheMaxCapacity = 200 # Cache size for the compiled regexes, set to 0 to disable caching
+ }
+ xpath {
+ #cacheMaxCapacity = 200 # Cache size for the compiled XPath queries, set to 0 to disable caching
+ }
+ jsonPath {
+ #cacheMaxCapacity = 200 # Cache size for the compiled jsonPath queries, set to 0 to disable caching
+ #preferJackson = false # When set to true, prefer Jackson over Boon for JSON-related operations
+ }
+ css {
+ #cacheMaxCapacity = 200 # Cache size for the compiled CSS selectors queries, set to 0 to disable caching
+ }
+ }
+
+ directory {
+ #data = user-files/data # Folder where user's data (e.g. files used by Feeders) is located
+ #bodies = user-files/bodies # Folder where bodies are located
+ #simulations = user-files/simulations # Folder where the bundle's simulations are located
+ #reportsOnly = "" # If set, name of report folder to look for in order to generate its report
+ #binaries = "" # If set, name of the folder where compiles classes are located: Defaults to GATLING_HOME/target.
+ #results = results # Name of the folder where all reports folder are located
+ }
+ }
+ charting {
+ #noReports = false # When set to true, don't generate HTML reports
+ #maxPlotPerSeries = 1000 # Number of points per graph in Gatling reports
+ #useGroupDurationMetric = false # Switch group timings from cumulated response time to group duration.
+ indicators {
+ #lowerBound = 800 # Lower bound for the requests' response time to track in the reports and the console summary
+ #higherBound = 1200 # Higher bound for the requests' response time to track in the reports and the console summary
+ #percentile1 = 50 # Value for the 1st percentile to track in the reports, the console summary and Graphite
+ #percentile2 = 75 # Value for the 2nd percentile to track in the reports, the console summary and Graphite
+ #percentile3 = 95 # Value for the 3rd percentile to track in the reports, the console summary and Graphite
+ #percentile4 = 99 # Value for the 4th percentile to track in the reports, the console summary and Graphite
+ }
+ }
+ http {
+ #fetchedCssCacheMaxCapacity = 200 # Cache size for CSS parsed content, set to 0 to disable
+ #fetchedHtmlCacheMaxCapacity = 200 # Cache size for HTML parsed content, set to 0 to disable
+ #perUserCacheMaxCapacity = 200 # Per virtual user cache size, set to 0 to disable
+ #warmUpUrl = "http://gatling.io" # The URL to use to warm-up the HTTP stack (blank means disabled)
+ #enableGA = true # Very light Google Analytics, please support
+ ssl {
+ keyStore {
+ #type = "" # Type of SSLContext's KeyManagers store
+ #file = "" # Location of SSLContext's KeyManagers store
+ #password = "" # Password for SSLContext's KeyManagers store
+ #algorithm = "" # Algorithm used SSLContext's KeyManagers store
+ }
+ trustStore {
+ #type = "" # Type of SSLContext's TrustManagers store
+ #file = "" # Location of SSLContext's TrustManagers store
+ #password = "" # Password for SSLContext's TrustManagers store
+ #algorithm = "" # Algorithm used by SSLContext's TrustManagers store
+ }
+ }
+ ahc {
+ #keepAlive = true # Allow pooling HTTP connections (keep-alive header automatically added)
+ #connectTimeout = 60000 # Timeout when establishing a connection
+ #pooledConnectionIdleTimeout = 60000 # Timeout when a connection stays unused in the pool
+ #readTimeout = 60000 # Timeout when a used connection stays idle
+ #maxRetry = 2 # Number of times that a request should be tried again
+ #requestTimeout = 60000 # Timeout of the requests
+ #acceptAnyCertificate = true # When set to true, doesn't validate SSL certificates
+ #httpClientCodecMaxInitialLineLength = 4096 # Maximum length of the initial line of the response (e.g. "HTTP/1.0 200 OK")
+ #httpClientCodecMaxHeaderSize = 8192 # Maximum size, in bytes, of each request's headers
+ #httpClientCodecMaxChunkSize = 8192 # Maximum length of the content or each chunk
+ #webSocketMaxFrameSize = 10240000 # Maximum frame payload size
+ #sslEnabledProtocols = [TLSv1.2, TLSv1.1, TLSv1] # Array of enabled protocols for HTTPS, if empty use the JDK defaults
+ #sslEnabledCipherSuites = [] # Array of enabled cipher suites for HTTPS, if empty use the JDK defaults
+ #sslSessionCacheSize = 0 # SSLSession cache size, set to 0 to use JDK's default
+ #sslSessionTimeout = 0 # SSLSession timeout in seconds, set to 0 to use JDK's default (24h)
+ #useOpenSsl = false # if OpenSSL should be used instead of JSSE (requires tcnative jar)
+ #useNativeTransport = false # if native transport should be used instead of Java NIO (requires netty-transport-native-epoll, currently Linux only)
+ #usePooledMemory = true # if Gatling should use pooled memory
+ #tcpNoDelay = true
+ #soReuseAddress = false
+ #soLinger = -1
+ #soSndBuf = -1
+ #soRcvBuf = -1
+ }
+ dns {
+ #queryTimeout = 5000 # Timeout of each DNS query in millis
+ #maxQueriesPerResolve = 3 # Maximum allowed number of DNS queries for a given name resolution
+ }
+ }
+ data {
+ #writers = [console, file] # The list of DataWriters to which Gatling write simulation data (currently supported : console, file, graphite, jdbc)
+ console {
+ #light = false # When set to true, displays a light version without detailed request stats
+ }
+ file {
+ #bufferSize = 8192 # FileDataWriter's internal data buffer size, in bytes
+ }
+ leak {
+ #noActivityTimeout = 30 # Period, in seconds, for which Gatling may have no activity before considering a leak may be happening
+ }
+ graphite {
+ #light = false # only send the all* stats
+ #host = "localhost" # The host where the Carbon server is located
+ #port = 2003 # The port to which the Carbon server listens to (2003 is default for plaintext, 2004 is default for pickle)
+ #protocol = "tcp" # The protocol used to send data to Carbon (currently supported : "tcp", "udp")
+ #rootPathPrefix = "gatling" # The common prefix of all metrics sent to Graphite
+ #bufferSize = 8192 # GraphiteDataWriter's internal data buffer size, in bytes
+ #writeInterval = 1 # GraphiteDataWriter's write interval, in seconds
+ }
+ }
+}
diff --git a/gatling/src/test/resources/logback.xml b/gatling/src/test/resources/logback.xml
new file mode 100644
index 0000000000..b9ba6255a0
--- /dev/null
+++ b/gatling/src/test/resources/logback.xml
@@ -0,0 +1,22 @@
+
+
+
+
+
+ %d{HH:mm:ss.SSS} [%-5level] %logger{15} - %msg%n%rEx
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/gatling/src/test/resources/recorder.conf b/gatling/src/test/resources/recorder.conf
new file mode 100644
index 0000000000..969b9e8668
--- /dev/null
+++ b/gatling/src/test/resources/recorder.conf
@@ -0,0 +1,53 @@
+recorder {
+ core {
+ #mode = "Proxy"
+ #encoding = "utf-8" # The encoding used for reading/writing request bodies and the generated simulation
+ #outputFolder = "" # The folder where generated simulation will we written
+ #package = "" # The package's name of the generated simulation
+ #className = "RecordedSimulation" # The name of the generated Simulation class
+ #thresholdForPauseCreation = 100 # The minimum time, in milliseconds, that must pass between requests to trigger a pause creation
+ #saveConfig = false # When set to true, the configuration from the Recorder GUI overwrites this configuration
+ #headless = false # When set to true, run the Recorder in headless mode instead of the GUI
+ #harFilePath = "" # The path of the HAR file to convert
+ }
+ filters {
+ #filterStrategy = "Disabled" # The selected filter resources filter strategy (currently supported : "Disabled", "BlackList", "WhiteList")
+ #whitelist = [] # The list of ressources patterns that are part of the Recorder's whitelist
+ #blacklist = [] # The list of ressources patterns that are part of the Recorder's blacklist
+ }
+ http {
+ #automaticReferer = true # When set to false, write the referer + enable 'disableAutoReferer' in the generated simulation
+ #followRedirect = true # When set to false, write redirect requests + enable 'disableFollowRedirect' in the generated simulation
+ #removeCacheHeaders = true # When set to true, removes from the generated requests headers leading to request caching
+ #inferHtmlResources = true # When set to true, add inferred resources + set 'inferHtmlResources' with the configured blacklist/whitelist in the generated simulation
+ #checkResponseBodies = false # When set to true, save response bodies as files and add raw checks in the generated simulation
+ }
+ proxy {
+ #port = 8000 # Local port used by Gatling's Proxy for HTTP/HTTPS
+ https {
+ #mode = "SelfSignedCertificate" # The selected "HTTPS mode" (currently supported : "SelfSignedCertificate", "ProvidedKeyStore", "GatlingCertificateAuthority", "CustomCertificateAuthority")
+ keyStore {
+ #path = "" # The path of the custom key store
+ #password = "" # The password for this key store
+ #type = "JKS" # The type of the key store (currently supported: "JKS")
+ }
+ certificateAuthority {
+ #certificatePath = "" # The path of the custom certificate
+ #privateKeyPath = "" # The certificate's private key path
+ }
+ }
+ outgoing {
+ #host = "" # The outgoing proxy's hostname
+ #username = "" # The username to use to connect to the outgoing proxy
+ #password = "" # The password corresponding to the user to use to connect to the outgoing proxy
+ #port = 0 # The HTTP port to use to connect to the outgoing proxy
+ #sslPort = 0 # If set, The HTTPS port to use to connect to the outgoing proxy
+ }
+ }
+ netty {
+ #maxInitialLineLength = 10000 # Maximum length of the initial line of the response (e.g. "HTTP/1.0 200 OK")
+ #maxHeaderSize = 20000 # Maximum size, in bytes, of each request's headers
+ #maxChunkSize = 8192 # Maximum length of the content or each chunk
+ #maxContentLength = 100000000 # Maximum length of the aggregated content of each response
+ }
+}
diff --git a/gatling/src/test/scala/Engine.scala b/gatling/src/test/scala/Engine.scala
new file mode 100644
index 0000000000..32c85fbe45
--- /dev/null
+++ b/gatling/src/test/scala/Engine.scala
@@ -0,0 +1,13 @@
+import io.gatling.app.Gatling
+import io.gatling.core.config.GatlingPropertiesBuilder
+
+object Engine extends App {
+
+ val props = new GatlingPropertiesBuilder
+ props.dataDirectory(IDEPathHelper.dataDirectory.toString)
+ props.resultsDirectory(IDEPathHelper.resultsDirectory.toString)
+ props.bodiesDirectory(IDEPathHelper.bodiesDirectory.toString)
+ props.binariesDirectory(IDEPathHelper.mavenBinariesDirectory.toString)
+
+ Gatling.fromMap(props.build)
+}
diff --git a/gatling/src/test/scala/IDEPathHelper.scala b/gatling/src/test/scala/IDEPathHelper.scala
new file mode 100644
index 0000000000..0abf6a42ef
--- /dev/null
+++ b/gatling/src/test/scala/IDEPathHelper.scala
@@ -0,0 +1,22 @@
+import java.nio.file.Path
+
+import io.gatling.commons.util.PathHelper._
+
+object IDEPathHelper {
+
+ val gatlingConfUrl: Path = getClass.getClassLoader.getResource("gatling.conf").toURI
+ val projectRootDir = gatlingConfUrl.ancestor(3)
+
+ val mavenSourcesDirectory = projectRootDir / "src" / "test" / "scala"
+ val mavenResourcesDirectory = projectRootDir / "src" / "test" / "resources"
+ val mavenTargetDirectory = projectRootDir / "target"
+ val mavenBinariesDirectory = mavenTargetDirectory / "test-classes"
+
+ val dataDirectory = mavenResourcesDirectory / "data"
+ val bodiesDirectory = mavenResourcesDirectory / "bodies"
+
+ val recorderOutputDirectory = mavenSourcesDirectory
+ val resultsDirectory = mavenTargetDirectory / "gatling"
+
+ val recorderConfigFile = mavenResourcesDirectory / "recorder.conf"
+}
diff --git a/gatling/src/test/scala/Recorder.scala b/gatling/src/test/scala/Recorder.scala
new file mode 100644
index 0000000000..6ad320618b
--- /dev/null
+++ b/gatling/src/test/scala/Recorder.scala
@@ -0,0 +1,12 @@
+import io.gatling.recorder.GatlingRecorder
+import io.gatling.recorder.config.RecorderPropertiesBuilder
+
+object Recorder extends App {
+
+ val props = new RecorderPropertiesBuilder
+ props.simulationOutputFolder(IDEPathHelper.recorderOutputDirectory.toString)
+ props.simulationPackage("org.baeldung")
+ props.bodiesFolder(IDEPathHelper.bodiesDirectory.toString)
+
+ GatlingRecorder.fromMap(props.build, Some(IDEPathHelper.recorderConfigFile))
+}
diff --git a/gatling/src/test/scala/org/baeldung/RecordedSimulation.scala b/gatling/src/test/scala/org/baeldung/RecordedSimulation.scala
new file mode 100644
index 0000000000..cdbef1bf3c
--- /dev/null
+++ b/gatling/src/test/scala/org/baeldung/RecordedSimulation.scala
@@ -0,0 +1,46 @@
+package org.baeldung
+
+import scala.concurrent.duration._
+
+import io.gatling.core.Predef._
+import io.gatling.http.Predef._
+import io.gatling.jdbc.Predef._
+
+class RecordedSimulation extends Simulation {
+
+ val httpProtocol = http
+ .baseURL("http://computer-database.gatling.io")
+ .inferHtmlResources(BlackList(""".*\.css""", """.*\.js""", """.*\.ico"""), WhiteList())
+ .acceptHeader("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
+ .acceptEncodingHeader("gzip, deflate")
+ .acceptLanguageHeader("it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3")
+ .userAgentHeader("Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0")
+
+
+
+
+
+ val scn = scenario("RecordedSimulation")
+ .exec(http("request_0")
+ .get("/"))
+ .pause(5)
+ .exec(http("request_1")
+ .get("/computers?f=amstrad"))
+ .pause(4)
+ .exec(http("request_2")
+ .get("/computers/412"))
+ .pause(2)
+ .exec(http("request_3")
+ .get("/"))
+ .pause(2)
+ .exec(http("request_4")
+ .get("/computers?p=1"))
+ .pause(1)
+ .exec(http("request_5")
+ .get("/computers?p=2"))
+ .pause(2)
+ .exec(http("request_6")
+ .get("/computers?p=3"))
+
+ setUp(scn.inject(atOnceUsers(1))).protocols(httpProtocol)
+}
diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapFromSet.java b/guava/src/test/java/org/baeldung/guava/GuavaMapFromSet.java
new file mode 100644
index 0000000000..602205ff9f
--- /dev/null
+++ b/guava/src/test/java/org/baeldung/guava/GuavaMapFromSet.java
@@ -0,0 +1,101 @@
+package org.baeldung.guava;
+
+import java.util.AbstractMap;
+import java.util.AbstractSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.WeakHashMap;
+
+import com.google.common.base.Function;
+
+public class GuavaMapFromSet extends AbstractMap {
+
+ private class SingleEntry implements Entry {
+ private K key;
+
+ public SingleEntry( K key) {
+ this.key = key;
+ }
+
+ @Override
+ public K getKey() {
+ return this.key;
+ }
+
+ @Override
+ public V getValue() {
+ V value = GuavaMapFromSet.this.cache.get(this.key);
+ if (value == null) {
+ value = GuavaMapFromSet.this.function.apply(this.key);
+ GuavaMapFromSet.this.cache.put(this.key, value);
+ }
+ return value;
+ }
+
+ @Override
+ public V setValue( V value) {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ private class MyEntrySet extends AbstractSet> {
+
+ public class EntryIterator implements Iterator> {
+ private Iterator inner;
+
+ public EntryIterator() {
+ this.inner = MyEntrySet.this.keys.iterator();
+ }
+
+ @Override
+ public boolean hasNext() {
+ return this.inner.hasNext();
+ }
+
+ @Override
+ public Map.Entry next() {
+ K key = this.inner.next();
+ return new SingleEntry(key);
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ private Set keys;
+
+ public MyEntrySet( Set keys) {
+ this.keys = keys;
+ }
+
+ @Override
+ public Iterator> iterator() {
+ return new EntryIterator();
+ }
+
+ @Override
+ public int size() {
+ return this.keys.size();
+ }
+
+ }
+
+ private WeakHashMap cache;
+ private Set> entries;
+ private Function super K, ? extends V> function;
+
+ public GuavaMapFromSet( Set keys, Function super K, ? extends V> function) {
+ this.function = function;
+ this.cache = new WeakHashMap();
+ this.entries = new MyEntrySet(keys);
+ }
+
+ @Override
+ public Set> entrySet() {
+ return this.entries;
+ }
+
+}
diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapFromSetTests.java b/guava/src/test/java/org/baeldung/guava/GuavaMapFromSetTests.java
new file mode 100644
index 0000000000..9abb5d14a9
--- /dev/null
+++ b/guava/src/test/java/org/baeldung/guava/GuavaMapFromSetTests.java
@@ -0,0 +1,66 @@
+package org.baeldung.guava;
+
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.junit.Test;
+
+import com.google.common.base.Function;
+
+public class GuavaMapFromSetTests {
+
+ @Test
+ public void givenStringSet_whenMapsToElementLength_thenCorrect() {
+ Function function = new Function() {
+
+ @Override
+ public String apply(Integer from) {
+ return Integer.toBinaryString(from.intValue());
+ }
+ };
+ Set set = (Set) new TreeSet(Arrays.asList(
+ 32, 64, 128));
+ Map map = new GuavaMapFromSet(set,
+ function);
+ assertTrue(map.get(32).equals("100000")
+ && map.get(64).equals("1000000")
+ && map.get(128).equals("10000000"));
+ }
+
+ @Test
+ public void givenIntSet_whenMapsToElementBinaryValue_thenCorrect() {
+ Function function = new Function() {
+
+ @Override
+ public Integer apply(String from) {
+ return from.length();
+ }
+ };
+ Set set = (Set) new TreeSet(Arrays.asList(
+ "four", "three", "twelve"));
+ Map map = new GuavaMapFromSet(set,
+ function);
+ assertTrue(map.get("four") == 4 && map.get("three") == 5
+ && map.get("twelve") == 6);
+ }
+ @Test
+ public void givenSet_whenNewSetElementAddedAndMappedLive_thenCorrect() {
+ Function function = new Function() {
+
+ @Override
+ public Integer apply(String from) {
+ return from.length();
+ }
+ };
+ Set set = (Set) new TreeSet(Arrays.asList(
+ "four", "three", "twelve"));
+ Map map = new GuavaMapFromSet(set,
+ function);
+ set.add("one");
+ assertTrue(map.get("one") == 3 && map.size()==4);
+ }
+}
diff --git a/httpclient/.settings/org.eclipse.jdt.ui.prefs b/httpclient/.settings/org.eclipse.jdt.ui.prefs
deleted file mode 100644
index 471e9b0d81..0000000000
--- a/httpclient/.settings/org.eclipse.jdt.ui.prefs
+++ /dev/null
@@ -1,55 +0,0 @@
-#Sat Jan 21 23:04:06 EET 2012
-eclipse.preferences.version=1
-editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
-sp_cleanup.add_default_serial_version_id=true
-sp_cleanup.add_generated_serial_version_id=false
-sp_cleanup.add_missing_annotations=true
-sp_cleanup.add_missing_deprecated_annotations=true
-sp_cleanup.add_missing_methods=false
-sp_cleanup.add_missing_nls_tags=false
-sp_cleanup.add_missing_override_annotations=true
-sp_cleanup.add_missing_override_annotations_interface_methods=true
-sp_cleanup.add_serial_version_id=false
-sp_cleanup.always_use_blocks=true
-sp_cleanup.always_use_parentheses_in_expressions=true
-sp_cleanup.always_use_this_for_non_static_field_access=false
-sp_cleanup.always_use_this_for_non_static_method_access=false
-sp_cleanup.convert_to_enhanced_for_loop=true
-sp_cleanup.correct_indentation=true
-sp_cleanup.format_source_code=true
-sp_cleanup.format_source_code_changes_only=true
-sp_cleanup.make_local_variable_final=true
-sp_cleanup.make_parameters_final=true
-sp_cleanup.make_private_fields_final=false
-sp_cleanup.make_type_abstract_if_missing_method=false
-sp_cleanup.make_variable_declarations_final=true
-sp_cleanup.never_use_blocks=false
-sp_cleanup.never_use_parentheses_in_expressions=false
-sp_cleanup.on_save_use_additional_actions=true
-sp_cleanup.organize_imports=true
-sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
-sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
-sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
-sp_cleanup.qualify_static_member_accesses_with_declaring_class=true
-sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
-sp_cleanup.remove_private_constructors=true
-sp_cleanup.remove_trailing_whitespaces=true
-sp_cleanup.remove_trailing_whitespaces_all=true
-sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
-sp_cleanup.remove_unnecessary_casts=true
-sp_cleanup.remove_unnecessary_nls_tags=false
-sp_cleanup.remove_unused_imports=true
-sp_cleanup.remove_unused_local_variables=false
-sp_cleanup.remove_unused_private_fields=true
-sp_cleanup.remove_unused_private_members=false
-sp_cleanup.remove_unused_private_methods=true
-sp_cleanup.remove_unused_private_types=true
-sp_cleanup.sort_members=false
-sp_cleanup.sort_members_all=false
-sp_cleanup.use_blocks=false
-sp_cleanup.use_blocks_only_for_return_and_throw=false
-sp_cleanup.use_parentheses_in_expressions=false
-sp_cleanup.use_this_for_non_static_field_access=true
-sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
-sp_cleanup.use_this_for_non_static_method_access=true
-sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
diff --git a/httpclient/README.md b/httpclient/README.md
index e06c57da71..a848edfea6 100644
--- a/httpclient/README.md
+++ b/httpclient/README.md
@@ -1,7 +1,9 @@
=========
-
## HttpClient 4.x Cookbooks and Examples
+###The Course
+The "REST With Spring" Classes: http://bit.ly/restwithspring
+
### Relevant Articles:
diff --git a/httpclient/src/test/java/org/baeldung/httpclient/SandboxTest.java b/httpclient/src/test/java/org/baeldung/httpclient/SandboxTest.java
new file mode 100644
index 0000000000..dc1a206f0d
--- /dev/null
+++ b/httpclient/src/test/java/org/baeldung/httpclient/SandboxTest.java
@@ -0,0 +1,188 @@
+package org.baeldung.httpclient;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+
+import org.apache.http.Header;
+import org.apache.http.HttpHost;
+import org.apache.http.HttpResponse;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.AuthenticationException;
+import org.apache.http.auth.MalformedChallengeException;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.client.AuthCache;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.CookieStore;
+import org.apache.http.client.CredentialsProvider;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.impl.auth.DigestScheme;
+import org.apache.http.impl.client.BasicAuthCache;
+import org.apache.http.impl.client.BasicCookieStore;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.impl.cookie.BasicClientCookie;
+import org.apache.http.util.EntityUtils;
+import org.junit.Ignore;
+import org.junit.Test;
+
+public class SandboxTest {
+
+ // original example
+ @Ignore
+ @Test
+ public final void whenInterestingDigestAuthScenario_then401UnAuthorized() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException {
+ final HttpHost targetHost = new HttpHost("httpbin.org", 80, "http");
+
+ // set up the credentials to run agains the server
+ final CredentialsProvider credsProvider = new BasicCredentialsProvider();
+ credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("user", "passwd"));
+
+ // We need a first run to get a 401 to seed the digest auth
+
+ // Make a client using those creds
+ final CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
+
+ // And make a call to the URL we are after
+ final HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");
+
+ // Create a context to use
+ final HttpClientContext context = HttpClientContext.create();
+
+ // Get a response from the sever (expect a 401!)
+ final HttpResponse authResponse = client.execute(targetHost, httpget, context);
+
+ // Pull out the auth header that came back from the server
+ final Header challenge = authResponse.getHeaders("WWW-Authenticate")[0];
+
+ // Lets use a digest scheme to solve it
+ final DigestScheme digest = new DigestScheme();
+ digest.processChallenge(challenge);
+
+ // Make a header with the solution based upon user/password and what the digest got out of the initial 401 reponse
+ final Header solution = digest.authenticate(new UsernamePasswordCredentials("user", "passwd"), httpget, context);
+
+ // Need an auth cache to use the new digest we made
+ final AuthCache authCache = new BasicAuthCache();
+ authCache.put(targetHost, digest);
+
+ // Add the authCache and thus solved digest to the context
+ context.setAuthCache(authCache);
+
+ // Pimp up our http get with the solved header made by the digest
+ httpget.addHeader(solution);
+
+ // use it!
+ System.out.println("Executing request " + httpget.getRequestLine() + " to target " + targetHost);
+
+ for (int i = 0; i < 3; i++) {
+ final CloseableHttpResponse responseGood = client.execute(targetHost, httpget, context);
+
+ try {
+ System.out.println("----------------------------------------");
+ System.out.println(responseGood.getStatusLine());
+ System.out.println(EntityUtils.toString(responseGood.getEntity()));
+ } finally {
+ responseGood.close();
+ }
+ }
+ }
+
+ @Test
+ public final void whenInterestingDigestAuthScenario_then200OK() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException {
+ final HttpHost targetHost = new HttpHost("httpbin.org", 80, "http");
+
+ // set up the credentials to run agains the server
+ final CredentialsProvider credsProvider = new BasicCredentialsProvider();
+ credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("user", "passwd"));
+
+ // This endpoint need fake cookie to work properly
+ final CookieStore cookieStore = new BasicCookieStore();
+ final BasicClientCookie cookie = new BasicClientCookie("fake", "fake_value");
+ cookie.setDomain("httpbin.org");
+ cookie.setPath("/");
+ cookieStore.addCookie(cookie);
+
+ // Make a client using those creds
+ final CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credsProvider).build();
+
+ // And make a call to the URL we are after
+ final HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");
+
+ // Create a context to use
+ final HttpClientContext context = HttpClientContext.create();
+
+ // Get a response from the sever (401 implicitly)
+ final HttpResponse authResponse = client.execute(targetHost, httpget, context);
+ assertEquals(200, authResponse.getStatusLine().getStatusCode());
+
+ // HttpClient will use cached digest parameters for future requests
+ System.out.println("Executing request " + httpget.getRequestLine() + " to target " + targetHost);
+
+ for (int i = 0; i < 3; i++) {
+ final CloseableHttpResponse responseGood = client.execute(targetHost, httpget, context);
+
+ try {
+ System.out.println("----------------------------------------");
+ System.out.println(responseGood.getStatusLine());
+ assertEquals(200, responseGood.getStatusLine().getStatusCode());
+ } finally {
+ responseGood.close();
+ }
+ }
+ client.close();
+ }
+
+ // This test needs module spring-security-rest-digest-auth to be running
+ @Test
+ public final void whenWeKnowDigestParameters_thenNo401Status() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException {
+ final HttpHost targetHost = new HttpHost("localhost", 8080, "http");
+
+ final CredentialsProvider credsProvider = new BasicCredentialsProvider();
+ credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user1", "user1Pass"));
+
+ final CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
+
+ final HttpGet httpget = new HttpGet("http://localhost:8080/spring-security-rest-digest-auth/api/foos/1");
+
+ final HttpClientContext context = HttpClientContext.create();
+ // == make it preemptive
+ final AuthCache authCache = new BasicAuthCache();
+ final DigestScheme digestAuth = new DigestScheme();
+ digestAuth.overrideParamter("realm", "Custom Realm Name");
+ digestAuth.overrideParamter("nonce", "nonce value goes here");
+ authCache.put(targetHost, digestAuth);
+ context.setAuthCache(authCache);
+ // == end
+ System.out.println("Executing The Request knowing the digest parameters ==== ");
+ final HttpResponse authResponse = client.execute(targetHost, httpget, context);
+ assertEquals(200, authResponse.getStatusLine().getStatusCode());
+ client.close();
+ }
+
+ // This test needs module spring-security-rest-digest-auth to be running
+ @Test
+ public final void whenDoNotKnowParameters_thenOnlyOne401() throws AuthenticationException, ClientProtocolException, IOException, MalformedChallengeException {
+ final HttpClientContext context = HttpClientContext.create();
+ final HttpHost targetHost = new HttpHost("localhost", 8080, "http");
+ final CredentialsProvider credsProvider = new BasicCredentialsProvider();
+ credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user1", "user1Pass"));
+ final CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
+
+ final HttpGet httpget = new HttpGet("http://localhost:8080/spring-security-rest-digest-auth/api/foos/1");
+ System.out.println("Executing The Request NOT knowing the digest parameters ==== ");
+ final HttpResponse tempResponse = client.execute(targetHost, httpget, context);
+ assertEquals(200, tempResponse.getStatusLine().getStatusCode());
+
+ for (int i = 0; i < 3; i++) {
+ System.out.println("No more Challenges or 401");
+ final CloseableHttpResponse authResponse = client.execute(targetHost, httpget, context);
+ assertEquals(200, authResponse.getStatusLine().getStatusCode());
+ authResponse.close();
+ }
+ client.close();
+ }
+}
diff --git a/jackson/README.md b/jackson/README.md
index 53b9c7c31d..68765de686 100644
--- a/jackson/README.md
+++ b/jackson/README.md
@@ -2,6 +2,9 @@
## Jackson Cookbooks and Examples
+###The Course
+The "REST With Spring" Classes: http://bit.ly/restwithspring
+
### Relevant Articles:
- [Jackson Ignore Properties on Marshalling](http://www.baeldung.com/jackson-ignore-properties-on-serialization)
- [Jackson – Unmarshall to Collection/Array](http://www.baeldung.com/jackson-collection-array)
diff --git a/jee7schedule/pom.xml b/jee7schedule/pom.xml
new file mode 100644
index 0000000000..627b8723e3
--- /dev/null
+++ b/jee7schedule/pom.xml
@@ -0,0 +1,311 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ jee7schedule
+ 1.0-SNAPSHOT
+ JavaEE 7 Arquillian Archetype Sample
+ war
+
+
+ 1.7
+ 3.0.0
+
+ 4.11
+ 7.0
+
+ 1.1.4.Final
+
+ 8.0.0.Final
+
+
+
+ ${maven.min.version}
+
+
+
+
+
+ org.jboss.arquillian
+ arquillian-bom
+ ${version.arquillian_core}
+ import
+ pom
+
+
+
+
+
+
+ javax
+ javaee-api
+ ${version.javaee_api}
+ provided
+
+
+
+ junit
+ junit
+ ${version.junit}
+ test
+
+
+ org.jboss.arquillian.junit
+ arquillian-junit-container
+ test
+
+
+ com.jayway.awaitility
+ awaitility
+ 1.6.0
+ test
+
+
+
+ org.jboss.shrinkwrap.resolver
+ shrinkwrap-resolver-impl-maven
+ test
+ jar
+
+
+
+ org.jboss.shrinkwrap.resolver
+ shrinkwrap-resolver-impl-maven-archive
+ test
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.1
+
+ ${java.min.version}
+ ${java.min.version}
+
+
+
+ org.apache.maven.plugins
+ maven-war-plugin
+ 2.1.1
+
+ false
+
+
+
+
+
+
+
+
+ wildfly-managed-arquillian
+
+ true
+
+
+ standalone-full.xml
+ ${project.build.directory}/wildfly-${version.wildfly}
+
+
+
+ io.undertow
+ undertow-websockets-jsr
+ 1.0.0.Beta25
+ test
+
+
+ org.jboss.resteasy
+ resteasy-client
+ 3.0.5.Final
+ test
+
+
+ org.jboss.resteasy
+ resteasy-jaxb-provider
+ 3.0.5.Final
+ test
+
+
+ org.jboss.resteasy
+ resteasy-json-p-provider
+ 3.0.5.Final
+ test
+
+
+ org.wildfly
+ wildfly-arquillian-container-managed
+ ${version.wildfly}
+ test
+
+
+
+
+
+ maven-dependency-plugin
+ 2.8
+
+ ${maven.test.skip}
+
+
+
+ unpack
+ process-test-classes
+
+ unpack
+
+
+
+
+ org.wildfly
+ wildfly-dist
+ ${version.wildfly}
+ zip
+ false
+ ${project.build.directory}
+
+
+
+
+
+
+
+ maven-surefire-plugin
+ 2.17
+
+
+ ${project.build.directory}/wildfly-${version.wildfly}
+
+
+
+
+
+
+
+ wildfly-remote-arquillian
+
+
+ io.undertow
+ undertow-websockets-jsr
+ 1.0.0.Beta25
+ test
+
+
+ org.jboss.resteasy
+ resteasy-client
+ 3.0.5.Final
+ test
+
+
+ org.jboss.resteasy
+ resteasy-jaxb-provider
+ 3.0.5.Final
+ test
+
+
+ org.jboss.resteasy
+ resteasy-json-p-provider
+ 3.0.5.Final
+ test
+
+
+ org.wildfly
+ wildfly-arquillian-container-remote
+ ${version.wildfly}
+ test
+
+
+
+
+ glassfish-embedded-arquillian
+
+
+ org.glassfish.main.extras
+ glassfish-embedded-all
+ 4.0
+ test
+
+
+ org.glassfish
+ javax.json
+ 1.0.4
+ test
+
+
+ org.glassfish.tyrus
+ tyrus-client
+ 1.3
+ test
+
+
+ org.glassfish.tyrus
+ tyrus-container-grizzly-client
+ 1.3
+ test
+
+
+ org.glassfish.jersey.core
+ jersey-client
+ 2.4
+ test
+
+
+ org.jboss.arquillian.container
+ arquillian-glassfish-embedded-3.1
+ 1.0.0.CR4
+ test
+
+
+
+
+ glassfish-remote-arquillian
+
+
+ org.glassfish
+ javax.json
+ 1.0.4
+ test
+
+
+ org.glassfish.tyrus
+ tyrus-client
+ 1.3
+ test
+
+
+ org.glassfish.tyrus
+ tyrus-container-grizzly-client
+ 1.3
+ test
+
+
+ org.glassfish.jersey.core
+ jersey-client
+ 2.4
+ test
+
+
+ org.glassfish.jersey.media
+ jersey-media-json-jackson
+ 2.4
+ test
+
+
+ org.glassfish.jersey.media
+ jersey-media-json-processing
+ 2.4
+ test
+
+
+ org.jboss.arquillian.container
+ arquillian-glassfish-remote-3.1
+ 1.0.0.CR4
+ test
+
+
+
+
+
diff --git a/jee7schedule/src/main/java/com/baeldung/timer/AutomaticTimerBean.java b/jee7schedule/src/main/java/com/baeldung/timer/AutomaticTimerBean.java
new file mode 100644
index 0000000000..373d962f02
--- /dev/null
+++ b/jee7schedule/src/main/java/com/baeldung/timer/AutomaticTimerBean.java
@@ -0,0 +1,27 @@
+package com.baeldung.timer;
+
+import javax.ejb.Schedule;
+import javax.ejb.Singleton;
+import javax.ejb.Startup;
+import javax.enterprise.event.Event;
+import javax.inject.Inject;
+import java.util.Date;
+
+
+@Startup
+@Singleton
+public class AutomaticTimerBean {
+
+
+ @Inject
+ Event event;
+
+ /**
+ * This method will be called every 10 second and will fire an @TimerEvent
+ */
+ @Schedule(hour = "*", minute = "*", second = "*/10", info = "Every 10 second timer")
+ public void printDate() {
+ event.fire(new TimerEvent("TimerEvent sent at :" + new Date()));
+ }
+
+}
diff --git a/jee7schedule/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java b/jee7schedule/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java
new file mode 100644
index 0000000000..a466682dea
--- /dev/null
+++ b/jee7schedule/src/main/java/com/baeldung/timer/FixedDelayTimerBean.java
@@ -0,0 +1,20 @@
+package com.baeldung.timer;
+
+import javax.ejb.*;
+
+/**
+ * Created by ccristianchiovari on 5/2/16.
+ */
+@Singleton
+public class FixedDelayTimerBean {
+
+ @EJB
+ private WorkerBean workerBean;
+
+ @Lock(LockType.READ)
+ @Schedule(second = "*/5", minute = "*", hour = "*", persistent = false)
+ public void atSchedule() throws InterruptedException {
+ workerBean.doTimerWork();
+ }
+
+}
\ No newline at end of file
diff --git a/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java b/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java
new file mode 100644
index 0000000000..c1c210c8ac
--- /dev/null
+++ b/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBean.java
@@ -0,0 +1,31 @@
+package com.baeldung.timer;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.Resource;
+import javax.ejb.*;
+import javax.enterprise.event.Event;
+import javax.inject.Inject;
+
+/**
+ * author: Cristian Chiovari
+ */
+@Startup
+@Singleton
+public class ProgrammaticAtFixedRateTimerBean {
+
+ @Inject
+ Event event;
+
+ @Resource
+ TimerService timerService;
+
+ @PostConstruct
+ public void initialize() {
+ timerService.createTimer(0,1000, "Every second timer");
+ }
+
+ @Timeout
+ public void programmaticTimout(Timer timer) {
+ event.fire(new TimerEvent(timer.getInfo().toString()));
+ }
+}
diff --git a/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java b/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java
new file mode 100644
index 0000000000..d2dba1239f
--- /dev/null
+++ b/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticTimerBean.java
@@ -0,0 +1,39 @@
+package com.baeldung.timer;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.Resource;
+import javax.ejb.*;
+import javax.enterprise.event.Event;
+import javax.inject.Inject;
+
+/**
+ * author: Jacek Jackowiak
+ */
+@Startup
+@Singleton
+public class ProgrammaticTimerBean {
+
+ @Inject
+ Event event;
+
+ @Resource
+ TimerService timerService;
+
+ @PostConstruct
+ public void initialize() {
+ ScheduleExpression scheduleExpression = new ScheduleExpression()
+ .hour("*")
+ .minute("*")
+ .second("*/5");
+
+ TimerConfig timerConfig = new TimerConfig();
+ timerConfig.setInfo("Every 5 second timer");
+
+ timerService.createCalendarTimer(scheduleExpression, timerConfig);
+ }
+
+ @Timeout
+ public void programmaticTimout(Timer timer) {
+ event.fire(new TimerEvent(timer.getInfo().toString()));
+ }
+}
diff --git a/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java b/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java
new file mode 100644
index 0000000000..9a1ebcdc57
--- /dev/null
+++ b/jee7schedule/src/main/java/com/baeldung/timer/ProgrammaticWithInitialFixedDelayTimerBean.java
@@ -0,0 +1,31 @@
+package com.baeldung.timer;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.Resource;
+import javax.ejb.*;
+import javax.enterprise.event.Event;
+import javax.inject.Inject;
+
+/**
+ * author: Cristian Chiovari
+ */
+@Startup
+@Singleton
+public class ProgrammaticWithInitialFixedDelayTimerBean {
+
+ @Inject
+ Event event;
+
+ @Resource
+ TimerService timerService;
+
+ @PostConstruct
+ public void initialize() {
+ timerService.createTimer(10000l,5000l, "Delay 10 seconds then every 5 second timer");
+ }
+
+ @Timeout
+ public void programmaticTimout(Timer timer) {
+ event.fire(new TimerEvent(timer.getInfo().toString()));
+ }
+}
diff --git a/jee7schedule/src/main/java/com/baeldung/timer/ScheduleTimerBean.java b/jee7schedule/src/main/java/com/baeldung/timer/ScheduleTimerBean.java
new file mode 100644
index 0000000000..09fb95c889
--- /dev/null
+++ b/jee7schedule/src/main/java/com/baeldung/timer/ScheduleTimerBean.java
@@ -0,0 +1,27 @@
+package com.baeldung.timer;
+
+import javax.ejb.Schedule;
+import javax.ejb.Singleton;
+import javax.ejb.Startup;
+import javax.ejb.Timer;
+import javax.enterprise.event.Event;
+import javax.inject.Inject;
+
+
+@Startup
+@Singleton
+public class ScheduleTimerBean {
+
+ @Inject
+ Event event;
+
+ @Schedule(hour = "*", minute = "*", second = "*/5", info = "Every 5 second timer")
+ public void automaticallyScheduled(Timer timer) {
+ fireEvent(timer);
+ }
+
+
+ private void fireEvent(Timer timer) {
+ event.fire(new TimerEvent(timer.getInfo().toString()));
+ }
+}
diff --git a/jee7schedule/src/main/java/com/baeldung/timer/TimerEvent.java b/jee7schedule/src/main/java/com/baeldung/timer/TimerEvent.java
new file mode 100644
index 0000000000..e430cfc1b1
--- /dev/null
+++ b/jee7schedule/src/main/java/com/baeldung/timer/TimerEvent.java
@@ -0,0 +1,27 @@
+package com.baeldung.timer;
+
+public class TimerEvent {
+
+ private String eventInfo;
+ private long time = System.currentTimeMillis();
+
+ public TimerEvent(String s) {
+ this.eventInfo = s;
+ }
+
+ public long getTime() {
+ return time;
+ }
+
+ public String getEventInfo() {
+ return eventInfo;
+ }
+
+ @Override
+ public String toString() {
+ return "TimerEvent {" +
+ "eventInfo='" + eventInfo + '\'' +
+ ", time=" + time +
+ '}';
+ }
+}
diff --git a/jee7schedule/src/main/java/com/baeldung/timer/TimerEventListener.java b/jee7schedule/src/main/java/com/baeldung/timer/TimerEventListener.java
new file mode 100644
index 0000000000..c89677213a
--- /dev/null
+++ b/jee7schedule/src/main/java/com/baeldung/timer/TimerEventListener.java
@@ -0,0 +1,26 @@
+package com.baeldung.timer;
+
+import javax.ejb.Singleton;
+import javax.ejb.Startup;
+import javax.enterprise.event.Observes;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+/**
+ * This class will listen to all TimerEvent and will collect them
+ */
+@Startup
+@Singleton
+public class TimerEventListener {
+
+ final List events = new CopyOnWriteArrayList<>();
+
+ public void listen(@Observes TimerEvent event) {
+ System.out.println("event = " + event);
+ events.add(event);
+ }
+
+ public List getEvents() {
+ return events;
+ }
+}
diff --git a/jee7schedule/src/main/java/com/baeldung/timer/WorkerBean.java b/jee7schedule/src/main/java/com/baeldung/timer/WorkerBean.java
new file mode 100644
index 0000000000..c1f781e95e
--- /dev/null
+++ b/jee7schedule/src/main/java/com/baeldung/timer/WorkerBean.java
@@ -0,0 +1,33 @@
+package com.baeldung.timer;
+
+import javax.ejb.Lock;
+import javax.ejb.LockType;
+import javax.ejb.Singleton;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * Created by cristianchiovari on 5/2/16.
+ */
+@Singleton
+public class WorkerBean {
+
+ private AtomicBoolean busy = new AtomicBoolean(false);
+
+ @Lock(LockType.READ)
+ public void doTimerWork() throws InterruptedException {
+
+ System.out.println("Timer method called but not started yet !");
+
+ if (!busy.compareAndSet(false, true)) {
+ return;
+ }
+
+ try {
+ System.out.println("Timer work started");
+ Thread.sleep(12000);
+ System.out.println("Timer work done");
+ } finally {
+ busy.set(false);
+ }
+ }
+}
\ No newline at end of file
diff --git a/jee7schedule/src/main/webapp/WEB-INF/beans.xml b/jee7schedule/src/main/webapp/WEB-INF/beans.xml
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/jee7schedule/src/test/java/com/baeldung/timer/AutomaticTimerBeanTest.java b/jee7schedule/src/test/java/com/baeldung/timer/AutomaticTimerBeanTest.java
new file mode 100644
index 0000000000..df922b28df
--- /dev/null
+++ b/jee7schedule/src/test/java/com/baeldung/timer/AutomaticTimerBeanTest.java
@@ -0,0 +1,66 @@
+package com.baeldung.timer;
+
+import com.jayway.awaitility.Awaitility;
+import org.hamcrest.Matchers;
+import org.jboss.arquillian.container.test.api.Deployment;
+import org.jboss.arquillian.junit.Arquillian;
+import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.spec.WebArchive;
+import org.jboss.shrinkwrap.resolver.api.maven.Maven;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import javax.inject.Inject;
+import java.io.File;
+import java.util.concurrent.TimeUnit;
+
+import static com.jayway.awaitility.Awaitility.await;
+import static com.jayway.awaitility.Awaitility.to;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+
+
+@RunWith(Arquillian.class)
+public class AutomaticTimerBeanTest {
+
+ //the @AutomaticTimerBean has a method called every 10 seconds
+ //testing the difference ==> 100000
+ final static long TIMEOUT = 10000l;
+
+ //the tolerance accepted , so if between two consecutive calls there has to be at least 9 or max 11 seconds.
+ //because the timer service is not intended for real-time applications so it will not be exactly 10 seconds
+ final static long TOLERANCE = 1000l;
+
+ @Inject
+ TimerEventListener timerEventListener;
+
+ @Deployment
+ public static WebArchive deploy() {
+ File[] jars = Maven.resolver().loadPomFromFile("pom.xml")
+ .resolve("com.jayway.awaitility:awaitility")
+ .withTransitivity().asFile();
+
+ //only @AutomaticTimerBean is deployed not the other timers
+ return ShrinkWrap.create(WebArchive.class)
+ .addAsLibraries(jars)
+ .addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, AutomaticTimerBean.class);
+ }
+
+
+
+ @Test
+ public void should_receive_two_pings() {
+ Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS);
+ //the test will wait here until two events are triggered
+ await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(2));
+
+ TimerEvent firstEvent = timerEventListener.getEvents().get(0);
+ TimerEvent secondEvent = timerEventListener.getEvents().get(1);
+
+ long delay = secondEvent.getTime() - firstEvent.getTime();
+ System.out.println("Actual timeout = " + delay);
+
+ //ensure that the delay between the events is more or less 10 seconds (no real time precision)
+ assertThat(delay, Matchers.is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
+ }
+}
diff --git a/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanTest.java b/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanTest.java
new file mode 100644
index 0000000000..76c0e3e5b8
--- /dev/null
+++ b/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanTest.java
@@ -0,0 +1,56 @@
+package com.baeldung.timer;
+
+import com.jayway.awaitility.Awaitility;
+import org.jboss.arquillian.container.test.api.Deployment;
+import org.jboss.arquillian.junit.Arquillian;
+import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.spec.WebArchive;
+import org.jboss.shrinkwrap.resolver.api.maven.Maven;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import javax.inject.Inject;
+import java.io.File;
+import java.util.concurrent.TimeUnit;
+
+import static com.jayway.awaitility.Awaitility.await;
+import static com.jayway.awaitility.Awaitility.to;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.is;
+
+
+@RunWith(Arquillian.class)
+public class ProgrammaticAtFixedRateTimerBeanTest {
+
+ final static long TIMEOUT = 1000;
+ final static long TOLERANCE = 500l;
+
+ @Inject
+ TimerEventListener timerEventListener;
+
+ @Deployment
+ public static WebArchive deploy() {
+ File[] jars = Maven.resolver().loadPomFromFile("pom.xml")
+ .resolve("com.jayway.awaitility:awaitility")
+ .withTransitivity().asFile();
+
+ return ShrinkWrap.create(WebArchive.class)
+ .addAsLibraries(jars)
+ .addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ProgrammaticAtFixedRateTimerBean.class);
+ }
+
+ @Test
+ public void should_receive_ten_pings() {
+
+ Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS);
+
+ await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(10));
+ TimerEvent firstEvent = timerEventListener.getEvents().get(0);
+ TimerEvent secondEvent = timerEventListener.getEvents().get(1);
+
+ long delay = secondEvent.getTime() - firstEvent.getTime();
+ System.out.println("Actual timeout = " + delay);
+ assertThat(delay, is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
+ }
+}
\ No newline at end of file
diff --git a/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanTest.java b/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanTest.java
new file mode 100644
index 0000000000..f93ba61fe3
--- /dev/null
+++ b/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.timer;
+
+import org.jboss.arquillian.container.test.api.Deployment;
+import org.jboss.arquillian.junit.Arquillian;
+import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.spec.WebArchive;
+import org.jboss.shrinkwrap.resolver.api.maven.Maven;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import javax.inject.Inject;
+import java.io.File;
+
+import static com.jayway.awaitility.Awaitility.await;
+import static com.jayway.awaitility.Awaitility.to;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.is;
+
+
+@RunWith(Arquillian.class)
+public class ProgrammaticTimerBeanTest {
+
+ final static long TIMEOUT = 5000l;
+ final static long TOLERANCE = 1000l;
+
+ @Inject
+ TimerEventListener timerEventListener;
+
+ @Deployment
+ public static WebArchive deploy() {
+ File[] jars = Maven.resolver().loadPomFromFile("pom.xml")
+ .resolve("com.jayway.awaitility:awaitility")
+ .withTransitivity().asFile();
+
+ return ShrinkWrap.create(WebArchive.class)
+ .addAsLibraries(jars)
+ .addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ProgrammaticTimerBean.class);
+ }
+
+ @Test
+ public void should_receive_two_pings() {
+
+ await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(2));
+
+ TimerEvent firstEvent = timerEventListener.getEvents().get(0);
+ TimerEvent secondEvent = timerEventListener.getEvents().get(1);
+
+ long delay = secondEvent.getTime() - firstEvent.getTime();
+ System.out.println("Actual timeout = " + delay);
+ assertThat(delay, is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
+ }
+}
\ No newline at end of file
diff --git a/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanTest.java b/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanTest.java
new file mode 100644
index 0000000000..6764aa386d
--- /dev/null
+++ b/jee7schedule/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanTest.java
@@ -0,0 +1,61 @@
+package com.baeldung.timer;
+
+import com.jayway.awaitility.Awaitility;
+import org.jboss.arquillian.container.test.api.Deployment;
+import org.jboss.arquillian.junit.Arquillian;
+import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.spec.WebArchive;
+import org.jboss.shrinkwrap.resolver.api.maven.Maven;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import javax.inject.Inject;
+import java.io.File;
+import java.util.concurrent.TimeUnit;
+
+import static com.jayway.awaitility.Awaitility.await;
+import static com.jayway.awaitility.Awaitility.to;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.is;
+
+
+@RunWith(Arquillian.class)
+public class ProgrammaticWithFixedDelayTimerBeanTest {
+
+ final static long TIMEOUT = 15000l;
+ final static long TOLERANCE = 1000l;
+
+ @Inject
+ TimerEventListener timerEventListener;
+
+ @Deployment
+ public static WebArchive deploy() {
+ File[] jars = Maven.resolver().loadPomFromFile("pom.xml")
+ .resolve("com.jayway.awaitility:awaitility")
+ .withTransitivity().asFile();
+
+ return ShrinkWrap.create(WebArchive.class)
+ .addAsLibraries(jars)
+ .addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ProgrammaticWithInitialFixedDelayTimerBean.class);
+ }
+
+ @Test
+ public void should_receive_two_pings() {
+
+ Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS);
+
+ // 10 seconds pause so we get the startTime and it will trigger first event
+ long startTime = System.currentTimeMillis();
+
+ await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(2));
+ TimerEvent firstEvent = timerEventListener.getEvents().get(0);
+ TimerEvent secondEvent = timerEventListener.getEvents().get(1);
+
+ long delay = secondEvent.getTime() - startTime;
+ System.out.println("Actual timeout = " + delay);
+
+ //apx 15 seconds = 10 delay + 2 timers (first after a pause of 10 seconds and the next others every 5 seconds)
+ assertThat(delay, is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
+ }
+}
\ No newline at end of file
diff --git a/jee7schedule/src/test/java/com/baeldung/timer/ScheduleTimerBeanTest.java b/jee7schedule/src/test/java/com/baeldung/timer/ScheduleTimerBeanTest.java
new file mode 100644
index 0000000000..7a5b043101
--- /dev/null
+++ b/jee7schedule/src/test/java/com/baeldung/timer/ScheduleTimerBeanTest.java
@@ -0,0 +1,59 @@
+package com.baeldung.timer;
+
+import com.jayway.awaitility.Awaitility;
+import org.hamcrest.Matchers;
+import org.jboss.arquillian.container.test.api.Deployment;
+import org.jboss.arquillian.junit.Arquillian;
+import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.spec.WebArchive;
+import org.jboss.shrinkwrap.resolver.api.maven.Maven;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import javax.inject.Inject;
+import java.io.File;
+import java.util.concurrent.TimeUnit;
+
+import static com.jayway.awaitility.Awaitility.await;
+import static com.jayway.awaitility.Awaitility.to;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+
+
+@RunWith(Arquillian.class)
+public class ScheduleTimerBeanTest {
+
+ final static long TIMEOUT = 5000l;
+ final static long TOLERANCE = 1000l;
+
+ @Inject
+ TimerEventListener timerEventListener;
+
+ @Deployment
+ public static WebArchive deploy() {
+ File[] jars = Maven.resolver().loadPomFromFile("pom.xml")
+ .resolve("com.jayway.awaitility:awaitility")
+ .withTransitivity().asFile();
+
+ return ShrinkWrap.create(WebArchive.class)
+ .addAsLibraries(jars)
+ .addClasses(WithinWindowMatcher.class, TimerEvent.class, TimerEventListener.class, ScheduleTimerBean.class);
+ }
+
+ @Test
+ public void should_receive_three_pings() {
+
+ Awaitility.setDefaultTimeout(30, TimeUnit.SECONDS);
+ await().untilCall(to(timerEventListener.getEvents()).size(), equalTo(3));
+
+ TimerEvent firstEvent = timerEventListener.getEvents().get(0);
+ TimerEvent secondEvent = timerEventListener.getEvents().get(1);
+ TimerEvent thirdEvent = timerEventListener.getEvents().get(2);
+
+ long delay = secondEvent.getTime() - firstEvent.getTime();
+ assertThat(delay, Matchers.is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
+ delay = thirdEvent.getTime() - secondEvent.getTime();
+ assertThat(delay, Matchers.is(WithinWindowMatcher.withinWindow(TIMEOUT, TOLERANCE)));
+
+ }
+}
diff --git a/jee7schedule/src/test/java/com/baeldung/timer/WithinWindowMatcher.java b/jee7schedule/src/test/java/com/baeldung/timer/WithinWindowMatcher.java
new file mode 100644
index 0000000000..91adca6042
--- /dev/null
+++ b/jee7schedule/src/test/java/com/baeldung/timer/WithinWindowMatcher.java
@@ -0,0 +1,30 @@
+package com.baeldung.timer;
+
+import org.hamcrest.BaseMatcher;
+import org.hamcrest.Description;
+import org.hamcrest.Matcher;
+
+class WithinWindowMatcher extends BaseMatcher {
+ private final long timeout;
+ private final long tolerance;
+
+ public WithinWindowMatcher(long timeout, long tolerance) {
+ this.timeout = timeout;
+ this.tolerance = tolerance;
+ }
+
+ @Override
+ public boolean matches(Object item) {
+ final Long actual = (Long) item;
+ return Math.abs(actual - timeout) < tolerance;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ //To change body of implemented methods use File | Settings | File Templates.
+ }
+
+ public static Matcher withinWindow(final long timeout, final long tolerance) {
+ return new WithinWindowMatcher(timeout, tolerance);
+ }
+}
diff --git a/jooq-spring/.classpath b/jooq-spring/.classpath
deleted file mode 100644
index 9ae7bca0fc..0000000000
--- a/jooq-spring/.classpath
+++ /dev/null
@@ -1,31 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/jooq-spring/.gitignore b/jooq-spring/.gitignore
new file mode 100644
index 0000000000..aba850c8e6
--- /dev/null
+++ b/jooq-spring/.gitignore
@@ -0,0 +1 @@
+/src/main/java/com/baeldung/jooq/introduction/db
\ No newline at end of file
diff --git a/jooq-spring/.project b/jooq-spring/.project
deleted file mode 100644
index a291146b79..0000000000
--- a/jooq-spring/.project
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
- jooq-spring
-
-
-
-
-
- org.eclipse.jdt.core.javabuilder
-
-
-
-
- org.springframework.ide.eclipse.core.springbuilder
-
-
-
-
- org.eclipse.m2e.core.maven2Builder
-
-
-
-
-
- org.springframework.ide.eclipse.core.springnature
- org.eclipse.jdt.core.javanature
- org.eclipse.m2e.core.maven2Nature
-
-
diff --git a/jooq-spring/pom.xml b/jooq-spring/pom.xml
index 76198c4993..e77ff0cbfd 100644
--- a/jooq-spring/pom.xml
+++ b/jooq-spring/pom.xml
@@ -5,14 +5,18 @@
jooq-spring
0.0.1-SNAPSHOT
-
- 3.7.3
- 1.4.191
- 4.2.5.RELEASE
- 1.7.18
- 1.1.3
- 4.12
-
+
+
+
+
+ org.springframework.boot
+ spring-boot-dependencies
+ 1.3.5.RELEASE
+ pom
+ import
+
+
+
@@ -33,25 +37,25 @@
org.springframework
spring-context
- ${org.springframework.version}
org.springframework
spring-jdbc
- ${org.springframework.version}
+
+
+ org.springframework.boot
+ spring-boot-starter-jooq
org.slf4j
slf4j-api
- ${org.slf4j.version}
runtime
ch.qos.logback
logback-classic
- ${ch.qos.logback.version}
runtime
@@ -59,13 +63,11 @@
junit
junit
- ${junit.version}
test
org.springframework
spring-test
- ${org.springframework.version}
test
@@ -148,6 +150,29 @@
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ 1.8
+ 1.8
+
+
+
+
+
+ 3.7.3
+ 1.4.191
+ 4.2.5.RELEASE
+ 1.7.18
+ 1.1.3
+ 4.12
+
+ 3.5.1
+
+
\ No newline at end of file
diff --git a/jooq-spring/src/main/resources/application.properties b/jooq-spring/src/main/resources/application.properties
new file mode 100644
index 0000000000..2b32da2356
--- /dev/null
+++ b/jooq-spring/src/main/resources/application.properties
@@ -0,0 +1,3 @@
+spring.datasource.url=jdbc:h2:~/jooq
+spring.datasource.username=sa
+spring.datasource.password=
\ No newline at end of file
diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java
index 7bee21f077..8312f20c05 100644
--- a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java
+++ b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/ExceptionTranslator.java
@@ -8,12 +8,12 @@ import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator;
import org.springframework.jdbc.support.SQLExceptionTranslator;
public class ExceptionTranslator extends DefaultExecuteListener {
- private static final long serialVersionUID = 649359748808106775L;
@Override
public void exception(ExecuteContext context) {
SQLDialect dialect = context.configuration().dialect();
SQLExceptionTranslator translator = new SQLErrorCodeSQLExceptionTranslator(dialect.name());
+
context.exception(translator.translate("Access database using jOOQ", context.sql(), context.sqlException()));
}
}
\ No newline at end of file
diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java
index ee34c00679..df628f9f78 100644
--- a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java
+++ b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/PersistenceContext.java
@@ -1,6 +1,5 @@
package com.baeldung.jooq.introduction;
-import javax.sql.DataSource;
import org.h2.jdbcx.JdbcDataSource;
import org.jooq.SQLDialect;
import org.jooq.impl.DataSourceConnectionProvider;
@@ -17,11 +16,14 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
+import javax.sql.DataSource;
+
@Configuration
@ComponentScan({ "com.baeldung.jooq.introduction.db.public_.tables" })
@EnableTransactionManagement
@PropertySource("classpath:intro_config.properties")
public class PersistenceContext {
+
@Autowired
private Environment environment;
diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java
index bc12dff5a0..68f975dd6d 100644
--- a/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java
+++ b/jooq-spring/src/test/java/com/baeldung/jooq/introduction/QueryTest.java
@@ -1,8 +1,5 @@
package com.baeldung.jooq.introduction;
-import com.baeldung.jooq.introduction.db.public_.tables.Author;
-import com.baeldung.jooq.introduction.db.public_.tables.AuthorBook;
-import com.baeldung.jooq.introduction.db.public_.tables.Book;
import org.jooq.DSLContext;
import org.jooq.Record3;
import org.jooq.Result;
@@ -15,6 +12,9 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
+import static com.baeldung.jooq.introduction.db.public_.tables.Author.AUTHOR;
+import static com.baeldung.jooq.introduction.db.public_.tables.AuthorBook.AUTHOR_BOOK;
+import static com.baeldung.jooq.introduction.db.public_.tables.Book.BOOK;
import static org.junit.Assert.assertEquals;
@ContextConfiguration(classes = PersistenceContext.class)
@@ -25,61 +25,98 @@ public class QueryTest {
@Autowired
private DSLContext dsl;
- Author author = Author.AUTHOR;
- Book book = Book.BOOK;
- AuthorBook authorBook = AuthorBook.AUTHOR_BOOK;
-
@Test
public void givenValidData_whenInserting_thenSucceed() {
- dsl.insertInto(author).set(author.ID, 4).set(author.FIRST_NAME, "Herbert").set(author.LAST_NAME, "Schildt").execute();
- dsl.insertInto(book).set(book.ID, 4).set(book.TITLE, "A Beginner's Guide").execute();
- dsl.insertInto(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 4).execute();
- Result> result = dsl.select(author.ID, author.LAST_NAME, DSL.count()).from(author).join(authorBook).on(author.ID.equal(authorBook.AUTHOR_ID)).join(book).on(authorBook.BOOK_ID.equal(book.ID))
- .groupBy(author.LAST_NAME).fetch();
+ dsl.insertInto(AUTHOR)
+ .set(AUTHOR.ID, 4)
+ .set(AUTHOR.FIRST_NAME, "Herbert")
+ .set(AUTHOR.LAST_NAME, "Schildt")
+ .execute();
+
+ dsl.insertInto(BOOK)
+ .set(BOOK.ID, 4)
+ .set(BOOK.TITLE, "A Beginner's Guide")
+ .execute();
+
+ dsl.insertInto(AUTHOR_BOOK)
+ .set(AUTHOR_BOOK.AUTHOR_ID, 4)
+ .set(AUTHOR_BOOK.BOOK_ID, 4)
+ .execute();
+
+ final Result> result = dsl.select(AUTHOR.ID, AUTHOR.LAST_NAME, DSL.count())
+ .from(AUTHOR)
+ .join(AUTHOR_BOOK).on(AUTHOR.ID.equal(AUTHOR_BOOK.AUTHOR_ID))
+ .join(BOOK).on(AUTHOR_BOOK.BOOK_ID.equal(BOOK.ID))
+ .groupBy(AUTHOR.LAST_NAME).fetch();
assertEquals(3, result.size());
- assertEquals("Sierra", result.getValue(0, author.LAST_NAME));
+ assertEquals("Sierra", result.getValue(0, AUTHOR.LAST_NAME));
assertEquals(Integer.valueOf(2), result.getValue(0, DSL.count()));
- assertEquals("Schildt", result.getValue(2, author.LAST_NAME));
+ assertEquals("Schildt", result.getValue(2, AUTHOR.LAST_NAME));
assertEquals(Integer.valueOf(1), result.getValue(2, DSL.count()));
}
@Test(expected = DataAccessException.class)
public void givenInvalidData_whenInserting_thenFail() {
- dsl.insertInto(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 5).execute();
+ dsl.insertInto(AUTHOR_BOOK).set(AUTHOR_BOOK.AUTHOR_ID, 4).set(AUTHOR_BOOK.BOOK_ID, 5).execute();
}
@Test
public void givenValidData_whenUpdating_thenSucceed() {
- dsl.update(author).set(author.LAST_NAME, "Baeldung").where(author.ID.equal(3)).execute();
- dsl.update(book).set(book.TITLE, "Building your REST API with Spring").where(book.ID.equal(3)).execute();
- dsl.insertInto(authorBook).set(authorBook.AUTHOR_ID, 3).set(authorBook.BOOK_ID, 3).execute();
- Result> result = dsl.select(author.ID, author.LAST_NAME, book.TITLE).from(author).join(authorBook).on(author.ID.equal(authorBook.AUTHOR_ID)).join(book).on(authorBook.BOOK_ID.equal(book.ID)).where(author.ID.equal(3))
+ dsl.update(AUTHOR)
+ .set(AUTHOR.LAST_NAME, "Baeldung")
+ .where(AUTHOR.ID.equal(3))
+ .execute();
+
+ dsl.update(BOOK)
+ .set(BOOK.TITLE, "Building your REST API with Spring")
+ .where(BOOK.ID.equal(3)).execute();
+
+ dsl.insertInto(AUTHOR_BOOK)
+ .set(AUTHOR_BOOK.AUTHOR_ID, 3)
+ .set(AUTHOR_BOOK.BOOK_ID, 3)
+ .execute();
+
+ final Result> result = dsl.select(AUTHOR.ID, AUTHOR.LAST_NAME, BOOK.TITLE)
+ .from(AUTHOR)
+ .join(AUTHOR_BOOK).on(AUTHOR.ID.equal(AUTHOR_BOOK.AUTHOR_ID))
+ .join(BOOK).on(AUTHOR_BOOK.BOOK_ID.equal(BOOK.ID))
+ .where(AUTHOR.ID.equal(3))
.fetch();
assertEquals(1, result.size());
- assertEquals(Integer.valueOf(3), result.getValue(0, author.ID));
- assertEquals("Baeldung", result.getValue(0, author.LAST_NAME));
- assertEquals("Building your REST API with Spring", result.getValue(0, book.TITLE));
+ assertEquals(Integer.valueOf(3), result.getValue(0, AUTHOR.ID));
+ assertEquals("Baeldung", result.getValue(0, AUTHOR.LAST_NAME));
+ assertEquals("Building your REST API with Spring", result.getValue(0, BOOK.TITLE));
}
@Test(expected = DataAccessException.class)
public void givenInvalidData_whenUpdating_thenFail() {
- dsl.update(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 5).execute();
+ dsl.update(AUTHOR_BOOK)
+ .set(AUTHOR_BOOK.AUTHOR_ID, 4)
+ .set(AUTHOR_BOOK.BOOK_ID, 5)
+ .execute();
}
@Test
public void givenValidData_whenDeleting_thenSucceed() {
- dsl.delete(author).where(author.ID.lt(3)).execute();
- Result> result = dsl.select(author.ID, author.FIRST_NAME, author.LAST_NAME).from(author).fetch();
+ dsl.delete(AUTHOR)
+ .where(AUTHOR.ID.lt(3))
+ .execute();
+
+ final Result> result = dsl.select(AUTHOR.ID, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME)
+ .from(AUTHOR)
+ .fetch();
assertEquals(1, result.size());
- assertEquals("Bryan", result.getValue(0, author.FIRST_NAME));
- assertEquals("Basham", result.getValue(0, author.LAST_NAME));
+ assertEquals("Bryan", result.getValue(0, AUTHOR.FIRST_NAME));
+ assertEquals("Basham", result.getValue(0, AUTHOR.LAST_NAME));
}
@Test(expected = DataAccessException.class)
public void givenInvalidData_whenDeleting_thenFail() {
- dsl.delete(book).where(book.ID.equal(1)).execute();
+ dsl.delete(BOOK)
+ .where(BOOK.ID.equal(1))
+ .execute();
}
}
\ No newline at end of file
diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/springboot/Application.java b/jooq-spring/src/test/java/com/baeldung/jooq/springboot/Application.java
new file mode 100644
index 0000000000..ff74851d2a
--- /dev/null
+++ b/jooq-spring/src/test/java/com/baeldung/jooq/springboot/Application.java
@@ -0,0 +1,9 @@
+package com.baeldung.jooq.springboot;
+
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+@SpringBootApplication
+@EnableTransactionManagement
+public class Application {
+}
\ No newline at end of file
diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/springboot/InitialConfiguration.java b/jooq-spring/src/test/java/com/baeldung/jooq/springboot/InitialConfiguration.java
new file mode 100644
index 0000000000..c0d9dac797
--- /dev/null
+++ b/jooq-spring/src/test/java/com/baeldung/jooq/springboot/InitialConfiguration.java
@@ -0,0 +1,39 @@
+package com.baeldung.jooq.springboot;
+
+import com.baeldung.jooq.introduction.ExceptionTranslator;
+import org.jooq.impl.DataSourceConnectionProvider;
+import org.jooq.impl.DefaultConfiguration;
+import org.jooq.impl.DefaultDSLContext;
+import org.jooq.impl.DefaultExecuteListenerProvider;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
+
+import javax.sql.DataSource;
+
+@Configuration
+public class InitialConfiguration {
+
+ @Autowired
+ private DataSource dataSource;
+
+ @Bean
+ public DataSourceConnectionProvider connectionProvider() {
+ return new DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(dataSource));
+ }
+
+ @Bean
+ public DefaultDSLContext dsl() {
+ return new DefaultDSLContext(configuration());
+ }
+
+ public DefaultConfiguration configuration() {
+ DefaultConfiguration jooqConfiguration = new DefaultConfiguration();
+
+ jooqConfiguration.set(connectionProvider());
+ jooqConfiguration.set(new DefaultExecuteListenerProvider(new ExceptionTranslator()));
+
+ return jooqConfiguration;
+ }
+}
diff --git a/jooq-spring/src/test/java/com/baeldung/jooq/springboot/SpringBootTest.java b/jooq-spring/src/test/java/com/baeldung/jooq/springboot/SpringBootTest.java
new file mode 100644
index 0000000000..f9427f30fb
--- /dev/null
+++ b/jooq-spring/src/test/java/com/baeldung/jooq/springboot/SpringBootTest.java
@@ -0,0 +1,124 @@
+package com.baeldung.jooq.springboot;
+
+import org.jooq.DSLContext;
+import org.jooq.Record3;
+import org.jooq.Result;
+import org.jooq.impl.DSL;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.SpringApplicationConfiguration;
+import org.springframework.dao.DataAccessException;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.transaction.annotation.Transactional;
+
+import static com.baeldung.jooq.introduction.db.public_.tables.Author.AUTHOR;
+import static com.baeldung.jooq.introduction.db.public_.tables.AuthorBook.AUTHOR_BOOK;
+import static com.baeldung.jooq.introduction.db.public_.tables.Book.BOOK;
+import static org.junit.Assert.assertEquals;
+
+@SpringApplicationConfiguration(Application.class)
+@Transactional("transactionManager")
+@RunWith(SpringJUnit4ClassRunner.class)
+public class SpringBootTest {
+
+ @Autowired
+ private DSLContext dsl;
+
+ @Test
+ public void givenValidData_whenInserting_thenSucceed() {
+ dsl.insertInto(AUTHOR)
+ .set(AUTHOR.ID, 4)
+ .set(AUTHOR.FIRST_NAME, "Herbert")
+ .set(AUTHOR.LAST_NAME, "Schildt")
+ .execute();
+
+ dsl.insertInto(BOOK)
+ .set(BOOK.ID, 4)
+ .set(BOOK.TITLE, "A Beginner's Guide")
+ .execute();
+
+ dsl.insertInto(AUTHOR_BOOK)
+ .set(AUTHOR_BOOK.AUTHOR_ID, 4)
+ .set(AUTHOR_BOOK.BOOK_ID, 4)
+ .execute();
+
+ final Result> result = dsl.select(AUTHOR.ID, AUTHOR.LAST_NAME, DSL.count())
+ .from(AUTHOR).join(AUTHOR_BOOK).on(AUTHOR.ID.equal(AUTHOR_BOOK.AUTHOR_ID))
+ .join(BOOK).on(AUTHOR_BOOK.BOOK_ID.equal(BOOK.ID))
+ .groupBy(AUTHOR.LAST_NAME)
+ .fetch();
+
+ assertEquals(3, result.size());
+ assertEquals("Sierra", result.getValue(0, AUTHOR.LAST_NAME));
+ assertEquals(Integer.valueOf(2), result.getValue(0, DSL.count()));
+ assertEquals("Schildt", result.getValue(2, AUTHOR.LAST_NAME));
+ assertEquals(Integer.valueOf(1), result.getValue(2, DSL.count()));
+ }
+
+ @Test(expected = DataAccessException.class)
+ public void givenInvalidData_whenInserting_thenFail() {
+ dsl.insertInto(AUTHOR_BOOK)
+ .set(AUTHOR_BOOK.AUTHOR_ID, 4)
+ .set(AUTHOR_BOOK.BOOK_ID, 5)
+ .execute();
+ }
+
+ @Test
+ public void givenValidData_whenUpdating_thenSucceed() {
+ dsl.update(AUTHOR)
+ .set(AUTHOR.LAST_NAME, "Baeldung")
+ .where(AUTHOR.ID.equal(3))
+ .execute();
+
+ dsl.update(BOOK)
+ .set(BOOK.TITLE, "Building your REST API with Spring")
+ .where(BOOK.ID.equal(3))
+ .execute();
+
+ dsl.insertInto(AUTHOR_BOOK)
+ .set(AUTHOR_BOOK.AUTHOR_ID, 3)
+ .set(AUTHOR_BOOK.BOOK_ID, 3)
+ .execute();
+
+ final Result> result = dsl.select(AUTHOR.ID, AUTHOR.LAST_NAME, BOOK.TITLE)
+ .from(AUTHOR).join(AUTHOR_BOOK).on(AUTHOR.ID.equal(AUTHOR_BOOK.AUTHOR_ID))
+ .join(BOOK).on(AUTHOR_BOOK.BOOK_ID.equal(BOOK.ID))
+ .where(AUTHOR.ID.equal(3))
+ .fetch();
+
+ assertEquals(1, result.size());
+ assertEquals(Integer.valueOf(3), result.getValue(0, AUTHOR.ID));
+ assertEquals("Baeldung", result.getValue(0, AUTHOR.LAST_NAME));
+ assertEquals("Building your REST API with Spring", result.getValue(0, BOOK.TITLE));
+ }
+
+ @Test(expected = DataAccessException.class)
+ public void givenInvalidData_whenUpdating_thenFail() {
+ dsl.update(AUTHOR_BOOK)
+ .set(AUTHOR_BOOK.AUTHOR_ID, 4)
+ .set(AUTHOR_BOOK.BOOK_ID, 5)
+ .execute();
+ }
+
+ @Test
+ public void givenValidData_whenDeleting_thenSucceed() {
+ dsl.delete(AUTHOR)
+ .where(AUTHOR.ID.lt(3))
+ .execute();
+
+ final Result> result = dsl.select(AUTHOR.ID, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME)
+ .from(AUTHOR).fetch();
+
+ assertEquals(1, result.size());
+ assertEquals("Bryan", result.getValue(0, AUTHOR.FIRST_NAME));
+ assertEquals("Basham", result.getValue(0, AUTHOR.LAST_NAME));
+ }
+
+ @Test(expected = DataAccessException.class)
+ public void givenInvalidData_whenDeleting_thenFail() {
+ dsl.delete(BOOK)
+ .where(BOOK.ID.equal(1))
+ .execute();
+ }
+}
\ No newline at end of file
diff --git a/jsf/pom.xml b/jsf/pom.xml
index 2f5d315e41..c4801996de 100644
--- a/jsf/pom.xml
+++ b/jsf/pom.xml
@@ -90,12 +90,21 @@
org.apache.maven.plugins
maven-compiler-plugin
- 3.5.1
+ ${maven-compiler-plugin.version}
1.8
1.8
+
+
+ org.apache.maven.plugins
+ maven-war-plugin
+ ${maven-war-plugin.version}
+
+ false
+
+
@@ -112,5 +121,10 @@
3.1.0
+
+
+ 3.5.1
+ 2.6
+
\ No newline at end of file
diff --git a/lombok/pom.xml b/lombok/pom.xml
new file mode 100644
index 0000000000..b816642165
--- /dev/null
+++ b/lombok/pom.xml
@@ -0,0 +1,151 @@
+
+
+
+ 4.0.0
+
+ lombok
+
+ com.baeldung
+ lombok
+ 0.1-SNAPSHOT
+
+
+
+
+ org.projectlombok
+ lombok
+
+ ${lombok.version}
+ provided
+
+
+
+ org.hibernate.javax.persistence
+ hibernate-jpa-2.1-api
+ ${hibernate-jpa-2.1-api.version}
+
+
+
+
+ org.slf4j
+ slf4j-api
+ ${org.slf4j.version}
+
+
+
+ ch.qos.logback
+ logback-core
+ ${logback.version}
+ runtime
+
+
+
+
+
+ junit
+ junit
+ ${junit.version}
+ test
+
+
+
+
+
+
+ lombok
+
+
+ src/main/resources
+ true
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ ${maven.compiler.source}
+ ${maven.compiler.target}
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+
+ org.projectlombok
+ lombok-maven-plugin
+ ${delombok-maven-plugin.version}
+
+
+ delombok
+ generate-sources
+
+ delombok
+
+
+ ${project.basedir}/src/main/java
+ false
+
+ skip
+
+ false
+
+
+
+
+
+
+
+
+
+
+
+ UTF-8
+
+ 1.8
+ 1.8
+
+
+ 1.16.8
+
+
+ 1.0.0.Final
+
+
+ 1.7.13
+ 1.1.3
+
+
+ 4.12
+
+
+ 3.5.1
+ 2.19.1
+
+
+ ${lombok.version}.0
+
+
+
diff --git a/lombok/src/main/java/com/baeldung/lombok/intro/ApiClientConfiguration.java b/lombok/src/main/java/com/baeldung/lombok/intro/ApiClientConfiguration.java
new file mode 100644
index 0000000000..74cc929d32
--- /dev/null
+++ b/lombok/src/main/java/com/baeldung/lombok/intro/ApiClientConfiguration.java
@@ -0,0 +1,22 @@
+package com.baeldung.lombok.intro;
+
+import lombok.Builder;
+import lombok.Getter;
+import lombok.extern.slf4j.Slf4j;
+
+@Builder
+@Slf4j
+@Getter
+public class ApiClientConfiguration {
+
+ private String host;
+ private int port;
+ private boolean useHttps;
+
+ private long connectTimeout;
+ private long readTimeout;
+
+ private String username;
+ private String password;
+
+}
diff --git a/lombok/src/main/java/com/baeldung/lombok/intro/ContactInformationSupport.java b/lombok/src/main/java/com/baeldung/lombok/intro/ContactInformationSupport.java
new file mode 100644
index 0000000000..ea9c3d23f5
--- /dev/null
+++ b/lombok/src/main/java/com/baeldung/lombok/intro/ContactInformationSupport.java
@@ -0,0 +1,17 @@
+package com.baeldung.lombok.intro;
+
+import lombok.Data;
+
+@Data
+public class ContactInformationSupport implements HasContactInformation {
+
+ private String firstName;
+ private String lastName;
+ private String phoneNr;
+
+ @Override
+ public String getFullName() {
+ return getFirstName() + " " + getLastName();
+ }
+
+}
diff --git a/lombok/src/main/java/com/baeldung/lombok/intro/HasContactInformation.java b/lombok/src/main/java/com/baeldung/lombok/intro/HasContactInformation.java
new file mode 100644
index 0000000000..9128df5fb0
--- /dev/null
+++ b/lombok/src/main/java/com/baeldung/lombok/intro/HasContactInformation.java
@@ -0,0 +1,16 @@
+package com.baeldung.lombok.intro;
+
+public interface HasContactInformation {
+
+ String getFirstName();
+ void setFirstName(String firstName);
+
+ String getFullName();
+
+ String getLastName();
+ void setLastName(String lastName);
+
+ String getPhoneNr();
+ void setPhoneNr(String phoneNr);
+
+}
diff --git a/lombok/src/main/java/com/baeldung/lombok/intro/LoginResult.java b/lombok/src/main/java/com/baeldung/lombok/intro/LoginResult.java
new file mode 100644
index 0000000000..6e75696612
--- /dev/null
+++ b/lombok/src/main/java/com/baeldung/lombok/intro/LoginResult.java
@@ -0,0 +1,25 @@
+package com.baeldung.lombok.intro;
+
+import java.net.URL;
+import java.time.Duration;
+import java.time.Instant;
+
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.NonNull;
+import lombok.RequiredArgsConstructor;
+import lombok.experimental.Accessors;
+
+@RequiredArgsConstructor
+@Accessors(fluent = true) @Getter
+@EqualsAndHashCode(of = {"authToken"})
+public class LoginResult {
+
+ private final @NonNull Instant loginTs;
+
+ private final @NonNull String authToken;
+ private final @NonNull Duration tokenValidity;
+
+ private final @NonNull URL tokenRefreshUrl;
+
+}
diff --git a/lombok/src/main/java/com/baeldung/lombok/intro/User.java b/lombok/src/main/java/com/baeldung/lombok/intro/User.java
new file mode 100644
index 0000000000..d032d1f9e7
--- /dev/null
+++ b/lombok/src/main/java/com/baeldung/lombok/intro/User.java
@@ -0,0 +1,43 @@
+package com.baeldung.lombok.intro;
+
+import java.io.Serializable;
+import java.util.List;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+import lombok.ToString;
+import lombok.experimental.Delegate;
+
+@Entity
+@Getter @Setter @NoArgsConstructor // <--- THIS is it
+@ToString(exclude = {"events"})
+public class User implements Serializable, HasContactInformation {
+
+ private @Id @Setter(AccessLevel.PROTECTED) Long id; // will be set when persisting
+
+ private String nickname;
+
+ // Whichever other User-specific attributes
+
+ @Delegate(types = {HasContactInformation.class})
+ private final ContactInformationSupport contactInformation = new ContactInformationSupport();
+
+ // User itelf will implement all contact information by delegation
+
+ @OneToMany(mappedBy = "user")
+ private List events;
+
+ public User(String nickname, String firstName, String lastName, String phoneNr) {
+ this.nickname = nickname;
+ contactInformation.setFirstName(firstName);
+ contactInformation.setLastName(lastName);
+ contactInformation.setPhoneNr(phoneNr);
+ }
+
+}
diff --git a/lombok/src/main/java/com/baeldung/lombok/intro/UserEvent.java b/lombok/src/main/java/com/baeldung/lombok/intro/UserEvent.java
new file mode 100644
index 0000000000..6a13608664
--- /dev/null
+++ b/lombok/src/main/java/com/baeldung/lombok/intro/UserEvent.java
@@ -0,0 +1,29 @@
+package com.baeldung.lombok.intro;
+
+import java.io.Serializable;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.ManyToOne;
+
+import lombok.AccessLevel;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
+@Entity
+@NoArgsConstructor @Getter @Setter
+public class UserEvent implements Serializable {
+
+ // This class is just for sample purposes.
+
+ private @Id @Setter(AccessLevel.PROTECTED) Long id;
+
+ @ManyToOne
+ private User user;
+
+ public UserEvent(User user) {
+ this.user = user;
+ }
+
+}
diff --git a/lombok/src/test/java/com/baeldung/lombok/intro/ApiClientConfigurationTest.java b/lombok/src/test/java/com/baeldung/lombok/intro/ApiClientConfigurationTest.java
new file mode 100644
index 0000000000..8283fc655e
--- /dev/null
+++ b/lombok/src/test/java/com/baeldung/lombok/intro/ApiClientConfigurationTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.lombok.intro;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+
+import com.baeldung.lombok.intro.ApiClientConfiguration.ApiClientConfigurationBuilder;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class ApiClientConfigurationTest {
+
+ @Test
+ public void givenAnnotatedConfiguration_thenCanBeBuiltViaBuilder() {
+ ApiClientConfiguration config =
+ new ApiClientConfigurationBuilder()
+ .host("api.server.com")
+ .port(443)
+ .useHttps(true)
+ .connectTimeout(15_000L)
+ .readTimeout(5_000L)
+ .username("myusername")
+ .password("secret")
+ .build();
+
+ Assert.assertEquals(config.getHost(), "api.server.com");
+ Assert.assertEquals(config.getPort(), 443);
+ Assert.assertEquals(config.isUseHttps(), true);
+ Assert.assertEquals(config.getConnectTimeout(), 15_000L);
+ Assert.assertEquals(config.getReadTimeout(), 5_000L);
+ Assert.assertEquals(config.getUsername(), "myusername");
+ Assert.assertEquals(config.getPassword(), "secret");
+ }
+
+ @Test
+ public void givenAnnotatedConfiguration_thenHasLoggerInstance() throws NoSuchFieldException {
+ Field loggerInstance = ApiClientConfiguration.class.getDeclaredField("log");
+ int modifiers = loggerInstance.getModifiers();
+ Assert.assertTrue(Modifier.isPrivate(modifiers));
+ Assert.assertTrue(Modifier.isStatic(modifiers));
+ Assert.assertTrue(Modifier.isFinal(modifiers));
+ }
+
+}
diff --git a/lombok/src/test/java/com/baeldung/lombok/intro/LoginResultTest.java b/lombok/src/test/java/com/baeldung/lombok/intro/LoginResultTest.java
new file mode 100644
index 0000000000..56878e4a03
--- /dev/null
+++ b/lombok/src/test/java/com/baeldung/lombok/intro/LoginResultTest.java
@@ -0,0 +1,59 @@
+package com.baeldung.lombok.intro;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.time.Duration;
+import java.time.Instant;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class LoginResultTest {
+
+ @Test
+ public void givenAnnotatedLoginResult_thenHasConstructorForAllFinalFields()
+ throws MalformedURLException {
+ /* LoginResult loginResult = */ new LoginResult(
+ Instant.now(),
+ "apitoken",
+ Duration.ofHours(1),
+ new URL("https://api.product.com/token-refresh"));
+ }
+
+ @Test
+ public void givenAnnotatedLoginResult_thenHasFluentGetters()
+ throws MalformedURLException {
+ Instant loginTs = Instant.now();
+ LoginResult loginResult = new LoginResult(
+ loginTs,
+ "apitoken",
+ Duration.ofHours(1),
+ new URL("https://api.product.com/token-refresh"));
+
+ Assert.assertEquals(loginResult.loginTs(), loginTs);
+ Assert.assertEquals(loginResult.authToken(), "apitoken");
+ Assert.assertEquals(loginResult.tokenValidity(), Duration.ofHours(1));
+ Assert.assertEquals(loginResult.tokenRefreshUrl(), new URL("https://api.product.com/token-refresh"));
+ }
+
+ @Test
+ public void givenAnnotatedLoginResult_whenSameApiToken_thenEqualInstances()
+ throws MalformedURLException {
+ String theSameApiToken = "testapitoken";
+
+ LoginResult loginResult1 = new LoginResult(
+ Instant.now(),
+ theSameApiToken,
+ Duration.ofHours(1),
+ new URL("https://api.product.com/token-refresh"));
+
+ LoginResult loginResult2 = new LoginResult(
+ Instant.now(),
+ theSameApiToken,
+ Duration.ofHours(2),
+ new URL("https://api.product.com/token-refresh-alt"));
+
+ Assert.assertEquals(loginResult1, loginResult2);
+ }
+
+}
diff --git a/lombok/src/test/java/com/baeldung/lombok/intro/UserTest.java b/lombok/src/test/java/com/baeldung/lombok/intro/UserTest.java
new file mode 100644
index 0000000000..b3bf21478f
--- /dev/null
+++ b/lombok/src/test/java/com/baeldung/lombok/intro/UserTest.java
@@ -0,0 +1,73 @@
+package com.baeldung.lombok.intro;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UserTest {
+
+ @Test
+ public void givenAnnotatedUser_thenHasEmptyConstructor() {
+ /* User user = */ new User();
+ }
+
+ @Test
+ public void givenAnnotatedUser_thenHasGettersAndSetters() {
+ User user = new User("testnickname", "Test", "JUnit", "123456");
+
+ Assert.assertEquals("testnickname", user.getNickname());
+ Assert.assertEquals("Test", user.getFirstName());
+ Assert.assertEquals("JUnit", user.getLastName());
+ Assert.assertEquals("123456", user.getPhoneNr());
+
+ user.setNickname("testnickname2");
+ user.setFirstName("Test2");
+ user.setLastName("JUnit2");
+ user.setPhoneNr("654321");
+
+ Assert.assertEquals("testnickname2", user.getNickname());
+ Assert.assertEquals("Test2", user.getFirstName());
+ Assert.assertEquals("JUnit2", user.getLastName());
+ Assert.assertEquals("654321", user.getPhoneNr());
+ }
+
+ @Test
+ public void givenAnnotatedUser_thenHasProtectedSetId() throws NoSuchMethodException {
+ Method setIdMethod = User.class.getDeclaredMethod("setId", Long.class);
+ int modifiers = setIdMethod.getModifiers();
+ Assert.assertTrue(Modifier.isProtected(modifiers));
+ }
+
+ @Test
+ public void givenAnnotatedUser_thenImplementsHasContactInformation() {
+ User user = new User("testnickname3", "Test3", "JUnit3", "987654");
+ Assert.assertTrue(user instanceof HasContactInformation);
+
+ Assert.assertEquals("Test3", user.getFirstName());
+ Assert.assertEquals("JUnit3", user.getLastName());
+ Assert.assertEquals("987654", user.getPhoneNr());
+ Assert.assertEquals("Test3 JUnit3", user.getFullName());
+
+ user.setFirstName("Test4");
+ user.setLastName("JUnit4");
+ user.setPhoneNr("456789");
+
+ Assert.assertEquals("Test4", user.getFirstName());
+ Assert.assertEquals("JUnit4", user.getLastName());
+ Assert.assertEquals("456789", user.getPhoneNr());
+ Assert.assertEquals("Test4 JUnit4", user.getFullName());
+ }
+
+ @Test
+ public void givenAnnotatedUser_whenHasEvents_thenToStringDumpsNoEvents() {
+ User user = new User("testnickname", "Test", "JUnit", "123456");
+ List events = Arrays.asList(new UserEvent(user), new UserEvent(user));
+ user.setEvents(events);
+ Assert.assertFalse(user.toString().contains("events"));
+ }
+
+}
diff --git a/mock-comparisons/README.md b/mock-comparisons/README.md
new file mode 100644
index 0000000000..7795487b77
--- /dev/null
+++ b/mock-comparisons/README.md
@@ -0,0 +1,7 @@
+=========
+
+## Mock comparison realated tutorials
+
+
+### Relevant Articles:
+- [Mockito vs EasyMock vs JMockit](http://www.baeldung.com/mockito-vs-easymock-vs-jmockit)
diff --git a/mock-comparisons/pom.xml b/mock-comparisons/pom.xml
new file mode 100644
index 0000000000..c5424d262d
--- /dev/null
+++ b/mock-comparisons/pom.xml
@@ -0,0 +1,86 @@
+
+ 4.0.0
+ org.baeldung
+ mock-comparisons
+ 0.1-SNAPSHOT
+
+ mockito
+
+
+ 4.12
+ 1.10.19
+ 3.4
+ 1.24
+
+ UTF-8
+
+
+ 3.3
+ 2.18.1
+
+
+
+
+ junit
+ junit
+ ${junit.version}
+ test
+
+
+
+ org.mockito
+ mockito-core
+ ${mockito.version}
+ test
+
+
+
+ org.easymock
+ easymock
+ ${easymock.version}
+ test
+
+
+
+ org.jmockit
+ jmockit
+ ${jmockit.version}
+ test
+
+
+
+
+
+ mock-comparisons
+
+
+ src/main/resources
+ true
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ 1.8
+ 1.8
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginController.java b/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginController.java
new file mode 100644
index 0000000000..914b0034d2
--- /dev/null
+++ b/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginController.java
@@ -0,0 +1,29 @@
+package org.baeldung.mocks.testCase;
+
+public class LoginController {
+
+ public LoginService loginService;
+
+ public String login(UserForm userForm) {
+ if (null == userForm) {
+ return "ERROR";
+ } else {
+ boolean logged;
+
+ try {
+ logged = loginService.login(userForm);
+ } catch (Exception e) {
+ return "ERROR";
+ }
+
+ if (logged) {
+ loginService.setCurrentUser(userForm.getUsername());
+ return "OK";
+ } else {
+ return "KO";
+ }
+ }
+ }
+
+ // standard setters and getters
+}
diff --git a/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginDao.java b/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginDao.java
new file mode 100644
index 0000000000..2cbff6c9d4
--- /dev/null
+++ b/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginDao.java
@@ -0,0 +1,9 @@
+package org.baeldung.mocks.testCase;
+
+public class LoginDao {
+
+ public int login(UserForm userForm) {
+ //actual call to a third party library
+ return 0;
+ }
+}
diff --git a/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginService.java b/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginService.java
new file mode 100644
index 0000000000..d6a31a8047
--- /dev/null
+++ b/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/LoginService.java
@@ -0,0 +1,33 @@
+package org.baeldung.mocks.testCase;
+
+public class LoginService {
+
+ private LoginDao loginDao;
+
+ private String currentUser;
+
+ public boolean login(UserForm userForm) {
+ assert null != userForm;
+
+ int loginResults = loginDao.login(userForm);
+
+ switch (loginResults) {
+ case 1:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ public void setCurrentUser(String username) {
+ if (null != username) {
+ this.currentUser = username;
+ }
+ }
+
+ public void setLoginDao(LoginDao loginDao) {
+ this.loginDao = loginDao;
+ }
+
+ // standard setters and getters
+}
diff --git a/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/UserForm.java b/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/UserForm.java
new file mode 100644
index 0000000000..14136d0f31
--- /dev/null
+++ b/mock-comparisons/src/main/java/org/baeldung/mocks/testCase/UserForm.java
@@ -0,0 +1,15 @@
+package org.baeldung.mocks.testCase;
+
+public class UserForm {
+
+ // public access modifiers as only for testing
+
+ public String password;
+
+ public String username;
+
+ public String getUsername() {
+ return username;
+ }
+
+}
diff --git a/mock-comparisons/src/test/java/org/baeldung/mocks/easymock/LoginControllerTest.java b/mock-comparisons/src/test/java/org/baeldung/mocks/easymock/LoginControllerTest.java
new file mode 100644
index 0000000000..25d2b91ede
--- /dev/null
+++ b/mock-comparisons/src/test/java/org/baeldung/mocks/easymock/LoginControllerTest.java
@@ -0,0 +1,143 @@
+package org.baeldung.mocks.easymock;
+
+import org.baeldung.mocks.testCase.LoginController;
+import org.baeldung.mocks.testCase.LoginDao;
+import org.baeldung.mocks.testCase.LoginService;
+import org.baeldung.mocks.testCase.UserForm;
+import org.easymock.*;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(EasyMockRunner.class)
+public class LoginControllerTest {
+
+ @Mock
+ private LoginDao loginDao;
+
+ @Mock
+ private LoginService loginService;
+
+ @TestSubject
+ private LoginController loginController = new LoginController();
+
+ @Test
+ public void assertThatNoMethodHasBeenCalled() {
+ EasyMock.replay(loginService);
+ loginController.login(null);
+
+ // no method called
+ EasyMock.verify(loginService);
+ }
+
+ @Test
+ public void assertTwoMethodsHaveBeenCalled() {
+ UserForm userForm = new UserForm();
+ userForm.username = "foo";
+ EasyMock.expect(loginService.login(userForm)).andReturn(true);
+ loginService.setCurrentUser("foo");
+ EasyMock.replay(loginService);
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("OK", login);
+ EasyMock.verify(loginService);
+ }
+
+ @Test
+ public void assertOnlyOneMethodHasBeenCalled() {
+ UserForm userForm = new UserForm();
+ userForm.username = "foo";
+ EasyMock.expect(loginService.login(userForm)).andReturn(false);
+ EasyMock.replay(loginService);
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("KO", login);
+ EasyMock.verify(loginService);
+ }
+
+ @Test
+ public void mockExceptionThrowing() {
+ UserForm userForm = new UserForm();
+ EasyMock.expect(loginService.login(userForm)).andThrow(new IllegalArgumentException());
+ EasyMock.replay(loginService);
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("ERROR", login);
+ EasyMock.verify(loginService);
+ }
+
+ @Test
+ public void mockAnObjectToPassAround() {
+ UserForm userForm = EasyMock.mock(UserForm.class);
+ EasyMock.expect(userForm.getUsername()).andReturn("foo");
+ EasyMock.expect(loginService.login(userForm)).andReturn(true);
+ loginService.setCurrentUser("foo");
+ EasyMock.replay(userForm);
+ EasyMock.replay(loginService);
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("OK", login);
+ EasyMock.verify(userForm);
+ EasyMock.verify(loginService);
+ }
+
+ @Test
+ public void argumentMatching() {
+ UserForm userForm = new UserForm();
+ userForm.username = "foo";
+ // default matcher
+ EasyMock.expect(loginService.login(EasyMock.isA(UserForm.class))).andReturn(true);
+ // complex matcher
+ loginService.setCurrentUser(specificArgumentMatching("foo"));
+ EasyMock.replay(loginService);
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("OK", login);
+ EasyMock.verify(loginService);
+ }
+
+ private static String specificArgumentMatching(final String expected) {
+ EasyMock.reportMatcher(new IArgumentMatcher() {
+ @Override
+ public boolean matches(Object argument) {
+ return argument instanceof String && ((String) argument).startsWith(expected);
+ }
+
+ @Override
+ public void appendTo(StringBuffer buffer) {
+ //NOOP
+ }
+ });
+ return null;
+ }
+
+ @Test
+ public void partialMocking() {
+ UserForm userForm = new UserForm();
+ userForm.username = "foo";
+ // use partial mock
+ LoginService loginServicePartial = EasyMock.partialMockBuilder(LoginService.class).
+ addMockedMethod("setCurrentUser").createMock();
+ loginServicePartial.setCurrentUser("foo");
+ // let service's login use implementation so let's mock DAO call
+ EasyMock.expect(loginDao.login(userForm)).andReturn(1);
+
+ loginServicePartial.setLoginDao(loginDao);
+ loginController.loginService = loginServicePartial;
+
+ EasyMock.replay(loginDao);
+ EasyMock.replay(loginServicePartial);
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("OK", login);
+ // verify mocked call
+ EasyMock.verify(loginServicePartial);
+ EasyMock.verify(loginDao);
+ }
+}
diff --git a/mock-comparisons/src/test/java/org/baeldung/mocks/jmockit/LoginControllerTest.java b/mock-comparisons/src/test/java/org/baeldung/mocks/jmockit/LoginControllerTest.java
new file mode 100644
index 0000000000..621342fed2
--- /dev/null
+++ b/mock-comparisons/src/test/java/org/baeldung/mocks/jmockit/LoginControllerTest.java
@@ -0,0 +1,159 @@
+package org.baeldung.mocks.jmockit;
+
+import mockit.*;
+import mockit.integration.junit4.JMockit;
+import org.baeldung.mocks.testCase.LoginController;
+import org.baeldung.mocks.testCase.LoginDao;
+import org.baeldung.mocks.testCase.LoginService;
+import org.baeldung.mocks.testCase.UserForm;
+import org.hamcrest.BaseMatcher;
+import org.hamcrest.Description;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(JMockit.class)
+public class LoginControllerTest {
+
+ @Injectable
+ private LoginDao loginDao;
+
+ @Injectable
+ private LoginService loginService;
+
+ @Tested
+ private LoginController loginController;
+
+ @Test
+ public void assertThatNoMethodHasBeenCalled() {
+ loginController.login(null);
+ // no method called
+ new FullVerifications(loginService) {
+ };
+ }
+
+ @Test
+ public void assertTwoMethodsHaveBeenCalled() {
+ final UserForm userForm = new UserForm();
+ userForm.username = "foo";
+ new Expectations() {{
+ loginService.login(userForm);
+ result = true;
+ loginService.setCurrentUser("foo");
+ }};
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("OK", login);
+ new FullVerifications(loginService) {
+ };
+ }
+
+ @Test
+ public void assertOnlyOneMethodHasBeenCalled() {
+ final UserForm userForm = new UserForm();
+ userForm.username = "foo";
+ new Expectations() {{
+ loginService.login(userForm);
+ result = false;
+ // no expectation for setCurrentUser
+ }};
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("KO", login);
+ new FullVerifications(loginService) {
+ };
+ }
+
+ @Test
+ public void mockExceptionThrowing() {
+ final UserForm userForm = new UserForm();
+ new Expectations() {{
+ loginService.login(userForm);
+ result = new IllegalArgumentException();
+ // no expectation for setCurrentUser
+ }};
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("ERROR", login);
+ new FullVerifications(loginService) {
+ };
+ }
+
+ @Test
+ public void mockAnObjectToPassAround(@Mocked final UserForm userForm) {
+ new Expectations() {{
+ userForm.getUsername();
+ result = "foo";
+ loginService.login(userForm);
+ result = true;
+ loginService.setCurrentUser("foo");
+ }};
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("OK", login);
+ new FullVerifications(loginService) {
+ };
+ new FullVerifications(userForm) {
+ };
+ }
+
+ @Test
+ public void argumentMatching() {
+ final UserForm userForm = new UserForm();
+ userForm.username = "foo";
+ // default matcher
+ new Expectations() {{
+ loginService.login((UserForm) any);
+ result = true;
+ // complex matcher
+ loginService.setCurrentUser(withArgThat(new BaseMatcher() {
+ @Override
+ public boolean matches(Object item) {
+ return item instanceof String && ((String) item).startsWith("foo");
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ //NOOP
+ }
+ }));
+ }};
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("OK", login);
+ new FullVerifications(loginService) {
+ };
+ }
+
+ @Test
+ public void partialMocking() {
+ // use partial mock
+ final LoginService partialLoginService = new LoginService();
+ partialLoginService.setLoginDao(loginDao);
+ loginController.loginService = partialLoginService;
+
+ final UserForm userForm = new UserForm();
+ userForm.username = "foo";
+ // let service's login use implementation so let's mock DAO call
+ new Expectations() {{
+ loginDao.login(userForm);
+ result = 1;
+ // no expectation for loginService.login
+ partialLoginService.setCurrentUser("foo");
+ }};
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("OK", login);
+ // verify mocked call
+ new FullVerifications(partialLoginService) {
+ };
+ new FullVerifications(loginDao) {
+ };
+ }
+}
diff --git a/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerTest.java b/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerTest.java
new file mode 100644
index 0000000000..59b28a2cb4
--- /dev/null
+++ b/mock-comparisons/src/test/java/org/baeldung/mocks/mockito/LoginControllerTest.java
@@ -0,0 +1,125 @@
+package org.baeldung.mocks.mockito;
+
+import org.baeldung.mocks.testCase.LoginController;
+import org.baeldung.mocks.testCase.LoginDao;
+import org.baeldung.mocks.testCase.LoginService;
+import org.baeldung.mocks.testCase.UserForm;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.*;
+
+public class LoginControllerTest {
+
+ @Mock
+ private LoginDao loginDao;
+
+ @Spy
+ @InjectMocks
+ private LoginService spiedLoginService;
+
+ @Mock
+ private LoginService loginService;
+
+ @InjectMocks
+ private LoginController loginController;
+
+ @Before
+ public void setUp() {
+ loginController = new LoginController();
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void assertThatNoMethodHasBeenCalled() {
+ loginController.login(null);
+ // no method called
+ Mockito.verifyZeroInteractions(loginService);
+ }
+
+ @Test
+ public void assertTwoMethodsHaveBeenCalled() {
+ UserForm userForm = new UserForm();
+ userForm.username = "foo";
+ Mockito.when(loginService.login(userForm)).thenReturn(true);
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("OK", login);
+ Mockito.verify(loginService).login(userForm);
+ Mockito.verify(loginService).setCurrentUser("foo");
+ }
+
+ @Test
+ public void assertOnlyOneMethodHasBeenCalled() {
+ UserForm userForm = new UserForm();
+ userForm.username = "foo";
+ Mockito.when(loginService.login(userForm)).thenReturn(false);
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("KO", login);
+ Mockito.verify(loginService).login(userForm);
+ Mockito.verifyNoMoreInteractions(loginService);
+ }
+
+ @Test
+ public void mockExceptionThrowing() {
+ UserForm userForm = new UserForm();
+ Mockito.when(loginService.login(userForm)).thenThrow(IllegalArgumentException.class);
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("ERROR", login);
+ Mockito.verify(loginService).login(userForm);
+ Mockito.verifyZeroInteractions(loginService);
+ }
+
+ @Test
+ public void mockAnObjectToPassAround() {
+ UserForm userForm = Mockito.when(Mockito.mock(UserForm.class).getUsername()).thenReturn("foo").getMock();
+ Mockito.when(loginService.login(userForm)).thenReturn(true);
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("OK", login);
+ Mockito.verify(loginService).login(userForm);
+ Mockito.verify(loginService).setCurrentUser("foo");
+ }
+
+ @Test
+ public void argumentMatching() {
+ UserForm userForm = new UserForm();
+ userForm.username = "foo";
+ // default matcher
+ Mockito.when(loginService.login(Mockito.any(UserForm.class))).thenReturn(true);
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("OK", login);
+ Mockito.verify(loginService).login(userForm);
+ // complex matcher
+ Mockito.verify(loginService).setCurrentUser(Mockito.argThat(new ArgumentMatcher() {
+ @Override
+ public boolean matches(Object argument) {
+ return argument instanceof String && ((String) argument).startsWith("foo");
+ }
+ }));
+ }
+
+ @Test
+ public void partialMocking() {
+ // use partial mock
+ loginController.loginService = spiedLoginService;
+ UserForm userForm = new UserForm();
+ userForm.username = "foo";
+ // let service's login use implementation so let's mock DAO call
+ Mockito.when(loginDao.login(userForm)).thenReturn(1);
+
+ String login = loginController.login(userForm);
+
+ Assert.assertEquals("OK", login);
+ // verify mocked call
+ Mockito.verify(spiedLoginService).setCurrentUser("foo");
+ }
+}
diff --git a/pom.xml b/pom.xml
index d6a1d7c034..75281ce80d 100644
--- a/pom.xml
+++ b/pom.xml
@@ -9,6 +9,8 @@
apache-fop
+ assertj
+
core-java
core-java-8
gson
@@ -20,8 +22,11 @@
httpclient
jackson
javaxval
+ jooq-spring
json-path
mockito
+ mock-comparisons
+ jee7schedule
querydsl
@@ -47,6 +52,7 @@
spring-mvc-no-xml
spring-mvc-xml
spring-openid
+ spring-protobuf
spring-quartz
spring-rest
@@ -65,7 +71,9 @@
spring-thymeleaf
spring-zuul
jsf
+ xml
+ lombok
diff --git a/raml/README.MD b/raml/README.MD
new file mode 100644
index 0000000000..2a87b46021
--- /dev/null
+++ b/raml/README.MD
@@ -0,0 +1,2 @@
+###The Course
+The "REST With Spring" Classes: http://bit.ly/restwithspring
diff --git a/rest-testing/.classpath b/rest-testing/.classpath
deleted file mode 100644
index 8ebf6d9c31..0000000000
--- a/rest-testing/.classpath
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/rest-testing/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/rest-testing/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch
deleted file mode 100644
index 627021fb96..0000000000
--- a/rest-testing/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
-
-
-
diff --git a/rest-testing/.gitignore b/rest-testing/.gitignore
index 83c05e60c8..601d2281e5 100644
--- a/rest-testing/.gitignore
+++ b/rest-testing/.gitignore
@@ -10,4 +10,8 @@
# Packaged files #
*.jar
*.war
-*.ear
\ No newline at end of file
+*.ear
+
+.externalToolBuilders
+.settings
+.springBeans
\ No newline at end of file
diff --git a/rest-testing/.project b/rest-testing/.project
deleted file mode 100644
index 1dc9ce93fe..0000000000
--- a/rest-testing/.project
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
- rest-testing
-
-
-
-
-
- org.eclipse.jdt.core.javabuilder
-
-
-
-
- org.eclipse.wst.common.project.facet.core.builder
-
-
-
-
- org.eclipse.wst.validation.validationbuilder
-
-
-
-
- org.eclipse.m2e.core.maven2Builder
-
-
-
-
-
- org.eclipse.jem.workbench.JavaEMFNature
- org.eclipse.wst.common.modulecore.ModuleCoreNature
- org.eclipse.jdt.core.javanature
- org.eclipse.m2e.core.maven2Nature
- org.eclipse.wst.common.project.facet.core.nature
-
-
diff --git a/rest-testing/.settings/.jsdtscope b/rest-testing/.settings/.jsdtscope
deleted file mode 100644
index 7b3f0c8b9f..0000000000
--- a/rest-testing/.settings/.jsdtscope
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/rest-testing/.settings/org.eclipse.jdt.core.prefs b/rest-testing/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index b126d6476b..0000000000
--- a/rest-testing/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,95 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.8
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=error
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=error
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.8
diff --git a/rest-testing/.settings/org.eclipse.jdt.ui.prefs b/rest-testing/.settings/org.eclipse.jdt.ui.prefs
deleted file mode 100644
index 471e9b0d81..0000000000
--- a/rest-testing/.settings/org.eclipse.jdt.ui.prefs
+++ /dev/null
@@ -1,55 +0,0 @@
-#Sat Jan 21 23:04:06 EET 2012
-eclipse.preferences.version=1
-editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
-sp_cleanup.add_default_serial_version_id=true
-sp_cleanup.add_generated_serial_version_id=false
-sp_cleanup.add_missing_annotations=true
-sp_cleanup.add_missing_deprecated_annotations=true
-sp_cleanup.add_missing_methods=false
-sp_cleanup.add_missing_nls_tags=false
-sp_cleanup.add_missing_override_annotations=true
-sp_cleanup.add_missing_override_annotations_interface_methods=true
-sp_cleanup.add_serial_version_id=false
-sp_cleanup.always_use_blocks=true
-sp_cleanup.always_use_parentheses_in_expressions=true
-sp_cleanup.always_use_this_for_non_static_field_access=false
-sp_cleanup.always_use_this_for_non_static_method_access=false
-sp_cleanup.convert_to_enhanced_for_loop=true
-sp_cleanup.correct_indentation=true
-sp_cleanup.format_source_code=true
-sp_cleanup.format_source_code_changes_only=true
-sp_cleanup.make_local_variable_final=true
-sp_cleanup.make_parameters_final=true
-sp_cleanup.make_private_fields_final=false
-sp_cleanup.make_type_abstract_if_missing_method=false
-sp_cleanup.make_variable_declarations_final=true
-sp_cleanup.never_use_blocks=false
-sp_cleanup.never_use_parentheses_in_expressions=false
-sp_cleanup.on_save_use_additional_actions=true
-sp_cleanup.organize_imports=true
-sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
-sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
-sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
-sp_cleanup.qualify_static_member_accesses_with_declaring_class=true
-sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
-sp_cleanup.remove_private_constructors=true
-sp_cleanup.remove_trailing_whitespaces=true
-sp_cleanup.remove_trailing_whitespaces_all=true
-sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
-sp_cleanup.remove_unnecessary_casts=true
-sp_cleanup.remove_unnecessary_nls_tags=false
-sp_cleanup.remove_unused_imports=true
-sp_cleanup.remove_unused_local_variables=false
-sp_cleanup.remove_unused_private_fields=true
-sp_cleanup.remove_unused_private_members=false
-sp_cleanup.remove_unused_private_methods=true
-sp_cleanup.remove_unused_private_types=true
-sp_cleanup.sort_members=false
-sp_cleanup.sort_members_all=false
-sp_cleanup.use_blocks=false
-sp_cleanup.use_blocks_only_for_return_and_throw=false
-sp_cleanup.use_parentheses_in_expressions=false
-sp_cleanup.use_this_for_non_static_field_access=true
-sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
-sp_cleanup.use_this_for_non_static_method_access=true
-sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
diff --git a/rest-testing/.settings/org.eclipse.m2e.core.prefs b/rest-testing/.settings/org.eclipse.m2e.core.prefs
deleted file mode 100644
index f897a7f1cb..0000000000
--- a/rest-testing/.settings/org.eclipse.m2e.core.prefs
+++ /dev/null
@@ -1,4 +0,0 @@
-activeProfiles=
-eclipse.preferences.version=1
-resolveWorkspaceProjects=true
-version=1
diff --git a/rest-testing/.settings/org.eclipse.m2e.wtp.prefs b/rest-testing/.settings/org.eclipse.m2e.wtp.prefs
deleted file mode 100644
index ef86089622..0000000000
--- a/rest-testing/.settings/org.eclipse.m2e.wtp.prefs
+++ /dev/null
@@ -1,2 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false
diff --git a/rest-testing/.settings/org.eclipse.wst.common.component b/rest-testing/.settings/org.eclipse.wst.common.component
deleted file mode 100644
index e98377cb0f..0000000000
--- a/rest-testing/.settings/org.eclipse.wst.common.component
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
-
-
-
diff --git a/rest-testing/.settings/org.eclipse.wst.common.project.facet.core.xml b/rest-testing/.settings/org.eclipse.wst.common.project.facet.core.xml
deleted file mode 100644
index f4ef8aa0a5..0000000000
--- a/rest-testing/.settings/org.eclipse.wst.common.project.facet.core.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
diff --git a/rest-testing/.settings/org.eclipse.wst.jsdt.ui.superType.container b/rest-testing/.settings/org.eclipse.wst.jsdt.ui.superType.container
deleted file mode 100644
index 3bd5d0a480..0000000000
--- a/rest-testing/.settings/org.eclipse.wst.jsdt.ui.superType.container
+++ /dev/null
@@ -1 +0,0 @@
-org.eclipse.wst.jsdt.launching.baseBrowserLibrary
\ No newline at end of file
diff --git a/rest-testing/.settings/org.eclipse.wst.jsdt.ui.superType.name b/rest-testing/.settings/org.eclipse.wst.jsdt.ui.superType.name
deleted file mode 100644
index 05bd71b6ec..0000000000
--- a/rest-testing/.settings/org.eclipse.wst.jsdt.ui.superType.name
+++ /dev/null
@@ -1 +0,0 @@
-Window
\ No newline at end of file
diff --git a/rest-testing/.settings/org.eclipse.wst.validation.prefs b/rest-testing/.settings/org.eclipse.wst.validation.prefs
deleted file mode 100644
index cacf5451ae..0000000000
--- a/rest-testing/.settings/org.eclipse.wst.validation.prefs
+++ /dev/null
@@ -1,14 +0,0 @@
-DELEGATES_PREFERENCE=delegateValidatorList
-USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
-USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
-USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.303.v201202090300
-eclipse.preferences.version=1
-override=true
-suspend=false
-vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01
-vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01
-vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01
-vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01
-vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01
-vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02
-vf.version=3
diff --git a/rest-testing/.settings/org.eclipse.wst.ws.service.policy.prefs b/rest-testing/.settings/org.eclipse.wst.ws.service.policy.prefs
deleted file mode 100644
index 9cfcabe16f..0000000000
--- a/rest-testing/.settings/org.eclipse.wst.ws.service.policy.prefs
+++ /dev/null
@@ -1,2 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.wst.ws.service.policy.projectEnabled=false
diff --git a/rest-testing/.springBeans b/rest-testing/.springBeans
deleted file mode 100644
index a79097f40d..0000000000
--- a/rest-testing/.springBeans
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
- 1
-
-
-
-
-
-
- src/main/webapp/WEB-INF/api-servlet.xml
-
-
-
-
diff --git a/rest-testing/README.md b/rest-testing/README.md
index db7f0c8a86..54a2e98dda 100644
--- a/rest-testing/README.md
+++ b/rest-testing/README.md
@@ -2,6 +2,8 @@
## REST Testing and Examples
+###The Course
+The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Test a REST API with Java](http://www.baeldung.com/2011/10/13/integration-testing-a-rest-api/)
diff --git a/rest-testing/pom.xml b/rest-testing/pom.xml
index e159af0b77..652f2ab601 100644
--- a/rest-testing/pom.xml
+++ b/rest-testing/pom.xml
@@ -1,173 +1,191 @@
-
- 4.0.0
- com.baeldung
- rest-testing
- 0.1-SNAPSHOT
+
+ 4.0.0
+ com.baeldung
+ rest-testing
+ 0.1-SNAPSHOT
- rest-testing
+ rest-testing
-
+
-
+
-
- com.google.guava
- guava
- ${guava.version}
-
+
+ com.google.guava
+ guava
+ ${guava.version}
+
-
- commons-io
- commons-io
- 2.4
-
+
+ commons-io
+ commons-io
+ 2.4
+
-
- org.apache.commons
- commons-lang3
- ${commons-lang3.version}
-
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
-
+
-
- org.apache.httpcomponents
- httpclient
- ${httpclient.version}
-
-
- org.apache.httpcomponents
- httpcore
- ${httpcore.version}
-
+
+ org.apache.httpcomponents
+ httpclient
+ ${httpclient.version}
+
+
+ org.apache.httpcomponents
+ httpcore
+ ${httpcore.version}
+
-
+
-
- com.fasterxml.jackson.core
- jackson-databind
- ${jackson.version}
-
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${jackson.version}
+
-
+
-
- org.slf4j
- slf4j-api
- ${org.slf4j.version}
-
-
- ch.qos.logback
- logback-classic
- ${logback.version}
-
-
-
- org.slf4j
- jcl-over-slf4j
- ${org.slf4j.version}
- runtime
-
-
- org.slf4j
- log4j-over-slf4j
- ${org.slf4j.version}
-
+
+ org.slf4j
+ slf4j-api
+ ${org.slf4j.version}
+
+
+ ch.qos.logback
+ logback-classic
+ ${logback.version}
+
+
+
+ org.slf4j
+ jcl-over-slf4j
+ ${org.slf4j.version}
+ runtime
+
+
+ org.slf4j
+ log4j-over-slf4j
+ ${org.slf4j.version}
+
-
+
-
- junit
- junit
- ${junit.version}
- test
-
+
+ junit
+ junit
+ ${junit.version}
+ test
+
-
- org.hamcrest
- hamcrest-core
- ${org.hamcrest.version}
- test
-
-
- org.hamcrest
- hamcrest-library
- ${org.hamcrest.version}
- test
-
+
+ org.hamcrest
+ hamcrest-core
+ ${org.hamcrest.version}
+ test
+
+
+ org.hamcrest
+ hamcrest-library
+ ${org.hamcrest.version}
+ test
+
-
- org.mockito
- mockito-core
- ${mockito.version}
- test
-
+
+ org.mockito
+ mockito-core
+ ${mockito.version}
+ test
+
+
+ com.github.tomakehurst
+ wiremock
+ 1.58
+ test
+
-
+
+ info.cukes
+ cucumber-java
+ 1.2.4
+ test
+
+
+ info.cukes
+ cucumber-junit
+ 1.2.4
+
+
-
- rest-testing
-
-
- src/main/resources
- true
-
-
+
+ rest-testing
+
+
+ src/main/resources
+ true
+
+
-
+
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
-
-
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ 1.8
+ 1.8
+
+
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
-
+
-
+
-
-
- 2.7.2
+
+
+ 2.7.2
-
- 1.7.13
- 1.1.3
+
+ 1.7.13
+ 1.1.3
-
- 5.1.3.Final
+
+ 5.1.3.Final
-
- 19.0
- 3.4
+
+ 19.0
+ 3.4
-
- 1.3
- 4.12
- 1.10.19
+
+ 1.3
+ 4.12
+ 1.10.19
- 4.4.1
- 4.5
+ 4.4.1
+ 4.5
- 2.9.0
+ 2.9.0
-
- 3.5.1
- 2.6
- 2.19.1
- 2.7
- 1.4.18
+
+ 3.5.1
+ 2.6
+ 2.19.1
+ 2.7
+ 1.4.18
-
+
\ No newline at end of file
diff --git a/rest-testing/src/main/resources/Feature/cucumber.feature b/rest-testing/src/main/resources/Feature/cucumber.feature
new file mode 100644
index 0000000000..99dd8249fe
--- /dev/null
+++ b/rest-testing/src/main/resources/Feature/cucumber.feature
@@ -0,0 +1,10 @@
+Feature: Testing a REST API
+ Users should be able to submit GET and POST requests to a web service, represented by WireMock
+
+ Scenario: Data Upload to a web service
+ When users upload data on a project
+ Then the server should handle it and return a success status
+
+ Scenario: Data retrieval from a web service
+ When users want to get information on the Cucumber project
+ Then the requested data is returned
\ No newline at end of file
diff --git a/rest-testing/src/main/resources/cucumber.json b/rest-testing/src/main/resources/cucumber.json
new file mode 100644
index 0000000000..38ebe066ac
--- /dev/null
+++ b/rest-testing/src/main/resources/cucumber.json
@@ -0,0 +1,14 @@
+{
+ "testing-framework": "cucumber",
+ "supported-language":
+ [
+ "Ruby",
+ "Java",
+ "Javascript",
+ "PHP",
+ "Python",
+ "C++"
+ ],
+
+ "website": "cucumber.io"
+}
\ No newline at end of file
diff --git a/rest-testing/src/main/resources/wiremock_intro.json b/rest-testing/src/main/resources/wiremock_intro.json
new file mode 100644
index 0000000000..ece2d35907
--- /dev/null
+++ b/rest-testing/src/main/resources/wiremock_intro.json
@@ -0,0 +1,5 @@
+{
+ "testing-library": "WireMock",
+ "creator": "Tom Akehurst",
+ "website": "wiremock.org"
+}
\ No newline at end of file
diff --git a/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberTest.java b/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberTest.java
new file mode 100644
index 0000000000..041de592e9
--- /dev/null
+++ b/rest-testing/src/test/java/com/baeldung/rest/cucumber/CucumberTest.java
@@ -0,0 +1,10 @@
+package com.baeldung.rest.cucumber;
+
+import org.junit.runner.RunWith;
+import cucumber.api.CucumberOptions;
+import cucumber.api.junit.Cucumber;
+
+@RunWith(Cucumber.class)
+@CucumberOptions(features = "classpath:Feature")
+public class CucumberTest {
+}
\ No newline at end of file
diff --git a/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java b/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java
new file mode 100644
index 0000000000..b461da8403
--- /dev/null
+++ b/rest-testing/src/test/java/com/baeldung/rest/cucumber/StepDefinition.java
@@ -0,0 +1,101 @@
+package com.baeldung.rest.cucumber;
+
+import com.github.tomakehurst.wiremock.WireMockServer;
+import cucumber.api.java.en.Then;
+import cucumber.api.java.en.When;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Scanner;
+
+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.containing;
+import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.get;
+import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.post;
+import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.verify;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
+public class StepDefinition {
+
+ private static final String CREATE_PATH = "/create";
+ private static final String APPLICATION_JSON = "application/json";
+
+ private final InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("cucumber.json");
+ private final String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next();
+
+ private final WireMockServer wireMockServer = new WireMockServer();
+ private final CloseableHttpClient httpClient = HttpClients.createDefault();
+
+ @When("^users upload data on a project$")
+ public void usersUploadDataOnAProject() throws IOException {
+ wireMockServer.start();
+
+ configureFor("localhost", 8080);
+ stubFor(post(urlEqualTo(CREATE_PATH))
+ .withHeader("content-type", equalTo(APPLICATION_JSON))
+ .withRequestBody(containing("testing-framework"))
+ .willReturn(aResponse().withStatus(200)));
+
+ HttpPost request = new HttpPost("http://localhost:8080/create");
+ StringEntity entity = new StringEntity(jsonString);
+ request.addHeader("content-type", APPLICATION_JSON);
+ request.setEntity(entity);
+ HttpResponse response = httpClient.execute(request);
+
+ assertEquals(200, response.getStatusLine().getStatusCode());
+ verify(postRequestedFor(urlEqualTo(CREATE_PATH))
+ .withHeader("content-type", equalTo(APPLICATION_JSON)));
+
+ wireMockServer.stop();
+ }
+
+ @When("^users want to get information on the (.+) project$")
+ public void usersGetInformationOnAProject(String projectName) throws IOException {
+ wireMockServer.start();
+
+ configureFor("localhost", 8080);
+ stubFor(get(urlEqualTo("/projects/cucumber")).withHeader("accept", equalTo(APPLICATION_JSON))
+ .willReturn(aResponse().withBody(jsonString)));
+
+ HttpGet request = new HttpGet("http://localhost:8080/projects/" + projectName.toLowerCase());
+ request.addHeader("accept", APPLICATION_JSON);
+ HttpResponse httpResponse = httpClient.execute(request);
+ String responseString = convertResponseToString(httpResponse);
+
+ assertThat(responseString, containsString("\"testing-framework\": \"cucumber\""));
+ assertThat(responseString, containsString("\"website\": \"cucumber.io\""));
+ verify(getRequestedFor(urlEqualTo("/projects/cucumber")).withHeader("accept", equalTo(APPLICATION_JSON)));
+
+ wireMockServer.stop();
+ }
+
+ @Then("^the server should handle it and return a success status$")
+ public void theServerShouldReturnASuccessStatus() {
+ }
+
+ @Then("^the requested data is returned$")
+ public void theRequestedDataIsReturned() {
+ }
+
+ private String convertResponseToString(HttpResponse response) throws IOException {
+ InputStream responseStream = response.getEntity().getContent();
+ Scanner scanner = new Scanner(responseStream, "UTF-8");
+ String responseString = scanner.useDelimiter("\\Z").next();
+ scanner.close();
+ return responseString;
+ }
+}
\ No newline at end of file
diff --git a/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManaged.java b/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManaged.java
new file mode 100644
index 0000000000..664c3fac78
--- /dev/null
+++ b/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManaged.java
@@ -0,0 +1,144 @@
+package com.baeldung.rest.wiremock.introduction;
+
+import com.github.tomakehurst.wiremock.junit.WireMockRule;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.junit.Rule;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Scanner;
+
+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.containing;
+import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.get;
+import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.matching;
+import static com.github.tomakehurst.wiremock.client.WireMock.post;
+import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
+import static com.github.tomakehurst.wiremock.client.WireMock.verify;
+import static org.junit.Assert.assertEquals;
+
+public class JUnitManaged {
+
+ private static final String BAELDUNG_WIREMOCK_PATH = "/baeldung/wiremock";
+ private static final String APPLICATION_JSON = "application/json";
+
+ @Rule
+ public WireMockRule wireMockRule = new WireMockRule();
+
+ @Test
+ public void givenJUnitManagedServer_whenMatchingURL_thenCorrect() throws IOException {
+ stubFor(get(urlPathMatching("/baeldung/.*"))
+ .willReturn(aResponse()
+ .withStatus(200)
+ .withHeader("Content-Type", APPLICATION_JSON)
+ .withBody("\"testing-library\": \"WireMock\"")));
+
+ CloseableHttpClient httpClient = HttpClients.createDefault();
+ HttpGet request = new HttpGet("http://localhost:8080/baeldung/wiremock");
+ HttpResponse httpResponse = httpClient.execute(request);
+ String stringResponse = convertHttpResponseToString(httpResponse);
+
+ verify(getRequestedFor(urlEqualTo(BAELDUNG_WIREMOCK_PATH)));
+ assertEquals(200, httpResponse.getStatusLine().getStatusCode());
+ assertEquals(APPLICATION_JSON, httpResponse.getFirstHeader("Content-Type").getValue());
+ assertEquals("\"testing-library\": \"WireMock\"", stringResponse);
+ }
+
+ @Test
+ public void givenJUnitManagedServer_whenMatchingHeaders_thenCorrect() throws IOException {
+ stubFor(get(urlPathEqualTo(BAELDUNG_WIREMOCK_PATH))
+ .withHeader("Accept", matching("text/.*"))
+ .willReturn(aResponse()
+ .withStatus(503)
+ .withHeader("Content-Type", "text/html")
+ .withBody("!!! Service Unavailable !!!")));
+
+ CloseableHttpClient httpClient = HttpClients.createDefault();
+ HttpGet request = new HttpGet("http://localhost:8080/baeldung/wiremock");
+ request.addHeader("Accept", "text/html");
+ HttpResponse httpResponse = httpClient.execute(request);
+ String stringResponse = convertHttpResponseToString(httpResponse);
+
+ verify(getRequestedFor(urlEqualTo(BAELDUNG_WIREMOCK_PATH)));
+ assertEquals(503, httpResponse.getStatusLine().getStatusCode());
+ assertEquals("text/html", httpResponse.getFirstHeader("Content-Type").getValue());
+ assertEquals("!!! Service Unavailable !!!", stringResponse);
+ }
+
+ @Test
+ public void givenJUnitManagedServer_whenMatchingBody_thenCorrect() throws IOException {
+ stubFor(post(urlEqualTo(BAELDUNG_WIREMOCK_PATH))
+ .withHeader("Content-Type", equalTo(APPLICATION_JSON))
+ .withRequestBody(containing("\"testing-library\": \"WireMock\""))
+ .withRequestBody(containing("\"creator\": \"Tom Akehurst\""))
+ .withRequestBody(containing("\"website\": \"wiremock.org\""))
+ .willReturn(aResponse().withStatus(200)));
+
+ InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("wiremock_intro.json");
+ String jsonString = convertInputStreamToString(jsonInputStream);
+ StringEntity entity = new StringEntity(jsonString);
+
+ CloseableHttpClient httpClient = HttpClients.createDefault();
+ HttpPost request = new HttpPost("http://localhost:8080/baeldung/wiremock");
+ request.addHeader("Content-Type", APPLICATION_JSON);
+ request.setEntity(entity);
+ HttpResponse response = httpClient.execute(request);
+
+ verify(postRequestedFor(urlEqualTo(BAELDUNG_WIREMOCK_PATH))
+ .withHeader("Content-Type", equalTo(APPLICATION_JSON)));
+ assertEquals(200, response.getStatusLine().getStatusCode());
+ }
+
+ @Test
+ public void givenJUnitManagedServer_whenNotUsingPriority_thenCorrect() throws IOException {
+ stubFor(get(urlPathMatching("/baeldung/.*")).willReturn(aResponse().withStatus(200)));
+ stubFor(get(urlPathEqualTo(BAELDUNG_WIREMOCK_PATH)).withHeader("Accept", matching("text/.*")).willReturn(aResponse().withStatus(503)));
+
+ HttpResponse httpResponse = generateClientAndReceiveResponseForPriorityTests();
+
+ verify(getRequestedFor(urlEqualTo(BAELDUNG_WIREMOCK_PATH)));
+ assertEquals(503, httpResponse.getStatusLine().getStatusCode());
+ }
+
+ @Test
+ public void givenJUnitManagedServer_whenUsingPriority_thenCorrect() throws IOException {
+ stubFor(get(urlPathMatching("/baeldung/.*")).atPriority(1).willReturn(aResponse().withStatus(200)));
+ stubFor(get(urlPathEqualTo(BAELDUNG_WIREMOCK_PATH)).atPriority(2).withHeader("Accept", matching("text/.*")).willReturn(aResponse().withStatus(503)));
+
+ HttpResponse httpResponse = generateClientAndReceiveResponseForPriorityTests();
+
+ verify(getRequestedFor(urlEqualTo(BAELDUNG_WIREMOCK_PATH)));
+ assertEquals(200, httpResponse.getStatusLine().getStatusCode());
+ }
+
+ private static String convertHttpResponseToString(HttpResponse httpResponse) throws IOException {
+ InputStream inputStream = httpResponse.getEntity().getContent();
+ return convertInputStreamToString(inputStream);
+ }
+
+ private static String convertInputStreamToString(InputStream inputStream) {
+ Scanner scanner = new Scanner(inputStream, "UTF-8");
+ String string = scanner.useDelimiter("\\Z").next();
+ scanner.close();
+ return string;
+ }
+
+ private HttpResponse generateClientAndReceiveResponseForPriorityTests() throws IOException {
+ CloseableHttpClient httpClient = HttpClients.createDefault();
+ HttpGet request = new HttpGet("http://localhost:8080/baeldung/wiremock");
+ request.addHeader("Accept", "text/xml");
+ return httpClient.execute(request);
+ }
+}
\ No newline at end of file
diff --git a/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/ProgrammaticallyManaged.java b/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/ProgrammaticallyManaged.java
new file mode 100644
index 0000000000..ad7caa52b5
--- /dev/null
+++ b/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/ProgrammaticallyManaged.java
@@ -0,0 +1,54 @@
+package com.baeldung.rest.wiremock.introduction;
+
+import com.github.tomakehurst.wiremock.WireMockServer;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Scanner;
+
+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.get;
+import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.verify;
+import static org.junit.Assert.assertEquals;
+
+public class ProgrammaticallyManaged {
+
+ private static final String BAELDUNG_PATH = "/baeldung";
+
+ private WireMockServer wireMockServer = new WireMockServer();
+ private CloseableHttpClient httpClient = HttpClients.createDefault();
+
+ @Test
+ public void givenProgrammaticallyManagedServer_whenUsingSimpleStubbing_thenCorrect() throws IOException {
+ wireMockServer.start();
+
+ configureFor("localhost", 8080);
+ stubFor(get(urlEqualTo(BAELDUNG_PATH)).willReturn(aResponse().withBody("Welcome to Baeldung!")));
+
+ HttpGet request = new HttpGet("http://localhost:8080/baeldung");
+ HttpResponse httpResponse = httpClient.execute(request);
+ String stringResponse = convertResponseToString(httpResponse);
+
+ verify(getRequestedFor(urlEqualTo(BAELDUNG_PATH)));
+ assertEquals("Welcome to Baeldung!", stringResponse);
+
+ wireMockServer.stop();
+ }
+
+ private static String convertResponseToString(HttpResponse response) throws IOException {
+ InputStream responseStream = response.getEntity().getContent();
+ Scanner scanner = new Scanner(responseStream, "UTF-8");
+ String stringResponse = scanner.useDelimiter("\\Z").next();
+ scanner.close();
+ return stringResponse;
+ }
+}
\ No newline at end of file
diff --git a/rest-testing/src/test/resources/.gitignore b/rest-testing/src/test/resources/.gitignore
deleted file mode 100644
index 83c05e60c8..0000000000
--- a/rest-testing/src/test/resources/.gitignore
+++ /dev/null
@@ -1,13 +0,0 @@
-*.class
-
-#folders#
-/target
-/neoDb*
-/data
-/src/main/webapp/WEB-INF/classes
-*/META-INF/*
-
-# Packaged files #
-*.jar
-*.war
-*.ear
\ No newline at end of file
diff --git a/spring-all/README.md b/spring-all/README.md
index 977b8b7357..47c947a414 100644
--- a/spring-all/README.md
+++ b/spring-all/README.md
@@ -4,6 +4,8 @@
This project is used to replicate Spring Exceptions only.
+###The Course
+The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant articles:
- [Properties with Spring](http://www.baeldung.com/2012/02/06/properties-with-spring) - checkout the `org.baeldung.properties` package for all scenarios of properties injection and usage
diff --git a/spring-boot/README.MD b/spring-boot/README.MD
new file mode 100644
index 0000000000..2a87b46021
--- /dev/null
+++ b/spring-boot/README.MD
@@ -0,0 +1,2 @@
+###The Course
+The "REST With Spring" Classes: http://bit.ly/restwithspring
diff --git a/spring-data-neo4j/README.md b/spring-data-neo4j/README.md
new file mode 100644
index 0000000000..e62c69f8b9
--- /dev/null
+++ b/spring-data-neo4j/README.md
@@ -0,0 +1,15 @@
+## Spring Data Neo4j
+
+### Relevant Articles:
+- [Introduction to Spring Data Neo4j](http://www.baeldung.com/spring-data-neo4j-tutorial)
+
+### Build the Project with Tests Running
+```
+mvn clean install
+```
+
+### Run Tests Directly
+```
+mvn test
+```
+
diff --git a/spring-data-neo4j/pom.xml b/spring-data-neo4j/pom.xml
new file mode 100644
index 0000000000..a5a2e9220a
--- /dev/null
+++ b/spring-data-neo4j/pom.xml
@@ -0,0 +1,93 @@
+
+
+ 4.0.0
+ com.baeldung
+ spring-data-neo4j
+ 1.0
+ jar
+
+
+ 1.8
+ UTF-8
+ UTF-8
+ 3.0.1
+ 4.1.1.RELEASE
+
+
+
+
+ org.springframework.data
+ spring-data-neo4j
+ ${spring-data-neo4j.version}
+
+
+
+ com.voodoodyne.jackson.jsog
+ jackson-jsog
+ 1.1
+ compile
+
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+
+ org.springframework.data
+ spring-data-neo4j
+ ${spring-data-neo4j.version}
+ test-jar
+
+
+
+ org.neo4j
+ neo4j-kernel
+ ${neo4j.version}
+ test-jar
+
+
+
+ org.neo4j.app
+ neo4j-server
+ ${neo4j.version}
+ test-jar
+
+
+
+ org.neo4j
+ neo4j-ogm-test
+ 2.0.2
+ test
+
+
+
+ org.neo4j.test
+ neo4j-harness
+ ${neo4j.version}
+ test
+
+
+ junit
+ junit
+ 4.12
+
+
+ org.springframework
+ spring-test
+ 4.2.3.RELEASE
+
+
+
+
+
+
+
+ maven-compiler-plugin
+
+
+
+
+
diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java
new file mode 100644
index 0000000000..ac9a7260be
--- /dev/null
+++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jConfiguration.java
@@ -0,0 +1,34 @@
+package com.baeldung.spring.data.neo4j.config;
+
+import org.neo4j.ogm.session.SessionFactory;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.neo4j.config.Neo4jConfiguration;
+import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
+import org.springframework.scheduling.annotation.EnableScheduling;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+
+@ComponentScan(basePackages = {"com.baeldung.spring.data.neo4j.services"})
+@Configuration
+@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory")
+public class MovieDatabaseNeo4jConfiguration extends Neo4jConfiguration {
+
+ public static final String URL = System.getenv("NEO4J_URL") != null ? System.getenv("NEO4J_URL") : "http://neo4j:movies@localhost:7474";
+
+ @Bean
+ public org.neo4j.ogm.config.Configuration getConfiguration() {
+ org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
+ config
+ .driverConfiguration()
+ .setDriverClassName("org.neo4j.ogm.drivers.http.driver.HttpDriver")
+ .setURI(URL);
+ return config;
+ }
+
+ @Override
+ public SessionFactory getSessionFactory() {
+ return new SessionFactory(getConfiguration(), "com.baeldung.spring.data.neo4j.domain");
+ }
+}
diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java
new file mode 100644
index 0000000000..2b6394184d
--- /dev/null
+++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/config/MovieDatabaseNeo4jTestConfiguration.java
@@ -0,0 +1,34 @@
+package com.baeldung.spring.data.neo4j.config;
+
+import org.neo4j.ogm.session.SessionFactory;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Profile;
+import org.springframework.data.neo4j.config.Neo4jConfiguration;
+import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
+import org.springframework.data.neo4j.server.Neo4jServer;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+
+@EnableTransactionManagement
+@ComponentScan(basePackages = {"com.baeldung.spring.data.neo4j.services"})
+@Configuration
+@EnableNeo4jRepositories(basePackages = "com.baeldung.spring.data.neo4j.repostory")
+@Profile({"embedded", "test"})
+public class MovieDatabaseNeo4jTestConfiguration extends Neo4jConfiguration {
+
+ @Bean
+ public org.neo4j.ogm.config.Configuration getConfiguration() {
+ org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
+ config
+ .driverConfiguration()
+ .setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");
+ return config;
+ }
+
+ @Override
+ public SessionFactory getSessionFactory() {
+ return new SessionFactory(getConfiguration(), "com.baeldung.spring.data.neo4j.domain");
+ }
+}
diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java
new file mode 100644
index 0000000000..e48dfaf276
--- /dev/null
+++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Movie.java
@@ -0,0 +1,61 @@
+package com.baeldung.spring.data.neo4j.domain;
+
+import com.fasterxml.jackson.annotation.JsonIdentityInfo;
+import com.voodoodyne.jackson.jsog.JSOGGenerator;
+import org.neo4j.ogm.annotation.GraphId;
+import org.neo4j.ogm.annotation.NodeEntity;
+import org.neo4j.ogm.annotation.Relationship;
+
+import java.util.Collection;
+import java.util.List;
+
+@JsonIdentityInfo(generator=JSOGGenerator.class)
+
+@NodeEntity
+public class Movie {
+ @GraphId
+ Long id;
+
+ private String title;
+
+ private int released;
+ private String tagline;
+
+ @Relationship(type="ACTED_IN", direction = Relationship.INCOMING) private List roles;
+
+ public Movie() { }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public int getReleased() {
+ return released;
+ }
+
+ public String getTagline() {
+ return tagline;
+ }
+
+ public Collection getRoles() {
+ return roles;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public void setReleased(int released) {
+ this.released = released;
+ }
+
+ public void setTagline(String tagline) {
+ this.tagline = tagline;
+ }
+
+ public void setRoles(List roles) {
+ this.roles = roles;
+ }
+
+
+}
diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java
new file mode 100644
index 0000000000..d96dc07530
--- /dev/null
+++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Person.java
@@ -0,0 +1,50 @@
+package com.baeldung.spring.data.neo4j.domain;
+
+
+import com.fasterxml.jackson.annotation.JsonIdentityInfo;
+import com.voodoodyne.jackson.jsog.JSOGGenerator;
+import org.neo4j.ogm.annotation.GraphId;
+import org.neo4j.ogm.annotation.NodeEntity;
+import org.neo4j.ogm.annotation.Relationship;
+
+import java.util.List;
+
+@JsonIdentityInfo(generator=JSOGGenerator.class)
+@NodeEntity
+public class Person {
+ @GraphId
+ Long id;
+
+ private String name;
+ private int born;
+
+ @Relationship(type = "ACTED_IN")
+ private List movies;
+
+ public Person() { }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getBorn() {
+ return born;
+ }
+
+ public List getMovies() {
+ return movies;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setBorn(int born) {
+ this.born = born;
+ }
+
+ public void setMovies(List movies) {
+ this.movies = movies;
+ }
+
+}
diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java
new file mode 100644
index 0000000000..20512a10ad
--- /dev/null
+++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/domain/Role.java
@@ -0,0 +1,50 @@
+package com.baeldung.spring.data.neo4j.domain;
+
+
+import com.fasterxml.jackson.annotation.JsonIdentityInfo;
+import com.voodoodyne.jackson.jsog.JSOGGenerator;
+import org.neo4j.ogm.annotation.EndNode;
+import org.neo4j.ogm.annotation.GraphId;
+import org.neo4j.ogm.annotation.RelationshipEntity;
+import org.neo4j.ogm.annotation.StartNode;
+
+import java.util.Collection;
+
+@JsonIdentityInfo(generator=JSOGGenerator.class)
+@RelationshipEntity(type = "ACTED_IN")
+public class Role {
+ @GraphId
+ Long id;
+ private Collection roles;
+ @StartNode
+ private Person person;
+ @EndNode
+ private Movie movie;
+
+ public Role() {
+ }
+
+ public Collection getRoles() {
+ return roles;
+ }
+
+ public Person getPerson() {
+ return person;
+ }
+
+ public Movie getMovie() {
+ return movie;
+ }
+
+ public void setRoles(Collection roles) {
+ this.roles = roles;
+ }
+
+ public void setPerson(Person person) {
+ this.person = person;
+ }
+
+ public void setMovie(Movie movie) {
+ this.movie = movie;
+ }
+}
diff --git a/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java
new file mode 100644
index 0000000000..850d2336ba
--- /dev/null
+++ b/spring-data-neo4j/src/main/java/com/baeldung/spring/data/neo4j/repostory/MovieRepository.java
@@ -0,0 +1,24 @@
+package com.baeldung.spring.data.neo4j.repostory;
+
+import com.baeldung.spring.data.neo4j.domain.Movie;
+import org.springframework.data.neo4j.annotation.Query;
+import org.springframework.data.neo4j.repository.GraphRepository;
+import org.springframework.data.repository.query.Param;
+import org.springframework.stereotype.Repository;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+@Repository
+public interface MovieRepository extends GraphRepository {
+ Movie findByTitle(@Param("title") String title);
+
+ @Query("MATCH (m:Movie) WHERE m.title =~ ('(?i).*'+{title}+'.*') RETURN m")
+ Collection findByTitleContaining(@Param("title") String title);
+
+ @Query("MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) RETURN m.title as movie, collect(a.name) as cast LIMIT {limit}")
+ List